//! Command-line arguments of `lutra`, and `path[:line[:column]]` targets. //! //! Arguments are untrusted: parsing never panics, and every problem is a //! usage error (exit code 2). use std::ffi::OsString; /// Usage text for `--help`. pub const USAGE: &str = "usage: lutra [--wait] [PATH[:LINE[:COLUMN]]]... Opens folders and files in the running Lutra, or starts it. PATH a folder becomes the project; a file opens in a tab :LINE[:COLUMN] moves the cursor there (1-based) --wait returns only after the opened files' tabs are closed --version prints the version --help prints this help -- treats every later argument as a path A file outside the open project is refused; without an open project, the file's folder is opened as the project. Lutra is started from LUTRA_DESKTOP, else lutra-desktop next to lutra, else lutra-desktop on PATH. Exit codes: 0 ok, 1 error, 2 bad usage."; /// One `path[:line[:column]]` argument. Line and column are 1-based as /// typed; [`Target::raw`] keeps the whole argument for paths that contain /// `:digits` themselves. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Target { /// The argument as given. pub raw: String, /// The path part. pub path: String, /// The line, from 1. pub line: Option, /// The column, from 1; only with a line. pub column: Option, } /// Parsed arguments. #[derive(Debug, Clone, PartialEq, Eq, Default)] pub struct Args { /// `--wait` was given. pub wait: bool, /// `--help` was given. pub help: bool, /// `--version` was given. pub version: bool, /// The targets, in order. pub targets: Vec, } /// Most targets accepted in one call. pub const MAX_TARGETS: usize = 256; /// Parses the raw arguments after the program name. /// /// # Errors /// A message for an argument that is not valid Unicode, an unknown option, /// a bad line or column, or too many targets. pub fn parse(args: impl IntoIterator) -> Result { let mut parsed = Args::default(); let mut options = true; for arg in args { let arg = arg .into_string() .map_err(|arg| format!("argument {arg:?} is not valid Unicode"))?; if options { match arg.as_str() { "--" => { options = false; continue; } "--wait" | "-w" => { parsed.wait = true; continue; } "--help" | "-h" => { parsed.help = true; continue; } "--version" | "-V" => { parsed.version = true; continue; } flag if flag.starts_with('-') && flag.len() > 1 => { return Err(format!("unknown option {flag}")); } _ => {} } } if parsed.targets.len() >= MAX_TARGETS { return Err(format!("at most {MAX_TARGETS} paths can be given")); } parsed.targets.push(parse_target(&arg)?); } Ok(parsed) } /// Splits `path[:line[:column]]`. A trailing `:N` counts as a position only /// if `N` is all ASCII digits and something is left before it; on Windows a /// lone drive letter (`C:5`) is not split off. /// /// # Errors /// A message for an empty argument, a line or column of 0, or a number /// that does not fit in 32 bits. pub fn parse_target(raw: &str) -> Result { if raw.is_empty() { return Err("an empty path was given".into()); } let mut path = raw; let mut numbers: Vec<&str> = Vec::new(); while numbers.len() < 2 { let Some((head, tail)) = path.rsplit_once(':') else { break; }; let digits = !tail.is_empty() && tail.bytes().all(|b| b.is_ascii_digit()); if !digits || head.is_empty() || is_drive(head) { break; } numbers.push(tail); path = head; } let number = |text: &str| -> Result { match text.parse::() { Ok(0) => Err(format!("{raw}: lines and columns start at 1")), Ok(n) => Ok(n), Err(_) => Err(format!("{raw}: {text} is not a valid line or column")), } }; let (line, column) = match numbers.as_slice() { [] => (None, None), [line] => (Some(number(line)?), None), [column, line, ..] => (Some(number(line)?), Some(number(column)?)), }; Ok(Target { raw: raw.to_string(), path: path.to_string(), line, column, }) } /// Whether `head` is a bare drive letter, which on Windows makes `C:5` a /// path rather than file `C` at line 5. fn is_drive(head: &str) -> bool { cfg!(windows) && head.len() == 1 && head.bytes().all(|b| b.is_ascii_alphabetic()) } #[cfg(test)] mod tests { use proptest::prelude::*; use super::*; fn p(args: &[&str]) -> Result { parse(args.iter().map(OsString::from)) } fn t(raw: &str) -> (String, Option, Option) { let t = parse_target(raw).unwrap(); (t.path, t.line, t.column) } #[test] fn parses_flags_and_targets() { let a = p(&["--wait", "a.php:3", "src"]).unwrap(); assert!(a.wait); assert_eq!(a.targets.len(), 2); assert_eq!(a.targets[0].line, Some(3)); assert!(p(&["--help"]).unwrap().help); assert!(p(&["-V"]).unwrap().version); assert_eq!(p(&[]).unwrap(), Args::default()); let a = p(&["--", "--wait", "-"]).unwrap(); assert!(!a.wait); assert_eq!(a.targets[0].path, "--wait"); assert_eq!(a.targets[1].path, "-"); } #[test] fn rejects_bad_usage() { assert!(p(&["--frobnicate"]).is_err()); assert!(p(&[""]).is_err()); assert!(p(&["a.php:0"]).is_err()); assert!(p(&["a.php:1:0"]).is_err()); assert!(p(&["a.php:99999999999"]).is_err()); let many: Vec = (0..=MAX_TARGETS).map(|i| format!("f{i}")).collect(); let many: Vec<&str> = many.iter().map(String::as_str).collect(); assert!(p(&many).is_err()); } #[test] fn splits_positions() { assert_eq!(t("a.php"), ("a.php".into(), None, None)); assert_eq!(t("a.php:10"), ("a.php".into(), Some(10), None)); assert_eq!(t("a.php:10:5"), ("a.php".into(), Some(10), Some(5))); assert_eq!(t("a:b:1:2:3"), ("a:b:1".into(), Some(2), Some(3))); assert_eq!(t("a.php:"), ("a.php:".into(), None, None)); assert_eq!(t("a.php:x"), ("a.php:x".into(), None, None)); assert_eq!(t(":5"), (":5".into(), None, None)); assert_eq!(t("a.php:+5"), ("a.php:+5".into(), None, None)); assert_eq!( t(r"C:\src\a.php:7:2"), (r"C:\src\a.php".into(), Some(7), Some(2)) ); } #[cfg(windows)] #[test] fn keeps_drive_letters() { assert_eq!(t("C:5"), ("C:5".into(), None, None)); assert_eq!(t("C:5:6"), ("C:5".into(), Some(6), None)); } #[test] fn rejects_non_unicode() { #[cfg(unix)] { use std::os::unix::ffi::OsStringExt; assert!(parse([OsString::from_vec(vec![0xff, b'a'])]).is_err()); } #[cfg(windows)] { use std::os::windows::ffi::OsStringExt; assert!(parse([OsString::from_wide(&[0xd800, 0x61])]).is_err()); } } proptest! { #[test] fn round_trips_path_line_column( path in "[a-zA-Z0-9_./\\\\-]{2,40}", line in 1u32.., column in proptest::option::of(1u32..), ) { let raw = match column { Some(c) => format!("{path}:{line}:{c}"), None => format!("{path}:{line}"), }; let target = parse_target(&raw).unwrap(); prop_assert_eq!(target.path, path); prop_assert_eq!(target.line, Some(line)); prop_assert_eq!(target.column, column); prop_assert_eq!(target.raw, raw); } #[test] fn never_panics(raw in ".{0,80}") { if let Ok(target) = parse_target(&raw) { prop_assert!(raw.starts_with(&target.path)); prop_assert!(target.column.is_none() || target.line.is_some()); } } #[test] fn any_arguments_parse_or_fail(args in proptest::collection::vec(".{0,20}", 0..8)) { let _ = parse(args.into_iter().map(OsString::from)); } } }