jj-hooks 0.3.4

Run pre-commit / lefthook / hk hooks against jj bookmark pushes
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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
use jj_hooks::init::{self, AddedItems, InitOutcome, InitPlan, ScriptedPrompter, add_jjui_actions};
use jj_hooks::runner::Runner;
use std::path::PathBuf;

#[test]
fn plan_with_all_yes() {
    let mut prompter = ScriptedPrompter::new(vec![true, true, true]);
    let plan = init::plan(Some(Runner::PreCommit), &mut prompter).unwrap();
    assert_eq!(
        plan,
        InitPlan {
            install_alias: true,
            advance_bookmarks: true,
            install_jjui_actions: true,
        }
    );
}

#[test]
fn plan_with_all_no() {
    let mut prompter = ScriptedPrompter::new(vec![false, false, false]);
    let plan = init::plan(Some(Runner::Lefthook), &mut prompter).unwrap();
    assert_eq!(
        plan,
        InitPlan {
            install_alias: false,
            advance_bookmarks: false,
            install_jjui_actions: false,
        }
    );
}

#[test]
fn plan_mixed() {
    let mut prompter = ScriptedPrompter::new(vec![true, false, true]);
    let plan = init::plan(Some(Runner::Hk), &mut prompter).unwrap();
    assert_eq!(
        plan,
        InitPlan {
            install_alias: true,
            advance_bookmarks: false,
            install_jjui_actions: true,
        }
    );
}

#[test]
fn plan_with_no_runner_detected_still_prompts() {
    let mut prompter = ScriptedPrompter::new(vec![true, true, true]);
    let plan = init::plan(None, &mut prompter).unwrap();
    assert_eq!(
        plan,
        InitPlan {
            install_alias: true,
            advance_bookmarks: true,
            install_jjui_actions: true,
        }
    );
}

