girt 0.15.0

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
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
use std::fmt::Display;
use std::path::Path;
use std::sync::Arc;

use super::reader::ObjectView;
use crate::config::ConfigInputs;
use crate::refs::{Dereference, Expected, RefEdit, RefName, Reflog, Target};
use crate::workflow::{self, Environment, FetchOptions, NoCallbacks, PushOptions};
use crate::{Commit, LooseObjects, ObjectId, ObjectKind, Repository, Signature};

/// An owning convenience interface for trusted local repositories.
///
/// Construct with [`Self::discover`] for Git-default configuration and process environment, or
/// [`Self::new`] for an explicitly configured repository. Objects load lazily with default limits.
/// Use [`Repository`] for explicit limits, cancellation, and untrusted input; [`Self::repository`]
/// exposes that interface for operations needing more control. Shared reads use immutable object
/// snapshots and a synchronized lazy cache. This type is `Send + Sync`; `Log` owns its reader
/// state and can outlive the handle. See the [module contract](super).
#[derive(Debug)]
pub struct Repo {
    pub(super) reader: Arc<ObjectView>,
    loose: LooseObjects,
    environment: Environment,
}

/// A convenience-policy refusal or a switch that failed after checkout.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
    /// The supplied byte path contains invalid components.
    #[error("invalid repository-relative path {path:?}")]
    InvalidPath {
        /// Original path bytes.
        path: Vec<u8>,
    },
    /// A component was absent from a tree.
    #[error("path {path:?} is absent from tree {tree}")]
    PathAbsent {
        /// Original path bytes.
        path: Vec<u8>,

        /// Tree missing the component.
        tree: ObjectId,
    },
    /// A path component has the wrong mode for this lookup.
    #[error("path {path:?} requires {wanted:?}, found {found:?}")]
    PathKind {
        /// Original path bytes.
        path: Vec<u8>,

        /// Required kind at this component.
        wanted: ObjectKind,

        /// Actual entry kind.
        found: ObjectKind,
    },
    /// The requested remote has no configuration record.
    #[error("remote {name:?} is not configured")]
    RemoteNotConfigured {
        /// Requested remote name.
        name: String,
    },
    /// A URL-only remote has no fetch mapping; HEAD-only fetching is outside this prototype.
    #[error("remote {name:?} has no fetch refspecs; use workflow::fetch with explicit options")]
    NoFetchRefspecs {
        /// Requested remote name.
        name: String,
    },
    /// Recognized operation metadata requires explicit continuation or abort.
    #[error("finish or abort the current repository operation first")]
    OperationInProgress,
    /// A commit cannot be ordered without a committer date.
    #[error("commit {id} has no committer date")]
    MissingCommitter {
        /// Commit being walked.
        id: ObjectId,
    },
    /// Files and index have changed; HEAD publication failed. Inspect both reports before recovery.
    #[error("checkout completed but HEAD publication failed")]
    SwitchHead {
        /// Completed checkout effects.
        checkout: Box<crate::checkout::Report>,

        /// Reference and reflog publication effects.
        #[source]
        source: Box<crate::refs::TransactionError>,
    },
    /// The file's diff driver configures `textconv`, which Git runs before blaming and girt does
    /// not. Blame through [`crate::Objects::blame_with`] to attribute the stored bytes.
    #[error("diff driver {driver:?} of {path:?} configures textconv, which girt does not run")]
    Textconv {
        /// Original path bytes.
        path: Vec<u8>,
        /// Driver name from the `diff` attribute.
        driver: Vec<u8>,
    },
}

impl Repo {
    /// Owns `repository`, capturing the process environment for identity and transfers.
    ///
    /// No object or reference store is opened. Compose [`Repository::open_with_config`] first to
    /// choose configuration inputs explicitly; use [`Self::with_environment`] for isolated callers.
    pub fn new(repository: Repository) -> Self {
        let loose = repository.loose_objects();
        Self {
            reader: Arc::new(ObjectView::new(repository)),
            loose,
            environment: Environment::from_process(),
        }
    }

