Skip to content

Commit

Permalink
refactor(cli): rename GlobalState to ProgramState (denoland#7914)
Browse files Browse the repository at this point in the history
  • Loading branch information
bartlomieju committed Oct 13, 2020
1 parent 000ac5c commit 0bd3cea
Show file tree
Hide file tree
Showing 15 changed files with 187 additions and 186 deletions.
82 changes: 41 additions & 41 deletions cli/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ mod flags_allow_net;
mod fmt;
mod fmt_errors;
mod fs;
mod global_state;
mod global_timer;
mod http_cache;
mod http_util;
Expand All @@ -38,15 +37,16 @@ mod media_type;
mod metrics;
mod module_graph;
mod module_graph2;
mod module_loader;
mod op_fetch_asset;
mod ops;
mod permissions;
mod program_state;
mod repl;
mod resolve_addr;
mod signal;
mod source_maps;
mod specifier_handler;
mod state;
mod test_runner;
mod text_encoding;
mod tokio_util;
Expand All @@ -61,9 +61,9 @@ use crate::coverage::PrettyCoverageReporter;
use crate::file_fetcher::SourceFile;
use crate::file_fetcher::SourceFileFetcher;
use crate::fs as deno_fs;
use crate::global_state::GlobalState;
use crate::media_type::MediaType;
use crate::permissions::Permissions;
use crate::program_state::ProgramState;
use crate::worker::MainWorker;
use deno_core::error::AnyError;
use deno_core::futures::future::FutureExt;
Expand All @@ -77,10 +77,10 @@ use deno_doc as doc;
use deno_doc::parser::DocFileLoader;
use flags::DenoSubcommand;
use flags::Flags;
use global_state::exit_unstable;
use import_map::ImportMap;
use log::Level;
use log::LevelFilter;
use program_state::exit_unstable;
use std::cell::RefCell;
use std::env;
use std::io::Read;
Expand Down Expand Up @@ -113,7 +113,7 @@ where
}

