mirror of
https://github.com/denoland/deno.git
synced 2024-12-22 15:24:46 -05:00
refactor(cli+core): various cleanups in Rust (#8336)
This commit is contained in:
parent
a52d883921
commit
2c8439bc1e
8 changed files with 52 additions and 85 deletions
|
@ -183,10 +183,10 @@ fn get_binary_sizes(target_dir: &PathBuf) -> Result<Value> {
|
||||||
// Because cargo's OUT_DIR is not predictable, search the build tree for
|
// Because cargo's OUT_DIR is not predictable, search the build tree for
|
||||||
// snapshot related files.
|
// snapshot related files.
|
||||||
for file in walkdir::WalkDir::new(target_dir) {
|
for file in walkdir::WalkDir::new(target_dir) {
|
||||||
if file.is_err() {
|
let file = match file {
|
||||||
continue;
|
Ok(file) => file,
|
||||||
}
|
Err(_) => continue,
|
||||||
let file = file.unwrap();
|
};
|
||||||
let filename = file.file_name().to_str().unwrap().to_string();
|
let filename = file.file_name().to_str().unwrap().to_string();
|
||||||
|
|
||||||
if !BINARY_TARGET_FILES.contains(&filename.as_str()) {
|
if !BINARY_TARGET_FILES.contains(&filename.as_str()) {
|
||||||
|
|
47
cli/diff.rs
47
cli/diff.rs
|
@ -2,8 +2,6 @@
|
||||||
|
|
||||||
use crate::colors;
|
use crate::colors;
|
||||||
use dissimilar::{diff as difference, Chunk};
|
use dissimilar::{diff as difference, Chunk};
|
||||||
use std::fmt;
|
|
||||||
use std::fmt::Write;
|
|
||||||
|
|
||||||
fn fmt_add() -> String {
|
fn fmt_add() -> String {
|
||||||
colors::green_bold("+").to_string()
|
colors::green_bold("+").to_string()
|
||||||
|
@ -36,33 +34,31 @@ fn write_line_diff(
|
||||||
line_number_width: usize,
|
line_number_width: usize,
|
||||||
orig: &mut String,
|
orig: &mut String,
|
||||||
edit: &mut String,
|
edit: &mut String,
|
||||||
) -> fmt::Result {
|
) {
|
||||||
let split = orig.split('\n').enumerate();
|
let split = orig.split('\n').enumerate();
|
||||||
for (i, s) in split {
|
for (i, s) in split {
|
||||||
write!(
|
diff.push_str(&format!(
|
||||||
diff,
|
|
||||||
"{:width$}{} ",
|
"{:width$}{} ",
|
||||||
*orig_line + i,
|
*orig_line + i,
|
||||||
colors::gray(" |"),
|
colors::gray(" |"),
|
||||||
width = line_number_width
|
width = line_number_width
|
||||||
)?;
|
));
|
||||||
write!(diff, "{}", fmt_rem())?;
|
diff.push_str(&fmt_rem());
|
||||||
write!(diff, "{}", s)?;
|
diff.push_str(s);
|
||||||
writeln!(diff)?;
|
diff.push('\n');
|
||||||
}
|
}
|
||||||
|
|
||||||
let split = edit.split('\n').enumerate();
|
let split = edit.split('\n').enumerate();
|
||||||
for (i, s) in split {
|
for (i, s) in split {
|
||||||
write!(
|
diff.push_str(&format!(
|
||||||
diff,
|
|
||||||
"{:width$}{} ",
|
"{:width$}{} ",
|
||||||
*edit_line + i,
|
*edit_line + i,
|
||||||
colors::gray(" |"),
|
colors::gray(" |"),
|
||||||
width = line_number_width
|
width = line_number_width
|
||||||
)?;
|
));
|
||||||
write!(diff, "{}", fmt_add())?;
|
diff.push_str(&fmt_add());
|
||||||
write!(diff, "{}", s)?;
|
diff.push_str(s);
|
||||||
writeln!(diff)?;
|
diff.push('\n');
|
||||||
}
|
}
|
||||||
|
|
||||||
*orig_line += orig.split('\n').count();
|
*orig_line += orig.split('\n').count();
|
||||||
|
@ -70,14 +66,12 @@ fn write_line_diff(
|
||||||
|
|
||||||
orig.clear();
|
orig.clear();
|
||||||
edit.clear();
|
edit.clear();
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Print diff of the same file_path, before and after formatting.
|
/// Print diff of the same file_path, before and after formatting.
|
||||||
///
|
///
|
||||||
/// Diff format is loosely based on Github diff formatting.
|
/// Diff format is loosely based on Github diff formatting.
|
||||||
pub fn diff(orig_text: &str, edit_text: &str) -> Result<String, fmt::Error> {
|
pub fn diff(orig_text: &str, edit_text: &str) -> String {
|
||||||
let lines = edit_text.split('\n').count();
|
let lines = edit_text.split('\n').count();
|
||||||
let line_number_width = lines.to_string().chars().count();
|
let line_number_width = lines.to_string().chars().count();
|
||||||
|
|
||||||
|
@ -87,10 +81,10 @@ pub fn diff(orig_text: &str, edit_text: &str) -> Result<String, fmt::Error> {
|
||||||
let mut text2 = edit_text.to_string();
|
let mut text2 = edit_text.to_string();
|
||||||
|
|
||||||
if !text1.ends_with('\n') {
|
if !text1.ends_with('\n') {
|
||||||
writeln!(text1)?;
|
text1.push('\n');
|
||||||
}
|
}
|
||||||
if !text2.ends_with('\n') {
|
if !text2.ends_with('\n') {
|
||||||
writeln!(text2)?;
|
text2.push('\n');
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut orig_line: usize = 1;
|
let mut orig_line: usize = 1;
|
||||||
|
@ -134,7 +128,7 @@ pub fn diff(orig_text: &str, edit_text: &str) -> Result<String, fmt::Error> {
|
||||||
line_number_width,
|
line_number_width,
|
||||||
&mut orig,
|
&mut orig,
|
||||||
&mut edit,
|
&mut edit,
|
||||||
)?;
|
);
|
||||||
changes = false
|
changes = false
|
||||||
} else {
|
} else {
|
||||||
orig.clear();
|
orig.clear();
|
||||||
|
@ -149,7 +143,7 @@ pub fn diff(orig_text: &str, edit_text: &str) -> Result<String, fmt::Error> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok(diff)
|
diff
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
@ -157,16 +151,17 @@ fn test_diff() {
|
||||||
let simple_console_log_unfmt = "console.log('Hello World')";
|
let simple_console_log_unfmt = "console.log('Hello World')";
|
||||||
let simple_console_log_fmt = "console.log(\"Hello World\");";
|
let simple_console_log_fmt = "console.log(\"Hello World\");";
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
colors::strip_ansi_codes(
|
colors::strip_ansi_codes(&diff(
|
||||||
&diff(simple_console_log_unfmt, simple_console_log_fmt).unwrap()
|
simple_console_log_unfmt,
|
||||||
),
|
simple_console_log_fmt
|
||||||
|
)),
|
||||||
"1 | -console.log('Hello World')\n1 | +console.log(\"Hello World\");\n"
|
"1 | -console.log('Hello World')\n1 | +console.log(\"Hello World\");\n"
|
||||||
);
|
);
|
||||||
|
|
||||||
let line_number_unfmt = "\n\n\n\nconsole.log(\n'Hello World'\n)";
|
let line_number_unfmt = "\n\n\n\nconsole.log(\n'Hello World'\n)";
|
||||||
let line_number_fmt = "console.log(\n\"Hello World\"\n);";
|
let line_number_fmt = "console.log(\n\"Hello World\"\n);";
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
colors::strip_ansi_codes(&diff(line_number_unfmt, line_number_fmt).unwrap()),
|
colors::strip_ansi_codes(&diff(line_number_unfmt, line_number_fmt)),
|
||||||
"1 | -\n2 | -\n3 | -\n4 | -\n5 | -console.log(\n1 | +console.log(\n6 | -'Hello World'\n2 | +\"Hello World\"\n7 | -)\n3 | +);\n"
|
"1 | -\n2 | -\n3 | -\n4 | -\n5 | -console.log(\n1 | +console.log(\n6 | -'Hello World'\n2 | +\"Hello World\"\n7 | -)\n3 | +);\n"
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
|
@ -55,11 +55,7 @@ struct FileCache(Arc<Mutex<HashMap<ModuleSpecifier, File>>>);
|
||||||
impl FileCache {
|
impl FileCache {
|
||||||
pub fn get(&self, specifier: &ModuleSpecifier) -> Option<File> {
|
pub fn get(&self, specifier: &ModuleSpecifier) -> Option<File> {
|
||||||
let cache = self.0.lock().unwrap();
|
let cache = self.0.lock().unwrap();
|
||||||
if let Some(file) = cache.get(specifier) {
|
cache.get(specifier).cloned()
|
||||||
Some(file.clone())
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn insert(&self, specifier: ModuleSpecifier, file: File) -> Option<File> {
|
pub fn insert(&self, specifier: ModuleSpecifier, file: File) -> Option<File> {
|
||||||
|
@ -259,19 +255,17 @@ fn map_js_like_extension(
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Remove shebangs from the start of source code strings
|
/// Remove shebangs from the start of source code strings
|
||||||
fn strip_shebang(value: String) -> String {
|
fn strip_shebang(mut value: String) -> String {
|
||||||
if value.starts_with("#!") {
|
if value.starts_with("#!") {
|
||||||
let value = if let Some(mid) = value.find('\n') {
|
if let Some(mid) = value.find('\n') {
|
||||||
let (_, rest) = value.split_at(mid);
|
let (_, rest) = value.split_at(mid);
|
||||||
rest.to_string()
|
value = rest.to_string()
|
||||||
} else {
|
} else {
|
||||||
"".to_string()
|
value.clear()
|
||||||
};
|
|
||||||
value
|
|
||||||
} else {
|
|
||||||
value
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
value
|
||||||
|
}
|
||||||
|
|
||||||
/// A structure for resolving, fetching and caching source files.
|
/// A structure for resolving, fetching and caching source files.
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
|
|
16
cli/flags.rs
16
cli/flags.rs
|
@ -9,6 +9,7 @@ use clap::SubCommand;
|
||||||
use log::Level;
|
use log::Level;
|
||||||
use std::net::SocketAddr;
|
use std::net::SocketAddr;
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
|
use std::str::FromStr;
|
||||||
|
|
||||||
/// Creates vector of strings, Vec<String>
|
/// Creates vector of strings, Vec<String>
|
||||||
macro_rules! svec {
|
macro_rules! svec {
|
||||||
|
@ -425,7 +426,6 @@ fn bundle_parse(flags: &mut Flags, matches: &clap::ArgMatches) {
|
||||||
fn completions_parse(flags: &mut Flags, matches: &clap::ArgMatches) {
|
fn completions_parse(flags: &mut Flags, matches: &clap::ArgMatches) {
|
||||||
let shell: &str = matches.value_of("shell").unwrap();
|
let shell: &str = matches.value_of("shell").unwrap();
|
||||||
let mut buf: Vec<u8> = vec![];
|
let mut buf: Vec<u8> = vec![];
|
||||||
use std::str::FromStr;
|
|
||||||
clap_root().gen_completions_to(
|
clap_root().gen_completions_to(
|
||||||
"deno",
|
"deno",
|
||||||
clap::Shell::from_str(shell).unwrap(),
|
clap::Shell::from_str(shell).unwrap(),
|
||||||
|
@ -1324,7 +1324,7 @@ fn reload_arg<'a, 'b>() -> Arg<'a, 'b> {
|
||||||
fn reload_arg_parse(flags: &mut Flags, matches: &ArgMatches) {
|
fn reload_arg_parse(flags: &mut Flags, matches: &ArgMatches) {
|
||||||
if let Some(cache_bl) = matches.values_of("reload") {
|
if let Some(cache_bl) = matches.values_of("reload") {
|
||||||
let raw_cache_blocklist: Vec<String> =
|
let raw_cache_blocklist: Vec<String> =
|
||||||
cache_bl.map(std::string::ToString::to_string).collect();
|
cache_bl.map(ToString::to_string).collect();
|
||||||
if raw_cache_blocklist.is_empty() {
|
if raw_cache_blocklist.is_empty() {
|
||||||
flags.reload = true;
|
flags.reload = true;
|
||||||
} else {
|
} else {
|
||||||
|
@ -1475,7 +1475,7 @@ fn permission_args_parse(flags: &mut Flags, matches: &clap::ArgMatches) {
|
||||||
|
|
||||||
if let Some(net_wl) = matches.values_of("allow-net") {
|
if let Some(net_wl) = matches.values_of("allow-net") {
|
||||||
let raw_net_allowlist: Vec<String> =
|
let raw_net_allowlist: Vec<String> =
|
||||||
net_wl.map(std::string::ToString::to_string).collect();
|
net_wl.map(ToString::to_string).collect();
|
||||||
if raw_net_allowlist.is_empty() {
|
if raw_net_allowlist.is_empty() {
|
||||||
flags.allow_net = true;
|
flags.allow_net = true;
|
||||||
} else {
|
} else {
|
||||||
|
@ -1515,18 +1515,16 @@ pub fn resolve_urls(urls: Vec<String>) -> Vec<String> {
|
||||||
use deno_core::url::Url;
|
use deno_core::url::Url;
|
||||||
let mut out: Vec<String> = vec![];
|
let mut out: Vec<String> = vec![];
|
||||||
for urlstr in urls.iter() {
|
for urlstr in urls.iter() {
|
||||||
use std::str::FromStr;
|
if let Ok(mut url) = Url::from_str(urlstr) {
|
||||||
let result = Url::from_str(urlstr);
|
|
||||||
if result.is_err() {
|
|
||||||
panic!("Bad Url: {}", urlstr);
|
|
||||||
}
|
|
||||||
let mut url = result.unwrap();
|
|
||||||
url.set_fragment(None);
|
url.set_fragment(None);
|
||||||
let mut full_url = String::from(url.as_str());
|
let mut full_url = String::from(url.as_str());
|
||||||
if full_url.len() > 1 && full_url.ends_with('/') {
|
if full_url.len() > 1 && full_url.ends_with('/') {
|
||||||
full_url.pop();
|
full_url.pop();
|
||||||
}
|
}
|
||||||
out.push(full_url);
|
out.push(full_url);
|
||||||
|
} else {
|
||||||
|
panic!("Bad Url: {}", urlstr);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
out
|
out
|
||||||
}
|
}
|
||||||
|
|
18
cli/fmt.rs
18
cli/fmt.rs
|
@ -71,25 +71,11 @@ async fn check_source_files(
|
||||||
if formatted_text != file_text {
|
if formatted_text != file_text {
|
||||||
not_formatted_files_count.fetch_add(1, Ordering::Relaxed);
|
not_formatted_files_count.fetch_add(1, Ordering::Relaxed);
|
||||||
let _g = output_lock.lock().unwrap();
|
let _g = output_lock.lock().unwrap();
|
||||||
match diff(&file_text, &formatted_text) {
|
let diff = diff(&file_text, &formatted_text);
|
||||||
Ok(diff) => {
|
|
||||||
info!("");
|
info!("");
|
||||||
info!(
|
info!("{} {}:", colors::bold("from"), file_path.display());
|
||||||
"{} {}:",
|
|
||||||
colors::bold("from"),
|
|
||||||
file_path.display().to_string()
|
|
||||||
);
|
|
||||||
info!("{}", diff);
|
info!("{}", diff);
|
||||||
}
|
}
|
||||||
Err(e) => {
|
|
||||||
eprintln!(
|
|
||||||
"Error generating diff: {}",
|
|
||||||
file_path.to_string_lossy()
|
|
||||||
);
|
|
||||||
eprintln!(" {}", e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
let _g = output_lock.lock().unwrap();
|
let _g = output_lock.lock().unwrap();
|
||||||
|
|
|
@ -1586,8 +1586,7 @@ pub mod tests {
|
||||||
assert_eq!(bufs.len(), 1);
|
assert_eq!(bufs.len(), 1);
|
||||||
assert_eq!(bufs[0].len(), 1);
|
assert_eq!(bufs[0].len(), 1);
|
||||||
assert_eq!(bufs[0][0], 42);
|
assert_eq!(bufs[0][0], 42);
|
||||||
let mut vec = Vec::<u8>::new();
|
let mut vec = vec![0u8; 100 * 1024 * 1024];
|
||||||
vec.resize(100 * 1024 * 1024, 0);
|
|
||||||
vec[0] = 99;
|
vec[0] = 99;
|
||||||
let buf = vec.into_boxed_slice();
|
let buf = vec.into_boxed_slice();
|
||||||
Op::Sync(buf)
|
Op::Sync(buf)
|
||||||
|
@ -1602,8 +1601,7 @@ pub mod tests {
|
||||||
assert_eq!(bufs.len(), 1);
|
assert_eq!(bufs.len(), 1);
|
||||||
assert_eq!(bufs[0].len(), 1);
|
assert_eq!(bufs[0].len(), 1);
|
||||||
assert_eq!(bufs[0][0], 42);
|
assert_eq!(bufs[0][0], 42);
|
||||||
let mut vec = Vec::<u8>::new();
|
let mut vec = vec![0u8; 100 * 1024 * 1024];
|
||||||
vec.resize(100 * 1024 * 1024, 0);
|
|
||||||
vec[0] = 4;
|
vec[0] = 4;
|
||||||
let buf = vec.into_boxed_slice();
|
let buf = vec.into_boxed_slice();
|
||||||
Op::Async(futures::future::ready(buf).boxed())
|
Op::Async(futures::future::ready(buf).boxed())
|
||||||
|
|
|
@ -42,9 +42,7 @@ pub struct SharedQueue {
|
||||||
|
|
||||||
impl SharedQueue {
|
impl SharedQueue {
|
||||||
pub fn new(len: usize) -> Self {
|
pub fn new(len: usize) -> Self {
|
||||||
let mut buf = Vec::new();
|
let buf = vec![0; HEAD_INIT + len].into_boxed_slice();
|
||||||
buf.resize(HEAD_INIT + len, 0);
|
|
||||||
let buf = buf.into_boxed_slice();
|
|
||||||
let buf = v8::SharedArrayBuffer::new_backing_store_from_boxed_slice(buf);
|
let buf = v8::SharedArrayBuffer::new_backing_store_from_boxed_slice(buf);
|
||||||
let mut q = Self {
|
let mut q = Self {
|
||||||
buf: buf.make_shared(),
|
buf: buf.make_shared(),
|
||||||
|
@ -263,9 +261,7 @@ mod tests {
|
||||||
}
|
}
|
||||||
|
|
||||||
fn alloc_buf(byte_length: usize) -> Box<[u8]> {
|
fn alloc_buf(byte_length: usize) -> Box<[u8]> {
|
||||||
let mut v = Vec::new();
|
vec![0; byte_length].into_boxed_slice()
|
||||||
v.resize(byte_length, 0);
|
|
||||||
v.into_boxed_slice()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|
|
@ -286,7 +286,7 @@ pub async fn run_all_servers() {
|
||||||
Box::new(res)
|
Box::new(res)
|
||||||
});
|
});
|
||||||
let bad_redirect = warp::path("bad_redirect").map(|| -> Box<dyn Reply> {
|
let bad_redirect = warp::path("bad_redirect").map(|| -> Box<dyn Reply> {
|
||||||
let mut res = Response::new(Body::from(""));
|
let mut res = Response::new(Body::empty());
|
||||||
*res.status_mut() = StatusCode::FOUND;
|
*res.status_mut() = StatusCode::FOUND;
|
||||||
Box::new(res)
|
Box::new(res)
|
||||||
});
|
});
|
||||||
|
|
Loading…
Reference in a new issue