grit-lib 0.5.24

Core library for the grit Git implementation
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
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
//! Exclusive lock files with optional Git-style acquisition backoff.
//!
//! Grit uses lock files (`.lock` siblings, `index.lock`, `packed-refs.lock`, …) the same way
//! Git does: create exclusively, write staged content, then rename over the target path.
//! [`LockFile::acquire`] retries with jittered exponential backoff when configured, matching
//! `core.filesRefLockTimeout`, `core.packedRefsTimeout`, and `reftable.lockTimeout`.
//!
//! ```rust
//! use grit_lib::config::ConfigSet;
//! use grit_lib::lockfile::LockWait;
//! let wait = LockWait::files_ref_lock(Some(&ConfigSet::new()));
//! assert!(matches!(wait, LockWait::Immediately | LockWait::Backoff { .. } | LockWait::Indefinitely));
//! ```

use std::fs::{self, File, OpenOptions};
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{Duration, Instant};

use thiserror::Error;

use crate::config::ConfigSet;
use crate::environment::Environment;

/// Whether to wait for an existing lock, and for how long.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LockWait {
    /// Fail immediately when the lock file already exists.
    Immediately,
    /// Retry with jittered exponential backoff until `budget` elapses.
    Backoff {
        /// Total time budget for acquisition attempts.
        budget: Duration,
    },
    /// Retry until the lock is acquired (Git `core.filesRefLockTimeout = -1`).
    Indefinitely,
}

impl LockWait {
    /// `core.filesRefLockTimeout` (milliseconds), default 100 ms when unset.
    #[must_use]
    pub fn files_ref_lock(config: Option<&ConfigSet>) -> Self {
        Self::from_files_ref_lock_timeout_ms(Self::parse_files_ref_lock_timeout_ms(config))
    }

    /// Parse `core.filesRefLockTimeout` the way Git does (milliseconds).
    #[must_use]
    pub fn parse_files_ref_lock_timeout_ms(config: Option<&ConfigSet>) -> i64 {
        config
            .and_then(|cfg| cfg.get("core.filesreflocktimeout"))
            .and_then(|v| v.trim().parse::<i64>().ok())
            .unwrap_or(100)
    }

    #[must_use]
    fn from_files_ref_lock_timeout_ms(timeout_ms: i64) -> Self {
        match timeout_ms {
            0 => Self::Immediately,
            ms if ms < 0 => Self::Indefinitely,
            ms => Self::Backoff {
                budget: Duration::from_millis(ms as u64),
            },
        }
    }

    /// `core.packedRefsTimeout` (milliseconds), default 1000 ms when unset.
    #[must_use]
    pub fn packed_refs(config: Option<&ConfigSet>) -> Self {
        Self::from_milliseconds_config(config, "core.packedrefstimeout", 1_000)
    }

    /// `reftable.lockTimeout` (milliseconds), default 1000 ms when unset.
    #[must_use]
    pub fn reftable_tables_list(config: Option<&ConfigSet>) -> Self {
        Self::from_milliseconds_config(config, "reftable.locktimeout", 1_000)
    }

    /// Load repository config from `git_dir` and return [`Self::files_ref_lock`].
    #[must_use]
    pub fn files_ref_lock_for_git_dir(git_dir: &Path) -> Self {
        let config = ConfigSet::load(&Environment::empty(), Some(git_dir), true).ok();
        Self::files_ref_lock(config.as_ref())
    }

    /// Load repository config from `git_dir` and return [`Self::packed_refs`].
    #[must_use]
    pub fn packed_refs_for_git_dir(git_dir: &Path) -> Self {
        let config = ConfigSet::load(&Environment::empty(), Some(git_dir), true).ok();
        Self::packed_refs(config.as_ref())
    }

    fn from_milliseconds_config(config: Option<&ConfigSet>, key: &str, default_ms: u64) -> Self {
        let ms = config
            .and_then(|cfg| cfg.get(key))
            .and_then(|v| v.trim().parse::<i64>().ok())
            .map(|v| v.max(0) as u64)
            .unwrap_or(default_ms);
        if ms == 0 {
            Self::Immediately
        } else {
            Self::Backoff {
                budget: Duration::from_millis(ms),
            }
        }
    }
}

