amphetamine 0.1.0

Reclaim memory and win scheduler contention on Apple Silicon, safely.
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
//! Editing the config file from the command line.
//!
//! Edits go through `toml_edit` rather than a serialise round-trip so the
//! template's comments survive — they carry the safety rationale, and a tool
//! that silently ate its own documentation on first use would be a poor trade
//! for the convenience.
//!
//! Every write is validated by parsing the result back into [`Config`] and then
//! swapped into place atomically, so an interrupted edit leaves the previous
//! config intact rather than a half-written file.

use crate::{apps::App, config, guard};
use anyhow::{Context, Result, bail};
use std::path::Path;
use toml_edit::{Array, DocumentMut, Item, Value};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum List {
    Close,
    Protect,
    Demote,
}

impl List {
    /// The `[table] key` this list lives at.
    fn location(self) -> (&'static str, &'static str) {
        match self {
            Self::Close => ("apps", "close"),
            Self::Protect => ("apps", "protect"),
            Self::Demote => ("focus", "demote"),
        }
    }

    pub fn label(self) -> &'static str {
        match self {
            Self::Close => "close list",
            Self::Protect => "protect list",
            Self::Demote => "demote list",
        }
    }
}

/// What happened to one name, so the caller can explain rather than just exit 0.
#[derive(Debug, Clone)]
pub enum Change {
    Added(String),
    Removed(String),
    AlreadyPresent(String),
    NotPresent(String),
    /// Refused because the built-in denylist would ignore it anyway.
    Pointless {
        name: String,
        why: String,
    },
}

/// Adds names to a list, resolving each against what is actually running.
pub fn add(list: List, names: &[String], running: &[App]) -> Result<Vec<Change>> {
    add_at(&config::path(), list, names, running)
}

pub fn add_at(path: &Path, list: List, names: &[String], running: &[App]) -> Result<Vec<Change>> {
    edit(path, |doc| {
        let mut changes = Vec::new();
        for raw in names {
            let (name, app) = resolve(raw, running);

            // Adding a protected app to the close or demote list produces a
            // line that can never do anything. Say so instead of accepting it.
            if list != List::Protect
                && let Some(deny) = guard::protected_match(&identities(&name, app))
            {
                changes.push(Change::Pointless {
                    name,
                    why: format!("protected ({deny}) — it would never be touched"),
                });
                continue;
            }

            let arr = array_at(doc, list)?;
            if contains(arr, &name) {
                changes.push(Change::AlreadyPresent(name));
                continue;
            }
            push_on_own_line(arr, &name);
            changes.push(Change::Added(name));
        }
        Ok(changes)
    })
}

pub fn remove(list: List, names: &[String], running: &[App]) -> Result<Vec<Change>> {
    remove_at(&config::path(), list, names, running)
}

pub fn remove_at(
    path: &Path,
    list: List,
    names: &[String],
    running: &[App],
) -> Result<Vec<Change>> {
    edit(path, |doc| {
        let mut changes = Vec::new();
        for raw in names {
            let (name, _) = resolve(raw, running);
            let arr = array_at(doc, list)?;
            match position(arr, &name) {
                Some(i) => {
                    arr.remove(i);
                    changes.push(Change::Removed(name));
                }
                None => changes.push(Change::NotPresent(name)),
            }
        }
        Ok(changes)
    })
}

/// Replaces a list's membership among a known candidate set.
///
/// Used by the interactive picker. Names outside `candidates` are deliberately
/// left in place: the picker can only show apps that are running, and it must
/// not silently drop an entry for something that happens to be closed.
pub fn set_within(list: List, chosen: &[String], candidates: &[String]) -> Result<Vec<Change>> {
    set_within_at(&config::path(), list, chosen, candidates)
}

pub fn set_within_at(
    path: &Path,
    list: List,
    chosen: &[String],
    candidates: &[String],
) -> Result<Vec<Change>> {
    edit(path, |doc| {
        let mut changes = Vec::new();
        let arr = array_at(doc, list)?;

        for c in candidates {
            let present = contains(arr, c);
            let want = chosen.iter().any(|s| s.eq_ignore_ascii_case(c));
            match (present, want) {
                (false, true) => {
                    push_on_own_line(arr, c);
                    changes.push(Change::Added(c.clone()));
                }
                (true, false) => {
                    if let Some(i) = position(arr, c) {
                        arr.remove(i);
                        changes.push(Change::Removed(c.clone()));
                    }
                }
                _ => {}
            }
        }
        Ok(changes)
    })
}

