Skip to main content

lune/desktop/
cli.rs

1use std::env;
2use std::ffi::OsString;
3use std::fmt;
4use std::path::PathBuf;
5
6use super::ipc::IpcCommand;
7use super::split::Axis;
8
9pub const HELP_TEXT: &str = "\
10Usage: lune [OPTIONS] [-- COMMAND [ARGS...]]
11       lune msg [--socket <PATH>] <SUBCOMMAND>
12
13Options:
14  -d, --working-directory <DIR>  Start the initial session in DIR
15  -T, --title <TITLE>            Set the initial window title
16      --class, --app-id <ID>     Set the Wayland application ID (default: lune)
17  -c, --config <PATH>            Load configuration from PATH
18  -e, --command <CMD> [ARGS...]  Run CMD instead of the default shell
19  -h, --help                     Print this help message and exit
20  -V, --version                  Print version information and exit
21
22IPC Subcommands (lune msg):
23  new-tab [-d <DIR>] [-T <TITLE>] [-- <CMD>...]  Open a tab in a running window
24  split [--right|--down] [-d <DIR>]              Split the active pane
25  set-theme <NAME>                               Switch theme in a running window
26  reload-config                                  Reload configuration
27  save-config                                    Save current settings to config
28  list                                           List active Lune IPC sockets
29";
30
31pub const VERSION_TEXT: &str = concat!("lune ", env!("CARGO_PKG_VERSION"));
32
33#[derive(Clone, Debug, Default, PartialEq, Eq)]
34pub struct LaunchOptions {
35    pub working_directory: Option<PathBuf>,
36    pub title: Option<String>,
37    pub app_id: Option<String>,
38    pub config: Option<PathBuf>,
39    pub command: Option<Vec<OsString>>,
40}
41
42#[derive(Clone, Debug, PartialEq, Eq)]
43pub enum MsgAction {
44    List,
45    Send {
46        socket: Option<PathBuf>,
47        command: IpcCommand,
48    },
49}
50
51#[derive(Clone, Debug, PartialEq, Eq)]
52pub enum CliAction {
53    Run(LaunchOptions),
54    Msg(MsgAction),
55    Help,
56    Version,
57}
58
59#[derive(Clone, Debug, PartialEq, Eq)]
60pub struct CliError {
61    message: String,
62}
63
64impl CliError {
65    fn new(message: impl Into<String>) -> Self {
66        Self {
67            message: message.into(),
68        }
69    }
70}
71
72impl fmt::Display for CliError {
73    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
74        f.write_str(&self.message)
75    }
76}
77
78impl std::error::Error for CliError {}
79
80pub fn parse_env() -> Result<CliAction, CliError> {
81    parse(env::args_os().skip(1))
82}
83
84pub fn parse<I>(args: I) -> Result<CliAction, CliError>
85where
86    I: IntoIterator<Item = OsString>,
87{
88    let mut iter = args.into_iter().peekable();
89    if iter.peek().and_then(|arg| arg.to_str()) == Some("msg") {
90        iter.next();
91        return parse_msg(iter);
92    }
93    let mut options = LaunchOptions::default();
94
95    while let Some(arg) = iter.next() {
96        let Some(text) = arg.to_str() else {
97            return Err(CliError::new(format!(
98                "unexpected argument: {}",
99                arg.to_string_lossy()
100            )));
101        };
102
103        match text {
104            "-h" | "--help" => return Ok(CliAction::Help),
105            "-V" | "--version" => return Ok(CliAction::Version),
106            "-d" | "--working-directory" => {
107                let value = next_value(&mut iter, text)?;
108                options.working_directory = Some(PathBuf::from(value));
109            }
110            "-T" | "--title" => {
111                let value = next_string(&mut iter, text)?;
112                options.title = Some(sanitize_title(&value));
113            }
114            "--class" | "--app-id" => {
115                let value = next_string(&mut iter, text)?;
116                options.app_id = Some(validate_app_id(&value)?);
117            }
118            "-c" | "--config" => {
119                let value = next_value(&mut iter, text)?;
120                options.config = Some(PathBuf::from(value));
121            }
122            "-e" | "--command" | "--" => {
123                let command: Vec<OsString> = iter.collect();
124                if command.is_empty() {
125                    return Err(CliError::new(format!("{text} requires a command to run")));
126                }
127                options.command = Some(command);
128                break;
129            }
130            _ => {
131                if let Some((flag, value)) = split_long_option(text) {
132                    match flag {
133                        "--working-directory" => {
134                            options.working_directory = Some(PathBuf::from(value));
135                        }
136                        "--title" => {
137                            options.title = Some(sanitize_title(value));
138                        }
139                        "--class" | "--app-id" => {
140                            options.app_id = Some(validate_app_id(value)?);
141                        }
142                        "--config" => {
143                            options.config = Some(PathBuf::from(value));
144                        }
145                        _ => {
146                            return Err(CliError::new(format!("unknown option: {flag}")));
147                        }
148                    }
149                } else if text.starts_with('-') {
150                    return Err(CliError::new(format!("unknown option: {text}")));
151                } else {
152                    return Err(CliError::new(format!(
153                        "unexpected argument: {text} (use -e or -- to run a command)"
154                    )));
155                }
156            }
157        }
158    }
159
160    Ok(CliAction::Run(options))
161}
162
163fn parse_msg(mut iter: impl Iterator<Item = OsString>) -> Result<CliAction, CliError> {
164    let mut socket: Option<PathBuf> = None;
165    let subcommand = loop {
166        let Some(arg) = iter.next() else {
167            return Err(CliError::new("msg requires a subcommand"));
168        };
169        let Some(text) = arg.to_str() else {
170            return Err(CliError::new("msg subcommand must be valid UTF-8"));
171        };
172        match text {
173            "-h" | "--help" => return Ok(CliAction::Help),
174            "--socket" => {
175                socket = Some(PathBuf::from(next_value(&mut iter, text)?));
176            }
177            _ => {
178                if let Some(value) = text.strip_prefix("--socket=") {
179                    if value.is_empty() {
180                        return Err(CliError::new("--socket requires a value"));
181                    }
182                    socket = Some(PathBuf::from(value));
183                } else {
184                    break text.to_owned();
185                }
186            }
187        }
188    };
189
190    let command = match subcommand.as_str() {
191        "list" => {
192            if iter.next().is_some() {
193                return Err(CliError::new("msg list takes no arguments"));
194            }
195            return Ok(CliAction::Msg(MsgAction::List));
196        }
197        "reload-config" => {
198            parse_trailing_socket_only(&mut iter, &mut socket, "reload-config")?;
199            IpcCommand::ReloadConfig
200        }
201        "save-config" => {
202            parse_trailing_socket_only(&mut iter, &mut socket, "save-config")?;
203            IpcCommand::SaveConfig
204        }
205        "set-theme" => {
206            let mut name: Option<String> = None;
207            while let Some(arg) = iter.next() {
208                let Some(text) = arg.to_str() else {
209                    return Err(CliError::new(
210                        "unexpected non-UTF-8 argument in msg set-theme",
211                    ));
212                };
213                if consume_socket_arg(text, &mut iter, &mut socket)? {
214                    continue;
215                }
216                if text.starts_with('-') {
217                    return Err(CliError::new(format!("unknown option: {text}")));
218                }
219                if name.is_some() {
220                    return Err(CliError::new("msg set-theme takes a single theme name"));
221                }
222                if text.is_empty() {
223                    return Err(CliError::new("set-theme requires a value"));
224                }
225                name = Some(text.to_owned());
226            }
227            let Some(name) = name else {
228                return Err(CliError::new("set-theme requires a value"));
229            };
230            IpcCommand::SetTheme(name)
231        }
232        "new-tab" => {
233            let mut working_directory = None;
234            let mut title = None;
235            let mut command = None;
236            while let Some(arg) = iter.next() {
237                let Some(text) = arg.to_str() else {
238                    return Err(CliError::new(
239                        "unexpected non-UTF-8 argument in msg new-tab",
240                    ));
241                };
242                if consume_socket_arg(text, &mut iter, &mut socket)? {
243                    continue;
244                }
245                match text {
246                    "-d" | "--working-directory" => {
247                        working_directory = Some(PathBuf::from(next_value(&mut iter, text)?));
248                    }
249                    "-T" | "--title" => {
250                        title = Some(sanitize_title(&next_string(&mut iter, text)?));
251                    }
252                    "-e" | "--command" | "--" => {
253                        let cmd: Vec<OsString> = iter.collect();
254                        if cmd.is_empty() {
255                            return Err(CliError::new(format!("{text} requires a command")));
256                        }
257                        command = Some(cmd);
258                        break;
259                    }
260                    _ => {
261                        if let Some((flag, value)) = split_long_option(text) {
262                            match flag {
263                                "--working-directory" => {
264                                    working_directory = Some(PathBuf::from(value));
265                                }
266                                "--title" => {
267                                    title = Some(sanitize_title(value));
268                                }
269                                _ => {
270                                    return Err(CliError::new(format!("unknown option: {flag}")));
271                                }
272                            }
273                        } else {
274                            return Err(CliError::new(format!("unknown option: {text}")));
275                        }
276                    }
277                }
278            }
279            IpcCommand::NewTab {
280                working_directory,
281                title,
282                command,
283            }
284        }
285        "split" => {
286            let mut axis = Axis::Columns;
287            let mut working_directory = None;
288            while let Some(arg) = iter.next() {
289                let Some(text) = arg.to_str() else {
290                    return Err(CliError::new("unexpected non-UTF-8 argument in msg split"));
291                };
292                if consume_socket_arg(text, &mut iter, &mut socket)? {
293                    continue;
294                }
295                match text {
296                    "--right" | "--columns" | "right" | "vertical" => axis = Axis::Columns,
297                    "--down" | "--rows" | "down" | "horizontal" => axis = Axis::Rows,
298                    "-d" | "--working-directory" => {
299                        working_directory = Some(PathBuf::from(next_value(&mut iter, text)?));
300                    }
301                    _ => {
302                        if let Some(value) = text.strip_prefix("--working-directory=") {
303                            working_directory = Some(PathBuf::from(value));
304                        } else {
305                            return Err(CliError::new(format!("unknown option: {text}")));
306                        }
307                    }
308                }
309            }
310            IpcCommand::Split {
311                axis,
312                working_directory,
313            }
314        }
315        other => {
316            return Err(CliError::new(format!("unknown msg subcommand: {other}")));
317        }
318    };
319
320    Ok(CliAction::Msg(MsgAction::Send { socket, command }))
321}
322
323fn consume_socket_arg(
324    text: &str,
325    iter: &mut impl Iterator<Item = OsString>,
326    socket: &mut Option<PathBuf>,
327) -> Result<bool, CliError> {
328    if text == "--socket" {
329        *socket = Some(PathBuf::from(next_value(iter, text)?));
330        return Ok(true);
331    }
332    if let Some(value) = text.strip_prefix("--socket=") {
333        if value.is_empty() {
334            return Err(CliError::new("--socket requires a value"));
335        }
336        *socket = Some(PathBuf::from(value));
337        return Ok(true);
338    }
339    Ok(false)
340}
341
342fn parse_trailing_socket_only(
343    iter: &mut impl Iterator<Item = OsString>,
344    socket: &mut Option<PathBuf>,
345    subcommand: &str,
346) -> Result<(), CliError> {
347    while let Some(arg) = iter.next() {
348        let Some(text) = arg.to_str() else {
349            return Err(CliError::new(format!(
350                "msg {subcommand} takes no arguments"
351            )));
352        };
353        if !consume_socket_arg(text, iter, socket)? {
354            return Err(CliError::new(format!(
355                "msg {subcommand} takes no arguments"
356            )));
357        }
358    }
359    Ok(())
360}
361
362fn split_long_option(text: &str) -> Option<(&str, &str)> {
363    let (flag, value) = text.split_once('=')?;
364    flag.starts_with("--").then_some((flag, value))
365}
366
367fn next_value(iter: &mut impl Iterator<Item = OsString>, flag: &str) -> Result<OsString, CliError> {
368    iter.next()
369        .filter(|value| !value.is_empty())
370        .ok_or_else(|| CliError::new(format!("{flag} requires a value")))
371}
372
373fn next_string(iter: &mut impl Iterator<Item = OsString>, flag: &str) -> Result<String, CliError> {
374    let value = next_value(iter, flag)?;
375    value
376        .into_string()
377        .map_err(|_| CliError::new(format!("{flag} value must be valid UTF-8")))
378}
379
380fn sanitize_title(value: &str) -> String {
381    value
382        .chars()
383        .filter(|ch| !ch.is_control())
384        .take(128)
385        .collect()
386}
387
388fn validate_app_id(value: &str) -> Result<String, CliError> {
389    if value.is_empty() || value.chars().any(char::is_control) {
390        return Err(CliError::new(
391            "application ID must be non-empty without control characters",
392        ));
393    }
394    Ok(value.to_owned())
395}
396
397#[cfg(test)]
398mod tests {
399    use std::ffi::OsString;
400    use std::path::PathBuf;
401
402    use super::{CliAction, LaunchOptions, parse};
403
404    fn os(items: &[&str]) -> Vec<OsString> {
405        items.iter().map(OsString::from).collect()
406    }
407
408    #[test]
409    fn parses_launch_options_and_trailing_command() {
410        let action = parse(os(&[
411            "--working-directory",
412            "/tmp",
413            "--title=Build\x07 Log",
414            "--app-id",
415            "lune.dev",
416            "-c",
417            "/etc/lune.conf",
418            "-e",
419            "sh",
420            "-c",
421            "echo --help",
422        ]))
423        .unwrap();
424        assert_eq!(
425            action,
426            CliAction::Run(LaunchOptions {
427                working_directory: Some(PathBuf::from("/tmp")),
428                title: Some("Build Log".into()),
429                app_id: Some("lune.dev".into()),
430                config: Some(PathBuf::from("/etc/lune.conf")),
431                command: Some(os(&["sh", "-c", "echo --help"])),
432            })
433        );
434    }
435
436    #[test]
437    fn parses_double_dash_command_and_help_version() {
438        assert_eq!(parse(os(&["--help"])).unwrap(), CliAction::Help);
439        assert_eq!(parse(os(&["-V"])).unwrap(), CliAction::Version);
440        let action = parse(os(&["-d", ".", "--", "ls", "-la"])).unwrap();
441        assert_eq!(
442            action,
443            CliAction::Run(LaunchOptions {
444                working_directory: Some(PathBuf::from(".")),
445                command: Some(os(&["ls", "-la"])),
446                ..LaunchOptions::default()
447            })
448        );
449    }
450
451    #[test]
452    fn rejects_invalid_flags_and_missing_values() {
453        for bad in [
454            &["--unknown"][..],
455            &["--working-directory"][..],
456            &["-c"][..],
457            &["-e"][..],
458            &["--"][..],
459            &["--app-id="][..],
460            &["positional"][..],
461        ] {
462            assert!(parse(os(bad)).is_err(), "{bad:?}");
463        }
464    }
465
466    #[test]
467    fn parses_msg_subcommands() {
468        let action = parse(os(&[
469            "msg",
470            "--socket=/tmp/lune.sock",
471            "new-tab",
472            "-d",
473            "/tmp",
474            "-T",
475            "Logs",
476            "--",
477            "tail",
478            "-f",
479        ]))
480        .unwrap();
481        assert_eq!(
482            action,
483            CliAction::Msg(super::MsgAction::Send {
484                socket: Some(PathBuf::from("/tmp/lune.sock")),
485                command: super::IpcCommand::NewTab {
486                    working_directory: Some(PathBuf::from("/tmp")),
487                    title: Some("Logs".into()),
488                    command: Some(os(&["tail", "-f"])),
489                },
490            })
491        );
492
493        let split = parse(os(&["msg", "split", "--down", "-d", "/var"])).unwrap();
494        assert_eq!(
495            split,
496            CliAction::Msg(super::MsgAction::Send {
497                socket: None,
498                command: super::IpcCommand::Split {
499                    axis: super::Axis::Rows,
500                    working_directory: Some(PathBuf::from("/var")),
501                },
502            })
503        );
504
505        assert_eq!(
506            parse(os(&["msg", "set-theme", "nord"])).unwrap(),
507            CliAction::Msg(super::MsgAction::Send {
508                socket: None,
509                command: super::IpcCommand::SetTheme("nord".into()),
510            })
511        );
512        assert_eq!(
513            parse(os(&["msg", "list"])).unwrap(),
514            CliAction::Msg(super::MsgAction::List)
515        );
516    }
517}