drep-ai 2.5.1

A local commit gate: runs the linters your repo configures, and sends changed code to an LLM for review
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
//! B8, B9, B10-B16: hooks.rs.
//!
//! The git-touching criteria need a real `git init` repository; the helper
//! at the bottom builds one with `user.email`/`user.name` set so git can
//! answer queries.

use std::path::Path;

use crate::cli::init::hooks::{
    HookKind, chainer_body, hook_body, hook_names, install, is_drep_managed,
};

#[test]
fn hook_names_match_spec_for_every_kind() {
    assert_eq!(hook_names(HookKind::None), &[] as &[&str]);
    assert_eq!(hook_names(HookKind::PrePush), &["pre-push"]);
    assert_eq!(hook_names(HookKind::PreCommit), &["pre-commit"]);
    assert_eq!(hook_names(HookKind::Both), &["pre-commit", "pre-push"]);
}

#[test]
fn is_drep_managed_recognises_own_bodies_only() {
    assert!(is_drep_managed(hook_body("pre-commit").unwrap()));
    assert!(is_drep_managed(hook_body("pre-push").unwrap()));
    assert!(is_drep_managed(&chainer_body("pre-push")));
    assert!(!is_drep_managed("#!/bin/sh\necho hi\n"));
    assert!(!is_drep_managed(
        "#!/bin/sh\n# This foreign hook mentions # Managed by `drep init`. in documentation.\n"
    ));
}

fn hooks_dir(root: &Path) -> std::path::PathBuf {
    root.join(".git/hooks")
}

/// Configure the shared-hooks fixture and return its resolved directory.
fn configured_chainer_dir(root: &Path) -> std::path::PathBuf {
    let relative = "shared/hooks";
    let status = crate::test_support::git(root)
        .args(["config", "--local", "core.hooksPath", relative])
        .status()
        .expect("set core.hooksPath");
    assert!(status.success());
    let chainer_dir = root.join(relative);
    std::fs::create_dir_all(&chainer_dir).expect("chainer dir");
    chainer_dir
}

#[tokio::test]
async fn install_writes_executable_repo_local_pre_push_hook() {
    let dir = tempfile::tempdir().expect("tempdir");
    crate::test_support::git_init(dir.path());

    let mut out = Vec::new();
    let result = install(&mut out, dir.path(), HookKind::PrePush, false).await;
    assert!(result.is_ok(), "install: {result:?}");

    let hook_path = hooks_dir(dir.path()).join("pre-push");
    let written = std::fs::read_to_string(&hook_path).expect("read hook");
    assert_eq!(
        written,
        hook_body("pre-push").expect("known"),
        "the installed hook's body equals the canonical pre-push body"
    );

    crate::test_support::assert_executable(&hook_path);
}

#[tokio::test]
async fn install_does_not_clobber_a_foreign_hook_without_force() {
    let dir = tempfile::tempdir().expect("tempdir");
    crate::test_support::git_init(dir.path());
    let foreign = "#!/bin/sh\necho mine\n";
    let hook_path = hooks_dir(dir.path()).join("pre-push");
    std::fs::write(&hook_path, foreign).expect("write foreign");

    let mut out = Vec::new();
    let result = install(&mut out, dir.path(), HookKind::PrePush, false).await;
    assert!(result.is_ok(), "install returned Ok for a foreign hook");
    let after = std::fs::read_to_string(&hook_path).expect("read");
    assert_eq!(after, foreign, "foreign hook is byte-for-byte unchanged");

    let rendered = String::from_utf8(out).expect("utf8");
    assert!(
        rendered.contains("--force"),
        "captured output mentions --force; got:\n{rendered}"
    );

    // Now force: the file is replaced.
    let mut out = Vec::new();
    let result = install(&mut out, dir.path(), HookKind::PrePush, true).await;
    assert!(result.is_ok(), "install with force");
    let after = std::fs::read_to_string(&hook_path).expect("read");
    assert_eq!(
        after,
        hook_body("pre-push").expect("known"),
        "force replaces the foreign hook"
    );
}

#[tokio::test]
async fn a_non_utf8_foreign_hook_is_preserved_or_backed_up_byte_for_byte() {
    let dir = tempfile::tempdir().expect("tempdir");
    crate::test_support::git_init(dir.path());
    let hook_path = hooks_dir(dir.path()).join("pre-push");
    let foreign = b"#!/bin/sh\n# latin-1: \xff\nexit 0\n";
    std::fs::write(&hook_path, foreign).expect("write foreign hook");

    install(&mut Vec::new(), dir.path(), HookKind::PrePush, false)
        .await
        .expect("leave foreign hook");
    assert_eq!(std::fs::read(&hook_path).expect("read hook"), foreign);

    install(&mut Vec::new(), dir.path(), HookKind::PrePush, true)
        .await
        .expect("replace foreign hook");
    assert_eq!(
        std::fs::read(hook_path.with_extension("drep-backup")).expect("read backup"),
        foreign
    );
}

#[tokio::test]
async fn force_refuses_to_overwrite_an_existing_hook_backup() {
    let dir = tempfile::tempdir().expect("tempdir");
    crate::test_support::git_init(dir.path());
    let hook_path = hooks_dir(dir.path()).join("pre-push");
    std::fs::write(&hook_path, "#!/bin/sh\necho current\n").expect("foreign hook");
    let backup = hook_path.with_extension("drep-backup");
    std::fs::write(&backup, "original backup\n").expect("backup");

    let error = install(&mut Vec::new(), dir.path(), HookKind::PrePush, true)
        .await
        .expect_err("an existing backup must never be replaced");

    assert!(
        error.to_string().contains("move the existing backup"),
        "the remedy must match the collision: {error:#}"
    );
    assert_eq!(
        std::fs::read_to_string(&backup).expect("read backup"),
        "original backup\n"
    );
    assert_eq!(
        std::fs::read_to_string(&hook_path).expect("read hook"),
        "#!/bin/sh\necho current\n"
    );
}

#[tokio::test]
async fn install_rewrites_its_own_modified_hook() {
    let dir = tempfile::tempdir().expect("tempdir");
    crate::test_support::git_init(dir.path());
    let hook_path = hooks_dir(dir.path()).join("pre-push");
    // Keep the marker, change a comment.
    let modified = "# Managed by `drep init`.\n# an older version\n";
    std::fs::write(&hook_path, modified).expect("write modified");

    let mut out = Vec::new();
    install(&mut out, dir.path(), HookKind::PrePush, false)
        .await
        .expect("install");

    let after = std::fs::read_to_string(&hook_path).expect("read");
    assert_eq!(
        after,
        hook_body("pre-push").expect("known"),
        "a drep-managed hook is restored even without --force"
    );
}

#[test]
fn resolve_hooks_dir_handles_relative_and_absolute() {
    // root is intentionally NOT the process cwd: an implementation that
    // resolved against cwd would write a chainer into /tmp or wherever.
    let root = Path::new("/srv/some/repo");
    assert_eq!(
        crate::cli::init::hooks::resolve_hooks_dir(root, "/etc/hooks"),
        Path::new("/etc/hooks").to_path_buf()
    );
    assert_eq!(
        crate::cli::init::hooks::resolve_hooks_dir(root, "shared/hooks"),
        Path::new("/srv/some/repo/shared/hooks").to_path_buf()
    );
}

#[tokio::test]
async fn install_writes_chainer_when_core_hooks_path_is_set() {
    let dir = tempfile::tempdir().expect("tempdir");
    crate::test_support::git_init(dir.path());
    let chainer_dir = configured_chainer_dir(dir.path());

    let mut out = Vec::new();
    install(&mut out, dir.path(), HookKind::PrePush, false)
        .await
        .expect("install");

    let rendered = String::from_utf8(out).expect("utf8");
    assert!(
        rendered.contains("core.hooksPath is set to"),
        "rendered:\n{rendered}"
    );

    // Repo-local hook was written too.
    let local = hooks_dir(dir.path()).join("pre-push");
    assert!(local.exists(), "repo-local pre-push must exist");
    assert_eq!(
        std::fs::read_to_string(&local).expect("read local"),
        hook_body("pre-push").expect("known")
    );

    // Chainer was written in the resolved hooks dir.
    let chainer = chainer_dir.join("pre-push");
    assert!(chainer.exists(), "chainer must exist at {chainer:?}");
    let body = std::fs::read_to_string(&chainer).expect("read chainer");
    assert!(
        body.contains("hooks/pre-push"),
        "chainer forwards to the repo-local hook: {body}"
    );
    crate::test_support::assert_executable(&chainer);
}

#[tokio::test]
async fn install_leaves_a_foreign_chainer_alone() {
    let dir = tempfile::tempdir().expect("tempdir");
    crate::test_support::git_init(dir.path());
    let chainer_dir = configured_chainer_dir(dir.path());

    // Write the repo-local hook so the foreign chainer doesn't get rewritten.
    std::fs::create_dir_all(hooks_dir(dir.path())).expect("hooks dir");
    std::fs::write(
        hooks_dir(dir.path()).join("pre-push"),
        hook_body("pre-push").expect("known"),
    )
    .expect("write local");

    // Foreign chainer.
    let foreign = "#!/bin/sh\necho other\n";
    crate::test_support::write_executable(&chainer_dir.join("pre-push"), foreign);

    let mut out = Vec::new();
    install(&mut out, dir.path(), HookKind::PrePush, false)
        .await
        .expect("install");
    let rendered = String::from_utf8(out).expect("utf8");
    assert!(
        rendered.contains("does not appear to chain"),
        "foreign chainer must be reported; rendered:\n{rendered}"
    );
    let after = std::fs::read_to_string(chainer_dir.join("pre-push")).expect("read");
    assert_eq!(after, foreign, "foreign chainer is untouched");
}

#[tokio::test]
async fn a_foreign_chainer_comment_does_not_count_as_forwarding() {
    let dir = tempfile::tempdir().expect("tempdir");
    crate::test_support::git_init(dir.path());
    let chainer_dir = configured_chainer_dir(dir.path());
    let foreign = "#!/bin/sh\n# docs mention hooks/pre-push but this never executes it\nexit 0\n";
    crate::test_support::write_executable(&chainer_dir.join("pre-push"), foreign);

    let mut out = Vec::new();
    install(&mut out, dir.path(), HookKind::PrePush, false)
        .await
        .expect("install");

    assert!(
        String::from_utf8(out)
            .expect("utf8")
            .contains("does not appear to chain")
    );
    assert_eq!(
        std::fs::read_to_string(chainer_dir.join("pre-push")).expect("read"),
        foreign
    );
}

#[tokio::test]
async fn install_refreshes_an_outdated_managed_chainer() {
    let dir = tempfile::tempdir().expect("tempdir");
    crate::test_support::git_init(dir.path());
    let chainer_dir = configured_chainer_dir(dir.path());
    std::fs::write(
        chainer_dir.join("pre-push"),
        "#!/bin/sh\n# Managed by `drep init`.\n# obsolete forwarding logic\nexit 0\n",
    )
    .expect("old chainer");

    let mut out = Vec::new();
    install(&mut out, dir.path(), HookKind::PrePush, false)
        .await
        .expect("install");

    assert_eq!(
        std::fs::read_to_string(chainer_dir.join("pre-push")).expect("read"),
        chainer_body("pre-push")
    );
}

#[tokio::test]
async fn an_unresolvable_hooks_path_leaves_repository_hooks_untouched() {
    let dir = tempfile::tempdir().expect("tempdir");
    crate::test_support::git_init(dir.path());
    let status = crate::test_support::git(dir.path())
        .args([
            "config",
            "--local",
            "core.hooksPath",
            "~drep-user-that-does-not-exist/hooks",
        ])
        .status()
        .expect("set core.hooksPath");
    assert!(status.success(), "git config core.hooksPath failed");

    let mut out = Vec::new();
    let result = install(&mut out, dir.path(), HookKind::PrePush, false).await;

    assert!(result.is_err(), "the invalid path must be reported");
    assert!(
        !hooks_dir(dir.path()).join("pre-push").exists(),
        "validation must finish before any hook is installed"
    );
}

/// In a **linked worktree**, the hook must land in the main repository's
/// `.git/hooks`, not in the worktree's own git directory.
///
/// This is the entire reason the installer asks git for `--git-common-dir`
/// rather than `--git-dir` (or, worse, joining `root/.git`). In an ordinary
/// checkout the two answers are identical, so every other test in this file
/// passes just as well against the wrong one — this is the only shape that
/// tells them apart. In a linked worktree `.git` is a *file*, `--git-dir`
/// points at `.git/worktrees/<name>`, and git runs hooks from the common dir:
/// install into the wrong one and the hook silently never fires.
#[tokio::test]
async fn a_linked_worktree_installs_into_the_main_repositorys_hooks_dir() {
    let dir = tempfile::tempdir().expect("tempdir");
    let main = dir.path().join("main");
    std::fs::create_dir_all(&main).expect("main dir");
    crate::test_support::git_init(&main);

    // A worktree needs a commit to branch from.
    std::fs::write(main.join("seed.txt"), "seed\n").expect("seed");
    for args in [
        vec!["add", "seed.txt"],
        vec!["commit", "--quiet", "-m", "root"],
    ] {
        let status = crate::test_support::git(&main)
            .args(&args)
            .status()
            .expect("git");
        assert!(status.success(), "git {args:?} failed");
    }

    let linked = dir.path().join("linked");
    let output = crate::test_support::git(&main)
        .args(["worktree", "add", "-b", "side"])
        .arg(&linked)
        .output()
        .expect("git worktree add");
    assert!(
        output.status.success(),
        "git worktree add failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    assert!(
        linked.join(".git").is_file(),
        "a linked worktree's .git is a file, which is the premise of this test"
    );

    let mut out: Vec<u8> = Vec::new();
    install(&mut out, &linked, HookKind::PrePush, false)
        .await
        .expect("install into a linked worktree");

    let shared = main.join(".git").join("hooks").join("pre-push");
    assert!(
        shared.is_file(),
        "the hook belongs in the main repository's hooks dir; output was:\n{}",
        String::from_utf8_lossy(&out)
    );
    assert_eq!(
        std::fs::read_to_string(&shared).expect("read hook"),
        hook_body("pre-push").expect("known"),
        "and it must be drep's body"
    );

    // The per-worktree git dir must NOT have received it: git does not run
    // hooks from there, so a hook written there is a hook that never fires.
    let per_worktree = main
        .join(".git")
        .join("worktrees")
        .join("linked")
        .join("hooks")
        .join("pre-push");
    assert!(
        !per_worktree.exists(),
        "the hook must not be written to the per-worktree git dir at {}",
        per_worktree.display()
    );
}

