Skip to content

Commit

Permalink
Merge branch 'main' into better-help-output
Browse files Browse the repository at this point in the history
  • Loading branch information
crowlKats authored Aug 9, 2024
2 parents cf10ef4 + fc02303 commit 8e43c97
Show file tree
Hide file tree
Showing 28 changed files with 1,503 additions and 986 deletions.
8 changes: 4 additions & 4 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ http_v02 = { package = "http", version = "0.2.9" }
httparse = "1.8.0"
hyper = { version = "1.4.1", features = ["full"] }
hyper-rustls = { version = "0.27.2", default-features = false, features = ["http1", "http2", "tls12", "ring"] }
hyper-util = { version = "=0.1.6", features = ["tokio", "client", "client-legacy", "server", "server-auto"] }
hyper-util = { version = "=0.1.7", features = ["tokio", "client", "client-legacy", "server", "server-auto"] }
hyper_v014 = { package = "hyper", version = "0.14.26", features = ["runtime", "http1"] }
indexmap = { version = "2", features = ["serde"] }
ipnet = "2.3"
Expand Down
2 changes: 1 addition & 1 deletion cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ deno_lockfile.workspace = true
deno_npm = "=0.21.4"
deno_package_json.workspace = true
deno_runtime = { workspace = true, features = ["include_js_files_for_snapshotting"] }
deno_semver = "=0.5.9"
deno_semver = "=0.5.10"
deno_task_shell = "=0.17.0"
deno_terminal.workspace = true
eszip = "=0.73.0"
Expand Down
38 changes: 33 additions & 5 deletions cli/args/flags.rs
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,7 @@ impl FmtFlags {
pub struct InitFlags {
pub dir: Option<String>,
pub lib: bool,
pub serve: bool,
}

#[derive(Clone, Debug, Eq, PartialEq)]
Expand Down Expand Up @@ -2145,6 +2146,14 @@ fn init_subcommand() -> Command {
.required(false)
.action(ArgAction::SetTrue),
)
.arg(
Arg::new("serve")
.long("serve")
.long_help("Generate an example project for `deno serve`")
.conflicts_with("lib")
.required(false)
.action(ArgAction::SetTrue),
)
})
}

Expand Down Expand Up @@ -3982,6 +3991,7 @@ fn init_parse(flags: &mut Flags, matches: &mut ArgMatches) {
flags.subcommand = DenoSubcommand::Init(InitFlags {
dir: matches.remove_one::<String>("dir"),
lib: matches.get_flag("lib"),
serve: matches.get_flag("serve"),
});
}