/// Failure to create or commit a lock file.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum LockError {
    /// Another process holds the lock (or the lock path already exists).
    #[error("lock held at {path}")]
    Held {
        /// Path to the lock file that could not be created exclusively.
        path: PathBuf,
    },

    /// Underlying I/O failure while creating, writing, syncing, or renaming.
    #[error("lock I/O at {path}")]
    Io {
        /// Lock file path associated with the failure.
        path: PathBuf,
        /// Underlying OS error.
        #[source]
        source: io::Error,
    },
}

/// Injectable clock and sleep for deterministic lock backoff tests.
pub trait LockClock: Send + Sync {
    /// Current instant (used for backoff deadlines).
    fn now(&self) -> Instant;
    /// Pause until the next acquisition attempt.
    fn sleep(&self, duration: Duration);
}

/// Injectable jitter so concurrent processes do not sleep in lockstep.
pub trait LockJitter: Send + Sync {
    /// Fraction in `[0.0, 1.0)` scaled into backoff delays.
    fn fraction(&self, lock_path: &Path, attempt: u32) -> f64;
}

/// OS random bytes for cross-process jitter (Git-style lock backoff).
#[derive(Debug, Default, Clone, Copy)]
pub struct SystemLockJitter;

impl LockJitter for SystemLockJitter {
    fn fraction(&self, _lock_path: &Path, _attempt: u32) -> f64 {
        let mut buf = [0u8; 8];
        if getrandom::getrandom(&mut buf).is_ok() {
            let n = u64::from_le_bytes(buf);
            (n % 10_000) as f64 / 10_000.0
        } else {
            0.5
        }
    }
}

/// Wall-clock backoff using [`std::thread::sleep`].
#[derive(Debug, Default, Clone, Copy)]
pub struct SystemLockClock;

impl LockClock for SystemLockClock {
    fn now(&self) -> Instant {
        Instant::now()
    }

    fn sleep(&self, duration: Duration) {
        if !duration.is_zero() {
            std::thread::sleep(duration);
        }
    }
}

/// Exclusive lock file created by this process.
///
/// Drop without [`Self::commit`] or [`Self::commit_to`] removes the lock file when this
/// handle created it. Foreign lock files are never removed.
pub struct LockFile {
    lock_path: PathBuf,
    commit_path: Option<PathBuf>,
    file: Option<File>,
    committed: bool,
    wrote_holder_pid: bool,
}

impl LockFile {
    /// Create `target` exclusively (`O_CREAT|O_EXCL`), optionally waiting per `wait`.
    ///
    /// `target` is the lock file path (for example `refs/heads/main.lock`), not the file being
    /// updated. Persist staged bytes with [`Self::commit_to`] (or [`Self::commit`] after
    /// [`Self::with_commit_target`]).
    ///
    /// # Errors
    ///
    /// Returns [`LockError::Held`] when the lock exists and the wait budget is exhausted, or
    /// [`LockError::Io`] for other failures.
    pub fn acquire(target: &Path, wait: LockWait) -> Result<Self, LockError> {
        Self::acquire_with_clock(
            target,
            wait,
            Arc::new(SystemLockClock),
            Arc::new(SystemLockJitter),
        )
    }

    /// Like [`Self::acquire`], with injectable clock and jitter for unit tests.
    pub fn acquire_with_clock(
        target: &Path,
        wait: LockWait,
        clock: Arc<dyn LockClock>,
        jitter: Arc<dyn LockJitter>,
    ) -> Result<Self, LockError> {
        let to_lock_error = |source: io::Error| {
            if source.kind() == io::ErrorKind::AlreadyExists {
                LockError::Held {
                    path: target.to_path_buf(),
                }
            } else {
                LockError::Io {
                    path: target.to_path_buf(),
                    source,
                }
            }
        };
        let open = || OpenOptions::new().write(true).create_new(true).open(target);
        // The parent usually exists, so it is only created once an open fails. Creating it
        // then still reports a parent blocked by a file as the directory error.
        let mut parent_ready = false;
        retry_while_held(
            target,
            || wait,
            clock.as_ref(),
            jitter.as_ref(),
            || match open() {
                Err(_) if !parent_ready => {
                    parent_ready = true;
                    if let Some(parent) = target.parent() {
                        fs::create_dir_all(parent).map_err(|source| LockError::Io {
                            path: target.to_path_buf(),
                            source,
                        })?;
                    }
                    open().map_err(to_lock_error)
                }
                other => other.map_err(to_lock_error),
            },
            |err| matches!(err, LockError::Held { .. }),
        )
        .map(|file| Self {
            lock_path: target.to_path_buf(),
            commit_path: None,
            file: Some(file),
            committed: false,
            wrote_holder_pid: false,
        })
    }

