postvak-core 0.3.0

Postvak's sync, store, rules and daemon, shared by its command line, window and MCP server
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
use std::ffi::OsString;
use std::fs;
use std::io;
use std::os::unix::fs::{DirBuilderExt, PermissionsExt};
use std::path::{Path, PathBuf};
use std::time::SystemTime;

#[derive(Debug, Clone)]
pub struct Paths {
    /// The root given to `under` (`POSTVAK_HOME`); None for the platform directories.
    pub home: Option<PathBuf>,
    pub config_dir: PathBuf,
    pub state_dir: PathBuf,
    pub cache_dir: PathBuf,
}

impl Paths {
    pub fn discover() -> anyhow::Result<Paths> {
        let dirs = directories::ProjectDirs::from("", "", "postvak")
            .ok_or_else(|| anyhow::anyhow!("no home directory found"))?;
        let state_dir = dirs
            .state_dir()
            .map(Path::to_path_buf)
            .unwrap_or_else(|| dirs.data_local_dir().to_path_buf());
        Ok(Paths {
            home: None,
            config_dir: dirs.config_dir().to_path_buf(),
            state_dir,
            cache_dir: dirs.cache_dir().to_path_buf(),
        })
    }

    pub fn under(root: &Path) -> Paths {
        Paths {
            home: Some(root.to_path_buf()),
            config_dir: root.join("config"),
            state_dir: root.join("state"),
            cache_dir: root.join("cache"),
        }
    }

    pub fn config_file(&self) -> PathBuf {
        self.config_dir.join("config.toml")
    }

    pub fn rules_file(&self) -> PathBuf {
        self.config_dir.join("rules.toml")
    }

    pub fn daemon_socket(&self) -> PathBuf {
        self.state_dir.join("daemon.sock")
    }

    pub fn daemon_lock(&self) -> PathBuf {
        self.state_dir.join("daemon.lock")
    }

    pub fn daemon_log(&self) -> PathBuf {
        self.state_dir.join("daemon.log")
    }

    pub fn update_check(&self) -> PathBuf {
        self.cache_dir.join("update-check.json")
    }

    pub fn account_dir(&self, name: &str) -> PathBuf {
        self.state_dir.join("accounts").join(name)
    }

    pub fn mail_db(&self, name: &str) -> PathBuf {
        self.account_dir(name).join("mail.db")
    }

    pub fn trash_dir(&self, name: &str) -> PathBuf {
        self.account_dir(name).join("trash")
    }

    pub fn ensure_account(&self, name: &str) -> io::Result<()> {
        create_private_dir(&self.config_dir)?;
        create_private_dir(&self.cache_dir)?;
        create_private_dir(&self.account_dir(name))?;
        create_private_dir(&self.trash_dir(name))
    }
}

pub fn create_private_dir(dir: &Path) -> io::Result<()> {
    fs::DirBuilder::new()
        .recursive(true)
        .mode(0o700)
        .create(dir)?;
    fs::set_permissions(dir, fs::Permissions::from_mode(0o700))
}

pub fn write_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> {
    write_atomic_in(path, bytes, true)
}

/// For a folder another app owns: an existing parent keeps its mode, a missing one is created private.
pub fn write_atomic_keeping_dir_mode(path: &Path, bytes: &[u8]) -> io::Result<()> {
    write_atomic_in(path, bytes, false)
}

fn write_atomic_in(path: &Path, bytes: &[u8], private_dir: bool) -> io::Result<()> {
    // A symlink (say into a dotfiles repo) is written through, not replaced; a dangling one fails in canonicalize.
    if fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_symlink()) {
        return write_file_atomic(&fs::canonicalize(path)?, bytes);
    }
    let dir = path
        .parent()
        .ok_or_else(|| io::Error::other("path has no parent"))?;
    if private_dir || !dir.exists() {
        create_private_dir(dir)?;
    }
    write_file_atomic(path, bytes)
}

/// This binary's path for anything that outlives the process (service file, MCP host config, an auto-started
/// daemon). On Linux `current_exe` resolves symlinks, so a Homebrew install reports its versioned keg, which
/// `brew upgrade` later deletes, and an AppImage reports its temporary mount, which goes away when it exits.
pub fn stable_exe() -> io::Result<PathBuf> {
    let exe = std::env::current_exe()?;
    let appimage = std::env::var_os("APPIMAGE").map(PathBuf::from);
    let appdir = std::env::var_os("APPDIR").map(PathBuf::from);
    if let Some(image) = appimage_path(&exe, appimage.as_deref(), appdir.as_deref()) {
        return Ok(image);
    }
    Ok(match homebrew_opt_path(&exe) {
        Some(opt) if same_file(&opt, &exe) => opt,
        _ => exe,
    })
}