fn print_cache_info(
state: &Arc<GlobalState>,
state: &Arc<ProgramState>,
json: bool,
) -> Result<(), AnyError> {
let deno_dir = &state.dir.root;
Expand Down Expand Up @@ -167,19 +167,19 @@ async fn info_command(
if json && !flags.unstable {
exit_unstable("--json");
}
let global_state = GlobalState::new(flags)?;
let program_state = ProgramState::new(flags)?;
if let Some(specifier) = maybe_specifier {
let specifier = ModuleSpecifier::resolve_url_or_path(&specifier)?;
let handler = Rc::new(RefCell::new(specifier_handler::FetchHandler::new(
&global_state,
&program_state,
Permissions::allow_all(),
)?));
let mut builder = module_graph2::GraphBuilder2::new(
handler,
global_state.maybe_import_map.clone(),
program_state.maybe_import_map.clone(),
);
builder.insert(&specifier).await?;
let graph = builder.get_graph(&global_state.lockfile)?;
let graph = builder.get_graph(&program_state.lockfile)?;
let info = graph.info()?;

if json {
Expand All @@ -190,7 +190,7 @@ async fn info_command(
Ok(())
} else {
// If it was just "deno info" print location of caches and exit
print_cache_info(&global_state, json)
print_cache_info(&program_state, json)
}
}

Expand All @@ -202,9 +202,9 @@ async fn install_command(
root: Option<PathBuf>,
force: bool,
) -> Result<(), AnyError> {
let global_state = GlobalState::new(flags.clone())?;
let program_state = ProgramState::new(flags.clone())?;
let main_module = ModuleSpecifier::resolve_url_or_path(&module_url)?;
let mut worker = MainWorker::new(&global_state, main_module.clone());
let mut worker = MainWorker::new(&program_state, main_module.clone());
// First, fetch and compile the module; this step ensures that the module exists.
worker.preload_module(&main_module).await?;
installer::install(flags, &module_url, args, name, root, force)
Expand Down Expand Up @@ -235,12 +235,12 @@ async fn cache_command(
) -> Result<(), AnyError> {
let main_module =
ModuleSpecifier::resolve_url_or_path("./$deno$cache.ts").unwrap();
let global_state = GlobalState::new(flags)?;
let mut worker = MainWorker::new(&global_state, main_module.clone());
let program_state = ProgramState::new(flags)?;
let mut worker = MainWorker::new(&program_state, main_module.clone());

for file in files {
let specifier = ModuleSpecifier::resolve_url_or_path(&file)?;
// TODO(bartlomieju): don't use `preload_module` in favor of calling "GlobalState::prepare_module_load()"
// TODO(bartlomieju): don't use `preload_module` in favor of calling "ProgramState::prepare_module_load()"
// explicitly? Seems wasteful to create multiple worker just to run TS compiler
worker.preload_module(&specifier).await.map(|_| ())?;
}
Expand All @@ -257,8 +257,8 @@ async fn eval_command(
// Force TypeScript compile.
let main_module =
ModuleSpecifier::resolve_url_or_path("./$deno$eval.ts").unwrap();
let global_state = GlobalState::new(flags)?;
let mut worker = MainWorker::new(&global_state, main_module.clone());
let program_state = ProgramState::new(flags)?;
let mut worker = MainWorker::new(&program_state, main_module.clone());
let main_module_url = main_module.as_url().to_owned();
// Create a dummy source file.
let source_code = if print {
Expand All @@ -281,7 +281,7 @@ async fn eval_command(
};
// Save our fake file into file fetcher cache
// to allow module access by TS compiler.
global_state
program_state
.file_fetcher
.save_source_file_in_cache(&main_module, source_file);
debug!("main_module {}", &main_module);
Expand All @@ -300,17 +300,17 @@ async fn bundle_command(
let module_specifier = ModuleSpecifier::resolve_url_or_path(&source_file)?;

debug!(">>>>> bundle START");
let global_state = GlobalState::new(flags)?;
let program_state = ProgramState::new(flags)?;

info!(
"{} {}",
colors::green("Bundle"),
module_specifier.to_string()
);

let output = global_state
let output = program_state
.ts_compiler
.bundle(&global_state, module_specifier)
.bundle(&program_state, module_specifier)
.await?;

debug!(">>>>> bundle END");
Expand Down Expand Up @@ -391,12 +391,12 @@ async fn doc_command(
maybe_filter: Option<String>,
private: bool,
) -> Result<(), AnyError> {
let global_state = GlobalState::new(flags.clone())?;
let program_state = ProgramState::new(flags.clone())?;
let source_file = source_file.unwrap_or_else(|| "--builtin".to_string());

let loader = Box::new(DocLoader {
fetcher: global_state.file_fetcher.clone(),
maybe_import_map: global_state.maybe_import_map.clone(),
fetcher: program_state.file_fetcher.clone(),
maybe_import_map: program_state.maybe_import_map.clone(),
});
let doc_parser = doc::DocParser::new(loader, private);

Expand Down Expand Up @@ -455,18 +455,18 @@ async fn doc_command(
async fn run_repl(flags: Flags) -> Result<(), AnyError> {
let main_module =
ModuleSpecifier::resolve_url_or_path("./$deno$repl.ts").unwrap();
let global_state = GlobalState::new(flags)?;
let mut worker = MainWorker::new(&global_state, main_module.clone());
let program_state = ProgramState::new(flags)?;
let mut worker = MainWorker::new(&program_state, main_module.clone());
worker.run_event_loop().await?;

repl::run(&global_state, worker).await
repl::run(&program_state, worker).await
}

async fn run_from_stdin(flags: Flags) -> Result<(), AnyError> {
let global_state = GlobalState::new(flags.clone())?;
let program_state = ProgramState::new(flags.clone())?;
let main_module =
ModuleSpecifier::resolve_url_or_path("./$deno$stdin.ts").unwrap();
let mut worker = MainWorker::new(&global_state.clone(), main_module.clone());
let mut worker = MainWorker::new(&program_state.clone(), main_module.clone());

let mut source = Vec::new();
std::io::stdin().read_to_end(&mut source)?;
Expand All @@ -481,7 +481,7 @@ async fn run_from_stdin(flags: Flags) -> Result<(), AnyError> {
};
// Save our fake file into file fetcher cache
// to allow module access by TS compiler
global_state
program_state
.file_fetcher
.save_source_file_in_cache(&main_module, source_file);

Expand All @@ -495,11 +495,11 @@ async fn run_from_stdin(flags: Flags) -> Result<(), AnyError> {

async fn run_with_watch(flags: Flags, script: String) -> Result<(), AnyError> {
let main_module = ModuleSpecifier::resolve_url_or_path(&script)?;
let global_state = GlobalState::new(flags.clone())?;
let program_state = ProgramState::new(flags.clone())?;

let mut module_graph_loader = module_graph::ModuleGraphLoader::new(
global_state.file_fetcher.clone(),
global_state.maybe_import_map.clone(),
program_state.file_fetcher.clone(),
program_state.maybe_import_map.clone(),
Permissions::allow_all(),
false,
false,
Expand All @@ -515,7 +515,7 @@ async fn run_with_watch(flags: Flags, script: String) -> Result<(), AnyError> {
.map(|url| url.to_file_path().unwrap())
.collect();

if let Some(import_map) = global_state.flags.import_map_path.clone() {
if let Some(import_map) = program_state.flags.import_map_path.clone() {
paths_to_watch.push(
Url::parse(&format!("file:https://{}", &import_map))?
.to_file_path()
Expand All @@ -525,9 +525,9 @@ async fn run_with_watch(flags: Flags, script: String) -> Result<(), AnyError> {

// FIXME(bartlomieju): new file watcher is created on after each restart
file_watcher::watch_func(&paths_to_watch, move || {
// FIXME(bartlomieju): GlobalState must be created on each restart - otherwise file fetcher
// FIXME(bartlomieju): ProgramState must be created on each restart - otherwise file fetcher
// will use cached source files
let gs = GlobalState::new(flags.clone()).unwrap();
let gs = ProgramState::new(flags.clone()).unwrap();
let main_module = main_module.clone();
async move {
let mut worker = MainWorker::new(&gs, main_module.clone());
Expand All @@ -554,8 +554,8 @@ async fn run_command(flags: Flags, script: String) -> Result<(), AnyError> {
}

let main_module = ModuleSpecifier::resolve_url_or_path(&script)?;
let global_state = GlobalState::new(flags.clone())?;
let mut worker = MainWorker::new(&global_state, main_module.clone());
let program_state = ProgramState::new(flags.clone())?;
let mut worker = MainWorker::new(&program_state, main_module.clone());
debug!("main_module {}", main_module);
worker.execute_module(&main_module).await?;
worker.execute("window.dispatchEvent(new Event('load'))")?;
Expand All @@ -572,7 +572,7 @@ async fn test_command(
allow_none: bool,
filter: Option<String>,
) -> Result<(), AnyError> {
let global_state = GlobalState::new(flags.clone())?;
let program_state = ProgramState::new(flags.clone())?;
let cwd = std::env::current_dir().expect("No current directory");
let include = include.unwrap_or_else(|| vec![".".to_string()]);
let test_modules = test_runner::prepare_test_modules_urls(include, &cwd)?;
Expand All @@ -596,7 +596,7 @@ async fn test_command(
);
let main_module =
ModuleSpecifier::resolve_url(&test_file_url.to_string()).unwrap();
let mut worker = MainWorker::new(&global_state, main_module.clone());
let mut worker = MainWorker::new(&program_state, main_module.clone());
// Create a dummy source file.
let source_file = SourceFile {
filename: test_file_url.to_file_path().unwrap(),
Expand All @@ -607,7 +607,7 @@ async fn test_command(
};
// Save our fake file into file fetcher cache
// to allow module access by TS compiler
global_state
program_state
.file_fetcher
.save_source_file_in_cache(&main_module, source_file);

Expand Down
6 changes: 3 additions & 3 deletions cli/module_graph.rs
Original file line number Diff line number Diff line change
Expand Up @@ -588,16 +588,16 @@ impl ModuleGraphLoader {
#[cfg(test)]
mod tests {
use super::*;
use crate::global_state::GlobalState;
use crate::program_state::ProgramState;
use deno_core::serde_json;
use deno_core::serde_json::json;

async fn build_graph(
module_specifier: &ModuleSpecifier,
) -> Result<ModuleGraph, AnyError> {
let global_state = GlobalState::new(Default::default()).unwrap();
let program_state = ProgramState::new(Default::default()).unwrap();
let mut graph_loader = ModuleGraphLoader::new(
global_state.file_fetcher.clone(),
program_state.file_fetcher.clone(),
None,
Permissions::allow_all(),
false,
Expand Down
2 changes: 1 addition & 1 deletion cli/module_graph2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -785,7 +785,7 @@ impl GraphBuilder2 {
/// graph.
///
/// TODO(@kitsonk) this should really be owned by the graph, but currently
/// the lockfile is behind a mutex in global_state, which makes it really
/// the lockfile is behind a mutex in program_state, which makes it really
/// hard to not pass around as a reference, which if the Graph owned it, it
/// would need lifetime parameters and lifetime parameters are 😭
pub fn get_graph(
Expand Down
18 changes: 9 additions & 9 deletions cli/state.rs → cli/module_loader.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.

use crate::global_state::GlobalState;
use crate::import_map::ImportMap;
use crate::permissions::Permissions;
use crate::program_state::ProgramState;
use crate::tsc::TargetLib;
use deno_core::error::AnyError;
use deno_core::futures::future::FutureExt;
Expand Down Expand Up @@ -51,13 +51,13 @@ impl ModuleLoader for CliModuleLoader {
referrer: &str,
is_main: bool,
) -> Result<ModuleSpecifier, AnyError> {
let global_state = {
let program_state = {
let state = op_state.borrow();
state.borrow::<Arc<GlobalState>>().clone()
state.borrow::<Arc<ProgramState>>().clone()
};

// FIXME(bartlomieju): hacky way to provide compatibility with repl
let referrer = if referrer.is_empty() && global_state.flags.repl {
let referrer = if referrer.is_empty() && program_state.flags.repl {
"<unknown>"
} else {
referrer
Expand Down Expand Up @@ -87,14 +87,14 @@ impl ModuleLoader for CliModuleLoader {
) -> Pin<Box<deno_core::ModuleSourceFuture>> {
let module_specifier = module_specifier.to_owned();
let module_url_specified = module_specifier.to_string();
let global_state = {
let program_state = {
let state = op_state.borrow();
state.borrow::<Arc<GlobalState>>().clone()
state.borrow::<Arc<ProgramState>>().clone()
};

// TODO(bartlomieju): `fetch_compiled_module` should take `load_id` param
let fut = async move {
let compiled_module = global_state
let compiled_module = program_state
.fetch_compiled_module(module_specifier, maybe_referrer)
.await?;
Ok(deno_core::ModuleSource {
Expand Down Expand Up @@ -130,7 +130,7 @@ impl ModuleLoader for CliModuleLoader {
} else {
state.borrow::<Permissions>().clone()
};
let global_state = state.borrow::<Arc<GlobalState>>().clone();
let program_state = state.borrow::<Arc<ProgramState>>().clone();
drop(state);

// TODO(bartlomieju): I'm not sure if it's correct to ignore
Expand All @@ -144,7 +144,7 @@ impl ModuleLoader for CliModuleLoader {

// TODO(bartlomieju): `prepare_module_load` should take `load_id` param
async move {
global_state
program_state
.prepare_module_load(
module_specifier,
maybe_referrer,
Expand Down
2 changes: 1 addition & 1 deletion cli/ops/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ fn op_apply_source_map(
args.line_number.into(),
args.column_number.into(),
&mut mappings_map,
&super::global_state(state).ts_compiler,
&super::program_state(state).ts_compiler,
);

Ok(json!({
Expand Down
Loading

0 comments on commit 0bd3cea

Please sign in to comment.