    /// Discovers a repository with [`ConfigInputs::git_default`] and
    /// [`Repository::discover_with_config`].
    ///
    /// # Errors
    ///
    /// Reports configuration and discovery errors before any mutation.
    pub fn discover(path: impl AsRef<Path>) -> crate::Result<Self> {
        let environment = Environment::from_process();
        let inputs = ConfigInputs::git_default(&environment)?;
        let repository = Repository::discover_with_config(path, &inputs)?;
        Ok(Self::new(repository).with_environment(environment))
    }

    /// Clones a URL and checks out its default branch with [`workflow::clone()`].
    ///
    /// Uses Git-default configuration and the process environment. For explicit options or
    /// callbacks use [`workflow::clone_with`], then construct a handle with [`Self::new`].
    ///
    /// # Errors
    ///
    /// Preserves workflow partial clone/checkout reports; see [`workflow::clone_with`].
    pub fn clone(url: &str, destination: impl AsRef<Path>) -> crate::Result<Self> {
        let outcome = workflow::clone(url, destination)?;
        let repository = outcome
            .clone
            .repository
            .ok_or_else(|| std::io::Error::other("completed clone has no repository"))?;
        Ok(Self::new(repository))
    }

    /// Chooses the environment for [`Signature`], [`Repository::ignore_rules`],
    /// [`Repository::diff_attributes`] and [`workflow`].
    /// Repository configuration is unchanged; load it with matching inputs before construction.
    #[must_use]
    pub fn with_environment(mut self, environment: Environment) -> Self {
        self.environment = environment;
        self
    }

    /// Borrows the explicit API for operations outside this prototype's policy.
    pub fn repository(&self) -> &Repository {
        &self.reader.repository
    }

    /// Resolves supported revision syntax through [`crate::revision::Resolver::resolve`].
    /// Accepts revision text or an [`ObjectId`]; other inputs are parsed from their [`Display`].
    ///
    /// # Errors
    ///
    /// Returns parse/resolution/storage errors. Unknown revisions and missing objects trigger one
    /// object refresh and retry; corruption and resource refusals do not.
    pub fn rev_parse(&self, revision: impl Display) -> crate::Result<ObjectId> {
        self.reader.resolve(revision, None)
    }

    /// Reads a byte path below a revision's tree using [`crate::revision::Resolver::resolve_to`],
    /// [`crate::Objects::read_tree`] and [`crate::Objects::read_blob`]. Paths are literal
    /// repository-relative components; revision path syntax is not interpolated into them. The
    /// revision accepts text or an [`ObjectId`], as in [`Self::rev_parse`].
    ///
    /// # Errors
    ///
    /// Reports invalid/absent paths, wrong kinds and storage failures. Each missing object gets
    /// one refresh and retry. Gitlinks are not traversed.
    pub fn blob_at(
        &self,
        revision: impl Display,
        path: impl AsRef<[u8]>,
    ) -> crate::Result<Vec<u8>> {
        let path = path.as_ref();
        if path.is_empty()
            || path
                .split(|b| *b == b'/')
                .any(|p| p.is_empty() || p == b"." || p == b".." || p.contains(&0))
        {
            return Err(Error::InvalidPath {
                path: path.to_vec(),
            }
            .into());
        }
        let mut id = self.reader.resolve(revision, Some(ObjectKind::Tree))?;
        let mut components = path.split(|b| *b == b'/').peekable();
        while let Some(component) = components.next() {
            let tree = self.reader.read_tree(id)?;
            let entry = tree
                .entries()
                .iter()
                .find(|e| e.name == component)
                .ok_or_else(|| Error::PathAbsent {
                    path: path.to_vec(),
                    tree: id,
                })?;
            let wanted = if components.peek().is_some() {
                ObjectKind::Tree
            } else {
                ObjectKind::Blob
            };
            if entry.mode.object_kind() != wanted {
                return Err(Error::PathKind {
                    path: path.to_vec(),
                    wanted,
                    found: entry.mode.object_kind(),
                }
                .into());
            }
            id = entry.id;
        }
        self.reader.read_blob(id)
    }

