//! `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, /// Column from 1. column: Option, }, } /// 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, 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, 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) -> 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, "