/// The app id when this process runs in a Flatpak sandbox, which sets `FLATPAK_ID`. The binary and config folders
/// there are the sandbox's own, so something the host runs later must go through `flatpak run`.
pub fn flatpak_id() -> Option<String> {
    std::env::var("FLATPAK_ID").ok().filter(|id| !id.is_empty())
}

/// The AppImage file this binary runs from: the runtime sets `APPIMAGE` and `APPDIR` (its mount), and only a binary
/// inside that mount is the AppImage; children of an AppImage inherit both variables.
fn appimage_path(exe: &Path, appimage: Option<&Path>, appdir: Option<&Path>) -> Option<PathBuf> {
    let (image, mount) = (appimage?, appdir?);
    exe.starts_with(mount).then(|| image.to_path_buf())
}

/// `<prefix>/Cellar/<formula>/<version>/<rest>` becomes `<prefix>/opt/<formula>/<rest>`, Homebrew's link to the
/// current keg.
fn homebrew_opt_path(exe: &Path) -> Option<PathBuf> {
    let parts: Vec<_> = exe.components().collect();
    let cellar = parts.iter().rposition(|c| c.as_os_str() == "Cellar")?;
    let (prefix, rest) = parts.split_at(cellar);
    let [_cellar, formula, _version, rest @ ..] = rest else {
        return None;
    };
    if rest.is_empty() {
        return None;
    }
    let mut opt: PathBuf = prefix.iter().collect();
    opt.push("opt");
    opt.push(formula);
    opt.extend(rest);
    Some(opt)
}

fn same_file(a: &Path, b: &Path) -> bool {
    match (fs::canonicalize(a), fs::canonicalize(b)) {
        (Ok(a), Ok(b)) => a == b,
        _ => false,
    }
}

/// Whether this process is the macOS app opened from Finder, the Dock or `open`: the binary sits in a bundle's
/// `Contents/MacOS`, got no arguments (very old macOS passes a `-psn_…` process serial number, which counts as none)
/// and stdin is not a terminal. Then the app opens the mail window instead of printing help; a terminal run of the
/// same binary (the cask links it as the `postvak` command) still prints help. `args` excludes argv\[0\].
pub fn launched_as_app(exe: &Path, args: &[OsString], stdin_is_terminal: bool) -> bool {
    let in_bundle = exe
        .parent()
        .is_some_and(|dir| dir.ends_with("Contents/MacOS"))
        && exe.ancestors().nth(3).is_some_and(|bundle| {
            bundle
                .extension()
                .is_some_and(|ext| ext.eq_ignore_ascii_case("app"))
        });
    let no_args = args
        .iter()
        .all(|a| a.to_str().is_some_and(|a| a.starts_with("-psn_")));
    in_bundle && no_args && !stdin_is_terminal
}

fn write_file_atomic(path: &Path, bytes: &[u8]) -> io::Result<()> {
    use std::io::Write;

    let dir = path
        .parent()
        .ok_or_else(|| io::Error::other("path has no parent"))?;
    let tmp = dir.join(format!(
        ".{}.{}.tmp",
        path.file_name().and_then(|n| n.to_str()).unwrap_or("file"),
        std::process::id()
    ));
    let mut file = fs::File::create(&tmp)?;
    file.set_permissions(fs::Permissions::from_mode(0o600))?;
    file.write_all(bytes)?;
    file.sync_all()?;
    fs::rename(&tmp, path)?;
    // The rename lives in the directory entry; without this a crash can bring back the old file or none.
    fs::File::open(dir)?.sync_all()?;
    Ok(())
}

/// A file's modification time, to notice edits by polling.
pub struct FileWatch {
    pub path: PathBuf,
    modified: Option<SystemTime>,
}

impl FileWatch {
    pub fn new(path: PathBuf) -> FileWatch {
        FileWatch {
            modified: modified_time(&path),
            path,
        }
    }

    /// Whether the modification time changed since the last call.
    pub fn changed(&mut self) -> bool {
        let modified = modified_time(&self.path);
        if modified == self.modified {
            return false;
        }
        self.modified = modified;
        true
    }
}