#[test]
fn apply_writes_expected_config_keys() {
    let tmp = tempfile::TempDir::new().unwrap();
    let config_path: PathBuf = tmp.path().join("config.toml");
    std::fs::write(&config_path, "").unwrap();

    let plan = InitPlan {
        install_alias: true,
        advance_bookmarks: true,
        install_jjui_actions: false,
    };
    let outcome = init::apply(&plan, Some(&config_path), None).unwrap();
    assert_eq!(
        outcome,
        InitOutcome {
            alias_set: true,
            advance_bookmarks_set: true,
            jjui_actions_added: AddedItems::default(),
        }
    );

    let contents = std::fs::read_to_string(&config_path).unwrap();
    assert!(
        contents.contains(r#"push = ["util", "exec", "--", "jj-hp", "push"]"#),
        "alias not written:\n{contents}"
    );
    assert!(
        contents.contains("advance-bookmarks = true"),
        "advance-bookmarks not written:\n{contents}"
    );
}

#[test]
fn apply_skips_when_all_false() {
    let tmp = tempfile::TempDir::new().unwrap();
    let config_path = tmp.path().join("config.toml");
    std::fs::write(&config_path, "").unwrap();

    let plan = InitPlan {
        install_alias: false,
        advance_bookmarks: false,
        install_jjui_actions: false,
    };
    let outcome = init::apply(&plan, Some(&config_path), None).unwrap();
    assert_eq!(
        outcome,
        InitOutcome {
            alias_set: false,
            advance_bookmarks_set: false,
            jjui_actions_added: AddedItems::default(),
        }
    );

    let contents = std::fs::read_to_string(&config_path).unwrap();
    assert!(
        !contents.contains("jj-hooks"),
        "should be empty:\n{contents}"
    );
}

#[test]
fn add_jjui_actions_to_empty_config() {
    let (output, added) = add_jjui_actions("").unwrap();
    assert!(added.added_jj_push);
    assert!(added.added_jj_push_selected);
    assert!(added.added_binding_x_p);
    assert!(added.added_binding_x_p_caps);

    // Re-parse so we don't depend on the pretty-printer's array layout.
    let parsed: toml::Table = output.parse().unwrap();
    let actions = parsed["actions"].as_array().unwrap();
    let action_names: Vec<&str> = actions
        .iter()
        .filter_map(|v| v.get("name").and_then(|n| n.as_str()))
        .collect();
    assert!(action_names.contains(&"jj-hp-push"), "{action_names:?}");
    assert!(
        action_names.contains(&"jj-hp-push-selected"),
        "{action_names:?}"
    );

    let bindings = parsed["bindings"].as_array().unwrap();
    let mut found_xp = false;
    let mut found_xp_caps = false;
    let mut xp_desc = "";
    let mut xp_caps_desc = "";
    for b in bindings {
        let action = b.get("action").and_then(|v| v.as_str()).unwrap_or("");
        let seq: Vec<&str> = b
            .get("seq")
            .and_then(|v| v.as_array())
            .map(|a| a.iter().filter_map(|v| v.as_str()).collect())
            .unwrap_or_default();
        let desc = b.get("desc").and_then(|v| v.as_str()).unwrap_or("");
        // Post-2026-05 swap: jj-hp-push-selected (the common case)
        // takes lowercase `x p`; jj-hp-push (push entire stack)
        // takes uppercase `x P`.
        if action == "jj-hp-push-selected" && seq == ["x", "p"] {
            found_xp = true;
            xp_desc = desc;
        }
        if action == "jj-hp-push" && seq == ["x", "P"] {
            found_xp_caps = true;
            xp_caps_desc = desc;
        }
    }
    assert!(found_xp, "expected jj-hp-push-selected bound to x p");
    assert!(found_xp_caps, "expected jj-hp-push bound to x P");
    assert_eq!(xp_desc, "jj-hp push selected bookmark(s)");
    assert_eq!(xp_caps_desc, "jj-hp push");

    // The lua bodies should invoke jj-hp directly.
    let lua_bodies: Vec<&str> = actions
        .iter()
        .filter_map(|v| v.get("lua").and_then(|l| l.as_str()))
        .collect();
    for lua in &lua_bodies {
        assert!(
            lua.contains("jj-hp"),
            "lua body should call jj-hp directly:\n{lua}"
        );
        assert!(
            !lua.contains("jj_async(\"push\""),
            "lua should not depend on the `jj push` alias:\n{lua}"
        );
    }
}

#[test]
fn add_jjui_actions_idempotent_on_second_run() {
    let (first, _) = add_jjui_actions("").unwrap();
    let (second, added) = add_jjui_actions(&first).unwrap();

    assert!(!added.added_jj_push);
    assert!(!added.added_jj_push_selected);
    assert!(!added.added_binding_x_p);
    assert!(!added.added_binding_x_p_caps);

    let parsed: toml::Table = second.parse().unwrap();
    let actions = parsed["actions"].as_array().unwrap();
    let count = actions
        .iter()
        .filter(|v| v.get("name").and_then(|n| n.as_str()) == Some("jj-hp-push"))
        .count();
    assert_eq!(count, 1);
}

#[test]
fn add_jjui_actions_preserves_existing_user_actions() {
    let existing = r#"
[[actions]]
name = "my-custom"
lua = "print('hi')"

[[bindings]]
action = "my-custom"
seq = ["q"]
scope = "revisions"
desc = "quit"
"#;
    let (output, added) = add_jjui_actions(existing).unwrap();

    assert!(added.added_jj_push);
    assert!(output.contains(r#"name = "my-custom""#), "{output}");
    assert!(output.contains(r#"["q"]"#), "{output}");
    assert!(output.contains(r#"name = "jj-hp-push""#), "{output}");
}

#[test]
fn add_jjui_actions_keeps_user_owned_jj_push_when_name_already_taken() {
    // User has *their own* action literally named "jj-push" with a custom
    // lua body. We must not rename or clobber it.
    let existing = r#"
[[actions]]
name = "jj-push"
lua = "print('user version')"
"#;
    let (output, added) = add_jjui_actions(existing).unwrap();
    assert!(
        !added.added_jj_push,
        "should not have added (user already has one with custom lua)"
    );
    assert!(output.contains("print('user version')"));
    // jj-hp-push-selected should still get added since its name is free.
    assert!(added.added_jj_push_selected);
    assert!(output.contains(r#"name = "jj-hp-push-selected""#));
}

#[test]
fn add_jjui_actions_renames_old_managed_jj_push_to_jj_hp_push() {
    // Existing config has the OLD action/binding names but lua bodies
    // we know we wrote (i.e. they're auto-installed, not user-customized).
    // Expected: rename `jj-push` → `jj-hp-push`, rename the binding's
    // `action` reference and update its `desc`.
    let existing = r#"
[[actions]]
name = "jj-push"
lua = """
  jj_async("util", "exec", "--", "jj-hp", "push")
  revisions.refresh()
"""

[[actions]]
name = "jj-push-selected"
lua = """
  jj_async("util", "exec", "--", "jj-hp", "push", "-r", context.commit_id())
  revisions.refresh()
"""

[[bindings]]
action = "jj-push"
seq = ["x", "p"]
scope = "revisions"
desc = "jj push"

[[bindings]]
action = "jj-push-selected"
seq = ["x", "P"]
scope = "revisions"
desc = "jj push selected bookmark(s)"
"#;
    let (output, added) = add_jjui_actions(existing).unwrap();

    // Nothing was "added" — everything was renamed in place.
    assert!(!added.added_jj_push, "should be a rename, not an add");
    assert!(
        !added.added_jj_push_selected,
        "should be a rename, not an add"
    );

    let parsed: toml::Table = output.parse().unwrap();
    let action_names: Vec<&str> = parsed["actions"]
        .as_array()
        .unwrap()
        .iter()
        .filter_map(|v| v.get("name").and_then(|n| n.as_str()))
        .collect();
    assert!(
        action_names.contains(&"jj-hp-push"),
        "expected rename to jj-hp-push: {action_names:?}"
    );
    assert!(
        action_names.contains(&"jj-hp-push-selected"),
        "expected rename to jj-hp-push-selected: {action_names:?}"
    );
    assert!(
        !action_names.contains(&"jj-push"),
        "old name should be gone: {action_names:?}"
    );

    // Bindings should have been rewired to the new action name AND
    // their descs updated.
    let bindings = parsed["bindings"].as_array().unwrap();
    let mut found_xp = false;
    let mut found_xp_caps = false;
    for b in bindings {
        let action = b.get("action").and_then(|v| v.as_str()).unwrap_or("");
        let desc = b.get("desc").and_then(|v| v.as_str()).unwrap_or("");
        if action == "jj-hp-push" {
            found_xp = true;
            assert_eq!(desc, "jj-hp push", "binding desc not updated");
        }
        if action == "jj-hp-push-selected" {
            found_xp_caps = true;
            assert_eq!(
                desc, "jj-hp push selected bookmark(s)",
                "binding desc not updated"
            );
        }
        assert_ne!(action, "jj-push", "stale binding action reference");
        assert_ne!(action, "jj-push-selected", "stale binding action reference");
    }
    assert!(found_xp);
    assert!(found_xp_caps);
}

#[test]
fn apply_writes_jjui_config_when_requested() {
    let tmp = tempfile::TempDir::new().unwrap();
    let jj_config = tmp.path().join("jj-config.toml");
    let jjui_config = tmp.path().join("jjui-config.toml");
    std::fs::write(&jj_config, "").unwrap();

    let plan = InitPlan {
        install_alias: false,
        advance_bookmarks: false,
        install_jjui_actions: true,
    };
    let outcome = init::apply(&plan, Some(&jj_config), Some(&jjui_config)).unwrap();
    assert!(outcome.jjui_actions_added.added_jj_push);
    assert!(outcome.jjui_actions_added.added_binding_x_p);

    let written = std::fs::read_to_string(&jjui_config).unwrap();
    assert!(written.contains(r#"name = "jj-hp-push""#));
}

#[test]
fn add_jjui_actions_swaps_managed_seq_from_pre_swap_to_post_swap() {
    // Pre-2026-05 config: jj-hp-push was bound to lowercase x p
    // and jj-hp-push-selected to uppercase x P. The migration
    // must swap them so jj-hp-push-selected (the common case)
    // gets the easier keypress.
    let existing = r#"
[[actions]]
name = "jj-hp-push"
lua = """
  jj_async("util", "exec", "--", "jj-hp", "push")
  revisions.refresh()
"""

[[actions]]
name = "jj-hp-push-selected"
lua = """
  jj_async("util", "exec", "--", "jj-hp", "push", "-r", context.commit_id())
  revisions.refresh()
"""

[[bindings]]
action = "jj-hp-push"
seq = ["x", "p"]
scope = "revisions"
desc = "jj-hp push"

[[bindings]]
action = "jj-hp-push-selected"
seq = ["x", "P"]
scope = "revisions"
desc = "jj-hp push selected bookmark(s)"
"#;
    let (output, _added) = add_jjui_actions(existing).unwrap();
    let parsed: toml::Table = output.parse().unwrap();

    let bindings = parsed["bindings"].as_array().unwrap();
    let mut push_seq: Option<Vec<String>> = None;
    let mut selected_seq: Option<Vec<String>> = None;
    for b in bindings {
        let action = b.get("action").and_then(|v| v.as_str()).unwrap_or("");
        let seq: Vec<String> = b
            .get("seq")
            .and_then(|v| v.as_array())
            .map(|a| {
                a.iter()
                    .filter_map(|v| v.as_str().map(|s| s.to_owned()))
                    .collect()
            })
            .unwrap_or_default();
        if action == "jj-hp-push" {
            push_seq = Some(seq);
        } else if action == "jj-hp-push-selected" {
            selected_seq = Some(seq);
        }
    }
    assert_eq!(
        push_seq.as_deref(),
        Some(&["x".to_owned(), "P".to_owned()][..])
    );
    assert_eq!(
        selected_seq.as_deref(),
        Some(&["x".to_owned(), "p".to_owned()][..])
    );
}

#[test]
fn add_jjui_actions_seq_swap_is_idempotent() {
    // Running twice on the same input should not flip the
    // sequences back. The post-swap state is at the head of
    // the seq-history list; the migrate-prior detection
    // doesn't fire.
    let pre_swap = r#"
[[actions]]
name = "jj-hp-push"
lua = """
  jj_async("util", "exec", "--", "jj-hp", "push")
  revisions.refresh()
"""

[[bindings]]
action = "jj-hp-push"
seq = ["x", "p"]
scope = "revisions"
desc = "jj-hp push"
"#;
    let (first, _) = add_jjui_actions(pre_swap).unwrap();
    let (second, _) = add_jjui_actions(&first).unwrap();
    assert_eq!(first, second, "second run should be a no-op");

    // The first run should have swapped the seq.
    let parsed: toml::Table = first.parse().unwrap();
    let bindings = parsed["bindings"].as_array().unwrap();
    let push_binding = bindings
        .iter()
        .find(|b| b.get("action").and_then(|v| v.as_str()) == Some("jj-hp-push"))
        .unwrap();
    let seq: Vec<&str> = push_binding["seq"]
        .as_array()
        .unwrap()
        .iter()
        .filter_map(|v| v.as_str())
        .collect();
    assert_eq!(seq, vec!["x", "P"]);
}

#[test]
fn add_jjui_actions_does_not_swap_user_customized_seq() {
    // The user picked their own key sequence for jj-hp-push.
    // The migration must leave it alone because it's not in
    // our installed-history list.
    let user_custom = r#"
[[actions]]
name = "jj-hp-push"
lua = """
  jj_async("util", "exec", "--", "jj-hp", "push")
  revisions.refresh()
"""

[[bindings]]
action = "jj-hp-push"
seq = ["g", "p", "u"]
scope = "revisions"
desc = "my custom push key"
"#;
    let (output, _) = add_jjui_actions(user_custom).unwrap();
    let parsed: toml::Table = output.parse().unwrap();
    let bindings = parsed["bindings"].as_array().unwrap();
    let push_binding = bindings
        .iter()
        .find(|b| b.get("action").and_then(|v| v.as_str()) == Some("jj-hp-push"))
        .unwrap();
    let seq: Vec<&str> = push_binding["seq"]
        .as_array()
        .unwrap()
        .iter()
        .filter_map(|v| v.as_str())
        .collect();
    assert_eq!(seq, vec!["g", "p", "u"], "user's custom key was clobbered");
    // The desc should also be preserved — the migration's desc
    // refresh only runs when the seq was actually a prior value.
    let desc = push_binding
        .get("desc")
        .and_then(|v| v.as_str())
        .unwrap_or("");
    assert_eq!(desc, "my custom push key");
}

#[test]
fn add_jjui_actions_orders_by_frequency() {
    // The menu order matters: jjui's `x`-prefix overlay surfaces
    // candidates top-down in the order they appear in the config.
    // Selected-bookmark push (the daily case) sits at index 0 so
    // the muscle-memory `x p` keystroke is the shortest path
    // through the menu; whole-stack push (`x P`) is rarer and
    // sits below. Pin both the action and binding order so a
    // future reshuffle has to update this list AND the swap in
    // src/init.rs.
    let (output, _) = add_jjui_actions("").unwrap();
    let parsed: toml::Table = output.parse().unwrap();
    let action_order: Vec<&str> = parsed["actions"]
        .as_array()
        .unwrap()
        .iter()
        .filter_map(|v| v.get("name").and_then(|n| n.as_str()))
        .collect();
    assert_eq!(
        action_order,
        vec![
            "jj-hp-push-selected", // daily: push focused bookmark only
            "jj-hp-push",          // whole-stack push (less common)
        ],
        "action order drifted from selected-first frequency layout",
    );
    let binding_order: Vec<&str> = parsed["bindings"]
        .as_array()
        .unwrap()
        .iter()
        .filter_map(|v| v.get("action").and_then(|n| n.as_str()))
        .collect();
    assert_eq!(
        binding_order,
        vec!["jj-hp-push-selected", "jj-hp-push"],
        "binding order drifted from selected-first frequency layout",
    );
}

#[test]
fn readme_toml_matches_generated_jjui_config() {
    // Drift guard: the README's jjui-integration TOML block must
    // mirror what `add_jjui_actions("")` produces, including the
    // ORDER of actions and bindings. Ordering matters because
    // jjui's `x`-prefix overlay surfaces candidates in the order
    // they appear in the config; reshuffling the swap in
    // src/init.rs without updating the README would silently
    // produce different menu sort orders for the two install
    // paths (auto via `jj-hooks init` vs hand-paste from README).
    //
    // The README has multiple ```toml blocks (config snippets for
    // other features); we grab the FIRST one because that's the
    // one the new section adds. Future shuffles that move the
    // jjui block past index 0 will need to update this test.
    let readme_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("README.md");
    let readme = std::fs::read_to_string(&readme_path)
        .unwrap_or_else(|e| panic!("read {}: {e}", readme_path.display()));

    let start_marker = "```toml\n";
    let start = readme
        .find(start_marker)
        .expect("no ```toml block in README");
    let body_start = start + start_marker.len();
    let end = readme[body_start..]
        .find("\n```")
        .expect("toml block has no closing fence");
    let readme_toml = &readme[body_start..body_start + end];

    let readme_parsed: toml::Table = readme_toml
        .parse()
        .unwrap_or_else(|e| panic!("parse README TOML: {e}\n---\n{readme_toml}\n---"));

    let readme_action_order: Vec<&str> = readme_parsed
        .get("actions")
        .and_then(|v| v.as_array())
        .expect("README TOML has no [[actions]]")
        .iter()
        .filter_map(|v| v.get("name").and_then(|n| n.as_str()))
        .collect();
    let readme_binding_order: Vec<(&str, Vec<&str>)> = readme_parsed
        .get("bindings")
        .and_then(|v| v.as_array())
        .expect("README TOML has no [[bindings]]")
        .iter()
        .filter_map(|v| {
            let action = v.get("action").and_then(|n| n.as_str())?;
            let seq: Vec<&str> = v
                .get("seq")
                .and_then(|n| n.as_array())?
                .iter()
                .filter_map(|s| s.as_str())
                .collect();
            Some((action, seq))
        })
        .collect();

    let (generated, _) = add_jjui_actions("").unwrap();
    let generated_parsed: toml::Table = generated.parse().unwrap();
    let generated_action_order: Vec<&str> = generated_parsed["actions"]
        .as_array()
        .unwrap()
        .iter()
        .filter_map(|v| v.get("name").and_then(|n| n.as_str()))
        .collect();
    let generated_binding_order: Vec<(&str, Vec<&str>)> = generated_parsed["bindings"]
        .as_array()
        .unwrap()
        .iter()
        .filter_map(|v| {
            let action = v.get("action").and_then(|n| n.as_str())?;
            let seq: Vec<&str> = v
                .get("seq")
                .and_then(|n| n.as_array())?
                .iter()
                .filter_map(|s| s.as_str())
                .collect();
            Some((action, seq))
        })
        .collect();

    assert_eq!(
        readme_action_order, generated_action_order,
        "README action ORDER drifted from generated config (jjui menu sort \
         order will differ between auto-install and copy/paste)",
    );
    assert_eq!(
        readme_binding_order, generated_binding_order,
        "README binding ORDER drifted from generated config",
    );
}