Skip to main content

mdo_cli/
handler.rs

1//! The Open-as-HTML handler invocation contract.
2//!
3//! Every platform surface that registers or forwards Open as HTML spells
4//! the same two facts — how a handler launches mdo (`--open` plus the
5//! file), and how mdo's binaries are found beside each other (siblings of
6//! the running executable). This module owns both; the Linux desktop-entry
7//! template, the Windows registry command builders, and the `mdo-open`
8//! forwarding binary are thin adapters consuming them, so a change to the
9//! invocation is made here once and every platform entry stays in step.
10//!
11//! The file argument itself is platform presentation: a `%f` placeholder in
12//! a desktop entry, `%1` in a Windows registry command string, and the real
13//! path when a binary is spawned. Only the argv prefix is the contract.
14
15use std::ffi::OsString;
16use std::io;
17use std::path::{Path, PathBuf};
18
19/// The flags a handler command puts before the file argument when it
20/// launches mdo directly. Spelled once: the desktop-entry template, the
21/// Windows registry command, and the forward binary all consume this, so
22/// the contract cannot drift between the six places that used to repeat it.
23pub const OPEN_FLAGS: &[&str] = &["--open"];
24
25/// The full open-mode argv a handler spawns mdo with: the contract flags
26/// (see [`OPEN_FLAGS`]) followed by the files to open, in order.
27pub fn open_argv(files: &[OsString]) -> Vec<OsString> {
28    let mut argv = Vec::with_capacity(OPEN_FLAGS.len() + files.len());
29    argv.extend(OPEN_FLAGS.iter().map(OsString::from));
30    argv.extend(files.iter().cloned());
31    argv
32}
33
34/// Locate a sibling binary beside the running one (or beside whichever
35/// executable the caller anchors on). This is the one discovery function
36/// and the one error mode for everything mdo ships: the binaries always
37/// run from the same directory.
38///
39/// The error is a `NotFound` io error naming the anchor and the path that
40/// was checked, so callers can print it as-is instead of inventing their
41/// own "not found" story.
42pub fn sibling_binary(exe: &Path, name: &str) -> io::Result<PathBuf> {
43    let parent = exe.parent().ok_or_else(|| {
44        io::Error::new(
45            io::ErrorKind::NotFound,
46            format!(
47                "no parent directory for {} (looking for {name})",
48                exe.display()
49            ),
50        )
51    })?;
52    let sibling = parent.join(name);
53    if !sibling.is_file() {
54        return Err(io::Error::new(
55            io::ErrorKind::NotFound,
56            format!(
57                "no {name} found beside {} (looked at {})",
58                exe.display(),
59                sibling.display()
60            ),
61        ));
62    }
63    Ok(sibling)
64}
65
66#[cfg(test)]
67mod tests {
68    use super::*;
69    use std::fs;
70
71    fn fixture_dir(name: &str) -> PathBuf {
72        let uuid = std::time::SystemTime::now()
73            .duration_since(std::time::UNIX_EPOCH)
74            .expect("system time should be after Unix epoch")
75            .as_nanos();
76        let dir = std::env::temp_dir().join(format!(
77            "mdo-handler-test-{name}-{}-{uuid}",
78            std::process::id()
79        ));
80        fs::create_dir_all(&dir).expect("failed to create temp fixture dir");
81        dir
82    }
83
84    #[test]
85    fn open_argv_prepends_the_contract_flags_before_the_files() {
86        let files = vec![OsString::from("notes.md"), OsString::from("todo.md")];
87        let argv = open_argv(&files);
88        let argv: Vec<String> = argv
89            .iter()
90            .map(|arg| arg.to_string_lossy().into_owned())
91            .collect();
92        assert_eq!(argv[0], OPEN_FLAGS[0], "the contract flag comes first");
93        assert_eq!(argv[1..], ["notes.md", "todo.md"]);
94    }
95
96    #[test]
97    fn sibling_binary_resolves_a_real_sibling() {
98        let dir = fixture_dir("resolves");
99        let anchor = dir.join("mdo");
100        fs::write(&anchor, "binary").expect("failed to write anchor fixture");
101        let sibling = dir.join("mdo-open");
102        fs::write(&sibling, "binary").expect("failed to write sibling fixture");
103
104        let found = sibling_binary(&anchor, "mdo-open")
105            .expect("a real sibling beside the anchor should resolve");
106        assert_eq!(found, sibling);
107    }
108
109    #[test]
110    fn sibling_binary_error_names_anchor_and_looked_at_path() {
111        let dir = fixture_dir("missing");
112        let anchor = dir.join("mdo");
113        fs::write(&anchor, "binary").expect("failed to write anchor fixture");
114
115        let err = sibling_binary(&anchor, "mdo-open")
116            .expect_err("a missing sibling is the one error mode");
117        assert_eq!(err.kind(), io::ErrorKind::NotFound);
118        let message = err.to_string();
119        assert!(
120            message.contains(&anchor.display().to_string()),
121            "error should name the anchor: {message}"
122        );
123        assert!(
124            message.contains(&dir.join("mdo-open").display().to_string()),
125            "error should name the path that was checked: {message}"
126        );
127    }
128
129    #[test]
130    fn sibling_binary_rejects_a_directory_named_like_a_binary() {
131        let dir = fixture_dir("not-a-file");
132        let anchor = dir.join("mdo");
133        fs::write(&anchor, "binary").expect("failed to write anchor fixture");
134        let dir_sibling = dir.join("mdo-open");
135        fs::create_dir_all(&dir_sibling).expect("failed to create decoy dir");
136
137        let err =
138            sibling_binary(&anchor, "mdo-open").expect_err("a directory is not a runnable sibling");
139        assert_eq!(err.kind(), io::ErrorKind::NotFound);
140    }
141}