fn modified_time(path: &Path) -> Option<SystemTime> {
    fs::metadata(path).and_then(|meta| meta.modified()).ok()
}

#[cfg(test)]
mod tests {
    use super::*;

    fn args(list: &[&str]) -> Vec<OsString> {
        list.iter().map(OsString::from).collect()
    }

    const APP_EXE: &str = "/Applications/Postvak.app/Contents/MacOS/postvak";

    #[test]
    fn finder_launch_of_the_bundle_opens_the_app() {
        assert!(launched_as_app(Path::new(APP_EXE), &[], false));
        assert!(launched_as_app(
            Path::new("/Users/me/Downloads/Postvak.APP/Contents/MacOS/postvak"),
            &[],
            false
        ));
    }

    #[test]
    fn an_old_macos_process_serial_number_counts_as_no_arguments() {
        assert!(launched_as_app(
            Path::new(APP_EXE),
            &args(&["-psn_0_12345"]),
            false
        ));
    }

    #[test]
    fn any_real_argument_runs_the_cli() {
        assert!(!launched_as_app(
            Path::new(APP_EXE),
            &args(&["list"]),
            false
        ));
        assert!(!launched_as_app(
            Path::new(APP_EXE),
            &args(&["-psn_0_1", "--help"]),
            false
        ));
    }

    #[test]
    fn a_terminal_run_of_the_bundled_binary_prints_help() {
        assert!(!launched_as_app(Path::new(APP_EXE), &[], true));
    }

    #[test]
    fn a_binary_outside_a_bundle_runs_the_cli() {
        for exe in [
            "/opt/homebrew/bin/postvak",
            "/usr/local/Cellar/postvak/0.1.0/bin/postvak",
            "/tmp/Contents/MacOS/postvak",
            "/x/Postvak.app/Contents/Resources/postvak",
            "postvak",
        ] {
            assert!(!launched_as_app(Path::new(exe), &[], false), "{exe}");
        }
    }

    #[test]
    fn under_root_lays_out_three_dirs() {
        let root = tempfile::tempdir().unwrap();
        let p = Paths::under(root.path());
        assert_eq!(p.config_file(), root.path().join("config/config.toml"));
        assert_eq!(p.rules_file(), root.path().join("config/rules.toml"));
        assert_eq!(
            p.mail_db("work"),
            root.path().join("state/accounts/work/mail.db")
        );
        assert_eq!(
            p.trash_dir("work"),
            root.path().join("state/accounts/work/trash")
        );
        assert_eq!(
            p.update_check(),
            root.path().join("cache/update-check.json")
        );
    }

    #[test]
    fn ensure_account_creates_dirs() {
        let root = tempfile::tempdir().unwrap();
        let p = Paths::under(root.path());
        p.ensure_account("work").unwrap();
        assert!(p.trash_dir("work").is_dir());
        assert!(p.config_dir.is_dir());
    }

    #[test]
    fn write_atomic_replaces_content_and_leaves_no_tmp() {
        let root = tempfile::tempdir().unwrap();
        let file = root.path().join("a.txt");
        write_atomic(&file, b"one").unwrap();
        write_atomic(&file, b"two").unwrap();
        assert_eq!(fs::read(&file).unwrap(), b"two");
        let leftovers: Vec<_> = fs::read_dir(root.path()).unwrap().collect();
        assert_eq!(leftovers.len(), 1);
    }

    #[test]
    fn write_atomic_creates_private_dir_and_file() {
        let root = tempfile::tempdir().unwrap();
        let path = root.path().join("config").join("config.toml");
        write_atomic(&path, b"x").unwrap();
        let mode = |p: &Path| fs::metadata(p).unwrap().permissions().mode() & 0o777;
        assert_eq!(mode(path.parent().unwrap()), 0o700);
        assert_eq!(mode(&path), 0o600);
    }

    #[test]
    fn ensure_account_dirs_are_private() {
        let root = tempfile::tempdir().unwrap();
        let p = Paths::under(root.path());
        p.ensure_account("work").unwrap();

        let check_mode = |dir: &Path| {
            let mode = fs::metadata(dir).unwrap().permissions().mode();
            assert_eq!(mode & 0o777, 0o700, "directory {:?} is not 0700", dir);
        };

        check_mode(&p.state_dir);
        check_mode(&p.state_dir.join("accounts"));
        check_mode(&p.account_dir("work"));
        check_mode(&p.trash_dir("work"));
    }

