mirror of
https://github.com/denoland/deno.git
synced 2024-12-21 23:04:45 -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
|
||||
// snapshot related files.
|
||||
for file in walkdir::WalkDir::new(target_dir) {
|
||||
if file.is_err() {
|
||||
continue;
|
||||
}
|
||||
let file = file.unwrap();
|
||||
let file = match file {
|
||||
Ok(file) => file,
|
||||
Err(_) => continue,
|
||||
};
|
||||
let filename = file.file_name().to_str().unwrap().to_string();
|
||||
|
||||
if !BINARY_TARGET_FILES.contains(&filename.as_str()) {
|
||||
|
|
47
cli/diff.rs
47
cli/diff.rs
|
@ -2,8 +2,6 @@
|
|||
|
||||
use crate::colors;
|
||||
use dissimilar::{diff as difference, Chunk};
|
||||
use std::fmt;
|
||||
use std::fmt::Write;
|
||||
|
||||
fn fmt_add() -> String {
|
||||
colors::green_bold("+").to_string()
|
||||
|
@ -36,33 +34,31 @@ fn write_line_diff(
|
|||
line_number_width: usize,
|
||||
orig: &mut String,
|
||||
edit: &mut String,
|
||||
) -> fmt::Result {
|
||||
) {
|
||||
let split = orig.split('\n').enumerate();
|
||||
for (i, s) in split {
|
||||
write!(
|
||||
diff,
|
||||
diff.push_str(&format!(
|
||||
"{:width$}{} ",
|
||||
*orig_line + i,
|
||||
colors::gray(" |"),
|
||||
width = line_number_width
|
||||
)?;
|
||||
write!(diff, "{}", fmt_rem())?;
|
||||
write!(diff, "{}", s)?;
|
||||
writeln!(diff)?;
|
||||
));
|
||||
diff.push_str(&fmt_rem());
|
||||
diff.push_str(s);
|
||||
diff.push('\n');
|
||||
}
|
||||
|
||||
let split = edit.split('\n').enumerate();
|
||||
for (i, s) in split {
|
||||
write!(
|
||||
diff,
|
||||
diff.push_str(&format!(
|
||||
"{:width$}{} ",
|
||||
*edit_line + i,
|
||||
colors::gray(" |"),
|
||||
width = line_number_width
|
||||
)?;
|
||||
write!(diff, "{}", fmt_add())?;
|
||||
write!(diff, "{}", s)?;
|
||||
writeln!(diff)?;
|
||||
));
|
||||
diff.push_str(&fmt_add());
|
||||
diff.push_str(s);
|
||||
diff.push('\n');
|
||||
}
|
||||
|
||||
*orig_line += orig.split('\n').count();
|
||||
|
@ -70,14 +66,12 @@ fn write_line_diff(
|
|||
|
||||
orig.clear();
|
||||
edit.clear();
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Print diff of the same file_path, before and after 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 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();
|
||||
|
||||
if !text1.ends_with('\n') {
|
||||
writeln!(text1)?;
|
||||
text1.push('\n');
|
||||
}
|
||||
if !text2.ends_with('\n') {
|
||||
writeln!(text2)?;
|
||||
text2.push('\n');
|
||||
}
|
||||
|
||||
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,
|
||||
&mut orig,
|
||||
&mut edit,
|
||||
)?;
|
||||
);
|
||||
changes = false
|
||||
} else {
|
||||
orig.clear();
|
||||
|
@ -149,7 +143,7 @@ pub fn diff(orig_text: &str, edit_text: &str) -> Result<String, fmt::Error> {
|
|||
}
|
||||
}
|
||||
}
|
||||
Ok(diff)
|
||||
diff
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
@ -157,16 +151,17 @@ fn test_diff() {
|
|||
let simple_console_log_unfmt = "console.log('Hello World')";
|
||||
let simple_console_log_fmt = "console.log(\"Hello World\");";
|
||||
assert_eq!(
|
||||
colors::strip_ansi_codes(
|
||||
&diff(simple_console_log_unfmt, simple_console_log_fmt).unwrap()
|
||||
),
|
||||
colors::strip_ansi_codes(&diff(
|
||||
simple_console_log_unfmt,
|
||||
simple_console_log_fmt
|
||||
)),
|
||||
"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_fmt = "console.log(\n\"Hello World\"\n);";
|
||||
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"
|
||||
)
|
||||
}
|
||||
|
|
|
@ -55,11 +55,7 @@ struct FileCache(Arc<Mutex<HashMap<ModuleSpecifier, File>>>);
|
|||
impl FileCache {
|
||||
pub fn get(&self, specifier: &ModuleSpecifier) -> Option<File> {
|
||||
let cache = self.0.lock().unwrap();
|
||||
if let Some(file) = cache.get(specifier) {
|
||||
Some(file.clone())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
cache.get(specifier).cloned()
|
||||
}
|
||||
|
||||
pub fn insert(&self, specifier: ModuleSpecifier, file: File) -> Option<File> {
|
||||
|
@ -259,18 +255,16 @@ fn map_js_like_extension(
|
|||
}
|
||||
|
||||
/// 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("#!") {
|
||||
let value = if let Some(mid) = value.find('\n') {
|
||||
if let Some(mid) = value.find('\n') {
|
||||
let (_, rest) = value.split_at(mid);
|
||||
rest.to_string()
|
||||
value = rest.to_string()
|
||||
} else {
|
||||
"".to_string()
|
||||
};
|
||||
value
|
||||
} else {
|
||||
value
|
||||
value.clear()
|
||||
}
|
||||
}
|
||||
value
|
||||
}
|
||||
|
||||
/// A structure for resolving, fetching and caching source files.
|
||||
|
|
24
cli/flags.rs
24
cli/flags.rs
|
@ -9,6 +9,7 @@ use clap::SubCommand;
|
|||
use log::Level;
|
||||
use std::net::SocketAddr;
|
||||
use std::path::PathBuf;
|
||||
use std::str::FromStr;
|
||||
|
||||
/// Creates vector of strings, Vec<String>
|
||||
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) {
|
||||
let shell: &str = matches.value_of("shell").unwrap();
|
||||
let mut buf: Vec<u8> = vec![];
|
||||
use std::str::FromStr;
|
||||
clap_root().gen_completions_to(
|
||||
"deno",
|
||||
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) {
|
||||
if let Some(cache_bl) = matches.values_of("reload") {
|
||||
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() {
|
||||
flags.reload = true;
|
||||
} 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") {
|
||||
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() {
|
||||
flags.allow_net = true;
|
||||
} else {
|
||||
|
@ -1515,18 +1515,16 @@ pub fn resolve_urls(urls: Vec<String>) -> Vec<String> {
|
|||
use deno_core::url::Url;
|
||||
let mut out: Vec<String> = vec![];
|
||||
for urlstr in urls.iter() {
|
||||
use std::str::FromStr;
|
||||
let result = Url::from_str(urlstr);
|
||||
if result.is_err() {
|
||||
if let Ok(mut url) = Url::from_str(urlstr) {
|
||||
url.set_fragment(None);
|
||||
let mut full_url = String::from(url.as_str());
|
||||
if full_url.len() > 1 && full_url.ends_with('/') {
|
||||
full_url.pop();
|
||||
}
|
||||
out.push(full_url);
|
||||
} else {
|
||||
panic!("Bad Url: {}", urlstr);
|
||||
}
|
||||
let mut url = result.unwrap();
|
||||
url.set_fragment(None);
|
||||
let mut full_url = String::from(url.as_str());
|
||||
if full_url.len() > 1 && full_url.ends_with('/') {
|
||||
full_url.pop();
|
||||
}
|
||||
out.push(full_url);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
|
22
cli/fmt.rs
22
cli/fmt.rs
|
@ -71,24 +71,10 @@ async fn check_source_files(
|
|||
if formatted_text != file_text {
|
||||
not_formatted_files_count.fetch_add(1, Ordering::Relaxed);
|
||||
let _g = output_lock.lock().unwrap();
|
||||
match diff(&file_text, &formatted_text) {
|
||||
Ok(diff) => {
|
||||
info!("");
|
||||
info!(
|
||||
"{} {}:",
|
||||
colors::bold("from"),
|
||||
file_path.display().to_string()
|
||||
);
|
||||
info!("{}", diff);
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!(
|
||||
"Error generating diff: {}",
|
||||
file_path.to_string_lossy()
|
||||
);
|
||||
eprintln!(" {}", e);
|
||||
}
|
||||
}
|
||||
let diff = diff(&file_text, &formatted_text);
|
||||
info!("");
|
||||
info!("{} {}:", colors::bold("from"), file_path.display());
|
||||
info!("{}", diff);
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
|
|
|
@ -1586,8 +1586,7 @@ pub mod tests {
|
|||
assert_eq!(bufs.len(), 1);
|
||||
assert_eq!(bufs[0].len(), 1);
|
||||
assert_eq!(bufs[0][0], 42);
|
||||
let mut vec = Vec::<u8>::new();
|
||||
vec.resize(100 * 1024 * 1024, 0);
|
||||
let mut vec = vec![0u8; 100 * 1024 * 1024];
|
||||
vec[0] = 99;
|
||||
let buf = vec.into_boxed_slice();
|
||||
Op::Sync(buf)
|
||||
|
@ -1602,8 +1601,7 @@ pub mod tests {
|
|||
assert_eq!(bufs.len(), 1);
|
||||
assert_eq!(bufs[0].len(), 1);
|
||||
assert_eq!(bufs[0][0], 42);
|
||||
let mut vec = Vec::<u8>::new();
|
||||
vec.resize(100 * 1024 * 1024, 0);
|
||||
let mut vec = vec![0u8; 100 * 1024 * 1024];
|
||||
vec[0] = 4;
|
||||
let buf = vec.into_boxed_slice();
|
||||
Op::Async(futures::future::ready(buf).boxed())
|
||||
|
|
|
@ -42,9 +42,7 @@ pub struct SharedQueue {
|
|||
|
||||
impl SharedQueue {
|
||||
pub fn new(len: usize) -> Self {
|
||||
let mut buf = Vec::new();
|
||||
buf.resize(HEAD_INIT + len, 0);
|
||||
let buf = buf.into_boxed_slice();
|
||||
let buf = vec![0; HEAD_INIT + len].into_boxed_slice();
|
||||
let buf = v8::SharedArrayBuffer::new_backing_store_from_boxed_slice(buf);
|
||||
let mut q = Self {
|
||||
buf: buf.make_shared(),
|
||||
|
@ -263,9 +261,7 @@ mod tests {
|
|||
}
|
||||
|
||||
fn alloc_buf(byte_length: usize) -> Box<[u8]> {
|
||||
let mut v = Vec::new();
|
||||
v.resize(byte_length, 0);
|
||||
v.into_boxed_slice()
|
||||
vec![0; byte_length].into_boxed_slice()
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
|
@ -286,7 +286,7 @@ pub async fn run_all_servers() {
|
|||
Box::new(res)
|
||||
});
|
||||
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;
|
||||
Box::new(res)
|
||||
});
|
||||
|
|
Loading…
Reference in a new issue