openlogi-core 0.8.14

Core types, config, and paths for OpenLogi. No I/O specifics.
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
//! Loading and saving the file: the canonical example, backups and rotation, a missing file, comment-preserving tracked saves, and what the TOML layout omits.

use super::*;

#[test]
fn canonical_configuration_example_parses() {
    let body = include_str!("../../../../../docs/config.example.toml");
    let config: Config = toml::from_str(body).expect("documented config must parse");
    assert_eq!(config.schema_version, SCHEMA_VERSION);
    let bindings = config.stored_bindings("receiver:aabbccdd:slot:1");
    let Some(Binding::LongPress(long_press)) = bindings.get(&ButtonId::DpiToggle) else {
        panic!("documented long-press binding should keep its shape");
    };
    assert_eq!(long_press.short(), &Action::ShowDesktop);
    assert_eq!(long_press.long(), &Action::MissionControl);
}

#[test]
fn first_save_preserves_the_previous_config_for_recovery() {
    let dir = tempfile::tempdir().expect("tempdir");
    let path = dir.path().join("config.toml");
    let backup = dir.path().join("config.toml.backup.1");
    let original = b"schema_version = 3\nselected_device = \"original\"\n";
    fs::write(&path, original).expect("write original config");

    let mut config = Config {
        selected_device: Some("replacement".to_string()),
        ..Config::default()
    };
    config.save_to_path(&path).expect("save replacement");
    assert_eq!(fs::read(&backup).expect("read backup"), original);

    config.selected_device = Some("second-save".to_string());
    config.save_to_path(&path).expect("save again");
    assert_eq!(
        fs::read(&backup).expect("read original backup"),
        original,
        "later saves in one process must not replace the recovery copy"
    );
}

#[test]
fn migrated_load_backs_up_the_pre_migration_source_exactly_once() {
    // A key-rewriting migration touches every entry, so the pre-migration
    // file is the user's only recovery path if the rewrite is wrong. The
    // backup must hold the source exactly as loaded — not the migrated,
    // re-serialized output — and must not be retaken on a later save from
    // the same `ConfigFile` (`migrated_from` is consumed with `Option::take`).
    let dir = tempfile::tempdir().expect("tempdir");
    let path = dir.path().join("config.toml");
    // Appended to the full file name, not substituted for its extension:
    // `config.toml` + `.v4.bak`, never `config.v4.bak`.
    let backup = dir.path().join("config.toml.v4.bak");
    let original =
        b"schema_version = 4\n\n[devices.\"direct:046d:c08d:unit:6be9d300\"]\ninvert_scroll = true\n";
    fs::write(&path, original).expect("write v4 config");

    let (config, mut file) = ConfigFile::load_from_path(&path).expect("load v4 config");
    assert!(
        config.devices.contains_key("unit:6be9d300"),
        "sanity: the key migration ran"
    );

    file.save(&config).expect("save migrated config");
    assert_eq!(
        fs::read(&backup).expect("read migration backup"),
        original,
        "the backup preserves the pre-migration source, not the rewritten output"
    );

    // Replace the backup with a sentinel that `original` never equals, so a
    // second write is observable even though it would write the same bytes
    // as the first: re-asserting against `original` here cannot distinguish
    // "not rewritten" from "rewritten with identical content", which is
    // exactly the regression this test exists to catch (`migrated_from`
    // going from a consuming `Option::take` to a plain read).
    let sentinel = b"sentinel: a second save must not touch this file";
    fs::write(&backup, sentinel).expect("overwrite backup with sentinel");

    let mut second = config.clone();
    second.selected_device = Some("unit:6be9d300".to_string());
    file.save(&second)
        .expect("save again from the same ConfigFile");
    assert_eq!(
        fs::read(&backup).expect("read backup after second save"),
        sentinel,
        "a second save from the same ConfigFile must not rewrite the backup"
    );
}

#[test]
fn config_backups_rotate_between_generations() {
    let dir = tempfile::tempdir().expect("tempdir");
    let path = dir.path().join("config.toml");
    super::backup_existing_config(&path, b"first").expect("back up first generation");
    super::backup_existing_config(&path, b"second").expect("back up second generation");

    assert_eq!(
        fs::read(super::config_backup_path(&path, 1).expect("backup path"))
            .expect("read newest backup"),
        b"second"
    );
    assert_eq!(
        fs::read(super::config_backup_path(&path, 2).expect("backup path"))
            .expect("read older backup"),
        b"first"
    );
}