    #[test]
    fn ensure_account_is_idempotent_across_accounts() {
        let root = tempfile::tempdir().unwrap();
        let p = Paths::under(root.path());
        p.ensure_account("work").unwrap();
        p.ensure_account("work").unwrap();
        p.ensure_account("personal").unwrap();
        assert!(p.trash_dir("work").is_dir());
        assert!(p.trash_dir("personal").is_dir());
    }

    #[test]
    fn an_appimage_reports_its_own_file_not_its_mount() {
        let exe = Path::new("/tmp/.mount_PostbXy12/usr/bin/postvak");
        let image = Path::new("/home/me/Apps/Postvak-x86_64.AppImage");
        let mount = Path::new("/tmp/.mount_PostbXy12");
        assert_eq!(
            appimage_path(exe, Some(image), Some(mount)),
            Some(image.to_path_buf())
        );
        // A postvak started from a shell that inherited another AppImage's environment is not that AppImage.
        let other = Path::new("/home/me/.cargo/bin/postvak");
        assert_eq!(appimage_path(other, Some(image), Some(mount)), None);
        assert_eq!(appimage_path(exe, None, Some(mount)), None);
        assert_eq!(appimage_path(exe, Some(image), None), None);
    }

    #[test]
    fn homebrew_keg_path_maps_to_opt() {
        let opt = |p: &str| homebrew_opt_path(Path::new(p));
        assert_eq!(
            opt("/home/linuxbrew/.linuxbrew/Cellar/postvak/0.3.0/bin/postvak"),
            Some(PathBuf::from(
                "/home/linuxbrew/.linuxbrew/opt/postvak/bin/postvak"
            ))
        );
        assert_eq!(
            opt("/opt/homebrew/Cellar/postvak/0.3.0_1/bin/postvak"),
            Some(PathBuf::from("/opt/homebrew/opt/postvak/bin/postvak"))
        );
        assert_eq!(opt("/home/me/.cargo/bin/postvak"), None);
        assert_eq!(opt("/opt/homebrew/Cellar/postvak/0.3.0"), None);
        assert_eq!(opt("/opt/homebrew/Cellar/postvak"), None);
    }

    #[test]
    fn opt_link_is_used_only_when_it_is_the_same_binary() {
        let root = tempfile::tempdir().unwrap();
        let keg = |v: &str| root.path().join(format!("Cellar/postvak/{v}/bin/postvak"));
        for v in ["0.3.0", "0.4.0"] {
            fs::create_dir_all(keg(v).parent().unwrap()).unwrap();
            fs::write(keg(v), v).unwrap();
        }
        fs::create_dir_all(root.path().join("opt")).unwrap();
        std::os::unix::fs::symlink(
            root.path().join("Cellar/postvak/0.4.0"),
            root.path().join("opt/postvak"),
        )
        .unwrap();
        let opt = homebrew_opt_path(&keg("0.4.0")).unwrap();
        assert_eq!(opt, root.path().join("opt/postvak/bin/postvak"));
        assert!(same_file(&opt, &keg("0.4.0")));
        // An older keg still running after an upgrade keeps its own path rather than pointing at another version.
        assert!(!same_file(
            &homebrew_opt_path(&keg("0.3.0")).unwrap(),
            &keg("0.3.0")
        ));
    }

    #[test]
    fn write_atomic_writes_through_a_symlink() {
        let root = tempfile::tempdir().unwrap();
        let real = root.path().join("dotfiles/rules.toml");
        fs::create_dir_all(real.parent().unwrap()).unwrap();
        fs::write(&real, "old").unwrap();
        let link = root.path().join("config/rules.toml");
        fs::create_dir_all(link.parent().unwrap()).unwrap();
        std::os::unix::fs::symlink(&real, &link).unwrap();
        write_atomic(&link, b"new").unwrap();
        assert!(
            fs::symlink_metadata(&link)
                .unwrap()
                .file_type()
                .is_symlink()
        );
        assert_eq!(fs::read_to_string(&real).unwrap(), "new");
    }

    #[test]
    fn write_atomic_refuses_a_dangling_symlink() {
        let root = tempfile::tempdir().unwrap();
        let link = root.path().join("rules.toml");
        std::os::unix::fs::symlink(root.path().join("missing/rules.toml"), &link).unwrap();
        assert!(write_atomic(&link, b"new").is_err());
        assert!(
            fs::symlink_metadata(&link)
                .unwrap()
                .file_type()
                .is_symlink()
        );
    }
}