    /// Attributes lines through [`crate::Objects::blame`] with default limits.
    /// Resolves `revision` to a commit; paths remain literal bytes.
    ///
    /// Reads the path's diff driver from [`Repository::diff_attributes`] as `git blame` does: a
    /// driver with `diff.<driver>.textconv` is refused, since Git would blame the converted text.
    /// `binary` and `-diff` do not change blame, in Git or here.
    ///
    /// # Errors
    ///
    /// Returns revision resolution, attribute and blame errors, and [`Error::Textconv`], without
    /// mutation.
    pub fn blame(
        &self,
        revision: impl Display,
        path: impl AsRef<[u8]>,
    ) -> crate::Result<Vec<crate::blame::Hunk>> {
        self.blame_with(
            revision,
            path,
            Default::default(),
            &std::sync::atomic::AtomicBool::new(false),
        )
    }

    /// Attributes lines through [`crate::Objects::blame_with`] with explicit controls.
    ///
    /// Refuses a textconv driver as [`Self::blame`] does.
    ///
    /// # Errors
    ///
    /// Returns revision resolution, attribute and blame errors, and [`Error::Textconv`], without
    /// partial attribution.
    pub fn blame_with(
        &self,
        revision: impl Display,
        path: impl AsRef<[u8]>,
        limits: crate::blame::Limits,
        cancel: &std::sync::atomic::AtomicBool,
    ) -> crate::Result<Vec<crate::blame::Hunk>> {
        let commit = self.reader.resolve(revision, Some(ObjectKind::Commit))?;
        let path = path.as_ref();
        let mut attributes = self.reader.repository.diff_attributes(&self.environment)?;
        // Blame itself reports an invalid path.
        if crate::blame::valid_path(path)
            && let Some(driver) = attributes.textconv_driver(path)?
        {
            return Err(Error::Textconv {
                path: path.to_vec(),
                driver,
            }
            .into());
        }
        Ok(self
            .reader
            .snapshot()?
            .blame_with(commit, path, limits, cancel)?)
    }

    /// Compares HEAD, index and working files with ignore-aware collapsed untracked paths.
    ///
    /// Loads [`Repository::ignore_rules`] with the captured environment, then calls
    /// [`Repository::status`] with HEAD as baseline and
    /// [`crate::status::UntrackedFiles::Collapsed`]. Tracked content still uses raw bytes;
    /// attributes, filters and normalization remain explicit policy. Use [`Self::repository`]
    /// and [`Repository::raw_status`] for a raw untracked listing.
    ///
    /// # Errors
    ///
    /// Returns ignore-rule loading and status platform, storage and resource failures unchanged.
    /// No mutation occurs.
    pub fn status(&self) -> crate::Result<crate::status::Report> {
        let rules = self.reader.repository.ignore_rules(&self.environment)?;
        Ok(self.reader.repository.status(
            crate::status::Baseline::Head,
            crate::status::UntrackedFiles::Collapsed,
            &rules,
        )?)
    }