    /// Set the destination path used by [`Self::commit`].
    #[must_use]
    pub fn with_commit_target(mut self, path: &Path) -> Self {
        self.commit_path = Some(path.to_path_buf());
        self
    }

    /// Path to the lock file held by this handle.
    #[must_use]
    pub fn lock_path(&self) -> &Path {
        &self.lock_path
    }

    /// Borrow the open lock file for writing.
    ///
    /// # Errors
    ///
    /// Returns [`LockError::Io`] when the handle was already taken (for example after
    /// the open file handle was moved out for index integration).
    pub fn as_file(&self) -> Result<&File, LockError> {
        self.file.as_ref().ok_or_else(|| LockError::Io {
            path: self.lock_path.clone(),
            source: io::Error::new(io::ErrorKind::NotConnected, "lock file handle missing"),
        })
    }

    /// Borrow the open lock file mutably for writing.
    ///
    /// # Errors
    ///
    /// Returns [`LockError::Io`] when the handle was already taken.
    pub fn as_file_mut(&mut self) -> Result<&mut File, LockError> {
        self.file.as_mut().ok_or_else(|| LockError::Io {
            path: self.lock_path.clone(),
            source: io::Error::new(io::ErrorKind::NotConnected, "lock file handle missing"),
        })
    }

    /// Yield the lock path and open file without removing the lock on drop.
    pub(crate) fn into_open_file(mut self) -> Result<(PathBuf, File), LockError> {
        self.committed = true;
        let file = self.file.take().ok_or_else(|| LockError::Io {
            path: self.lock_path.clone(),
            source: io::Error::new(io::ErrorKind::NotConnected, "lock file handle missing"),
        })?;
        Ok((self.lock_path.clone(), file))
    }

    /// Fsync the lock file, rename it over `commit_path` from [`Self::with_commit_target`], and
    /// disarm drop cleanup.
    ///
    /// # Errors
    ///
    /// Returns [`LockError::Io`] when no commit target was configured or rename fails.
    pub fn commit(self) -> Result<(), LockError> {
        let dest = self.commit_path.clone().ok_or_else(|| LockError::Io {
            path: self.lock_path.clone(),
            source: io::Error::new(
                io::ErrorKind::InvalidInput,
                "lock commit target not configured",
            ),
        })?;
        self.commit_to(&dest)
    }

    /// Fsync the lock file and atomically rename it over `other_path`.
    ///
    /// # Errors
    ///
    /// Returns [`LockError::Io`] on sync or rename failure.
    pub fn commit_to(mut self, other_path: &Path) -> Result<(), LockError> {
        let file = self.file.take().ok_or_else(|| LockError::Io {
            path: self.lock_path.clone(),
            source: io::Error::new(io::ErrorKind::NotConnected, "lock file handle missing"),
        })?;
        file.sync_all().map_err(|source| LockError::Io {
            path: self.lock_path.clone(),
            source,
        })?;
        drop(file);
        fs::rename(&self.lock_path, other_path).map_err(|source| LockError::Io {
            path: self.lock_path.clone(),
            source,
        })?;
        self.remove_holder_pid_sidecar();
        self.committed = true;
        Ok(())
    }

    /// Record this process as the holder of [`Self::lock_path`] in a Git-compatible pid sidecar.
    ///
    /// # Errors
    ///
    /// Returns [`LockError::Io`] when the sidecar cannot be written.
    pub fn write_holder_pid(&mut self) -> Result<(), LockError> {
        write_lock_pid_file(&pid_path_for_lock(&self.lock_path)).map_err(|source| {
            LockError::Io {
                path: self.lock_path.clone(),
                source,
            }
        })?;
        self.wrote_holder_pid = true;
        Ok(())
    }

    /// Release the lock without committing (same as drop).
    pub fn rollback(mut self) {
        if self.committed {
            return;
        }
        drop(self.file.take());
        let _ = fs::remove_file(&self.lock_path);
        self.remove_holder_pid_sidecar();
        self.committed = true;
    }

    fn remove_holder_pid_sidecar(&self) {
        if self.wrote_holder_pid {
            let _ = fs::remove_file(pid_path_for_lock(&self.lock_path));
        }
    }

    /// Close this handle but leave the lock file on disk (mutex-only locks).
    pub fn detach(mut self) {
        self.committed = true;
    }
}

