Skip to main content

ktrs_cli/
ktrs.rs

1//! The native `ktrs` command. `ktrs fmt` maps its flags onto ktfmt's [`ParsedArgs`] and runs the
2//! same [`Main`], so output, messages and exit codes stay those of the `ktfmt` drop-in; `ktrs lint`
3//! does the same over the `ktlint` drop-in (`crate::ktrs_lint`).
4
5use std::io;
6use std::path::Path;
7
8use ktrs_fmt::{FormattingOptions, GOOGLE_FORMAT, KOTLINLANG_FORMAT, META_FORMAT};
9
10use crate::ktfmt::{KTFMT_VERSION, Main, ParsedArgs, editor_config_resolver};
11
12const HELP_TEMPLATE: &str = "\
13ktrs - fast Kotlin tooling
14
15Usage:
16  ktrs fmt [OPTIONS] [PATH ...]    Format .kt/.kts files in place (default PATH: .)
17  ktrs fmt [OPTIONS] -             Format stdin to stdout
18  ktrs lint [OPTIONS] [PATH ...]   Check .kt/.kts files with ktlint's rules (default PATH: .); exit 1
19                                     on violations. Rules are being ported: `ktrs lint --list-rules`
20  ktrs lint [OPTIONS] -            Check stdin (with --format: fixed code to stdout)
21  ktrs serve                      Format requests framed on stdin until it closes (for build tools;
22                                     protocol: crates/ktrs-cli/src/serve.rs)
23  ktrs --version
24
25Format options:
26  --style <meta|google|kotlinlang>  Code style (default: meta)
27  --check                           Don't write; list files that would change and exit 1 if any
28  --keep-unused-imports             Leave unused imports in place
29  --editorconfig                    Apply .editorconfig overrides (max_line_length, indent sizes,
30                                      ktfmt_trailing_comma_management_strategy); for stdin, at
31                                      --stdin-name
32  --stdin-name <name>               Name (path) of the stdin input, for messages and .editorconfig
33  -v, --verbose                     Report each formatted file
34
35{LINT_HELP}
36
37`ktfmt` and `ktlint` binaries with those tools' exact flags ship alongside, for existing scripts
38and integrations.";
39
40fn help() -> String {
41    HELP_TEMPLATE.replace("{LINT_HELP}", crate::ktrs_lint::HELP)
42}
43
44pub fn run(args: &[String]) -> i32 {
45    match args.first().map(String::as_str) {
46        Some("fmt") => match parse_fmt_args(&args[1..]) {
47            Ok(parsed) => Main::new(io::stdin(), io::stdout(), io::stderr()).run_parsed(&parsed),
48            Err(message) => {
49                eprintln!("error: {message}\n\n{}", help());
50                2
51            }
52        },
53        Some("lint") => crate::ktrs_lint::run(&args[1..]).unwrap_or_else(|message| {
54            eprintln!("error: {message}\n\n{}", help());
55            2
56        }),
57        Some("serve") if args.len() == 1 => crate::serve::run(io::stdin().lock(), io::stdout().lock()),
58        Some("--version" | "-V") => {
59            println!("ktrs {} (formats like ktfmt {KTFMT_VERSION})", env!("CARGO_PKG_VERSION"));
60            0
61        }
62        Some("help" | "--help" | "-h") => {
63            println!("{}", help());
64            0
65        }
66        _ => {
67            eprintln!("{}", help());
68            2
69        }
70    }
71}
72
73pub fn parse_fmt_args(args: &[String]) -> Result<ParsedArgs, String> {
74    let mut parsed = ParsedArgs {
75        file_names: Vec::new(),
76        formatting_options: META_FORMAT,
77        dry_run: false,
78        set_exit_if_changed: false,
79        stdin_name: None,
80        editor_config: false,
81        quiet: true,
82    };
83    let mut keep_unused_imports = false;
84    let mut args = args.iter();
85    while let Some(arg) = args.next() {
86        let (flag, inline_value) = match arg.split_once('=') {
87            Some((flag, value)) if arg.starts_with("--") => (flag, Some(value.to_owned())),
88            _ => (arg.as_str(), None),
89        };
90        let mut value = || inline_value.clone().or_else(|| args.next().cloned()).ok_or(format!("{flag} needs a value"));
91        match flag {
92            "--style" => parsed.formatting_options = style(&value()?)?,
93            "--check" => (parsed.dry_run, parsed.set_exit_if_changed) = (true, true),
94            "--keep-unused-imports" => keep_unused_imports = true,
95            "--editorconfig" => parsed.editor_config = true,
96            "--stdin-name" => parsed.stdin_name = Some(value()?),
97            "-v" | "--verbose" => parsed.quiet = false,
98            "-" => parsed.file_names.push(arg.clone()),
99            _ if flag.starts_with('-') => return Err(format!("unknown option {arg}")),
100            _ => parsed.file_names.push(arg.clone()),
101        }
102    }
103    parsed.formatting_options.remove_unused_imports = !keep_unused_imports;
104    if parsed.file_names.is_empty() {
105        parsed.file_names.push(".".to_owned());
106    }
107    let reads_stdin = parsed.file_names.iter().any(|f| f == "-");
108    if reads_stdin && parsed.file_names.len() > 1 {
109        return Err("cannot read from stdin and files in the same run".to_owned());
110    }
111    if parsed.stdin_name.is_some() && !reads_stdin {
112        return Err("--stdin-name can only be used when reading from stdin (-)".to_owned());
113    }
114    // Unlike ktfmt 0.64 (the `ktfmt` binary), resolve .editorconfig for stdin at --stdin-name, as
115    // ktfmt's next release will: editors format buffers through stdin.
116    if let (true, true, Some(name)) = (reads_stdin, parsed.editor_config, &parsed.stdin_name) {
117        parsed.formatting_options =
118            editor_config_resolver::resolve_formatting_options(Path::new(name), &parsed.formatting_options);
119    }
120    Ok(parsed)
121}
122
123pub(crate) fn style(name: &str) -> Result<FormattingOptions, String> {
124    match name {
125        "meta" => Ok(META_FORMAT),
126        "google" => Ok(GOOGLE_FORMAT),
127        "kotlinlang" => Ok(KOTLINLANG_FORMAT),
128        _ => Err(format!("unknown style '{name}' (expected meta, google or kotlinlang)")),
129    }
130}