girt 0.6.2

An incremental, idiomatic Rust implementation of Git
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
//! Caller-controlled release of this process's transient girt lock files.
//!
//! Call [`cleanup`] during shutdown in normal thread context, after requesting cancellation and
//! preventing new work. Cleanup also cancels pending reference lock waits. A caller-owned signal
//! callback thread can do this; a raw POSIX signal trampoline cannot. Girt installs no signal
//! handlers. Cleanup waits for active lock operations, invalidates live guards and removes only
//! files whose registered identity still matches.
//!
//! Completed publication is never rolled back. Surviving guards refuse publication after cleanup;
//! another acquisition after cleanup is allowed. The caller must exclude hostile lock-path and
//! parent-directory replacement races. Identity checks cannot make check/unlink atomic against a
//! non-cooperating writer. SIGKILL, process crashes and power loss cannot run this API.
//!
//! Unix uses device/inode identities. Other platforms preserve registered locks and report an
//! unsupported cleanup failure, retaining guard validity for ordinary Drop/abort. Persistent
//! worktree `locked` markers and pack `.keep` protections are not transient locks and are never
//! registered.
use std::cell::Cell;
use std::collections::HashMap;
use std::fs::{self, File};
use std::io;
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, RwLock, RwLockReadGuard, Weak};

static GATE: RwLock<()> = RwLock::new(());
static WAIT_GENERATION: AtomicUsize = AtomicUsize::new(0);
static REGISTRY: std::sync::LazyLock<Mutex<HashMap<usize, Weak<Registration>>>> =
    std::sync::LazyLock::new(|| Mutex::new(HashMap::new()));
thread_local! { static DEPTH: Cell<usize> = const { Cell::new(0) }; }

/// Effects of one cleanup attempt; failures do not prevent attempts on other owned locks.
#[derive(Debug, Default)]
#[non_exhaustive]
pub struct CleanupReport {
    /// Owned locks removed, or already absent, after their guards were invalidated.
    pub removed: Vec<PathBuf>,
    /// Replaced or non-regular paths preserved after invalidating the old guard.
    pub preserved: Vec<PathBuf>,
    /// Locks whose inspection or removal failed. Inspect these before manual recovery.
    pub failures: Vec<CleanupFailure>,
}

/// One cleanup refusal or filesystem failure, retaining its path and underlying cause.
#[derive(Debug, thiserror::Error)]
#[error("lock cleanup at {path:?}")]
#[non_exhaustive]
pub struct CleanupFailure {
    /// Absolute registered lock path.
    pub path: PathBuf,
    /// Identity inspection, unsupported platform, or unlink failure.
    #[source]
    pub source: io::Error,
}

/// Releases Unix identity-matched transient locks and invalidates their live registered guards.
///
/// This process-wide operation includes index/config edits, refs/reflogs/reftable, shallow
/// metadata, clone config, credentials and worktree administration mutexes. It does not scan for
/// stale locks. Cleanup cancels pending reference lock waits before waiting for active publication
/// and drop operations. On Unix, retained edits may still own open handles but cannot subsequently
/// publish. Unsupported platforms preserve guard validity for ordinary Drop/abort. Partial effects
/// completed before cleanup remain completed; new work after cleanup must be excluded by the
/// caller.
///
/// # Errors
///
/// Returns `WouldBlock` if invoked reentrantly from an active girt lock operation, avoiding
/// self-deadlock. Per-file failures are returned in [`CleanupReport::failures`]. No raw signal
/// handler may call this function: it locks, allocates and performs filesystem I/O.
///
/// ```no_run
/// # use std::sync::atomic::{AtomicBool, Ordering};
/// # let cancel = AtomicBool::new(false);
/// // In a normal shutdown callback, first stop admitting work and wake writers.
/// cancel.store(true, Ordering::Relaxed);
/// let report = girt::locks::cleanup()?;
/// // Join cancelled writers before exiting; retain failures for manual recovery.
/// for failure in report.failures {
///     eprintln!(
///         "lock cleanup failed at {:?}: {}",
///         failure.path, failure.source
///     );
/// }
/// # Ok::<(), std::io::Error>(())
/// ```
pub fn cleanup() -> io::Result<CleanupReport> {
    cleanup_matching(|_| true, true)
}

#[cfg(test)]
pub(crate) fn cleanup_under(root: &std::path::Path) -> io::Result<CleanupReport> {
    cleanup_matching(|path| path.starts_with(root), false)
}