    /// Writes the `git diff <old> <new>` patch between two revisions' trees.
    ///
    /// Resolves both revisions to trees as [`Self::rev_parse`] does, detects renames (including
    /// empty files, as Git does) with [`crate::Objects::diff_trees_with`], loads
    /// [`Repository::diff_attributes`], then calls [`crate::Objects::write_patch_with`] with
    /// default options and limits. Attributes come from the working tree (`attr.tree` or
    /// `GIT_ATTR_SOURCE` when set, none in a bare repository), so `binary`, `-diff` and
    /// `diff=<driver>` apply as in `git diff`; a driver with textconv or an external command is
    /// refused. Abbreviation is automatic; `core.abbrev` and `diff.*` settings other than
    /// drivers are not read. Use [`crate::Objects::write_patch_with`] for context, abbreviation,
    /// binary policy, drivers or limits. Pass a buffered writer: each patch line is a separate
    /// write.
    ///
    /// # Errors
    ///
    /// Returns resolution, attribute, comparison and [`crate::patch::Error`] failures. Lines
    /// written before a failure remain in `out`.
    pub fn write_patch(
        &self,
        out: impl std::io::Write,
        old: impl Display,
        new: impl Display,
    ) -> crate::Result<()> {
        let old = self.reader.resolve(old, Some(ObjectKind::Tree))?;
        let new = self.reader.resolve(new, Some(ObjectKind::Tree))?;
        let objects = self.reader.snapshot()?;
        let options = crate::rewrites::Options::default();
        let comparison = objects.diff_trees_with(
            Some(old),
            Some(new),
            options,
            Default::default(),
            &std::sync::atomic::AtomicBool::new(false),
        )?;
        let mut attributes = self.reader.repository.diff_attributes(&self.environment)?;
        Ok(objects.write_patch_with(
            out,
            &comparison.entries,
            crate::patch::Options::default(),
            Some(&mut attributes),
            crate::patch::Limits::default(),
            &std::sync::atomic::AtomicBool::new(false),
        )?)
    }