impl Write for LockFile {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        match self.file.as_mut() {
            Some(file) => file.write(buf),
            None => Err(io::Error::new(
                io::ErrorKind::NotConnected,
                "lock file handle missing",
            )),
        }
    }

    fn flush(&mut self) -> io::Result<()> {
        match self.file.as_mut() {
            Some(file) => file.flush(),
            None => Err(io::Error::new(
                io::ErrorKind::NotConnected,
                "lock file handle missing",
            )),
        }
    }
}

impl Drop for LockFile {
    fn drop(&mut self) {
        if self.committed {
            return;
        }
        drop(self.file.take());
        let _ = fs::remove_file(&self.lock_path);
        self.remove_holder_pid_sidecar();
    }
}

/// Run `attempt` until it succeeds, fails with an error `is_held` does not accept, or the wait
/// budget is spent, sleeping the jittered backoff between attempts.
///
/// The deadline starts before the first attempt, so time spent inside `attempt` (which may
/// itself wait on a lock) counts against the budget. `wait` is resolved only after the first
/// held failure, so callers that read it from config pay nothing when the lock is free.
/// `key` names the lock for [`LockJitter::fraction`].
///
/// # Errors
///
/// Returns the last error from `attempt`: immediately when `is_held` rejects it, otherwise
/// once the budget is exhausted.
pub(crate) fn retry_while_held<T, E>(
    key: &Path,
    wait: impl FnOnce() -> LockWait,
    clock: &dyn LockClock,
    jitter: &dyn LockJitter,
    mut attempt: impl FnMut() -> Result<T, E>,
    is_held: impl Fn(&E) -> bool,
) -> Result<T, E> {
    let start = clock.now();
    let mut err = match attempt() {
        Err(err) if is_held(&err) => err,
        other => return other,
    };
    let deadline = match wait() {
        LockWait::Immediately => return Err(err),
        LockWait::Backoff { budget } => Some(start + budget),
        LockWait::Indefinitely => None,
    };
    let mut tries: u32 = 0;
    loop {
        if deadline.is_some_and(|deadline| clock.now() >= deadline) {
            return Err(err);
        }
        let delay = backoff_delay(key, tries, jitter);
        tries = tries.saturating_add(1);
        clock.sleep(match deadline {
            Some(deadline) => delay.min(deadline.saturating_duration_since(clock.now())),
            None => delay,
        });
        match attempt() {
            Err(held) if is_held(&held) => err = held,
            other => return other,
        }
    }
}

fn backoff_delay(lock_path: &Path, attempt: u32, jitter: &dyn LockJitter) -> Duration {
    const INITIAL_MS: u64 = 1;
    const CAP_MS: u64 = 50;
    let shift = attempt.min(16);
    let base_ms = (INITIAL_MS.saturating_mul(1_u64 << shift)).min(CAP_MS);
    let span_ms = base_ms / 2 + 1;
    let jitter_ms = (jitter.fraction(lock_path, attempt) * span_ms as f64) as u64;
    Duration::from_millis(base_ms.saturating_add(jitter_ms))
}

/// Process recorded as the owner of a lock file.
///
/// With `core.lockfilePid` enabled, the lock owner writes `pid <n>` to a sidecar named after
/// the lock (`index.lock` → `index~pid.lock`). Git and grit share this layout.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LockHolder {
    /// Process id read from the sidecar.
    pub pid: u64,
    /// Whether a process with [`Self::pid`] exists right now.
    ///
    /// `false` means the lock is stale. `true` is only a hint: the id may have been reused by
    /// an unrelated process.
    pub running: bool,
}

impl LockHolder {
    /// Read the holder recorded for `lock_path` and probe whether it is still running.
    ///
    /// `lock_path` is the lock file itself (for example `.git/index.lock`).
    ///
    /// Returns `None` when no pid sidecar exists or it does not contain a process id.
    #[must_use]
    pub fn read(lock_path: &Path) -> Option<Self> {
        let pid = read_lock_pid(&pid_path_for_lock(lock_path))?;
        Some(Self {
            pid,
            running: is_process_running(pid),
        })
    }