fn cleanup_matching(
    select: impl Fn(&std::path::Path) -> bool,
    cancel_waits: bool,
) -> io::Result<CleanupReport> {
    if DEPTH.with(|depth| depth.get() != 0) {
        return Err(io::Error::new(
            io::ErrorKind::WouldBlock,
            "cleanup inside a lock operation",
        ));
    }
    // Wake pending reference lock waits before waiting for an active publisher's read gate.
    if cancel_waits {
        WAIT_GENERATION.fetch_add(1, Ordering::Relaxed);
    }
    let _exclusive = GATE.write().unwrap_or_else(|poison| poison.into_inner());
    let registrations = {
        let registry = REGISTRY.lock().unwrap_or_else(|poison| poison.into_inner());
        registry
            .values()
            .filter_map(Weak::upgrade)
            .collect::<Vec<_>>()
    };
    let mut report = CleanupReport::default();
    for registration in registrations {
        if !select(&registration.path) || !registration.active.load(Ordering::Relaxed) {
            continue;
        }
        #[cfg(unix)]
        registration.active.store(false, Ordering::Relaxed);
        match registration.remove_owned() {
            Ok(true) => {
                registration.active.store(false, Ordering::Relaxed);
                report.removed.push(registration.path.clone());
            }
            Ok(false) => report.preserved.push(registration.path.clone()),
            Err(source) => report.failures.push(CleanupFailure {
                path: registration.path.clone(),
                source,
            }),
        }
    }
    Ok(report)
}

pub(crate) fn wait_generation() -> usize {
    WAIT_GENERATION.load(Ordering::Relaxed)
}

/// Shares one OS handle between its writer and the Unix identity pin; cloning never duplicates a
/// descriptor. Windows registrations do not pin a handle, preserving existing delete-sharing rules.
#[derive(Clone, Debug)]
pub(crate) struct SharedFile(Arc<File>);

impl From<File> for SharedFile {
    fn from(file: File) -> Self {
        Self(Arc::new(file))
    }
}

impl std::ops::Deref for SharedFile {
    type Target = File;
    fn deref(&self) -> &File {
        &self.0
    }
}

impl std::io::Write for SharedFile {
    fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
        let mut file = self.0.as_ref();
        std::io::Write::write(&mut file, bytes)
    }
    fn flush(&mut self) -> io::Result<()> {
        let mut file = self.0.as_ref();
        std::io::Write::flush(&mut file)
    }
}

/// An identity failure cannot authorize unlinking the file. Keep the original cause and name
/// the lock requiring manual recovery, rather than returning a context-free metadata error.
#[derive(Debug, thiserror::Error)]
#[error("lock identity unavailable at {path:?}; cleanup refused")]
struct IdentityFailure {
    path: PathBuf,
    #[source]
    source: io::Error,
}

pub(crate) fn capture_identity(path: &std::path::Path, file: &File) -> io::Result<fs::Metadata> {
    file.metadata().map_err(|source| {
        io::Error::new(
            source.kind(),
            IdentityFailure {
                path: path.to_owned(),
                source,
            },
        )
    })
}

/// Serializes acquisition, publication and destruction against caller cleanup. Nested library
/// phases on one thread share the outer read guard, so a waiting cleanup writer cannot deadlock
/// a nested read acquisition. This guard is deliberately not Send.
pub(crate) struct Operation {
    _guard: Option<RwLockReadGuard<'static, ()>>,
}

pub(crate) fn operation() -> Operation {
    let guard = DEPTH.with(|depth| {
        let guard = if depth.get() == 0 {
            Some(GATE.read().unwrap_or_else(|poison| poison.into_inner()))
        } else {
            None
        };
        depth.set(depth.get() + 1);
        guard
    });
    Operation { _guard: guard }
}

impl Drop for Operation {
    fn drop(&mut self) {
        DEPTH.with(|depth| depth.set(depth.get() - 1));
    }
}

#[derive(Debug)]
pub(crate) struct Guard(Arc<Registration>);

#[derive(Debug)]
struct Registration {
    path: PathBuf,
    identity: fs::Metadata,
    #[cfg(unix)]
    _pinned: SharedFile,
    active: AtomicBool,
}

impl Guard {
    /// The caller holds an operation guard across exclusive creation and registration.
    pub(crate) fn new(path: &std::path::Path, file: &SharedFile, identity: fs::Metadata) -> Self {
        debug_assert!(path.is_absolute());
        #[cfg(not(unix))]
        let _ = file;
        let registration = Arc::new(Registration {
            path: path.to_owned(),
            identity,
            #[cfg(unix)]
            _pinned: file.clone(),
            active: AtomicBool::new(true),
        });
        let mut registry = REGISTRY.lock().unwrap_or_else(|poison| poison.into_inner());
        registry.insert(
            Arc::as_ptr(&registration) as usize,
            Arc::downgrade(&registration),
        );
        Self(registration)
    }

    pub(crate) fn check_path(&self) -> io::Result<()> {
        self.check()?;
        self.0.check_identity()
    }

    pub(crate) fn check(&self) -> io::Result<()> {
        if self.0.active.load(Ordering::Relaxed) {
            Ok(())
        } else {
            Err(io::Error::new(
                io::ErrorKind::Interrupted,
                "lock invalidated by caller cleanup",
            ))
        }
    }
}

impl Drop for Guard {
    fn drop(&mut self) {
        REGISTRY
            .lock()
            .unwrap_or_else(|poison| poison.into_inner())
            .remove(&(Arc::as_ptr(&self.0) as usize));
    }
}