    /// Starts an empty snapshot through [`crate::tree::TreeEditor::new`].
    /// Supply stored subtrees explicitly with `set_entry`; this does not load HEAD or stage files.
    pub fn tree_editor(&self) -> crate::tree::TreeEditor<'_> {
        crate::tree::TreeEditor::new(&self.loose)
    }

    /// Writes a commit with configured [`Signature::author`] and [`Signature::committer`], then
    /// advances resolved HEAD conditionally through [`crate::refs::References::transaction`].
    /// Uses [`Commit::builder`] and [`LooseObjects::write_commit`]. The current HEAD is the sole
    /// parent; unborn HEAD creates a root. Appends a Git-style commit subject to HEAD and each
    /// symbolic alias/branch in its chain (only HEAD when detached), even if
    /// `core.logAllRefUpdates` is disabled. This deliberate policy always keeps a reflog for
    /// convenience commits. The index and working files remain unchanged; this does not stage
    /// paths. Recognized in-progress operation metadata is refused through
    /// [`Repository::operation_state`]; merge/rebase commits need explicit orchestration.
    /// Before switching, the index/files must represent the new HEAD tree: commit an already
    /// staged index, or materialize the supplied snapshot separately.
    ///
    /// # Errors
    ///
    /// Rejects missing/wrong-kind trees, invalid identities and concurrent HEAD changes. A commit
    /// object may remain after publication failure. Reference errors retain partial effects;
    /// inspect them before retrying. Caller exclusion must cover HEAD observation through
    /// publication.
    pub fn commit(&mut self, tree: ObjectId, message: impl AsRef<[u8]>) -> crate::Result<ObjectId> {
        self.require_idle()?;
        self.reader.read_tree(tree)?;
        let author = Signature::author(self.reader.repository.config(), &self.environment)?;
        let committer = Signature::committer(self.reader.repository.config(), &self.environment)?;
        let refs = self.reader.repository.references()?;
        let parent = refs.resolve(&RefName::HEAD)?.id;
        let expected = parent.map_or(Expected::Absent, |id| Expected::Value(Target::Direct(id)));
        let commit = Commit::builder(tree, author, message.as_ref())
            .committer(committer.clone())
            .parents(parent)
            .build()?;
        let prefix = if parent.is_some() {
            b"commit: ".as_slice()
        } else {
            b"commit (initial): ".as_slice()
        };
        let message = [prefix, &commit.subject()].concat();
        let id = self.loose.write_commit(&commit)?;
        let edit = RefEdit::new(
            RefName::HEAD,
            Some(Target::Direct(id)),
            expected,
            Reflog::Append { committer, message },
        );
        let edit = edit.with_dereference(Dereference::Follow);
        refs.transaction(&[edit])?;
        Ok(id)
    }

    /// Checks out an existing local branch through [`Repository::checkout_tree`] and changes
    /// stored HEAD through [`crate::refs::References::transaction`], appending a Git-style checkout
    /// reflog on HEAD even when `core.logAllRefUpdates` is disabled.
    /// Holds prepared HEAD/reference locks across checkout. Caller must exclude all other working
    /// tree and reference writers, including activity in linked worktrees; branch occupancy is not
    /// checked. [`Repository::operation_state`] refuses recognized in-progress operations. Raw
    /// checkout requires Linux/macOS and refuses dirty or obstructed paths. The index and files
    /// must already match HEAD: a preceding `commit(tree, message)` does not stage or check out
    /// that tree.
    ///
    /// # Errors
    ///
    /// Preparation and checkout failures preserve HEAD. Checkout failures carry partial file/index
    /// effects. [`Error::SwitchHead`] retains a completed checkout when HEAD publication fails;
    /// inspect the new index/files and reference effects before recovery. No rollback is attempted.
    pub fn switch(&mut self, branch: &str) -> crate::Result<crate::checkout::Report> {
        self.switch_with(branch, || {}, || {})
    }

    fn switch_with(
        &mut self,
        branch: &str,
        after_prepare: impl FnOnce(),
        after_checkout: impl FnOnce(),
    ) -> crate::Result<crate::checkout::Report> {
        self.require_idle()?;
        let branch_name = branch;
        let branch = RefName::branch(branch_name)?;
        let repository = &self.reader.repository;
        let refs = repository.references()?;
        let stored = refs.read(&RefName::HEAD)?;
        let from = match &stored {
            Some(Target::Symbolic(name)) => name
                .as_bytes()
                .strip_prefix(b"refs/heads/")
                .unwrap_or(name.as_bytes())
                .to_vec(),
            Some(Target::Direct(id)) => id.to_string().into_bytes(),
            None => Vec::new(),
        };
        let message = [
            b"checkout: moving from ".as_slice(),
            &from,
            b" to ",
            branch_name.as_bytes(),
        ]
        .concat();
        let committer = Signature::committer(repository.config(), &self.environment)?;
        let expected = stored.map_or(Expected::Absent, Expected::Value);
        let edit = RefEdit::new(
            RefName::HEAD,
            Some(Target::Symbolic(branch)),
            expected,
            Reflog::Append { committer, message },
        )
        .with_dereference(Dereference::Stored);
        let prepared = refs.prepare_transaction(&[edit])?;
        after_prepare();
        // Old and new symbolic chains are now locked. Read their tips under those same locks.
        let old = refs.resolve(&RefName::HEAD)?.id;
        let baseline = old
            .map(|id| self.reader.read_commit(id).map(|commit| commit.tree()))
            .transpose()?;
        let revision = format!("refs/heads/{branch_name}");
        let target = self.reader.resolve(&revision, Some(ObjectKind::Commit))?;
        let target_tree = self.reader.read_commit(target)?.tree();
        let checkout = self
            .reader
            .repository
            .checkout_tree(baseline, Some(target_tree))?;
        after_checkout();
        if let Err(source) = prepared.publish() {
            return Err(Error::SwitchHead {
                checkout: Box::new(checkout),
                source: Box::new(source),
            }
            .into());
        }
        Ok(checkout)
    }

    fn require_idle(&self) -> crate::Result<()> {
        if !self
            .reader
            .repository
            .operation_state(Default::default())?
            .is_empty()
        {
            return Err(Error::OperationInProgress.into());
        }
        Ok(())
    }

    /// Fetches a configured remote using its fetch refspecs and [`workflow::fetch`].
    /// Uses the captured environment and [`NoCallbacks`]; use `workflow` for prompts or progress.
    /// Requires at least one configured fetch refspec. `remote.<name>.tagopt`, remote/fetch prune
    /// settings, automatic tag following and depth configuration are not interpreted; use explicit
    /// [`FetchOptions`] through `workflow` to choose those policies.
    ///
    /// # Errors
    ///
    /// Returns configured-remote and transfer errors, preserving partial installation/publication
    /// reports. Shallow boundaries in this handle remain unchanged; reopen after shallow changes.
    pub fn fetch(&self, remote: &str) -> crate::Result<workflow::FetchOutcome> {
        let configured = crate::remote::ConfiguredRemote::find(
            self.reader.repository.config(),
            remote.as_bytes(),
        )?
        .ok_or_else(|| Error::RemoteNotConfigured {
            name: remote.to_owned(),
        })?;
        if configured.fetch_refspecs().is_empty() {
            return Err(Error::NoFetchRefspecs {
                name: remote.to_owned(),
            }
            .into());
        }
        let options = FetchOptions::new(configured.fetch_refspecs().iter().map(|r| r.to_bytes()));
        Ok(workflow::fetch(
            &self.reader.repository,
            remote,
            &options,
            &self.environment,
            &mut NoCallbacks,
        )?)
    }

    /// Pushes explicit leased commands by remote name through [`workflow::push`].
    /// Destination/lease selection stays with the caller; push.default is not interpreted.
    /// Check `all_succeeded()` on the returned report. Uses [`PushOptions`] with a configured
    /// [`Signature::committer`] for reflogs and no prompts.
    ///
    /// # Errors
    ///
    /// Preserves workflow partial/uncertain effects. Read remote state before retrying uncertainty.
    pub fn push(
        &self,
        remote: &str,
        commands: Vec<crate::push::PushCommand>,
    ) -> crate::Result<crate::push::PushReport> {
        let identity = Signature::committer(self.reader.repository.config(), &self.environment)?;
        let options = PushOptions::default().with_identity(identity);
        Ok(workflow::push(
            &self.reader.repository,
            remote,
            commands,
            &options,
            &self.environment,
            &mut NoCallbacks,
        )?)
    }
}

