Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(init): support initializing npm projects #26896

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions cli/args/flags.rs
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,7 @@ impl FmtFlags {

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct InitFlags {
pub package: Option<String>,
pub dir: Option<String>,
pub lib: bool,
pub serve: bool,
Expand Down Expand Up @@ -4652,6 +4653,8 @@ fn fmt_parse(

fn init_parse(flags: &mut Flags, matches: &mut ArgMatches) {
flags.subcommand = DenoSubcommand::Init(InitFlags {
// TODO:
package: None,
dir: matches.remove_one::<String>("dir"),
lib: matches.get_flag("lib"),
serve: matches.get_flag("serve"),
Expand Down Expand Up @@ -10600,6 +10603,7 @@ mod tests {
r.unwrap(),
Flags {
subcommand: DenoSubcommand::Init(InitFlags {
package: None,
dir: None,
lib: false,
serve: false,
Expand All @@ -10613,6 +10617,7 @@ mod tests {
r.unwrap(),
Flags {
subcommand: DenoSubcommand::Init(InitFlags {
package: None,
dir: Some(String::from("foo")),
lib: false,
serve: false,
Expand All @@ -10626,6 +10631,7 @@ mod tests {
r.unwrap(),
Flags {
subcommand: DenoSubcommand::Init(InitFlags {
package: None,
dir: None,
lib: false,
serve: false,
Expand All @@ -10640,6 +10646,7 @@ mod tests {
r.unwrap(),
Flags {
subcommand: DenoSubcommand::Init(InitFlags {
package: None,
dir: None,
lib: true,
serve: false,
Expand All @@ -10653,6 +10660,7 @@ mod tests {
r.unwrap(),
Flags {
subcommand: DenoSubcommand::Init(InitFlags {
package: None,
dir: None,
lib: false,
serve: true,
Expand All @@ -10666,13 +10674,34 @@ mod tests {
r.unwrap(),
Flags {
subcommand: DenoSubcommand::Init(InitFlags {
package: None,
dir: Some(String::from("foo")),
lib: true,
serve: false,
}),
..Flags::default()
}
);

let r = flags_from_vec(svec!["deno", "init", "npm:vite", "--lib"]);
assert!(r.is_err());

let r = flags_from_vec(svec!["deno", "init", "npm:vite", "--serve"]);
assert!(r.is_err());

let r = flags_from_vec(svec!["deno", "init", "npm:vite", "new_dir"]);
assert_eq!(
r.unwrap(),
Flags {
subcommand: DenoSubcommand::Init(InitFlags {
package: Some("npm:vite".to_string()),
dir: Some(String::from("new_dir")),
lib: true,
serve: false,
}),
..Flags::default()
}
);
}

#[test]
Expand Down
3 changes: 2 additions & 1 deletion cli/args/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1621,8 +1621,9 @@ impl CliOptions {
DenoSubcommand::Install(_)
| DenoSubcommand::Add(_)
| DenoSubcommand::Remove(_)
| DenoSubcommand::Init(_)
) {
// For `deno install/add/remove` we want to force the managed resolver so it can set up `node_modules/` directory.
// For `deno install/add/remove/init` we want to force the managed resolver so it can set up `node_modules/` directory.
return false;
}
if self.node_modules_dir().ok().flatten().is_none()
Expand Down
12 changes: 12 additions & 0 deletions cli/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,11 @@ use crate::util::display;
use crate::util::v8::get_v8_flags_from_env;
use crate::util::v8::init_v8_flags;

use args::PackagesAllowedScripts;
use args::PermissionFlags;
use args::RunFlags;
use args::TaskFlags;
use deno_core::anyhow::bail;
use deno_resolver::npm::ByonmResolvePkgFolderFromDenoReqError;
use deno_resolver::npm::ResolvePkgFolderFromDenoReqError;
use deno_runtime::WorkerExecutionMode;
Expand Down Expand Up @@ -143,6 +147,14 @@ async fn run_subcommand(flags: Arc<Flags>) -> Result<i32, AnyError> {
)
}
DenoSubcommand::Init(init_flags) => {
if let Some(dir) = &init_flags.dir {
if dir.starts_with("jsr:") {
bail!("Initializing project from a jsr package is currently not supported.");
} else if dir.starts_with("npm:") {
return tools::init::init_npm(dir).await;
}
}

spawn_subcommand(async {
// make compiler happy since init_project is sync
tokio::task::yield_now().await;
Expand Down
33 changes: 33 additions & 0 deletions cli/tools/init/mod.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.

use crate::args::DenoSubcommand;
use crate::args::Flags;
use crate::args::InitFlags;
use crate::args::PackagesAllowedScripts;
use crate::args::PermissionFlags;
use crate::args::RunFlags;
use crate::colors;
use deno_core::anyhow::Context;
use deno_core::error::AnyError;
use deno_core::serde_json::json;
use deno_runtime::WorkerExecutionMode;
use log::info;
use std::io::Write;
use std::path::Path;
Expand Down Expand Up @@ -238,6 +244,33 @@ Deno.test(function addTest() {
Ok(())
}

pub async fn init_npm(name: &str) -> Result<i32, AnyError> {
// TODO: do prompt
let script_name =
format!("npm:create-{}", name.strip_prefix("npm:").unwrap());

let new_flags = Flags {
permissions: PermissionFlags {
allow_all: true,
..Default::default()
},
allow_scripts: PackagesAllowedScripts::All,
// TODO:
argv: vec![],
subcommand: DenoSubcommand::Run(RunFlags {
script: script_name,
..Default::default()
}),
..Default::default()
};
crate::tools::run::run_script(
WorkerExecutionMode::Run,
new_flags.into(),
None,
)
.await
}

fn create_json_file(
dir: &Path,
filename: &str,
Expand Down
Loading