/// Loads the document, applies `f`, validates, and swaps the file into place.
fn edit<T>(path: &Path, f: impl FnOnce(&mut DocumentMut) -> Result<T>) -> Result<T> {
    if !path.exists() {
        config::init(path)?;
    }
    let text =
        std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
    let mut doc: DocumentMut = text
        .parse()
        .with_context(|| format!("parsing {}", path.display()))?;

    let out = f(&mut doc)?;
    let rendered = doc.to_string();

    // The edit is only trustworthy if the result is still a valid config.
    // Catching it here means a bad write never reaches disk.
    toml::from_str::<config::Config>(&rendered)
        .context("the edit would have produced an invalid config; nothing was written")?;

    write_atomically(path, &rendered)?;
    Ok(out)
}

fn write_atomically(path: &Path, contents: &str) -> Result<()> {
    let tmp = path.with_extension("toml.tmp");
    std::fs::write(&tmp, contents).with_context(|| format!("writing {}", tmp.display()))?;
    // rename is atomic within a filesystem, so a crash mid-write leaves the
    // old config whole rather than a truncated one.
    std::fs::rename(&tmp, path).with_context(|| format!("replacing {}", path.display()))?;
    Ok(())
}

fn array_at(doc: &mut DocumentMut, list: List) -> Result<&mut Array> {
    let (table, key) = list.location();
    let tbl = doc
        .entry(table)
        .or_insert(Item::Table(toml_edit::Table::new()))
        .as_table_mut()
        .with_context(|| format!("[{table}] is not a table"))?;
    let item = tbl
        .entry(key)
        .or_insert(Item::Value(Value::Array(Array::new())));
    match item.as_array_mut() {
        Some(a) => Ok(a),
        None => bail!("{table}.{key} is not a list"),
    }
}

fn contains(arr: &Array, name: &str) -> bool {
    position(arr, name).is_some()
}

fn position(arr: &Array, name: &str) -> Option<usize> {
    arr.iter()
        .position(|v| v.as_str().is_some_and(|s| s.eq_ignore_ascii_case(name)))
}

/// Appends an entry on its own indented line, keeping these lists readable and
/// diffable rather than collapsing them into one long row.
fn push_on_own_line(arr: &mut Array, name: &str) {
    let mut v = Value::from(name);
    v.decor_mut().set_prefix("\n  ");
    arr.push_formatted(v);
    arr.set_trailing_comma(true);

    // An empty array's commented-out examples live in its trailing decor, so
    // overwriting that unconditionally would delete the very suggestions the
    // template exists to offer. Only supply a newline when there is nothing
    // there worth keeping.
    let trailing = arr.trailing().as_str().unwrap_or_default().to_owned();
    if trailing.trim().is_empty() {
        arr.set_trailing("\n");
    }
}

/// Maps user input onto a running app, preferring the app's own spelling.
///
/// Typing `slack` should store `Slack`, so the config reads the way the app
/// presents itself rather than the way it was typed.
fn resolve<'a>(input: &str, running: &'a [App]) -> (String, Option<&'a App>) {
    match running
        .iter()
        .find(|a| guard::identity_matches(&a.identities(), input))
    {
        Some(app) => (app.name.clone(), Some(app)),
        None => (input.to_owned(), None),
    }
}

