Skip to content

Commit

Permalink
fix(cli): short-circuit in prepare_module_load() (denoland#12604)
Browse files Browse the repository at this point in the history
  • Loading branch information
nayeemrmn committed Nov 15, 2021
1 parent 243d3ba commit cd9193f
Show file tree
Hide file tree
Showing 24 changed files with 268 additions and 317 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.

4 changes: 2 additions & 2 deletions cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,8 @@ winres = "0.1.11"
[dependencies]
deno_ast = { version = "0.5.0", features = ["bundler", "codegen", "dep_graph", "module_specifier", "proposal", "react", "sourcemap", "transforms", "typescript", "view", "visit"] }
deno_core = { version = "0.107.0", path = "../core" }
deno_doc = "0.20.0"
deno_graph = "0.11.1"
deno_doc = "0.21.0"
deno_graph = "0.12.0"
deno_lint = { version = "0.19.0", features = ["docs"] }
deno_runtime = { version = "0.33.0", path = "../runtime" }
deno_tls = { version = "0.12.0", path = "../ext/tls" }
Expand Down
148 changes: 1 addition & 147 deletions cli/emit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ use crate::version;

use deno_ast::swc;
use deno_core::error::anyhow;
use deno_core::error::custom_error;
use deno_core::error::AnyError;
use deno_core::error::Context;
use deno_core::serde::Deserialize;
Expand All @@ -26,7 +25,6 @@ use deno_core::serde::Serialize;
use deno_core::serde::Serializer;
use deno_core::serde_json::json;
use deno_core::serde_json::Value;
use deno_core::ModuleSource;
use deno_core::ModuleSpecifier;
use deno_graph::MediaType;
use deno_graph::ModuleGraph;
Expand All @@ -43,7 +41,7 @@ use std::time::Instant;
/// Represents the "default" type library that should be used when type
/// checking the code in the module graph. Note that a user provided config
/// of `"lib"` would override this value.
#[derive(Debug, Clone, Eq, PartialEq)]
#[derive(Debug, Clone, Eq, Hash, PartialEq)]
pub(crate) enum TypeLib {
DenoWindow,
DenoWorker,
Expand Down Expand Up @@ -76,8 +74,6 @@ impl Serialize for TypeLib {
}
}

type Modules = HashMap<ModuleSpecifier, Result<ModuleSource, AnyError>>;

/// A structure representing stats from an emit operation for a graph.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub(crate) struct Stats(pub Vec<(String, u32)>);
Expand Down Expand Up @@ -790,74 +786,9 @@ pub(crate) fn to_file_map(
files
}

/// Convert a module graph to a map of module sources, which are used by
/// `deno_core` to load modules into V8.
pub(crate) fn to_module_sources(
graph: &ModuleGraph,
cache: &dyn Cacher,
) -> Modules {
graph
.specifiers()
.into_iter()
.map(|(requested_specifier, r)| match r {
Err(err) => (requested_specifier, Err(err.into())),
Ok((found_specifier, media_type)) => {
// First we check to see if there is an emitted file in the cache.
if let Some(code) = cache.get(CacheType::Emit, &found_specifier) {
(
requested_specifier.clone(),
Ok(ModuleSource {
code,
module_url_found: found_specifier.to_string(),
module_url_specified: requested_specifier.to_string(),
}),
)
// Then if the file is JavaScript (or unknown) and wasn't emitted, we
// will load the original source code in the module.
} else if matches!(
media_type,
MediaType::JavaScript
| MediaType::Unknown
| MediaType::Cjs
| MediaType::Mjs
) {
if let Some(module) = graph.get(&found_specifier) {
(
requested_specifier.clone(),
Ok(ModuleSource {
code: module.source.as_str().to_string(),
module_url_found: module.specifier.to_string(),
module_url_specified: requested_specifier.to_string(),
}),
)
} else {
unreachable!(
"unexpected module missing from graph: {}",
found_specifier
)
}
// Otherwise we will add a not found error.
} else {
(
requested_specifier.clone(),
Err(custom_error(
"NotFound",
format!(
"Emitted code for \"{}\" not found.",
requested_specifier
),
)),
)
}
}
})
.collect()
}

#[cfg(test)]
mod tests {
use super::*;
use crate::cache::MemoryCacher;

#[test]
fn test_is_emittable() {
Expand All @@ -873,81 +804,4 @@ mod tests {
assert!(is_emittable(&MediaType::Jsx, false));
assert!(!is_emittable(&MediaType::Json, false));
}

async fn setup<S: AsRef<str>>(
root: S,
sources: Vec<(S, S)>,
) -> (ModuleGraph, MemoryCacher) {
let roots = vec![ModuleSpecifier::parse(root.as_ref()).unwrap()];
let sources = sources
.into_iter()
.map(|(s, c)| (s.as_ref().to_string(), Arc::new(c.as_ref().to_string())))
.collect();
let mut cache = MemoryCacher::new(sources);
let graph = deno_graph::create_graph(
roots, false, None, &mut cache, None, None, None,
)
.await;
(graph, cache)
}

#[tokio::test]
async fn test_to_module_sources_emitted() {
let (graph, mut cache) = setup(
"https://example.com/a.ts",
vec![("https://example.com/a.ts", r#"console.log("hello deno");"#)],
)
.await;
let (ts_config, _) = get_ts_config(ConfigType::Emit, None, None).unwrap();
emit(
&graph,
&mut cache,
EmitOptions {
ts_config,
reload_exclusions: HashSet::default(),
reload: false,
},
)
.unwrap();
let modules = to_module_sources(&graph, &cache);
assert_eq!(modules.len(), 1);
let root = ModuleSpecifier::parse("https://example.com/a.ts").unwrap();
let maybe_result = modules.get(&root);
assert!(maybe_result.is_some());
let result = maybe_result.unwrap();
assert!(result.is_ok());
let module_source = result.as_ref().unwrap();
assert!(module_source
.code
.starts_with(r#"console.log("hello deno");"#));
}

#[tokio::test]
async fn test_to_module_sources_not_emitted() {
let (graph, mut cache) = setup(
"https://example.com/a.js",
vec![("https://example.com/a.js", r#"console.log("hello deno");"#)],
)
.await;
let (ts_config, _) = get_ts_config(ConfigType::Emit, None, None).unwrap();
emit(
&graph,
&mut cache,
EmitOptions {
ts_config,
reload_exclusions: HashSet::default(),
reload: false,
},
)
.unwrap();
let modules = to_module_sources(&graph, &cache);
assert_eq!(modules.len(), 1);
let root = ModuleSpecifier::parse("https://example.com/a.js").unwrap();
let maybe_result = modules.get(&root);
assert!(maybe_result.is_some());
let result = maybe_result.unwrap();
assert!(result.is_ok());
let module_source = result.as_ref().unwrap();
assert_eq!(module_source.code, r#"console.log("hello deno");"#);
}
}
4 changes: 1 addition & 3 deletions cli/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -582,11 +582,9 @@ async fn cache_command(
lib.clone(),
Permissions::allow_all(),
Permissions::allow_all(),
false,
)
.await?;
if let Some(graph_error) = ps.take_graph_error() {
return Err(graph_error.into());
}
}

Ok(())
Expand Down
1 change: 1 addition & 0 deletions cli/module_loader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ impl ModuleLoader for CliModuleLoader {
lib,
root_permissions,
dynamic_permissions,
false,
)
.await
}
Expand Down
Loading

0 comments on commit cd9193f

Please sign in to comment.