#[cfg(all(test, any(target_os = "linux", target_os = "macos")))]
mod tests {
    use super::*;
    use crate::{InitKind, ObjectFormat};

    #[test]
    fn switch_locks_target_before_reading_and_retains_checkout_on_publication_failure() {
        let dir = tempfile::tempdir().unwrap();
        let repository =
            Repository::init(ObjectFormat::Sha1, dir.path(), InitKind::Worktree).unwrap();
        let environment = Environment::default()
            .with("GIT_AUTHOR_NAME", "A")
            .with("GIT_AUTHOR_EMAIL", "a@example.com")
            .with("GIT_COMMITTER_NAME", "A")
            .with("GIT_COMMITTER_EMAIL", "a@example.com");
        let mut handle = Repo::new(repository).with_environment(environment);
        let tree = handle.tree_editor().write().unwrap();
        let root = handle.commit(tree, "root").unwrap();
        handle
            .repository()
            .references()
            .unwrap()
            .transaction(&[RefEdit::create(
                RefName::branch("topic").unwrap(),
                root,
                Reflog::Preserve,
            )])
            .unwrap();
        let git_dir = handle.repository().git_dir().to_path_buf();

        let error = handle
            .switch_with(
                "topic",
                || {
                    assert!(git_dir.join("HEAD.lock").exists());
                    assert!(git_dir.join("refs/heads/topic.lock").exists());
                },
                || std::fs::remove_file(git_dir.join("HEAD.lock")).unwrap(),
            )
            .unwrap_err();

        let Error::SwitchHead {
            checkout,
            source: _,
        } = error.downcast::<Error>().unwrap()
        else {
            panic!("expected a post-checkout publication failure");
        };
        assert!(checkout.index_published);
        assert!(handle.repository().git_dir().join("index").exists());
        assert_eq!(
            handle.repository().head().unwrap().name,
            RefName::branch("main").unwrap()
        );
    }
}