#[test]
fn missing_file_yields_default() {
    let dir = tempfile::tempdir().expect("tempdir");
    let path = dir.path().join("nonexistent.toml");
    let cfg = Config::load_from_path(&path).expect("load");
    assert_eq!(cfg.schema_version, SCHEMA_VERSION);
    assert!(cfg.devices.is_empty());
}

#[test]
fn human_readable_toml_layout() {
    let mut cfg = Config::default();
    cfg.set_binding(
        "2b042",
        ButtonId::Back,
        Binding::Single(Action::BrowserBack),
    );
    let body = toml::to_string_pretty(&cfg).expect("serialize");

    // The key only contains [A-Za-z0-9_], so TOML emits it as a bare-word
    // table key (no surrounding quotes). The test asserts the observable
    // structure rather than locking in a specific quoting.
    assert!(
        body.contains(&format!("schema_version = {SCHEMA_VERSION}")),
        "got: {body}"
    );
    assert!(body.contains("[devices.2b042.bindings]"), "got: {body}");
    // A `Single` binding serializes byte-identically to the pre-v2 bare
    // `Action`, so the leaf line is unchanged.
    assert!(body.contains("Back = \"BrowserBack\""), "got: {body}");
}

#[test]
fn selected_device_roundtrips() {
    let mut cfg = Config::default();
    assert_eq!(cfg.selected_device(), None);
    cfg.set_selected_device(Some("2b042".into()));
    let parsed = write_and_read(&cfg);
    assert_eq!(parsed.selected_device(), Some("2b042"));
}

#[test]
fn cleared_selected_device_omits_field() {
    let mut cfg = Config::default();
    cfg.set_selected_device(Some("2b042".into()));
    cfg.set_selected_device(None);
    let body = toml::to_string_pretty(&cfg).expect("serialize");
    assert!(
        !body.contains("selected_device"),
        "cleared selection should not appear: {body}"
    );
}

#[test]
fn empty_device_block_is_skipped_in_output() {
    // Inserting then clearing should not leave a [devices."x"] header
    // with no bindings under it (skip_serializing_if on bindings).
    let mut cfg = Config::default();
    cfg.set_binding("2b042", ButtonId::Back, Binding::Single(Action::Copy));
    cfg.devices
        .get_mut("2b042")
        .expect("entry")
        .bindings
        .clear();
    let body = toml::to_string_pretty(&cfg).expect("serialize");
    assert!(
        !body.contains("Back"),
        "cleared bindings should not appear: {body}"
    );
}

#[test]
fn tracked_save_preserves_comments_and_rejects_concurrent_edits() {
    let dir = tempfile::tempdir().expect("tempdir");
    let path = dir.path().join("config.toml");
    fs::write(
        &path,
        "# keep this comment\nschema_version = 6\nselected_device = \"one\" # and this one\n",
    )
    .expect("write");
    let (mut config, mut file) = ConfigFile::load_from_path(&path).expect("load tracked");
    config.set_selected_device(Some("two".into()));
    file.save(&config).expect("save tracked");
    let saved = fs::read_to_string(&path).expect("read saved");
    assert!(saved.contains("# keep this comment"));
    assert!(saved.contains("# and this one"));
    assert!(saved.contains("selected_device = \"two\""));

    let external = format!("{saved}# external editor\n");
    fs::write(&path, &external).expect("external edit");
    config.set_selected_device(Some("three".into()));
    assert_matches!(file.save(&config), Err(ConfigError::Conflict { .. }));
    assert_eq!(fs::read_to_string(path).expect("read conflict"), external);
}

#[test]
fn tracked_save_respects_the_writer_lock_and_releases_it_after_errors() {
    let dir = tempfile::tempdir().expect("tempdir");
    let path = dir.path().join("config.toml");
    let lock_path = dir.path().join("config.toml.lock");
    let original = "schema_version = 6\nselected_device = \"original\"\n";
    fs::write(&path, original).expect("write original");
    let (mut config, mut file) = ConfigFile::load_from_path(&path).expect("load");
    let (stale_config, mut stale_file) = ConfigFile::load_from_path(&path).expect("load stale");
    config.set_selected_device(Some("replacement".into()));
    let lock = fs::OpenOptions::new()
        .read(true)
        .write(true)
        .create(true)
        .truncate(false)
        .open(&lock_path)
        .expect("open lock");
    lock.try_lock().expect("hold writer lock");
    let error = file
        .save(&config)
        .expect_err("another writer holds the lock");
    assert_matches!(error, ConfigError::Write { source, .. }
        if source.kind() == std::io::ErrorKind::WouldBlock);
    assert_eq!(fs::read_to_string(&path).expect("read unchanged"), original);
    assert!(!dir.path().join("config.toml.backup.1").exists());
    drop(lock);

    file.save(&config).expect("retry after release");
    assert_eq!(
        Config::load_from_path(&path)
            .expect("reload")
            .selected_device(),
        Some("replacement")
    );
    assert_matches!(
        stale_file.save(&stale_config),
        Err(ConfigError::Conflict { .. })
    );
    // Reopen the same persistent sidecar after both success and conflict.
    let lock = fs::OpenOptions::new()
        .read(true)
        .write(true)
        .open(&lock_path)
        .expect("sidecar remains");
    lock.try_lock().expect("neither save leaked its lock");
}