impl Registration {
    fn check_identity(&self) -> io::Result<()> {
        #[cfg(unix)]
        {
            use std::os::unix::fs::MetadataExt;
            let current = fs::symlink_metadata(&self.path)?;
            if !current.is_file()
                || current.dev() != self.identity.dev()
                || current.ino() != self.identity.ino()
            {
                return Err(io::Error::other("registered lock path replaced"));
            }
        }
        Ok(())
    }
    #[cfg(unix)]
    fn remove_owned(&self) -> io::Result<bool> {
        use std::os::unix::fs::MetadataExt;
        let current = match fs::symlink_metadata(&self.path) {
            Ok(metadata) => metadata,
            Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(true),
            Err(error) => return Err(error),
        };
        if !current.is_file()
            || current.dev() != self.identity.dev()
            || current.ino() != self.identity.ino()
        {
            return Ok(false);
        }
        fs::remove_file(&self.path)?;
        Ok(true)
    }

    #[cfg(not(unix))]
    fn remove_owned(&self) -> io::Result<bool> {
        let _ = &self.identity;
        match fs::symlink_metadata(&self.path) {
            Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(true),
            Err(error) => return Err(error),
            Ok(_) => {}
        }
        Err(io::Error::new(
            io::ErrorKind::Unsupported,
            "owned lock cleanup identity on this platform",
        ))
    }
}

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

    #[cfg(unix)]
    #[test]
    fn cleanup_waits_for_registration_and_nested_operation() {
        let root = tempfile::tempdir().unwrap();
        let path = root.path().join("owned.lock");
        let (created, observe) = std::sync::mpsc::channel();
        let (release, wait) = std::sync::mpsc::channel();
        let (cleaned, done) = std::sync::mpsc::channel();
        std::thread::scope(|scope| {
            let path_ref = &path;
            let creator = scope.spawn(move || {
                let _operation = operation();
                let file = fs::OpenOptions::new()
                    .write(true)
                    .create_new(true)
                    .open(path_ref)
                    .unwrap();
                created.send(()).unwrap();
                wait.recv().unwrap();
                let _nested = operation();
                let identity = file.metadata().unwrap();
                let file = SharedFile::from(file);
                let guard = Guard::new(path_ref, &file, identity);
                // Keep the registration alive after the operation releases the acquisition gate.
                guard
            });
            observe.recv().unwrap();
            let worker = scope.spawn(|| {
                let report = cleanup_under(root.path()).unwrap();
                cleaned.send(()).unwrap();
                report
            });
            assert!(
                done.recv_timeout(std::time::Duration::from_millis(50))
                    .is_err()
            );
            release.send(()).unwrap();
            let report = worker.join().unwrap();
            assert!(report.failures.is_empty());
            // The creator's returned guard is retained by its JoinHandle until scope completion.
            assert_eq!(report.removed, vec![path.clone()]);
            let guard = creator.join().unwrap();
            assert!(guard.check().is_err());
        });
        assert!(!path.exists());
    }

    #[test]
    fn cleanup_from_a_lock_callback_refuses_without_deadlock() {
        let _operation = operation();
        assert_eq!(cleanup().unwrap_err().kind(), io::ErrorKind::WouldBlock);
    }
}

#[cfg(all(test, unix))]
mod failure_tests {
    use super::*;

    #[test]
    fn inspection_failure_preserves_the_old_file_and_reports_its_path() {
        let root = tempfile::tempdir().unwrap();
        let parent = root.path().join("parent");
        fs::create_dir(&parent).unwrap();
        let path = parent.join("owned.lock");
        let file = fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(&path)
            .unwrap();
        let guard = {
            let _operation = operation();
            let identity = file.metadata().unwrap();
            let file = SharedFile::from(file);
            Guard::new(&path, &file, identity)
        };
        fs::rename(&parent, root.path().join("saved-parent")).unwrap();
        fs::write(&parent, b"foreign parent replacement").unwrap();
        let report = cleanup_under(root.path()).unwrap();
        assert_eq!(report.failures.len(), 1);
        assert_eq!(report.failures[0].path, path);
        assert!(guard.check().is_err());
        assert!(root.path().join("saved-parent/owned.lock").is_file());
        assert_eq!(fs::read(parent).unwrap(), b"foreign parent replacement");
    }
}

#[cfg(all(test, unix))]
mod handle_tests {
    use std::os::fd::AsRawFd;

    use super::*;

    #[test]
    fn identity_pin_shares_the_writers_single_descriptor() {
        let root = tempfile::tempdir().unwrap();
        let path = root.path().join("owned.lock");
        let raw = fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(&path)
            .unwrap();
        let identity = raw.metadata().unwrap();
        let file = SharedFile::from(raw);
        let _operation = operation();
        let guard = Guard::new(&path, &file, identity);
        assert_eq!(file.as_raw_fd(), guard.0._pinned.as_raw_fd());
    }
}