M3.7: lutra CLI and single instance
- crates/control: rendezvous file (<data_dir>/instance.json, port + random token, atomic write, 0600 on Unix, stale detection), token-protected listener (start_with_token, app.auth first, constant-time compare, 10 s auth timeout), app.focus, and a blocking client (connect_live, request/execute/subscribe/next_event, open_folder/open_file/reveal) - lutra-desktop: a normal start forwards its path to a running instance and exits, otherwise claims the rendezvous; --control instances skip it unless LUTRA_RENDEZVOUS_DIR is set; non-Unicode args are usage errors - lutra-cli (binary lutra, now L6): path[:line[:column]] targets, folder -> project.open, file -> file.open (parent opened without a project, outside the project refused), editor.reveal, starts the desktop if needed, --wait until bufferClosed, --version/--help, exit codes 0/1/2 - tests: proptest target parsing, rendezvous read/write/stale, token check over TCP, forwarding against a test backend, --wait end to end - docs: architecture, G7, ROADMAP (agent automation 18% est.), roadmap, README Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
9ccfc1bf6a
commit
9b278099cf
26 changed files with 2162 additions and 37 deletions
261
apps/lutra-cli/src/args.rs
Normal file
261
apps/lutra-cli/src/args.rs
Normal file
|
|
@ -0,0 +1,261 @@
|
|||
//! 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<u32>,
|
||||
/// The column, from 1; only with a line.
|
||||
pub column: Option<u32>,
|
||||
}
|
||||
|
||||
/// 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<Target>,
|
||||
}
|
||||
|
||||
/// 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<Item = OsString>) -> Result<Args, String> {
|
||||
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<Target, String> {
|
||||
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<u32, String> {
|
||||
match text.parse::<u32>() {
|
||||
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<Args, String> {
|
||||
parse(args.iter().map(OsString::from))
|
||||
}
|
||||
|
||||
fn t(raw: &str) -> (String, Option<u32>, Option<u32>) {
|
||||
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<String> = (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));
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue