forked from denoland/deno
-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.rs
333 lines (297 loc) · 8.12 KB
/
main.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
#[macro_use]
extern crate futures;
#[macro_use]
extern crate serde_json;
extern crate clap;
extern crate deno;
mod ansi;
pub mod compiler;
pub mod deno_dir;
pub mod errors;
pub mod flags;
mod fs;
mod global_timer;
mod http_body;
mod http_util;
pub mod js_errors;
pub mod msg;
pub mod msg_util;
pub mod ops;
pub mod permissions;
mod repl;
pub mod resolve_addr;
pub mod resources;
mod startup_data;
pub mod state;
mod tokio_util;
mod tokio_write;
pub mod version;
pub mod worker;
use crate::errors::RustOrJsError;
use crate::state::ThreadSafeState;
use crate::worker::root_specifier_to_url;
use crate::worker::Worker;
use deno::v8_set_flags;
use flags::DenoFlags;
use futures::lazy;
use futures::Future;
use log::{LevelFilter, Metadata, Record};
use std::env;
use std::path::Path;
static LOGGER: Logger = Logger;
struct Logger;
impl log::Log for Logger {
fn enabled(&self, metadata: &Metadata) -> bool {
metadata.level() <= log::max_level()
}
fn log(&self, record: &Record) {
if self.enabled(record.metadata()) {
println!("{} RS - {}", record.level(), record.args());
}
}
fn flush(&self) {}
}
fn print_err_and_exit(err: RustOrJsError) {
eprintln!("{}", err.to_string());
std::process::exit(1);
}
fn js_check<E>(r: Result<(), E>)
where
E: Into<RustOrJsError>,
{
if let Err(err) = r {
print_err_and_exit(err.into());
}
}
// TODO(ry) Move this to main.rs
pub fn print_file_info(worker: &Worker, url: &str) {
let maybe_out =
worker::fetch_module_meta_data_and_maybe_compile(&worker.state, url, ".");
if let Err(err) = maybe_out {
println!("{}", err);
return;
}
let out = maybe_out.unwrap();
println!("{} {}", ansi::bold("local:".to_string()), &(out.filename));
println!(
"{} {}",
ansi::bold("type:".to_string()),
msg::enum_name_media_type(out.media_type)
);
if out.maybe_output_code_filename.is_some() {
println!(
"{} {}",
ansi::bold("compiled:".to_string()),
out.maybe_output_code_filename.as_ref().unwrap(),
);
}
if out.maybe_source_map_filename.is_some() {
println!(
"{} {}",
ansi::bold("map:".to_string()),
out.maybe_source_map_filename.as_ref().unwrap()
);
}
if let Some(deps) = worker.modules.deps(&out.module_name) {
println!("{}{}", ansi::bold("deps:\n".to_string()), deps.name);
if let Some(ref depsdeps) = deps.deps {
for d in depsdeps {
println!("{}", d);
}
}
} else {
println!(
"{} cannot retrieve full dependency graph",
ansi::bold("deps:".to_string()),
);
}
}
fn create_worker_and_state(
flags: DenoFlags,
argv: Vec<String>,
) -> (Worker, ThreadSafeState) {
let state = ThreadSafeState::new(flags, argv, ops::op_selector_std);
let worker = Worker::new(
"main".to_string(),
startup_data::deno_isolate_init(),
state.clone(),
);
(worker, state)
}
fn types_command() {
let p = Path::new(concat!(
env!("GN_OUT_DIR"),
"/gen/cli/lib/lib.deno_runtime.d.ts"
));
let content_bytes = std::fs::read(p).unwrap();
let content = std::str::from_utf8(&content_bytes[..]).unwrap();
println!("{}", content);
}
fn prefetch_or_info_command(
flags: DenoFlags,
argv: Vec<String>,
print_info: bool,
) {
let (mut worker, state) = create_worker_and_state(flags, argv);
let main_module = state.main_module().unwrap();
let main_future = lazy(move || {
// Setup runtime.
js_check(worker.execute("denoMain()"));
debug!("main_module {}", main_module);
let main_url = root_specifier_to_url(&main_module).unwrap();
worker
.execute_mod_async(&main_url, true)
.and_then(move |worker| {
if print_info {
print_file_info(&worker, &main_module);
}
worker.then(|result| {
js_check(result);
Ok(())
})
}).map_err(|(err, _worker)| print_err_and_exit(err))
});
tokio_util::run(main_future);
}
fn eval_command(flags: DenoFlags, argv: Vec<String>) {
let (mut worker, state) = create_worker_and_state(flags, argv);
// Wrap provided script in async function so asynchronous methods
// work. This is required until top-level await is not supported.
let js_source = format!(
"async function _topLevelWrapper(){{
{}
}}
_topLevelWrapper();
",
&state.argv[1]
);
let main_future = lazy(move || {
js_check(worker.execute("denoMain()"));
// ATM imports in `deno eval` are not allowed
// TODO Support ES modules once Worker supports evaluating anonymous modules.
js_check(worker.execute(&js_source));
worker.then(|result| {
js_check(result);
Ok(())
})
});
tokio_util::run(main_future);
}
fn run_repl(flags: DenoFlags, argv: Vec<String>) {
let (mut worker, _state) = create_worker_and_state(flags, argv);
// REPL situation.
let main_future = lazy(move || {
// Setup runtime.
js_check(worker.execute("denoMain()"));
worker
.then(|result| {
js_check(result);
Ok(())
}).map_err(|(err, _worker): (RustOrJsError, Worker)| {
print_err_and_exit(err)
})
});
tokio_util::run(main_future);
}
fn run_script(flags: DenoFlags, argv: Vec<String>) {
let (mut worker, state) = create_worker_and_state(flags, argv);
let main_module = state.main_module().unwrap();
// Normal situation of executing a module.
let main_future = lazy(move || {
// Setup runtime.
js_check(worker.execute("denoMain()"));
debug!("main_module {}", main_module);
let main_url = root_specifier_to_url(&main_module).unwrap();
worker
.execute_mod_async(&main_url, false)
.and_then(move |worker| {
worker.then(|result| {
js_check(result);
Ok(())
})
}).map_err(|(err, _worker)| print_err_and_exit(err))
});
tokio_util::run(main_future);
}
fn fmt_command(mut flags: DenoFlags, mut argv: Vec<String>) {
argv.insert(1, "https://deno.land/std/prettier/main.ts".to_string());
flags.allow_read = true;
flags.allow_write = true;
run_script(flags, argv);
}
fn main() {
#[cfg(windows)]
ansi_term::enable_ansi_support().ok(); // For Windows 10
log::set_logger(&LOGGER).unwrap();
let args: Vec<String> = env::args().collect();
let cli_app = flags::create_cli_app();
let matches = cli_app.get_matches_from(args);
let flags = flags::parse_flags(matches.clone());
let mut argv: Vec<String> = vec!["deno".to_string()];
if flags.v8_help {
// show v8 help and exit
v8_set_flags(vec!["--help".to_string()]);
}
match &flags.v8_flags {
Some(v8_flags) => {
v8_set_flags(v8_flags.clone());
}
_ => {}
};
log::set_max_level(if flags.log_debug {
LevelFilter::Debug
} else {
LevelFilter::Warn
});
match matches.subcommand() {
("types", Some(_)) => {
types_command();
}
("eval", Some(eval_match)) => {
let code: &str = eval_match.value_of("code").unwrap();
argv.extend(vec![code.to_string()]);
eval_command(flags, argv);
}
("info", Some(info_match)) => {
let file: &str = info_match.value_of("file").unwrap();
argv.extend(vec![file.to_string()]);
prefetch_or_info_command(flags, argv, true);
}
("prefetch", Some(prefetch_match)) => {
let file: &str = prefetch_match.value_of("file").unwrap();
argv.extend(vec![file.to_string()]);
prefetch_or_info_command(flags, argv, false);
}
("fmt", Some(fmt_match)) => {
let files: Vec<String> = fmt_match
.values_of("files")
.unwrap()
.map(String::from)
.collect();
argv.extend(files);
fmt_command(flags, argv);
}
(script, Some(script_match)) => {
argv.extend(vec![script.to_string()]);
// check if there are any extra arguments that should
// be passed to script
if script_match.is_present("") {
let script_args: Vec<String> = script_match
.values_of("")
.unwrap()
.map(String::from)
.collect();
argv.extend(script_args);
}
run_script(flags, argv);
}
_ => {
run_repl(flags, argv);
}
}
}