Expand Down Expand Up @@ -9900,7 +9910,8 @@ mod tests {
Flags {
subcommand: DenoSubcommand::Init(InitFlags {
dir: None,
lib: false
lib: false,
serve: false,
}),
..Flags::default()
}
Expand All @@ -9912,7 +9923,8 @@ mod tests {
Flags {
subcommand: DenoSubcommand::Init(InitFlags {
dir: Some(String::from("foo")),
lib: false
lib: false,
serve: false,
}),
..Flags::default()
}
Expand All @@ -9924,7 +9936,8 @@ mod tests {
Flags {
subcommand: DenoSubcommand::Init(InitFlags {
dir: None,
lib: false
lib: false,
serve: false,
}),
log_level: Some(Level::Error),
..Flags::default()
Expand All @@ -9937,7 +9950,21 @@ mod tests {
Flags {
subcommand: DenoSubcommand::Init(InitFlags {
dir: None,
lib: true
lib: true,
serve: false,
}),
..Flags::default()
}
);

let r = flags_from_vec(svec!["deno", "init", "--serve"]);
assert_eq!(
r.unwrap(),
Flags {
subcommand: DenoSubcommand::Init(InitFlags {
dir: None,
lib: false,
serve: true,
}),
..Flags::default()
}
Expand All @@ -9949,7 +9976,8 @@ mod tests {
Flags {
subcommand: DenoSubcommand::Init(InitFlags {
dir: Some(String::from("foo")),
lib: true
lib: true,
serve: false,
}),
..Flags::default()
}
Expand Down
26 changes: 24 additions & 2 deletions cli/lsp/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1115,6 +1115,7 @@ pub enum ConfigWatchedFileType {
#[derive(Debug, Clone)]
pub struct ConfigData {
pub scope: Arc<ModuleSpecifier>,
pub canonicalized_scope: Option<Arc<ModuleSpecifier>>,
pub member_dir: Arc<WorkspaceDirectory>,
pub fmt_config: Arc<FmtConfig>,
pub lint_config: Arc<LintConfig>,
Expand Down Expand Up @@ -1253,6 +1254,16 @@ impl ConfigData {
watched_files.entry(specifier).or_insert(file_type);
};

let canonicalized_scope = (|| {
let path = scope.to_file_path().ok()?;
let path = canonicalize_path_maybe_not_exists(&path).ok()?;
let specifier = ModuleSpecifier::from_directory_path(path).ok()?;
if specifier == *scope {
return None;
}
Some(Arc::new(specifier))
})();

if let Some(deno_json) = member_dir.maybe_deno_json() {
lsp_log!(
" Resolved Deno configuration file: \"{}\"",
Expand Down Expand Up @@ -1559,6 +1570,7 @@ impl ConfigData {

ConfigData {
scope,
canonicalized_scope,
member_dir,
resolver,
sloppy_imports_resolver,
Expand Down Expand Up @@ -1587,6 +1599,15 @@ impl ConfigData {
pub fn maybe_pkg_json(&self) -> Option<&Arc<deno_package_json::PackageJson>> {
self.member_dir.maybe_pkg_json()
}

pub fn scope_contains_specifier(&self, specifier: &ModuleSpecifier) -> bool {
specifier.as_str().starts_with(self.scope.as_str())
|| self
.canonicalized_scope
.as_ref()
.map(|s| specifier.as_str().starts_with(s.as_str()))
.unwrap_or(false)
}
}

#[derive(Clone, Debug, Default)]
Expand All @@ -1601,8 +1622,9 @@ impl ConfigTree {
) -> Option<&ModuleSpecifier> {
self
.scopes
.keys()
.rfind(|s| specifier.as_str().starts_with(s.as_str()))
.iter()
.rfind(|(_, d)| d.scope_contains_specifier(specifier))
.map(|(s, _)| s)
}

pub fn data_for_specifier(
Expand Down
14 changes: 9 additions & 5 deletions cli/lsp/resolver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ use crate::args::create_default_npmrc;
use crate::args::CacheSetting;
use crate::args::CliLockfile;
use crate::args::PackageJsonInstallDepsProvider;
use crate::args::DENO_FUTURE;
use crate::graph_util::CliJsrUrlProvider;
use crate::http_util::HttpClientProvider;
use crate::lsp::config::Config;
Expand Down Expand Up @@ -421,9 +420,14 @@ impl LspResolver {
};
self
.by_scope
.iter()
.rfind(|(s, _)| file_referrer.as_str().starts_with(s.as_str()))
.map(|(_, r)| r.as_ref())
.values()
.rfind(|r| {
r.config_data
.as_ref()
.map(|d| d.scope_contains_specifier(file_referrer))
.unwrap_or(false)
})
.map(|r| r.as_ref())
.unwrap_or(self.unscoped.as_ref())
}
}
Expand All @@ -433,7 +437,7 @@ async fn create_npm_resolver(
cache: &LspCache,
http_client_provider: &Arc<HttpClientProvider>,
) -> Option<Arc<dyn CliNpmResolver>> {
let enable_byonm = config_data.map(|d| d.byonm).unwrap_or(*DENO_FUTURE);
let enable_byonm = config_data.map(|d| d.byonm).unwrap_or(false);
let options = if enable_byonm {
CliNpmResolverCreateOptions::Byonm(CliNpmResolverByonmCreateOptions {
fs: Arc::new(deno_fs::RealFs),
Expand Down
4 changes: 4 additions & 0 deletions cli/npm/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,10 @@ impl NpmFetchResolver {
let maybe_get_nv = || async {
let name = req.name.clone();
let package_info = self.package_info(&name).await?;
if let Some(dist_tag) = req.version_req.tag() {
let version = package_info.dist_tags.get(dist_tag)?.clone();
return Some(PackageNv { name, version });
}
// Find the first matching version of the package.
let mut versions = package_info.versions.keys().collect::<Vec<_>>();
versions.sort();
Expand Down
96 changes: 94 additions & 2 deletions cli/tools/init/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,87 @@ pub fn init_project(init_flags: InitFlags) -> Result<(), AnyError> {
cwd
};

if init_flags.lib {
if init_flags.serve {
create_file(
&dir,
"main.ts",
r#"import { type Route, route, serveDir } from "@std/http";
const routes: Route[] = [
{
pattern: new URLPattern({ pathname: "/" }),
handler: () => new Response("Home page"),
},
{
pattern: new URLPattern({ pathname: "/users/:id" }),
handler: (_req, _info, params) => new Response(params?.pathname.groups.id),
},
{
pattern: new URLPattern({ pathname: "/static/*" }),
handler: (req) => serveDir(req, { urlRoot: "./" }),
},
];
function defaultHandler(_req: Request) {
return new Response("Not found", { status: 404 });
}
const handler = route(routes, defaultHandler);
export default {
fetch(req) {
return handler(req);
},
} satisfies Deno.ServeDefaultExport;
"#,
)?;
create_file(
&dir,
"main_test.ts",
r#"import { assertEquals } from "@std/assert";
import server from "./main.ts";
Deno.test(async function serverFetch() {
const req = new Request("https://deno.land");
const res = await server.fetch(req);
assertEquals(await res.text(), "Home page");
});
Deno.test(async function serverFetchNotFound() {
const req = new Request("https://deno.land/404");
const res = await server.fetch(req);
assertEquals(res.status, 404);
});
Deno.test(async function serverFetchUsers() {
const req = new Request("https://deno.land/users/123");
const res = await server.fetch(req);
assertEquals(await res.text(), "123");
});
Deno.test(async function serverFetchStatic() {
const req = new Request("https://deno.land/static/main.ts");
const res = await server.fetch(req);
assertEquals(res.headers.get("content-type"), "text/plain;charset=UTF-8");
});
"#,
)?;

create_json_file(
&dir,
"deno.json",
&json!({
"tasks": {
"dev": "deno serve --watch -R main.ts",
},
"imports": {
"@std/assert": "jsr:@std/assert@1",
"@std/http": "jsr:@std/http@1",
}
}),
)?;
} else if init_flags.lib {
// Extract the directory name to use as the project name
let project_name = dir
.file_name()
Expand Down Expand Up @@ -111,7 +191,19 @@ Deno.test(function addTest() {
info!(" cd {}", dir);
info!("");
}
if init_flags.lib {
if init_flags.serve {
info!(" {}", colors::gray("# Run the server"));
info!(" deno serve -R main.ts");
info!("");
info!(
" {}",
colors::gray("# Run the server and watch for file changes")
);
info!(" deno task dev");
info!("");
info!(" {}", colors::gray("# Run the tests"));
info!(" deno -R test");
} else if init_flags.lib {
info!(" {}", colors::gray("# Run the tests"));
info!(" deno test");
info!("");
Expand Down
Loading

0 comments on commit 8e43c97

Please sign in to comment.