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:
danny 2026-10-18 00:23:09 +02:00
parent 9ccfc1bf6a
commit 9b278099cf
26 changed files with 2162 additions and 37 deletions

View file

@ -9,9 +9,21 @@ authors.workspace = true
publish.workspace = true
[package.metadata.lutra]
layer = 5
layer = 6
[[bin]]
name = "lutra"
path = "src/main.rs"
[dependencies]
lutra-control.workspace = true
serde_json = "1.0.154"
[dev-dependencies]
lutra-engine.workspace = true
lutra-testkit.workspace = true
proptest.workspace = true
tempfile.workspace = true
[lints]
workspace = true

261
apps/lutra-cli/src/args.rs Normal file
View 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));
}
}
}

View file

@ -0,0 +1,105 @@
//! Finding and starting the desktop app when no Lutra is running.
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::thread;
use std::time::{Duration, Instant};
use lutra_control::client::{self, Client};
/// Environment variable with the path of the desktop binary to start.
pub const DESKTOP_ENV: &str = "LUTRA_DESKTOP";
/// File name of the desktop binary.
const DESKTOP_NAME: &str = if cfg!(windows) {
"lutra-desktop.exe"
} else {
"lutra-desktop"
};
/// How long to wait for a started app to write its rendezvous file and
/// answer.
pub const START_TIMEOUT: Duration = Duration::from_secs(60);
/// Time between two looks at the rendezvous file while the app starts.
const POLL: Duration = Duration::from_millis(150);
/// Time to wait for one connection attempt while the app starts.
const PROBE: Duration = Duration::from_secs(2);
/// The desktop binary: `LUTRA_DESKTOP` if set, else `lutra-desktop` next to
/// this executable, else the first `lutra-desktop` on `PATH`.
///
/// # Errors
/// A message naming the places that were tried.
pub fn find_desktop() -> Result<PathBuf, String> {
if let Some(path) = std::env::var_os(DESKTOP_ENV).filter(|v| !v.is_empty()) {
return Ok(PathBuf::from(path));
}
let sibling = std::env::current_exe()
.ok()
.and_then(|exe| Some(exe.parent()?.join(DESKTOP_NAME)))
.filter(|path| path.is_file());
if let Some(path) = sibling {
return Ok(path);
}
std::env::var_os("PATH")
.and_then(|paths| {
std::env::split_paths(&paths)
.map(|dir| dir.join(DESKTOP_NAME))
.find(|path| path.is_file())
})
.ok_or_else(|| {
format!(
"cannot find {DESKTOP_NAME}: set {DESKTOP_ENV}, or put it next to lutra or on PATH"
)
})
}
/// Starts `desktop` detached from this terminal and waits until it answers
/// on the rendezvous file in `dir`. A desktop that exits successfully may
/// have forwarded to an instance that started at the same time, so only a
/// failed exit ends the wait early.
///
/// # Errors
/// A message if it cannot be started, exits early, or does not answer
/// within [`START_TIMEOUT`].
pub fn start(desktop: &Path, dir: &Path) -> Result<Client, String> {
let mut command = Command::new(desktop);
command
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null());
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
const DETACHED_PROCESS: u32 = 0x0000_0008;
const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200;
command.creation_flags(DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP);
}
let mut child = command
.spawn()
.map_err(|e| format!("cannot start {}: {e}", desktop.display()))?;
let deadline = Instant::now() + START_TIMEOUT;
loop {
if let Ok((_, client)) = client::connect_live(dir, PROBE) {
return Ok(client);
}
if let Ok(Some(status)) = child.try_wait()
&& !status.success()
{
return Err(format!(
"{} exited before it was ready ({status})",
desktop.display()
));
}
if Instant::now() >= deadline {
return Err(format!(
"{} did not answer within {} s",
desktop.display(),
START_TIMEOUT.as_secs()
));
}
thread::sleep(POLL);
}
}

View file

@ -1,10 +1,46 @@
//! The `lutra` command-line tool (layer L5).
//! The `lutra` command-line tool (layer L6, on top of the control channel).
//!
//! Will open projects and files in a running Lutra, wait for tabs to close,
//! open the diff viewer and serve MCP. Until milestone M3 it only reports its
//! version.
//! `lutra [--wait] [PATH[:LINE[:COLUMN]]]...` opens folders and files in
//! the running Lutra, or starts it, through the single-instance rendezvous
//! file (see `lutra_control::rendezvous`). Later milestones add the diff
//! viewer, `lutra mcp`, `lutra perf` and `lutra bench`.
//!
//! Exit codes: 0 ok, 1 error, 2 bad usage.
/// Prints the version and exits.
fn main() {
println!("lutra {}", env!("CARGO_PKG_VERSION"));
mod args;
mod launch;
mod open;
use std::process::ExitCode;
use crate::open::Failure;
/// Parses the arguments and runs the command.
fn main() -> ExitCode {
let args = match args::parse(std::env::args_os().skip(1)) {
Ok(args) => args,
Err(message) => return usage_error(&message),
};
if args.help {
println!("{}", args::USAGE);
return ExitCode::SUCCESS;
}
if args.version {
println!("lutra {}", env!("CARGO_PKG_VERSION"));
return ExitCode::SUCCESS;
}
match open::run(&args) {
Ok(()) => ExitCode::SUCCESS,
Err(Failure::Usage(message)) => usage_error(&message),
Err(Failure::Error(message)) => {
eprintln!("lutra: {message}");
ExitCode::FAILURE
}
}
}
/// Prints a usage error and returns exit code 2.
fn usage_error(message: &str) -> ExitCode {
eprintln!("lutra: {message}\n\n{}", args::USAGE);
ExitCode::from(2)
}

244
apps/lutra-cli/src/open.rs Normal file
View 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(_))
));
}
}

