Skip to content

Commit

Permalink
--stdin to single -
Browse files Browse the repository at this point in the history
  • Loading branch information
kevinkassimo committed Feb 9, 2020
1 parent 53ea7cd commit d55a5b9
Show file tree
Hide file tree
Showing 4 changed files with 50 additions and 29 deletions.
17 changes: 3 additions & 14 deletions cli/flags.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@ pub enum DenoSubcommand {
},
Format {
check: bool,
stdin: bool,
files: Option<Vec<String>>,
},
Help,
Expand Down Expand Up @@ -304,11 +303,9 @@ fn fmt_parse(flags: &mut DenoFlags, matches: &clap::ArgMatches) {
};

let check = matches.is_present("check");
let stdin = matches.is_present("stdin");

flags.subcommand = DenoSubcommand::Format {
check,
stdin,
files: maybe_files,
}
}
Expand Down Expand Up @@ -552,20 +549,15 @@ fn fmt_subcommand<'a, 'b>() -> App<'a, 'b> {
deno fmt --check
cat file.ts | deno fmt --stdin",
# Format stdin and write to stdout
cat file.ts | deno fmt -",
)
.arg(
Arg::with_name("check")
.long("check")
.help("Check if the source files are formatted.")
.takes_value(false),
)
.arg(
Arg::with_name("stdin")
.long("stdin")
.help("Read from stdin and write formatted code to stdout.")
.takes_value(false),
)
.arg(
Arg::with_name("files")
.takes_value(true)
Expand Down Expand Up @@ -1375,7 +1367,6 @@ mod tests {
DenoFlags {
subcommand: DenoSubcommand::Format {
check: false,
stdin: false,
files: Some(svec!["script_1.ts", "script_2.ts"])
},
..DenoFlags::default()
Expand All @@ -1388,20 +1379,18 @@ mod tests {
DenoFlags {
subcommand: DenoSubcommand::Format {
check: true,
stdin: false,
files: None
},
..DenoFlags::default()
}
);

let r = flags_from_vec_safe(svec!["deno", "fmt", "--stdin"]);
let r = flags_from_vec_safe(svec!["deno", "fmt"]);
assert_eq!(
r.unwrap(),
DenoFlags {
subcommand: DenoSubcommand::Format {
check: false,
stdin: true,
files: None
},
..DenoFlags::default()
Expand Down
32 changes: 30 additions & 2 deletions cli/fmt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@
//! the future it can be easily extended to provide
//! the same functions as ops available in JS runtime.
use crate::deno_error::DenoError;
use crate::deno_error::ErrorKind;
use deno_core::ErrBox;
use dprint_plugin_typescript as dprint;
use glob;
use regex::Regex;
Expand Down Expand Up @@ -161,9 +164,29 @@ fn get_matching_files(glob_paths: Vec<String>) -> Vec<PathBuf> {
///
/// First argument supports globs, and if it is `None`
/// then the current directory is recursively walked.
pub fn format_files(maybe_files: Option<Vec<String>>, check: bool) {
pub fn format_files(
maybe_files: Option<Vec<String>>,
check: bool,
) -> Result<(), ErrBox> {
// TODO: improve glob to look for tsx?/jsx? files only
let glob_paths = maybe_files.unwrap_or_else(|| vec!["**/*".to_string()]);

for glob_path in glob_paths.iter() {
if glob_path == "-" {
// If the only given path is '-', format stdin.
if glob_paths.len() == 1 {
format_stdin(check);
} else {
// Otherwise it is an error
return Err(ErrBox::from(DenoError::new(
ErrorKind::Other,
"Ambiguous filename input. To format stdin, provide a single '-' instead.".to_owned()
)));
}
return Ok(());
}
}

let matching_files = get_matching_files(glob_paths);
let matching_files = get_supported_files(matching_files);
let config = get_config();
Expand All @@ -173,9 +196,14 @@ pub fn format_files(maybe_files: Option<Vec<String>>, check: bool) {
} else {
format_source_files(config, matching_files);
}

Ok(())
}

pub fn format_stdin(check: bool) {
/// Format stdin and write result to stdout.
/// Treats input as TypeScript.
/// Compatible with `--check` flag.
fn format_stdin(check: bool) {
let mut source = String::new();
if stdin().read_to_string(&mut source).is_err() {
eprintln!("Failed to read from stdin");
Expand Down
16 changes: 6 additions & 10 deletions cli/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -403,11 +403,9 @@ async fn run_script(flags: DenoFlags, script: String) {
js_check(worker.execute("window.dispatchEvent(new Event('unload'))"));
}

async fn fmt_command(files: Option<Vec<String>>, check: bool, stdin: bool) {
if stdin {
fmt::format_stdin(check);
} else {
fmt::format_files(files, check);
async fn fmt_command(files: Option<Vec<String>>, check: bool) {
if let Err(err) = fmt::format_files(files, check) {
print_err_and_exit(err);
}
}

Expand Down Expand Up @@ -442,11 +440,9 @@ pub fn main() {
}
DenoSubcommand::Eval { code } => eval_command(flags, code).await,
DenoSubcommand::Fetch { files } => fetch_command(flags, files).await,
DenoSubcommand::Format {
check,
stdin,
files,
} => fmt_command(files, check, stdin).await,
DenoSubcommand::Format { check, files } => {
fmt_command(files, check).await
}
DenoSubcommand::Info { file } => info_command(flags, file).await,
DenoSubcommand::Install {
dir,
Expand Down
14 changes: 11 additions & 3 deletions cli/tests/integration_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -602,19 +602,27 @@ itest!(bundle {
});

itest!(fmt_stdin {
args: "fmt --stdin",
args: "fmt -",
input: Some("const a = 1\n"),
output_str: Some("const a = 1;\n"),
});

itest!(fmt_stdin_ambiguous {
args: "fmt - file.ts",
input: Some("const a = 1\n"),
check_stderr: true,
exit_code: 1,
output_str: Some("Ambiguous filename input. To format stdin, provide a single '-' instead.\n"),
});

itest!(fmt_stdin_check_formatted {
args: "fmt --stdin --check",
args: "fmt --check -",
input: Some("const a = 1;\n"),
output_str: Some(""),
});

itest!(fmt_stdin_check_not_formatted {
args: "fmt --stdin --check",
args: "fmt --check -",
input: Some("const a = 1\n"),
output_str: Some("Not formatted stdin\n"),
});
Expand Down

0 comments on commit d55a5b9

Please sign in to comment.