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
244
apps/lutra-cli/src/open.rs
Normal file
244
apps/lutra-cli/src/open.rs
Normal file
|
|
@ -0,0 +1,244 @@
|
|||
//! `lutra [--wait] [PATH[:LINE[:COLUMN]]]...`: resolve the targets, reach
|
||||
//! or start Lutra, open them, and optionally wait for their tabs to close.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
|
||||
use lutra_control::client::{self, Client, ClientError};
|
||||
use lutra_control::rendezvous;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::args::{Args, Target};
|
||||
use crate::launch;
|
||||
|
||||
/// How long `editor.reveal` is retried while the window is still loading.
|
||||
const REVEAL_WAIT: Duration = Duration::from_secs(20);
|
||||
|
||||
/// Why `lutra` failed, which decides the exit code.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Failure {
|
||||
/// Bad usage: exit code 2.
|
||||
Usage(String),
|
||||
/// Anything else: exit code 1.
|
||||
Error(String),
|
||||
}
|
||||
|
||||
/// A target checked against the file system.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Resolved {
|
||||
/// A folder to open as the project.
|
||||
Folder(PathBuf),
|
||||
/// A file to open, with an optional 1-based position.
|
||||
File {
|
||||
/// Absolute path.
|
||||
path: PathBuf,
|
||||
/// Line from 1.
|
||||
line: Option<u32>,
|
||||
/// Column from 1.
|
||||
column: Option<u32>,
|
||||
},
|
||||
}
|
||||
|
||||
/// Checks every target: the path part must exist (if it does not but the
|
||||
/// whole argument does, the argument is a path containing `:digits`), a
|
||||
/// folder has no position, and at most one folder is given. The folder
|
||||
/// comes first, files keep their order.
|
||||
///
|
||||
/// # Errors
|
||||
/// [`Failure::Usage`] for a positioned folder or two folders,
|
||||
/// [`Failure::Error`] for a path that does not exist.
|
||||
pub fn resolve(targets: &[Target]) -> Result<Vec<Resolved>, Failure> {
|
||||
let mut folder = None;
|
||||
let mut files = Vec::new();
|
||||
for target in targets {
|
||||
let (path, line, column) = if Path::new(&target.path).exists() {
|
||||
(target.path.as_str(), target.line, target.column)
|
||||
} else if Path::new(&target.raw).exists() {
|
||||
(target.raw.as_str(), None, None)
|
||||
} else {
|
||||
return Err(Failure::Error(format!("{} does not exist", target.path)));
|
||||
};
|
||||
let path = std::path::absolute(path).map_err(|e| Failure::Error(format!("{path}: {e}")))?;
|
||||
if path.is_dir() {
|
||||
if line.is_some() {
|
||||
return Err(Failure::Usage(format!(
|
||||
"{} is a folder and has no lines",
|
||||
target.raw
|
||||
)));
|
||||
}
|
||||
if folder.is_some() {
|
||||
return Err(Failure::Usage("only one folder can be opened".into()));
|
||||
}
|
||||
folder = Some(Resolved::Folder(path));
|
||||
} else {
|
||||
files.push(Resolved::File { path, line, column });
|
||||
}
|
||||
}
|
||||
Ok(folder.into_iter().chain(files).collect())
|
||||
}
|
||||
|
||||
/// Runs `lutra` with parsed arguments.
|
||||
///
|
||||
/// # Errors
|
||||
/// The [`Failure`] to report.
|
||||
pub fn run(args: &Args) -> Result<(), Failure> {
|
||||
let targets = resolve(&args.targets)?;
|
||||
let dir = rendezvous::dir()
|
||||
.ok_or_else(|| Failure::Error("cannot find the Lutra data directory".into()))?;
|
||||
let mut client = match client::connect_live(&dir, client::DEFAULT_TIMEOUT) {
|
||||
Ok((_, client)) => client,
|
||||
Err(_) => {
|
||||
let desktop = launch::find_desktop().map_err(Failure::Error)?;
|
||||
launch::start(&desktop, &dir).map_err(Failure::Error)?
|
||||
}
|
||||
};
|
||||
if args.wait {
|
||||
client.subscribe().map_err(failed)?;
|
||||
}
|
||||
let opened = open_all(&mut client, &targets, REVEAL_WAIT)?;
|
||||
let _ = client.focus();
|
||||
if args.wait {
|
||||
wait_closed(client, &dir, opened.into_iter().collect())?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Opens the targets in order and moves to their positions.
|
||||
///
|
||||
/// # Returns
|
||||
/// The buffer ids of the opened files.
|
||||
///
|
||||
/// # Errors
|
||||
/// [`Failure::Error`] naming the first target that could not be opened.
|
||||
pub fn open_all(
|
||||
client: &mut Client,
|
||||
targets: &[Resolved],
|
||||
reveal_wait: Duration,
|
||||
) -> Result<Vec<u64>, Failure> {
|
||||
let mut ids = Vec::new();
|
||||
for target in targets {
|
||||
match target {
|
||||
Resolved::Folder(path) => {
|
||||
client
|
||||
.open_folder(path)
|
||||
.map_err(|e| cannot_open(path, &e))?;
|
||||
}
|
||||
Resolved::File { path, line, column } => {
|
||||
let file = client.open_file(path).map_err(|e| cannot_open(path, &e))?;
|
||||
if let Some(line) = line {
|
||||
let column = column.unwrap_or(1);
|
||||
client
|
||||
.reveal(
|
||||
&file.path,
|
||||
line.saturating_sub(1),
|
||||
column.saturating_sub(1),
|
||||
reveal_wait,
|
||||
)
|
||||
.map_err(|e| cannot_open(path, &e))?;
|
||||
}
|
||||
ids.push(file.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
/// Blocks until every buffer in `ids` is closed: by `bufferClosed`, by
|
||||
/// `projectClosed`, or because Lutra exited (its tabs are gone too). A lost
|
||||
/// subscription is renewed through the rendezvous file in `dir`, and
|
||||
/// buffers that closed meanwhile are found with `buffer.get`.
|
||||
///
|
||||
/// # Errors
|
||||
/// [`Failure::Error`] for a malformed line or a subscription that cannot
|
||||
/// be renewed.
|
||||
pub fn wait_closed(mut client: Client, dir: &Path, mut ids: BTreeSet<u64>) -> Result<(), Failure> {
|
||||
while !ids.is_empty() {
|
||||
let event = match client.next_event(None) {
|
||||
Ok(Some(event)) => event,
|
||||
Ok(None) => continue,
|
||||
Err(ClientError::Io(_)) => return Ok(()),
|
||||
Err(e) => return Err(failed(e)),
|
||||
};
|
||||
match event.get("kind").and_then(Value::as_str) {
|
||||
Some("bufferClosed") => {
|
||||
if let Some(id) = event.get("id").and_then(Value::as_u64) {
|
||||
ids.remove(&id);
|
||||
}
|
||||
}
|
||||
Some("projectClosed") => ids.clear(),
|
||||
Some("subscriptionLost") => {
|
||||
client = match client::connect_live(dir, client::DEFAULT_TIMEOUT) {
|
||||
Ok((_, client)) => client,
|
||||
Err(_) => return Ok(()),
|
||||
};
|
||||
client.subscribe().map_err(failed)?;
|
||||
ids.retain(|id| client.execute("buffer.get", json!({ "id": id })).is_ok());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A failure to open `path`.
|
||||
fn cannot_open(path: &Path, error: &ClientError) -> Failure {
|
||||
Failure::Error(format!("cannot open {}: {error}", path.display()))
|
||||
}
|
||||
|
||||
/// A failure talking to Lutra.
|
||||
fn failed(error: ClientError) -> Failure {
|
||||
Failure::Error(error.to_string())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::args::parse_target;
|
||||
|
||||
#[test]
|
||||
fn resolves_targets() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let file = dir.path().join("a.php");
|
||||
std::fs::write(&file, "<?php\n").unwrap();
|
||||
let odd = dir.path().join("b:3");
|
||||
if std::fs::write(&odd, "x").is_err() {
|
||||
return;
|
||||
}
|
||||
let t = |raw: &Path| parse_target(raw.to_str().unwrap()).unwrap();
|
||||
let positioned = parse_target(&format!("{}:4:2", file.display())).unwrap();
|
||||
let resolved = resolve(&[positioned, t(dir.path()), t(&odd)]).unwrap();
|
||||
assert_eq!(resolved[0], Resolved::Folder(dir.path().to_path_buf()));
|
||||
assert_eq!(
|
||||
resolved[1],
|
||||
Resolved::File {
|
||||
path: file.clone(),
|
||||
line: Some(4),
|
||||
column: Some(2)
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
resolved[2],
|
||||
Resolved::File {
|
||||
path: odd,
|
||||
line: None,
|
||||
column: None
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_bad_targets() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let t = |raw: String| parse_target(&raw).unwrap();
|
||||
let missing = t(dir.path().join("nope.php").display().to_string());
|
||||
assert!(matches!(resolve(&[missing]), Err(Failure::Error(_))));
|
||||
let folder_line = t(format!("{}:3", dir.path().display()));
|
||||
assert!(matches!(resolve(&[folder_line]), Err(Failure::Usage(_))));
|
||||
let folder = t(dir.path().display().to_string());
|
||||
assert!(matches!(
|
||||
resolve(&[folder.clone(), folder]),
|
||||
Err(Failure::Usage(_))
|
||||
));
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue