thirdshift 0.14.1

Turn a GitHub issue into a ready-for-review pull request, unattended
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
//! Git behavior in isolated Commands, so recorded interruption cannot leak
//! into another test running in the same process.

use super::*;
use crate::interrupt;
use crate::test_support::with_recorded_signal;
use std::fs;
use std::sync::mpsc;

/// Observe whether acquisition finishes while an independent open still
/// holds the lock. Release and join before the caller can assert, even when
/// acquisition ignores interruption or returns unexpectedly early.
fn contended_repository_lock(git: &Git, signal: Option<libc::c_int>) -> (bool, Result<File>) {
    let path = git.common_dir().unwrap().join("thirdshift-test.lock");
    let held = File::create(path).unwrap();
    held.lock().unwrap();
    std::thread::scope(|scope| {
        let (finished, received) = mpsc::channel();
        let contender = scope.spawn(move || {
            let result = git.lock("thirdshift-test.lock");
            let _ = finished.send(());
            result
        });
        std::thread::sleep(Duration::from_millis(200));
        let delivered = signal.map(signal_hook::low_level::raise);
        let finished_while_held = received.recv_timeout(Duration::from_secs(1)).is_ok();
        drop(held);
        let result = contender.join().unwrap();
        if let Some(delivered) = delivered {
            delivered.unwrap();
        }
        (finished_while_held, result)
    })
}

#[test]
fn ordinary_repository_lock_contention_stops_before_the_holder_releases() {
    with_recorded_signal(
        "git::execution_tests::ordinary_repository_lock_contention_stops_before_the_holder_releases",
        |signal| {
            let (_temp, git) = super::tests::repo_with_origin();
            let (finished_while_held, result) = contended_repository_lock(&git, Some(signal));

            assert!(finished_while_held, "acquisition waited for holder release");
            assert_eq!(result.unwrap_err().to_string(), "interrupted");
            assert!(interrupt::requested());
            let independent = File::open(git.dir().join(".git/thirdshift-test.lock")).unwrap();
            independent.try_lock().unwrap();
        },
    );
}

#[test]
fn completion_repository_lock_waits_through_arriving_and_recorded_interruption() {
    with_recorded_signal(
        "git::execution_tests::completion_repository_lock_waits_through_arriving_and_recorded_interruption",
        |signal| {
            let (_temp, git) = super::tests::repo_with_origin();
            let completion = git.completion();
            let path = git.common_dir().unwrap().join("thirdshift-test.lock");
            // First deliver a new request during contention, then acquire
            // again with that request already recorded.
            for signal in [Some(signal), None] {
                let (finished_while_held, result) = contended_repository_lock(&completion, signal);

                assert!(!finished_while_held, "completion did not wait for release");
                let acquired = result.unwrap();
                let independent = File::open(&path).unwrap();
                assert!(matches!(
                    independent.try_lock(),
                    Err(TryLockError::WouldBlock)
                ));
                assert!(interrupt::requested());
                assert_eq!(
                    git.lock("ordinary.lock").unwrap_err().to_string(),
                    "interrupted"
                );
                assert_eq!(
                    Git::new(git.dir())
                        .lock("ordinary.lock")
                        .unwrap_err()
                        .to_string(),
                    "interrupted"
                );
                assert_eq!(
                    git.run(&["rev-parse", "HEAD"]).unwrap_err().to_string(),
                    "interrupted"
                );
                assert!(!path.with_file_name("ordinary.lock").exists());
                drop(acquired);
                independent.try_lock().unwrap();
                assert!(path.exists(), "release removed the shared locking identity");
            }
        },
    );
}

#[test]
fn repository_lock_is_shared_by_worktrees_and_owned_until_drop() {
    let (temp, git) = super::tests::repo_with_origin();
    let worktree_path = temp.path().join("worktree");
    git.run(&[
        "worktree",
        "add",
        "--detach",
        worktree_path.to_str().unwrap(),
        "HEAD",
    ])
    .unwrap();
    let worktree = Git::new(worktree_path);
    let path = git.common_dir().unwrap().join("thirdshift-test.lock");
    let acquired = git.lock("thirdshift-test.lock").unwrap();
    let independent =
        File::open(worktree.common_dir().unwrap().join("thirdshift-test.lock")).unwrap();

    assert!(matches!(
        independent.try_lock(),
        Err(TryLockError::WouldBlock)
    ));
    drop(acquired);
    let acquired = worktree.lock("thirdshift-test.lock").unwrap();
    assert!(matches!(
        independent.try_lock(),
        Err(TryLockError::WouldBlock)
    ));
    drop(acquired);
    independent.try_lock().unwrap();
    assert!(path.exists(), "release removed the shared locking identity");
}

/// A path with a newline, or ending in a space, still reads as it is.
#[test]
fn a_checkout_location_reads_a_linked_worktree_whatever_its_path() {
    let (temp, git) = super::tests::repo_with_origin();
    let head = git.run(&["rev-parse", "HEAD"]).unwrap();
    for name in ["worktree", "work\ntree", "worktree "] {
        let path = temp.path().join(name);
        git.run(&[
            "worktree",
            "add",
            "--detach",
            path.to_str().unwrap(),
            "HEAD",
        ])
        .unwrap();
        let worktree = Git::new(&path);
        let location = worktree.checkout_location().unwrap();
        assert_eq!(
            location.root,
            Path::new(&worktree.run(&["rev-parse", "--show-toplevel"]).unwrap()),
            "{name:?}"
        );
        assert_eq!(
            location.admin,
            Path::new(&worktree.run(&["rev-parse", "--absolute-git-dir"]).unwrap()),
            "{name:?}"
        );
        assert_eq!(location.common, worktree.common_dir().unwrap(), "{name:?}");
        assert_eq!(location.head, head, "{name:?}");
    }
}

#[test]
fn ordinary_git_refuses_to_spawn_after_interruption() {
    with_recorded_signal(
        "git::execution_tests::ordinary_git_refuses_to_spawn_after_interruption",
        |signal| {
            let (_temp, git) = super::tests::repo_with_origin();
            signal_hook::low_level::raise(signal).unwrap();
            let error = git
                .run(&["-c", "alias.start=!touch started", "start"])
                .unwrap_err();
            assert_eq!(error.to_string(), "interrupted");
            assert!(!git.dir().join("started").exists());
            assert_eq!(
                git.lock("ordinary.lock").unwrap_err().to_string(),
                "interrupted"
            );
            assert!(!git.dir().join(".git/ordinary.lock").exists());
        },
    );
}

#[test]
fn completion_git_finishes_without_permitting_the_original_view() {
    with_recorded_signal(
        "git::execution_tests::completion_git_finishes_without_permitting_the_original_view",
        |signal| {
            let (_temp, git) = super::tests::repo_with_origin();
            let completion = git.completion();
            signal_hook::low_level::raise(signal).unwrap();
            completion
                .run(&["config", "thirdshift.finished", "yes"])
                .unwrap();
            assert_eq!(
                completion.run(&["config", "thirdshift.finished"]).unwrap(),
                "yes"
            );
            assert_eq!(completion.dir(), git.dir());
            assert!(interrupt::requested());
            assert_eq!(
                git.run(&["config", "thirdshift.finished"])
                    .unwrap_err()
                    .to_string(),
                "interrupted"
            );
            assert_eq!(
                Git::new(git.dir())
                    .succeeds(&["rev-parse", "HEAD"])
                    .unwrap_err()
                    .to_string(),
                "interrupted"
            );
        },
    );
}

#[test]
fn optional_answers_distinguish_absence_from_execution_failure() {
    with_recorded_signal(
        "git::execution_tests::optional_answers_distinguish_absence_from_execution_failure",
        |signal| {
            let (_temp, git) = super::tests::repo_with_origin();
            assert_eq!(
                git.run_optional(&["symbolic-ref", "--short", "HEAD"])
                    .unwrap()
                    .as_deref(),
                Some("main")
            );
            assert_eq!(
                git.run_optional(&["rev-parse", "--verify", "--quiet", "refs/heads/absent"])
                    .unwrap(),
                None
            );
            assert!(
                !git.succeeds(&["rev-parse", "--verify", "--quiet", "refs/heads/absent"])
                    .unwrap()
            );
            assert!(git.succeeds(&["rev-parse", "HEAD"]).unwrap());
            let missing = Git::new(git.dir().join("absent-directory"));
            assert!(missing.run_optional(&["rev-parse", "HEAD"]).is_err());
            assert!(missing.succeeds(&["rev-parse", "HEAD"]).is_err());
            signal_hook::low_level::raise(signal).unwrap();
            assert_eq!(
                git.run_optional(&["rev-parse", "--verify", "--quiet", "refs/heads/absent"])
                    .unwrap_err()
                    .to_string(),
                "interrupted"
            );
            assert_eq!(
                git.succeeds(&["rev-parse", "--verify", "--quiet", "refs/heads/absent"])
                    .unwrap_err()
                    .to_string(),
                "interrupted"
            );
        },
    );
}

/// The executable is a real Git alias. Only its recorded PID is used for
/// fallback cleanup, including when an assertion fails.
struct Fixture {
    pid: PathBuf,
}

impl Fixture {
    fn new(git: &Git, script: &str) -> Self {
        let pid = git.dir().join("fixture.pid");
        let path = git.dir().join("fixture.sh");
        crate::test_support::write_executable(
            &path,
            &format!("#!/bin/sh\necho $$ > fixture.pid\n{script}\n"),
        );
        Self { pid }
    }

    fn pid(&self) -> Option<libc::pid_t> {
        fs::read_to_string(&self.pid).ok()?.trim().parse().ok()
    }
}

fn exists(pid: libc::pid_t) -> bool {
    // SAFETY: signal 0 only probes the PID recorded by this fixture.
    unsafe { libc::kill(pid, 0) == 0 }
}

impl Drop for Fixture {
    fn drop(&mut self) {
        if let Some(pid) = self.pid()
            && exists(pid)
        {
            // SAFETY: this PID belongs to the test's finite executable.
            unsafe { libc::kill(pid, libc::SIGKILL) };
        }
    }
}

const FIXTURE: &[&str] = &["-c", "alias.fixture=!./fixture.sh", "fixture"];

#[test]
fn a_parent_only_signal_stops_active_git_and_propagates_through_probes() {
    with_recorded_signal(
        "git::execution_tests::a_parent_only_signal_stops_active_git_and_propagates_through_probes",
        |signal| {
            let (_temp, git) = super::tests::repo_with_origin();
            let fixture = Fixture::new(
                &git,
                &format!("kill -{signal} {}\nexec sleep 3", std::process::id()),
            );
            let started = Instant::now();
            assert_eq!(
                git.succeeds(FIXTURE).unwrap_err().to_string(),
                "interrupted"
            );
            assert!(
                started.elapsed() < Duration::from_secs(2),
                "Git waited for natural expiry"
            );
            let pid = fixture.pid().expect("the executable never started");
            let deadline = Instant::now() + Duration::from_secs(2);
            while exists(pid) && Instant::now() < deadline {
                std::thread::sleep(Duration::from_millis(10));
            }
            assert!(!exists(pid), "Git left its owned executable alive");
            assert_eq!(
                git.run_optional(FIXTURE).unwrap_err().to_string(),
                "interrupted"
            );
            assert_eq!(git.run(FIXTURE).unwrap_err().to_string(), "interrupted");
        },
    );
}

#[test]
fn completion_git_finishes_with_a_newly_arriving_signal() {
    with_recorded_signal(
        "git::execution_tests::completion_git_finishes_with_a_newly_arriving_signal",
        |signal| {
            let (_temp, git) = super::tests::repo_with_origin();
            let _fixture = Fixture::new(
                &git,
                &format!(
                    "kill -{signal} {}\nsleep 0.1\nprintf 'completed\\n'",
                    std::process::id()
                ),
            );
            assert_eq!(git.completion().run(FIXTURE).unwrap(), "completed");
            assert!(interrupt::requested());
            assert_eq!(git.run(FIXTURE).unwrap_err().to_string(), "interrupted");
        },
    );
}

#[test]
fn an_optional_probe_propagates_active_cancellation() {
    with_recorded_signal(
        "git::execution_tests::an_optional_probe_propagates_active_cancellation",
        |signal| {
            let (_temp, git) = super::tests::repo_with_origin();
            let _fixture = Fixture::new(
                &git,
                &format!("kill -{signal} {}\nexec sleep 3", std::process::id()),
            );
            assert_eq!(
                git.run_optional(FIXTURE).unwrap_err().to_string(),
                "interrupted"
            );
        },
    );
}

fn interrupt_lock_retry(git: &Git, signal: libc::c_int) -> Result<String> {
    let held = git.dir().join("held");
    let tried = git.dir().join("tried");
    fs::write(&held, "").unwrap();
    let _fixture = Fixture::new(
        git,
        "if test -f held; then\n touch tried\n echo \"fatal: Unable to create 'config.lock': File exists\" >&2\n exit 1\nfi\nprintf 'finished\\n'",
    );
    let release = std::thread::spawn(move || {
        let deadline = Instant::now() + Duration::from_secs(5);
        while !tried.exists() && Instant::now() < deadline {
            std::thread::sleep(Duration::from_millis(10));
        }
        let attempted = tried.exists();
        std::thread::sleep(Duration::from_millis(50));
        signal_hook::low_level::raise(signal).unwrap();
        std::thread::sleep(Duration::from_millis(200));
        fs::remove_file(held).unwrap();
        assert!(attempted, "Git never reached the held lock");
    });
    let result = git.run(FIXTURE);
    release.join().unwrap();
    result
}

#[test]
fn ordinary_lock_retries_observe_interruption() {
    with_recorded_signal(
        "git::execution_tests::ordinary_lock_retries_observe_interruption",
        |signal| {
            let (_temp, git) = super::tests::repo_with_origin();
            assert_eq!(
                interrupt_lock_retry(&git, signal).unwrap_err().to_string(),
                "interrupted"
            );
        },
    );
}

#[test]
fn completion_lock_retries_ignore_existing_and_arriving_interruption() {
    with_recorded_signal(
        "git::execution_tests::completion_lock_retries_ignore_existing_and_arriving_interruption",
        |signal| {
            let (_temp, git) = super::tests::repo_with_origin();
            let completion = git.completion();
            assert_eq!(
                interrupt_lock_retry(&completion, signal).unwrap(),
                "finished"
            );
            // The same held-lock path also works with the flag already recorded.
            fs::remove_file(git.dir().join("tried")).unwrap();
            assert_eq!(
                interrupt_lock_retry(&completion, signal).unwrap(),
                "finished"
            );
            assert!(interrupt::requested());
            assert_eq!(git.run(FIXTURE).unwrap_err().to_string(), "interrupted");
        },
    );
}

#[test]
fn interruption_ends_the_wait_before_a_read_of_origin_is_run_again() {
    with_recorded_signal(
        "git::execution_tests::interruption_ends_the_wait_before_a_read_of_origin_is_run_again",
        |signal| {
            let (temp, git) = super::tests::repo_with_origin();
            let count = super::tests::origin_fails(
                &temp,
                &git,
                "uploadpack",
                3,
                super::tests::DROPPED_STREAM,
            );
            std::thread::scope(|scope| {
                let reader = scope.spawn(|| git.on_origin("main"));
                // The first attempt fails at once; its retry waits a second.
                while !count.exists() {
                    std::thread::sleep(Duration::from_millis(10));
                }
                std::thread::sleep(Duration::from_millis(200));
                let interrupted = Instant::now();
                signal_hook::low_level::raise(signal).unwrap();
                let result = reader.join().unwrap();

                assert!(interrupted.elapsed() < Duration::from_millis(500));
                assert_eq!(result.unwrap_err().to_string(), "interrupted");
                assert_eq!(fs::read_to_string(&count).unwrap().trim(), "1");
            });
        },
    );
}