/// An **empty** `core.hooksPath` means "hooks are disabled", not "hooks live
/// in the current directory".
///
/// git reads an empty value back as present-but-blank. Treating it as a
/// directory resolves to `root.join("")`, i.e. the repository root, so drep
/// would scatter chainers next to the user's source files and report a
/// `core.hooksPath is set to` line naming nothing.
#[tokio::test]
async fn an_empty_core_hooks_path_is_treated_as_unset() {
    let dir = tempfile::tempdir().expect("tempdir");
    crate::test_support::git_init(dir.path());
    // `git_init` already sets it empty; state it here so the test does not
    // silently depend on that and still means what its name says.
    let status = crate::test_support::git(dir.path())
        .args(["config", "--local", "core.hooksPath", ""])
        .status()
        .expect("git config");
    assert!(status.success());

    let mut out: Vec<u8> = Vec::new();
    install(&mut out, dir.path(), HookKind::PrePush, false)
        .await
        .expect("install");
    let text = String::from_utf8(out).expect("utf8");

    assert!(
        !text.contains("core.hooksPath is set to"),
        "an empty value is not a hooks path; got:\n{text}"
    );
    assert!(
        !dir.path().join("pre-push").exists(),
        "no chainer may be written into the repository root"
    );
    assert!(
        dir.path()
            .join(".git")
            .join("hooks")
            .join("pre-push")
            .is_file(),
        "the repo-local hook is still installed"
    );
}

/// An existing chainer that chains but is **not executable** is made
/// executable; one that already is, is left untouched.
///
/// git ignores a non-executable hook without saying anything, so this branch
/// is the difference between "drep runs on push" and "drep silently never
/// runs, and nothing tells you". Both halves are asserted in one test because
/// either alone leaves the condition free to invert: without the second, a
/// version that chmods unconditionally passes, and it is the *unconditional*
/// version that rewrites file modes the user set deliberately.
#[tokio::test]
async fn a_chainer_that_is_not_executable_is_fixed_and_an_executable_one_is_left_alone() {
    let dir = tempfile::tempdir().expect("tempdir");
    crate::test_support::git_init(dir.path());

    let shared = dir.path().join("shared-hooks");
    std::fs::create_dir_all(&shared).expect("shared hooks dir");
    let status = crate::test_support::git(dir.path())
        .args(["config", "--local", "core.hooksPath"])
        .arg(&shared)
        .status()
        .expect("git config");
    assert!(status.success());

    // A chainer that chains correctly, but with the executable bit cleared.
    let chainer = shared.join("pre-push");
    std::fs::write(&chainer, chainer_body("pre-push")).expect("write chainer");
    crate::test_support::clear_executable(&chainer);

    let mut out: Vec<u8> = Vec::new();
    install(&mut out, dir.path(), HookKind::PrePush, false)
        .await
        .expect("install");
    let text = String::from_utf8(out).expect("utf8");

    crate::test_support::assert_executable(&chainer);
    assert!(
        text.contains("is not executable; making it so"),
        "and the fix must be reported; got:\n{text}"
    );

    // Second run: it is executable now, so drep has nothing to say about it -
    // and, critically, must not take the bit back off. Re-applying the mode to
    // an already-executable file is the only situation that can tell OR from
    // XOR, and XOR here would silently disable the chainer on every second
    // `drep init`.
    let mut out: Vec<u8> = Vec::new();
    install(&mut out, dir.path(), HookKind::PrePush, false)
        .await
        .expect("install again");
    let text = String::from_utf8(out).expect("utf8");
    assert!(
        !text.contains("is not executable"),
        "an already-executable chainer needs no announcement; got:\n{text}"
    );
    crate::test_support::assert_executable(&chainer);
}