    /// Remove `lock_path` and its pid sidecar when [`Self::read`] reports a dead holder.
    ///
    /// Returns `true` when both files were removed (or were already absent after the lock).
    /// Returns `false` when there is no sidecar, the holder is still running, or the sidecar
    /// looks left over from an earlier holder (lock file newer than the sidecar).
    ///
    /// # Errors
    ///
    /// Returns [`io::Error`] when metadata or removal fails for reasons other than
    /// [`io::ErrorKind::NotFound`].
    pub fn remove_if_stale(lock_path: &Path) -> io::Result<bool> {
        let Some(holder) = Self::read(lock_path) else {
            return Ok(false);
        };
        if holder.running {
            return Ok(false);
        }
        let pid_path = pid_path_for_lock(lock_path);
        if lock_path.is_file() && pid_path.is_file() {
            let lock_mtime = fs::metadata(lock_path)?.modified()?;
            let pid_mtime = fs::metadata(&pid_path)?.modified()?;
            if lock_mtime > pid_mtime {
                return Ok(false);
            }
        }
        for path in [lock_path, &pid_path] {
            match fs::remove_file(path) {
                Ok(()) => {}
                Err(e) if e.kind() == io::ErrorKind::NotFound => {}
                Err(e) => return Err(e),
            }
        }
        Ok(true)
    }
}

/// Whether grit writes pid sidecars for locks it creates.
///
/// Honors an explicit `core.lockfilePid=false`. When unset, grit defaults to `true` so crash
/// recovery can detect stale index locks without requiring Git's opt-in.
///
/// When `config` is `None`, values are loaded from `git_dir` when provided.
#[must_use]
pub fn grit_lockfile_pid_enabled(config: Option<&ConfigSet>, git_dir: Option<&Path>) -> bool {
    fn from_config(cfg: &ConfigSet) -> bool {
        match cfg.get_bool("core.lockfilepid") {
            Some(Ok(false)) => false,
            Some(Ok(true)) | Some(Err(_)) | None => true,
        }
    }
    if let Some(cfg) = config {
        return from_config(cfg);
    }
    if let Some(dir) = git_dir {
        if let Ok(cfg) = ConfigSet::load(&Environment::empty(), Some(dir), true) {
            return from_config(&cfg);
        }
    }
    true
}

/// Path of the pid sidecar for `lock_path` (`name.lock` → `name~pid.lock`).
pub fn pid_path_for_lock(lock_path: &Path) -> PathBuf {
    let file_name = lock_path
        .file_name()
        .map(|s| s.to_string_lossy().into_owned())
        .unwrap_or_else(|| "index.lock".to_owned());
    let base = file_name.strip_suffix(".lock").unwrap_or(&file_name);
    lock_path.with_file_name(format!("{base}~pid.lock"))
}

pub(crate) fn write_lock_pid_file(pid_path: &Path) -> io::Result<()> {
    let mut file = OpenOptions::new()
        .write(true)
        .create(true)
        .truncate(true)
        .open(pid_path)?;
    writeln!(file, "pid {}", std::process::id())?;
    Ok(())
}

fn read_lock_pid(pid_path: &Path) -> Option<u64> {
    let raw = fs::read_to_string(pid_path).ok()?;
    let trimmed = raw.trim();
    trimmed
        .strip_prefix("pid ")
        .unwrap_or(trimmed)
        .trim()
        .parse::<u64>()
        .ok()
}