fn identities<'a>(name: &'a str, app: Option<&'a App>) -> Vec<&'a str> {
    match app {
        Some(a) => a.identities(),
        None => vec![name],
    }
}

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

    /// A scratch config file. Each test owns its own path, so the suite stays
    /// safe to run in parallel — no process-wide state is involved.
    struct Scratch(std::path::PathBuf);

    impl Scratch {
        fn new(tag: &str) -> Self {
            let p = std::env::temp_dir().join(format!("amph-manage-{tag}.toml"));
            std::fs::remove_file(&p).ok();
            Self(p)
        }
        fn path(&self) -> &Path {
            &self.0
        }
        fn read(&self) -> String {
            std::fs::read_to_string(&self.0).unwrap()
        }
        fn cfg(&self) -> config::Config {
            toml::from_str(&self.read()).unwrap()
        }
    }

    impl Drop for Scratch {
        fn drop(&mut self) {
            std::fs::remove_file(&self.0).ok();
        }
    }

    #[test]
    fn add_creates_config_and_appends_without_eating_comments() {
        let s = Scratch::new("comments");
        let changes = add_at(s.path(), List::Close, &["Spotify".into()], &[]).unwrap();
        assert!(matches!(changes[0], Change::Added(_)));

        let text = s.read();
        // The rationale comments in the shipped template must survive an edit;
        // they are where the safety reasoning is written down.
        assert!(
            text.contains("Nothing is closed or reprioritised until you list it below"),
            "template prose was lost"
        );
        assert!(
            text.contains("# \"Slack\","),
            "commented examples were lost"
        );
        assert!(
            text.contains("skip_running_apps"),
            "unrelated sections were lost"
        );
        assert!(text.contains("\"Spotify\""));

        assert_eq!(s.cfg().apps.close, vec!["Spotify"]);
    }

    #[test]
    fn add_is_idempotent_and_case_insensitive() {
        let s = Scratch::new("idem");
        add_at(s.path(), List::Close, &["Spotify".into()], &[]).unwrap();
        let again = add_at(s.path(), List::Close, &["spotify".into()], &[]).unwrap();
        assert!(matches!(again[0], Change::AlreadyPresent(_)));
        assert_eq!(s.cfg().apps.close.len(), 1, "duplicate entry was added");
    }

    #[test]
    fn adding_a_protected_app_is_refused_rather_than_silently_useless() {
        let s = Scratch::new("protected");
        for name in ["Cursor", "Finder", "Docker"] {
            let changes = add_at(s.path(), List::Close, &[name.into()], &[]).unwrap();
            assert!(
                matches!(changes[0], Change::Pointless { .. }),
                "{name} should have been refused"
            );
        }
        assert!(s.cfg().apps.close.is_empty());
    }

    #[test]
    fn protected_apps_may_still_be_added_to_the_protect_list() {
        let s = Scratch::new("protectlist");
        let changes = add_at(s.path(), List::Protect, &["Slack".into()], &[]).unwrap();
        assert!(matches!(changes[0], Change::Added(_)));
        assert_eq!(s.cfg().apps.protect, vec!["Slack"]);
    }

    #[test]
    fn remove_reports_absence_instead_of_failing() {
        let s = Scratch::new("remove");
        add_at(
            s.path(),
            List::Close,
            &["Spotify".into(), "Slack".into()],
            &[],
        )
        .unwrap();

        let gone = remove_at(s.path(), List::Close, &["SPOTIFY".into()], &[]).unwrap();
        assert!(matches!(gone[0], Change::Removed(_)));
        let missing = remove_at(s.path(), List::Close, &["Nothing".into()], &[]).unwrap();
        assert!(matches!(missing[0], Change::NotPresent(_)));

        assert_eq!(s.cfg().apps.close, vec!["Slack"]);
    }

    #[test]
    fn set_within_leaves_entries_it_was_not_shown() {
        let s = Scratch::new("setwithin");
        add_at(
            s.path(),
            List::Close,
            &["Spotify".into(), "Discord".into()],
            &[],
        )
        .unwrap();

        // The picker only saw Spotify and Slack; Discord was not running.
        let candidates = vec!["Spotify".to_string(), "Slack".to_string()];
        set_within_at(s.path(), List::Close, &["Slack".into()], &candidates).unwrap();

        let close = s.cfg().apps.close;
        assert!(close.contains(&"Slack".to_string()), "selection not added");
        assert!(
            !close.contains(&"Spotify".to_string()),
            "deselection not removed"
        );
        assert!(
            close.contains(&"Discord".to_string()),
            "an entry the picker never showed was dropped"
        );
    }

    #[test]
    fn demote_writes_to_the_focus_table() {
        let s = Scratch::new("demote");
        add_at(s.path(), List::Demote, &["Spotify".into()], &[]).unwrap();
        let cfg = s.cfg();
        assert_eq!(cfg.focus.demote, vec!["Spotify"]);
        assert!(cfg.apps.close.is_empty(), "wrote to the wrong list");
    }

    #[test]
    fn a_corrupt_edit_never_reaches_disk() {
        let s = Scratch::new("corrupt");
        add_at(s.path(), List::Close, &["Spotify".into()], &[]).unwrap();
        let before = s.read();

        // Introduce a key the config rejects, and confirm the guard refuses it.
        let attempt = edit(s.path(), |doc| {
            doc["apps"]["not_a_real_key"] = toml_edit::value("x");
            Ok(())
        });
        assert!(attempt.is_err(), "invalid edit was accepted");
        assert_eq!(s.read(), before, "file was modified despite the failure");
    }

    #[test]
    fn repeated_edits_stay_parseable_and_readable() {
        let s = Scratch::new("churn");
        for name in ["Slack", "Spotify", "Messages", "Discord", "Telegram"] {
            add_at(s.path(), List::Close, &[name.into()], &[]).unwrap();
        }
        remove_at(s.path(), List::Close, &["Messages".into()], &[]).unwrap();
        add_at(s.path(), List::Close, &["Notion".into()], &[]).unwrap();

        let cfg = s.cfg();
        assert_eq!(cfg.apps.close.len(), 5);
        assert!(!cfg.apps.close.contains(&"Messages".to_string()));
        // Entries stay one-per-line rather than collapsing into a single row.
        let text = s.read();
        assert!(
            text.contains("\n  \"Notion\","),
            "formatting degraded:\n{text}"
        );
    }
}