156
apps/lutra-cli/tests/cli.rs Normal file
View file

@ -0,0 +1,156 @@
//! The `lutra` binary end to end against a test backend that claims a
//! temporary rendezvous directory (`LUTRA_RENDEZVOUS_DIR`).
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)]
use std::path::Path;
use std::process::{Command, Output, Stdio};
use std::sync::Arc;
use std::thread;
use std::time::{Duration, Instant};
use lutra_control::rendezvous::{self, Instance};
use lutra_engine::Event;
use lutra_testkit::EngineBackend;
use serde_json::json;
/// A backend with a token listener and the UI command `editor.reveal`
/// registered, as a loaded window would have it.
fn instance(dir: &Path) -> Arc<EngineBackend> {
use lutra_control::Backend;
let backend = Arc::new(EngineBackend::new());
backend
.execute(
"ui.registerCommands",
json!({"commands": [{"id": "editor.reveal", "labelKey": "command.editor.reveal"}]}),
)
.unwrap();
let token = rendezvous::new_token().unwrap();
let server = lutra_control::start_with_token(0, backend.clone(), &token).unwrap();
rendezvous::write(
dir,
&Instance {
port: server.local_addr().port(),
token,
pid: std::process::id(),
version: "test".into(),
},
)
.unwrap();
backend
}
fn lutra(dir: &Path, args: &[&str]) -> Command {
let mut command = Command::new(env!("CARGO_BIN_EXE_lutra"));
command
.args(args)
.env(rendezvous::DIR_ENV, dir)
.env("LUTRA_DESKTOP", dir.join("no-such-desktop"))
.stdout(Stdio::piped())
.stderr(Stdio::piped());
command
}
fn run(dir: &Path, args: &[&str]) -> Output {
lutra(dir, args).output().unwrap()
}
fn buffer_ids(backend: &EngineBackend) -> Vec<u64> {
backend.engine.lock().unwrap().state().buffers.ids()
}
#[test]
fn version_help_and_usage_errors() {
let dir = tempfile::tempdir().unwrap();
let out = run(dir.path(), &["--version"]);
assert_eq!(out.status.code(), Some(0));
assert!(String::from_utf8_lossy(&out.stdout).starts_with("lutra "));
let out = run(dir.path(), &["--help"]);
assert_eq!(out.status.code(), Some(0));
assert!(String::from_utf8_lossy(&out.stdout).contains("--wait"));
assert_eq!(run(dir.path(), &["--bogus"]).status.code(), Some(2));
assert_eq!(run(dir.path(), &["a.php:0"]).status.code(), Some(2));
assert_eq!(run(dir.path(), &[""]).status.code(), Some(2));
}
#[test]
fn errors_exit_with_one() {
let dir = tempfile::tempdir().unwrap();
let missing = dir.path().join("missing.php");
let out = run(dir.path(), &[missing.to_str().unwrap()]);
assert_eq!(out.status.code(), Some(1));
let out = run(dir.path(), &[]);
assert_eq!(
out.status.code(),
Some(1),
"no instance and no desktop to start"
);
assert!(String::from_utf8_lossy(&out.stderr).contains("no-such-desktop"));
}
#[test]
fn opens_a_file_at_a_line_in_the_running_instance() {
let rv = tempfile::tempdir().unwrap();
let project = tempfile::tempdir().unwrap();
let file = project.path().join("a.php");
std::fs::write(&file, "<?php\n".repeat(20)).unwrap();
let backend = instance(rv.path());
let (sink, events) = std::sync::mpsc::sync_channel(64);
lutra_control::Backend::subscribe(backend.as_ref(), sink);
let arg = format!("{}:10:3", file.display());
let out = run(rv.path(), &[&arg]);
assert_eq!(
out.status.code(),
Some(0),
"{}",
String::from_utf8_lossy(&out.stderr)
);
assert_eq!(buffer_ids(&backend).len(), 1);
let reveal = events
.try_iter()
.find(|e| matches!(e, Event::UiCommand { .. }))
.unwrap();
assert_eq!(
reveal,
Event::UiCommand {
id: "editor.reveal".into(),
params: json!({"path": "a.php", "line": 9, "column": 2}),
}
);
}
#[test]
fn wait_returns_after_the_tab_is_closed() {
use lutra_control::Backend;
let rv = tempfile::tempdir().unwrap();
let project = tempfile::tempdir().unwrap();
let file = project.path().join("COMMIT_EDITMSG");
std::fs::write(&file, "msg\n").unwrap();
let backend = instance(rv.path());
let mut child = lutra(rv.path(), &["--wait", file.to_str().unwrap()])
.spawn()
.unwrap();
let deadline = Instant::now() + Duration::from_secs(20);
let id = loop {
if let Some(id) = buffer_ids(&backend).first() {
break *id;
}
assert!(Instant::now() < deadline, "the file was never opened");
thread::sleep(Duration::from_millis(50));
};
thread::sleep(Duration::from_millis(300));
assert!(child.try_wait().unwrap().is_none(), "--wait returned early");
backend.execute("buffer.close", json!({"id": id})).unwrap();
let deadline = Instant::now() + Duration::from_secs(20);
let status = loop {
if let Some(status) = child.try_wait().unwrap() {
break status;
}
assert!(Instant::now() < deadline, "--wait did not return");
thread::sleep(Duration::from_millis(50));
};
assert_eq!(status.code(), Some(0));
}