/// Whether a process with `pid` exists on this machine.
pub(crate) fn is_process_running(pid: u64) -> bool {
    if pid == 0 || pid > i32::MAX as u64 {
        return false;
    }
    #[cfg(windows)]
    {
        use windows_sys::Win32::Foundation::CloseHandle;
        use windows_sys::Win32::System::Threading::{
            OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION,
        };
        // SAFETY: `OpenProcess` is called with a numeric pid and a read-only access mask.
        unsafe {
            let handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid as u32);
            if handle.is_null() {
                return false;
            }
            CloseHandle(handle);
            true
        }
    }
    #[cfg(all(unix, target_os = "linux"))]
    {
        Path::new(&format!("/proc/{pid}")).exists()
    }
    #[cfg(all(unix, not(target_os = "linux")))]
    {
        use rustix::io::Errno;
        use rustix::process::{test_kill_process, Pid};
        let Some(pid) = Pid::from_raw(pid as i32) else {
            return false;
        };
        match test_kill_process(pid) {
            Ok(()) => true,
            Err(Errno::SRCH) => false,
            Err(Errno::PERM) => true,
            Err(_) => false,
        }
    }
}

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

    struct FakeLockClock {
        now: Mutex<Instant>,
        sleeps: Mutex<Vec<Duration>>,
    }

    impl FakeLockClock {
        fn new(start: Instant) -> Arc<Self> {
            Arc::new(Self {
                now: Mutex::new(start),
                sleeps: Mutex::new(Vec::new()),
            })
        }

        fn sleeps(&self) -> Vec<Duration> {
            self.sleeps.lock().unwrap().clone()
        }
    }

    impl LockClock for FakeLockClock {
        fn now(&self) -> Instant {
            *self.now.lock().unwrap()
        }

        fn sleep(&self, duration: Duration) {
            self.sleeps.lock().unwrap().push(duration);
            *self.now.lock().unwrap() += duration;
        }
    }

    #[test]
    fn drop_without_commit_removes_own_lock() {
        let dir = tempfile::tempdir().unwrap();
        let lock = dir.path().join("resource.lock");
        {
            let _lock = LockFile::acquire(&lock, LockWait::Immediately).unwrap();
            assert!(lock.is_file());
        }
        assert!(!lock.exists());
    }

    #[test]
    fn commit_to_replaces_target() {
        let dir = tempfile::tempdir().unwrap();
        let target = dir.path().join("resource");
        let lock_path = dir.path().join("resource.lock");
        let mut lock = LockFile::acquire(&lock_path, LockWait::Immediately).unwrap();
        lock.write_all(b"payload\n").unwrap();
        lock.commit_to(&target).unwrap();
        assert!(!lock_path.exists());
        assert_eq!(fs::read_to_string(&target).unwrap(), "payload\n");
    }

    struct FixedJitter(f64);

    impl LockJitter for FixedJitter {
        fn fraction(&self, _lock_path: &Path, _attempt: u32) -> f64 {
            self.0
        }
    }

    #[test]
    fn held_when_budget_exhausted() {
        let dir = tempfile::tempdir().unwrap();
        let lock_path = dir.path().join("x.lock");
        fs::write(&lock_path, b"foreign").unwrap();
        let start = Instant::now();
        let clock = FakeLockClock::new(start);
        let err = match LockFile::acquire_with_clock(
            &lock_path,
            LockWait::Backoff {
                budget: Duration::from_millis(10),
            },
            clock.clone(),
            Arc::new(FixedJitter(0.5)),
        ) {
            Err(e) => e,
            Ok(_) => panic!("expected lock held error"),
        };
        assert!(matches!(err, LockError::Held { .. }));
        assert!(lock_path.is_file());
        assert_eq!(fs::read_to_string(&lock_path).unwrap(), "foreign");
        assert!(!clock.sleeps().is_empty());
    }

    #[test]
    fn pid_sidecar_path_replaces_lock_suffix() {
        assert_eq!(
            pid_path_for_lock(Path::new("/r/.git/index.lock")),
            Path::new("/r/.git/index~pid.lock")
        );
        assert_eq!(
            pid_path_for_lock(Path::new("/r/.git/refs/heads/main.lock")),
            Path::new("/r/.git/refs/heads/main~pid.lock")
        );
        assert_eq!(
            pid_path_for_lock(Path::new("/r/odd")),
            Path::new("/r/odd~pid.lock")
        );
    }

    #[test]
    fn remove_if_stale_skips_when_lock_is_newer_than_sidecar() {
        use std::thread;
        use std::time::Duration;

        let dir = tempfile::tempdir().unwrap();
        let lock_path = dir.path().join("index.lock");
        fs::write(&lock_path, b"").unwrap();
        let pid_path = pid_path_for_lock(&lock_path);
        fs::write(&pid_path, "pid 999999999\n").unwrap();
        thread::sleep(Duration::from_millis(20));
        fs::write(&lock_path, b"replaced").unwrap();

        assert!(!LockHolder::remove_if_stale(&lock_path).unwrap());
        assert!(lock_path.is_file());
        assert!(pid_path.is_file());
    }

    #[test]
    fn held_converts_to_typed_error_with_holder() {
        let dir = tempfile::tempdir().unwrap();
        let lock_path = dir.path().join("index.lock");
        fs::write(&lock_path, b"").unwrap();
        fs::write(
            dir.path().join("index~pid.lock"),
            format!("pid {}\n", std::process::id()),
        )
        .unwrap();
        let err = LockFile::acquire(&lock_path, LockWait::Immediately)
            .err()
            .expect("held");
        match crate::error::Error::from(err) {
            crate::error::Error::LockHeld { path, holder } => {
                assert_eq!(path, lock_path);
                assert_eq!(
                    holder,
                    Some(LockHolder {
                        pid: u64::from(std::process::id()),
                        running: true,
                    })
                );
            }
            other => panic!("expected LockHeld, got {other:?}"),
        }
    }

    #[test]
    fn io_failure_converts_to_io_error() {
        let err = LockError::Io {
            path: PathBuf::from("x.lock"),
            source: io::Error::from(io::ErrorKind::PermissionDenied),
        };
        assert!(matches!(
            crate::error::Error::from(err),
            crate::error::Error::Io(e) if e.kind() == io::ErrorKind::PermissionDenied
        ));
    }

    #[test]
    fn rollback_removes_own_lock() {
        let dir = tempfile::tempdir().unwrap();
        let lock = dir.path().join("resource.lock");
        let lock_file = LockFile::acquire(&lock, LockWait::Immediately).unwrap();
        assert!(lock.is_file());
        lock_file.rollback();
        assert!(!lock.exists());
    }

    #[test]
    fn files_ref_lock_timeout_uses_milliseconds() {
        let mut cfg = ConfigSet::new();
        cfg.add_command_override("core.filesreflocktimeout", "100")
            .expect("set timeout");
        assert_eq!(LockWait::parse_files_ref_lock_timeout_ms(Some(&cfg)), 100);
        match LockWait::files_ref_lock(Some(&cfg)) {
            LockWait::Backoff { budget } => {
                assert_eq!(budget, Duration::from_millis(100));
            }
            other => panic!("expected backoff, got {other:?}"),
        }
    }

    #[test]
    fn files_ref_lock_timeout_negative_retries_indefinitely() {
        let mut cfg = ConfigSet::new();
        cfg.add_command_override("core.filesreflocktimeout", "-1")
            .expect("set timeout");
        assert!(matches!(
            LockWait::files_ref_lock(Some(&cfg)),
            LockWait::Indefinitely
        ));
    }

    #[test]
    fn indefinite_wait_succeeds_when_lock_cleared() {
        let dir = tempfile::tempdir().unwrap();
        let lock_path = dir.path().join("x.lock");
        fs::write(&lock_path, b"foreign").unwrap();
        let clock = FakeLockClock::new(Instant::now());
        let lock_path_thread = lock_path.clone();
        std::thread::spawn(move || {
            std::thread::sleep(Duration::from_millis(5));
            let _ = fs::remove_file(&lock_path_thread);
        });
        let _guard = LockFile::acquire_with_clock(
            &lock_path,
            LockWait::Indefinitely,
            clock,
            Arc::new(FixedJitter(0.0)),
        )
        .expect("indefinite wait should eventually acquire");
    }

    #[test]
    fn retry_while_held_resolves_wait_lazily_and_counts_attempt_time() {
        let key = Path::new("refs");
        let jitter = FixedJitter(0.0);
        let clock = FakeLockClock::new(Instant::now());

        let ok: Result<u32, u32> = retry_while_held(
            key,
            || panic!("wait resolved without contention"),
            clock.as_ref(),
            &jitter,
            || Ok(7),
            |_| true,
        );
        assert_eq!(ok, Ok(7));

        let mut calls = 0;
        let other = retry_while_held(
            key,
            || LockWait::Indefinitely,
            clock.as_ref(),
            &jitter,
            || {
                calls += 1;
                Err::<(), _>("io")
            },
            |e| *e == "held",
        );
        assert_eq!((other, calls), (Err("io"), 1));
        assert!(clock.sleeps().is_empty());

        // The first attempt itself takes the whole budget, so nothing is retried.
        let mut calls = 0;
        let slow = retry_while_held(
            key,
            || LockWait::Backoff {
                budget: Duration::from_millis(10),
            },
            clock.as_ref(),
            &jitter,
            || {
                calls += 1;
                clock.sleep(Duration::from_millis(10));
                Err::<(), _>(calls)
            },
            |_| true,
        );
        assert_eq!(slow, Err(1));

        let mut calls = 0;
        let later = retry_while_held(
            key,
            || LockWait::Backoff {
                budget: Duration::from_secs(1),
            },
            clock.as_ref(),
            &jitter,
            || {
                calls += 1;
                if calls < 4 {
                    Err(calls)
                } else {
                    Ok(calls)
                }
            },
            |_| true,
        );
        assert_eq!(later, Ok(4));
    }
}