#[test]
fn a_failed_backup_write_leaves_the_migration_backup_still_owed() {
    // The pre-migration file is the user's only recovery path from a
    // key-rewriting migration. If the backup write fails — full disk,
    // read-only directory — and the debt is cleared anyway, the next save
    // that *does* succeed overwrites the v4 file with migrated content and no copy
    // ever exists.
    let dir = tempfile::tempdir().expect("tempdir");
    let path = dir.path().join("config.toml");
    // Appended to the full file name, not substituted for its extension:
    // `config.toml` + `.v4.bak`, never `config.v4.bak`.
    let backup = dir.path().join("config.toml.v4.bak");
    let original =
        b"schema_version = 4\n\n[devices.\"direct:046d:c08d:unit:6be9d300\"]\ninvert_scroll = true\n";
    fs::write(&path, original).expect("write v4 config");
    // A directory where the backup file belongs: the write fails, and
    // nothing about the config file itself is wrong.
    fs::create_dir(&backup).expect("occupy the backup path");

    let (config, mut file) = ConfigFile::load_from_path(&path).expect("load v4 config");
    let error = file.save(&config).expect_err("the backup write must fail");
    assert_matches!(error, ConfigError::Write { .. });
    assert_eq!(
        fs::read(&path).expect("read config"),
        original,
        "a failed save leaves the v4 file in place"
    );

    fs::remove_dir(&backup).expect("free the backup path");
    file.save(&config).expect("save once the path is writable");
    assert_eq!(
        fs::read(&backup).expect("read migration backup"),
        original,
        "the retried save still has the pre-migration source to write"
    );
}

#[cfg(unix)]
#[test]
fn saving_through_a_symlink_writes_the_target_and_keeps_the_link() {
    let dir = tempfile::tempdir().expect("tempdir");
    let dotfiles = dir.path().join("dotfiles/openlogi");
    let config_dir = dir.path().join("config/openlogi");
    fs::create_dir_all(&dotfiles).expect("create dotfiles dir");
    fs::create_dir_all(&config_dir).expect("create config dir");
    let target = dotfiles.join("config.toml");
    let link = config_dir.join("config.toml");
    let original = "# dotfiles config\nschema_version = 6\nselected_device = \"one\"\n";
    fs::write(&target, original).expect("write target");
    std::os::unix::fs::symlink("../../dotfiles/openlogi/config.toml", &link).expect("symlink");

    let (mut config, mut file) = ConfigFile::load_from_path(&link).expect("load through link");
    config.set_selected_device(Some("two".into()));
    file.save(&config).expect("save through link");
    assert!(
        fs::symlink_metadata(&link).expect("stat link").is_symlink(),
        "saving must preserve the symlink"
    );
    assert_eq!(
        Config::load_from_path(&target)
            .expect("read target")
            .selected_device(),
        Some("two")
    );
    let backup = config_dir.join("config.toml.backup.1");
    assert_eq!(fs::read_to_string(&backup).expect("read backup"), original);
    assert_eq!(
        fs::read_to_string(config_dir.join("config.toml.v6.bak")).expect("read migration backup"),
        original
    );
    assert!(!dotfiles.join("config.toml.backup.1").exists());
    assert!(!dotfiles.join("config.toml.v6.bak").exists());

    config.set_selected_device(Some("three".into()));
    file.save(&config).expect("second save through link");
    assert_eq!(
        Config::load_from_path(&target)
            .expect("read second save")
            .selected_device(),
        Some("three")
    );
    assert_eq!(
        fs::read_to_string(&backup).expect("read original backup"),
        original
    );

    let external = format!(
        "{}# external edit\n",
        fs::read_to_string(&target).expect("read target")
    );
    fs::write(&target, &external).expect("edit target externally");
    assert_matches!(file.save(&config), Err(ConfigError::Conflict { .. }));
    assert_eq!(
        fs::read_to_string(&target).expect("read external edit"),
        external
    );
    assert!(
        fs::symlink_metadata(&link)
            .expect("stat link after conflict")
            .is_symlink()
    );
}

