Lutra/apps/lutra-desktop/src/args.rs
danny b17d26b400
Some checks are pending
ci / ci (macos-15) (push) Waiting to run
ci / ci (ubuntu-24.04) (push) Waiting to run
ci / ci (windows-2025) (push) Waiting to run
B2: setup finish without hang, Open with for PHP files, 0.1.0-alpha
- Finish page starts Lutra through Explorer (Exec, returns at once)
  instead of RunAsUser/ShellExecute on the setup's UI thread. The 0.0.0
  setup hung there while the new, unsigned exe was checked (Norton 360
  active); Windows ended it and left lutra-desktop.exe suspended.
  The NSIS template is an adapted copy of tauri-bundler 2.10.2's.
- installer/hooks.nsh registers Lutra only under OpenWithProgids and
  Applications\lutra-desktop.exe for .php/.phtml/.phpt/.inc; the
  default app stays. The uninstaller removes exactly those entries.
  macOS gets an Alternate-rank CFBundleDocumentTypes entry and handles
  RunEvent::Opened.
- A file path argument opens the file inside its Git/Composer root (or
  folder); a running instance takes it over, switching projects only
  when the file lies outside (never over unsaved changes).
- Version 0.1.0-alpha in the workspace, tauri.conf.json and ui; a test
  keeps tauri.conf.json in step with the crate version.
- xtask bundle passes CARGO_TARGET_DIR to the Tauri CLI as an absolute
  path.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 22:37:56 +01:00

168 lines
5.7 KiB
Rust

//! Command-line arguments of the desktop app.
use std::ffi::OsString;
use std::path::PathBuf;
/// Parsed arguments.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Args {
/// Port for the JSON control channel (`--control PORT`).
pub control: Option<u16>,
/// Isolated data directory (`--data-dir PATH`), see [`crate::datadir`].
pub data_dir: Option<PathBuf>,
/// Folder or file to open (see [`crate::open`]).
pub path: Option<PathBuf>,
/// `--help` was given.
pub help: bool,
/// `--version` was given.
pub version: bool,
}
/// Usage text for `--help`.
pub const USAGE: &str = "usage: lutra-desktop [--control PORT] [--data-dir DIR] [PATH]
PATH a folder to open as the project, or a file to open in the
project around it (its Git or Composer root, else its
folder); a running Lutra takes it over
--control PORT serve the JSON control channel on 127.0.0.1:PORT; without
--data-dir or LUTRA_DATA_DIR the data lives in
<temp>/lutra-control/PORT
--data-dir DIR keep settings, the recovery journal and webview data in
DIR instead of the user's data (also: LUTRA_DATA_DIR)
--version print the version
--help print this help";
/// Parses the raw arguments after the program name.
///
/// # Errors
/// A message for an argument that is not valid Unicode, or as [`parse`].
pub fn parse_os(args: impl IntoIterator<Item = OsString>) -> Result<Args, String> {
let args = args
.into_iter()
.map(|arg| {
arg.into_string()
.map_err(|arg| format!("argument {arg:?} is not valid Unicode"))
})
.collect::<Result<Vec<_>, _>>()?;
parse(args)
}
/// Parses the arguments after the program name.
///
/// # Errors
/// A message for an unknown flag, a missing or invalid port, a missing or
/// empty data directory, or more than one path.
pub fn parse(args: impl IntoIterator<Item = String>) -> Result<Args, String> {
let mut parsed = Args::default();
let mut args = args.into_iter();
while let Some(arg) = args.next() {
if let Some(value) = arg.strip_prefix("--control=") {
parsed.control = Some(port(value)?);
continue;
}
if let Some(value) = arg.strip_prefix("--data-dir=") {
parsed.data_dir = Some(data_dir(value)?);
continue;
}
match arg.as_str() {
"--control" => {
let value = args.next().ok_or("--control needs a port")?;
parsed.control = Some(port(&value)?);
}
"--data-dir" => {
let value = args.next().ok_or("--data-dir needs a directory")?;
parsed.data_dir = Some(data_dir(&value)?);
}
"--help" | "-h" => parsed.help = true,
"--version" | "-V" => parsed.version = true,
flag if flag.starts_with('-') => return Err(format!("unknown option {flag}")),
path => {
if parsed.path.is_some() {
return Err("only one PATH can be given".into());
}
parsed.path = Some(PathBuf::from(path));
}
}
}
Ok(parsed)
}
/// Parses a TCP port number.
///
/// # Errors
/// A message if the value is not a number from 1 to 65535.
fn port(value: &str) -> Result<u16, String> {
match value.parse::<u16>() {
Ok(0) | Err(_) => Err(format!("invalid port {value:?}; expected 1-65535")),
Ok(port) => Ok(port),
}
}
/// Parses a `--data-dir` value.
///
/// # Errors
/// A message if the value is empty.
fn data_dir(value: &str) -> Result<PathBuf, String> {
if value.is_empty() {
return Err("--data-dir needs a directory".into());
}
Ok(PathBuf::from(value))
}
#[cfg(test)]
mod tests {
use super::*;
fn p(args: &[&str]) -> Result<Args, String> {
parse(args.iter().map(|s| s.to_string()))
}
#[test]
fn parses_control_and_path() {
let a = p(&["--control", "7979", "/tmp/demo"]).unwrap();
assert_eq!(a.control, Some(7979));
assert_eq!(a.path, Some(PathBuf::from("/tmp/demo")));
assert_eq!(p(&["--control=80"]).unwrap().control, Some(80));
assert_eq!(p(&[]).unwrap(), Args::default());
}
#[test]
fn parses_data_dir() {
let a = p(&["--control", "7956", "--data-dir", "/tmp/iso", "x"]).unwrap();
assert_eq!(a.data_dir, Some(PathBuf::from("/tmp/iso")));
assert_eq!(a.path, Some(PathBuf::from("x")));
let b = p(&["--data-dir=/tmp/other"]).unwrap();
assert_eq!(b.data_dir, Some(PathBuf::from("/tmp/other")));
assert!(p(&["--data-dir"]).is_err());
assert!(p(&["--data-dir="]).is_err());
}
#[test]
fn rejects_bad_input() {
assert!(p(&["--control"]).is_err());
assert!(p(&["--control", "0"]).is_err());
assert!(p(&["--control", "70000"]).is_err());
assert!(p(&["--frobnicate"]).is_err());
assert!(p(&["a", "b"]).is_err());
}
#[test]
fn takes_a_bare_file_path_from_open_with() {
let a = p(&[r"C:\Users\me\My Projects\shop\src\Kernel.php"]).unwrap();
assert_eq!(
a.path,
Some(PathBuf::from(
r"C:\Users\me\My Projects\shop\src\Kernel.php"
))
);
assert_eq!(a.control, None);
let b = parse_os([OsString::from("/home/me/app/index.php")]).unwrap();
assert_eq!(b.path, Some(PathBuf::from("/home/me/app/index.php")));
}
#[test]
fn reads_raw_arguments() {
let a = parse_os([OsString::from("--control"), OsString::from("7937")]).unwrap();
assert_eq!(a.control, Some(7937));
}
}