#[cfg(unix)]
#[test]
fn symlink_aliases_share_the_target_writer_lock() {
    let dir = tempfile::tempdir().expect("tempdir");
    let target = dir.path().join("target.toml");
    let first = dir.path().join("first.toml");
    let second = dir.path().join("second.toml");
    let original = "schema_version = 6\nselected_device = \"original\"\n";
    fs::write(&target, original).expect("write target");
    std::os::unix::fs::symlink("target.toml", &first).expect("first alias");
    std::os::unix::fs::symlink(&target, &second).expect("second alias");
    let (mut config, mut first_file) =
        ConfigFile::load_from_path(&first).expect("load first alias");
    let (stale_config, mut second_file) =
        ConfigFile::load_from_path(&second).expect("load second alias");
    config.set_selected_device(Some("replacement".into()));
    let lock = fs::OpenOptions::new()
        .read(true)
        .write(true)
        .create(true)
        .truncate(false)
        .open(target.with_added_extension("lock"))
        .expect("open target lock");
    lock.try_lock().expect("hold target lock");

    for file in [&mut first_file, &mut second_file] {
        let error = file
            .save(&config)
            .expect_err("the target already has a writer");
        assert_matches!(error, ConfigError::Write { source, .. }
            if source.kind() == std::io::ErrorKind::WouldBlock);
    }
    assert_eq!(
        fs::read_to_string(&target).expect("read unchanged target"),
        original
    );
    for alias in [&first, &second] {
        assert!(
            fs::symlink_metadata(alias)
                .expect("stat alias")
                .is_symlink()
        );
        assert!(
            !super::config_backup_path(alias, 1)
                .expect("backup path")
                .exists()
        );
        assert!(!alias.with_added_extension("v6.bak").exists());
    }
    drop(lock);

    first_file
        .save(&config)
        .expect("retry after releasing target lock");
    assert_matches!(
        second_file.save(&stale_config),
        Err(ConfigError::Conflict { .. })
    );
    assert_eq!(
        Config::load_from_path(&target)
            .expect("read saved target")
            .selected_device(),
        Some("replacement")
    );
}

#[cfg(unix)]
#[test]
fn saving_through_a_dangling_symlink_chain_creates_the_target() {
    let dir = tempfile::tempdir().expect("tempdir");
    let config_dir = dir.path().join("config/openlogi");
    fs::create_dir_all(&config_dir).expect("create config dir");
    let target = dir.path().join("dotfiles/openlogi/config.toml");
    let intermediate = config_dir.join("target.toml");
    let link = config_dir.join("config.toml");
    std::os::unix::fs::symlink("../../dotfiles/openlogi/config.toml", &intermediate)
        .expect("target link");
    std::os::unix::fs::symlink("target.toml", &link).expect("config link");
    let (mut config, mut file) = ConfigFile::load_from_path(&link).expect("load dangling link");
    config.set_selected_device(Some("new".into()));

    file.save(&config).expect("create target through links");
    for path in [&link, &intermediate] {
        assert!(fs::symlink_metadata(path).expect("stat link").is_symlink());
    }
    assert_eq!(
        Config::load_from_path(&target)
            .expect("read created target")
            .selected_device(),
        Some("new")
    );
    assert!(!config_dir.join("config.toml.backup.1").exists());
}

#[cfg(unix)]
#[test]
fn symlink_resolution_follows_the_full_hop_limit() {
    let dir = tempfile::tempdir().expect("tempdir");
    let target = dir.path().join("config.toml");
    fs::write(&target, "").expect("write target");
    let link = |hop: usize| dir.path().join(format!("link{hop}"));
    let mut previous = target.clone();
    for hop in 1..=41 {
        std::os::unix::fs::symlink(&previous, link(hop)).expect("symlink");
        previous = link(hop);
    }

    assert_eq!(
        super::resolve_symlinks(&link(40)).expect("40 hops is within the limit"),
        target
    );
    assert!(
        super::resolve_symlinks(&link(41)).is_err(),
        "41 hops exceeds the limit"
    );
}