grit-lib 0.5.32

Core library for the grit Git implementation
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
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
//! Repository-scoped reference and reflog access via [`References`].
use std::ops::ControlFlow;

use crate::config::ident_resolve::IdentRole;
use crate::error::{Error, Result};
use crate::lockfile::LockWait;
use crate::objects::ObjectId;
use crate::porcelain::CommitError;
use crate::reflog::ReflogEntry;
use crate::refs::listing::{query_refs, RefListing, RefQuery, RefQueryOptions};
use crate::refs::on_store::reflog_wanted;
use crate::refs::store::{
    Expected, RawRef, RefName, RefNameRef, RefStoreError, RefUpdate, RefUpdateFlags, ReflogUpdate,
};
use crate::refs::{
    commit_ref_update_on_store, commit_ref_updates_non_atomic_on_store,
    commit_ref_updates_on_store, commit_ref_updates_on_store_with_wait, delete_ref_on_store,
    ensure_refname_safe_for_storage, list_refs_glob_in, list_refs_in,
    read_symbolic_ref_for_repository, shorten::expand_ref_dwim_full_name,
    store_write_value_on_store, write_symbolic_ref_on_store, RefUpdateCommitOutcome,
};
use crate::repo::Repository;
use crate::state::HeadState;

/// The ref a short name such as `main` or `v1.0` stands for, from [`References::dwim`].
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct DwimMatch {
    /// Full name of the ref the short name expands to, with symbolic refs followed to the
    /// last ref in the chain (`HEAD` on `main` yields `refs/heads/main`).
    pub name: RefName,
    /// Object [`Self::name`] resolves to.
    pub oid: ObjectId,
    /// How many expansion rules (`<name>`, `refs/<name>`, `refs/tags/<name>`,
    /// `refs/heads/<name>`, …) named an existing ref. More than one means the short name is
    /// ambiguous; [`Self::name`] is the first by Git's precedence. With
    /// `core.warnAmbiguousRefs = false` the scan stops at the first match, so this is `1`.
    pub candidates: usize,
}

/// A ref returned by [`References::read_existing`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ExistingRef {
    /// Value as stored (a direct oid or a symbolic target).
    pub(crate) raw: RawRef,
    /// Object the ref resolves to.
    pub(crate) oid: ObjectId,
}

/// Resolve, list, and update refs for one open repository.
#[derive(Debug, Copy, Clone)]
pub struct References<'repo> {
    repo: &'repo Repository,
}

impl<'repo> References<'repo> {
    /// Bind ref operations to `repo`.
    #[inline]
    #[must_use]
    pub fn new(repo: &'repo Repository) -> Self {
        Self { repo }
    }

    /// Underlying repository.
    #[inline]
    #[must_use]
    pub fn repository(&self) -> &'repo Repository {
        self.repo
    }

    /// Low-level ref storage backend (same as [`Repository::ref_store`]).
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> grit_lib::error::Result<()> {
    /// use grit_lib::refs::store::RefNameRef;
    /// use grit_lib::repo::{InitOptions, Repository};
    /// let dir = tempfile::tempdir()?;
    /// let (repo, _) = Repository::init(dir.path(), &InitOptions::default())?;
    /// let _ = repo
    ///     .references()
    ///     .store()
    ///     .read_raw(RefNameRef::from_trusted("HEAD"))?;
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    #[must_use]
    pub fn store(&self) -> &'repo dyn crate::refs::store::RefStore {
        self.repo.ref_store()
    }

    /// Resolve a ref name to an object id, following symbolic refs.
    ///
    /// # Errors
    ///
    /// Propagates ref store and resolution errors.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> grit_lib::error::Result<()> {
    /// use grit_lib::refs::store::{RefName, RefNameRef};
    /// use grit_lib::repo::{InitOptions, Repository};
    /// use grit_lib::ident::Signature;
    /// use grit_lib::porcelain::commit::CommitRequest;
    /// use grit_lib::progress::NullProgress;
    /// let dir = std::env::temp_dir().join("grit-refs-resolve-doc");
    /// let (repo, _) = Repository::init(&dir, &InitOptions::default())?;
    /// let mut req = CommitRequest::new("doc");
    /// req.author = Some(Signature::new("Doc", "doc@example.com", repo.identity_now())?);
    /// req.committer = Some(Signature::new("Doc", "doc@example.com", repo.identity_now())?);
    /// req.allow_empty = true;
    /// let _ = repo.commits().create_staged(&req, &mut NullProgress, &grit_lib::progress::CancelToken::never())?;
    /// let main = RefName::try_from("refs/heads/main").expect("valid ref");
    /// let head = repo.references().resolve(&main)?;
    /// assert!(!head.to_hex().is_empty());
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    pub fn resolve(&self, name: impl AsRef<RefNameRef>) -> Result<ObjectId> {
        self.repo.resolve_ref_oid(name.as_ref().as_str())
    }

    /// Where `HEAD` points: a branch (possibly unborn), a detached commit, or nothing usable.
    ///
    /// Files repositories read the on-disk `HEAD` (including a symlinked `HEAD`) and resolve
    /// the branch tip through this repository's ref store; reftable and injected stores are
    /// the only source of `HEAD`. A missing or malformed `HEAD` is [`HeadState::Invalid`],
    /// not an error.
    ///
    /// # Errors
    ///
    /// Propagates ref store read and resolution failures other than a missing branch tip.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> grit_lib::error::Result<()> {
    /// use grit_lib::repo::{InitOptions, Repository};
    /// let dir = tempfile::tempdir()?;
    /// let (repo, _) = Repository::init(dir.path(), &InitOptions::default())?;
    /// let head = repo.references().head()?;
    /// assert!(head.is_unborn());
    /// assert_eq!(head.branch_name(), Some("main"));
    /// # Ok(())
    /// # }
    /// ```
    pub fn head(&self) -> Result<HeadState> {
        crate::state::resolve_head_for_repository(self.repo)
    }

    /// The target of the symbolic ref `name`, or `None` when `name` is missing or direct.
    ///
    /// Only one level is read: `HEAD` pointing at `refs/heads/main` yields
    /// `refs/heads/main` even when that ref is itself symbolic.
    ///
    /// # Errors
    ///
    /// Propagates ref store read failures.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> grit_lib::error::Result<()> {
    /// use grit_lib::repo::{InitOptions, Repository};
    /// let dir = tempfile::tempdir()?;
    /// let (repo, _) = Repository::init(dir.path(), &InitOptions::default())?;
    /// let target = repo.references().symbolic("HEAD")?;
    /// assert_eq!(target.as_ref().map(|name| name.as_str()), Some("refs/heads/main"));
    /// # Ok(())
    /// # }
    /// ```
    pub fn symbolic(&self, name: impl AsRef<RefNameRef>) -> Result<Option<RefName>> {
        Ok(read_symbolic_ref_for_repository(self.repo, name)?.map(RefName::from_trusted))
    }

    /// Expand a short name the way revision arguments are expanded (`main` to
    /// `refs/heads/main`, `v1.0` to `refs/tags/v1.0`, `origin` to
    /// `refs/remotes/origin/HEAD`, …).
    ///
    /// Returns `None` when no rule names an existing ref that resolves. A symbolic ref whose
    /// target is missing does not match; the repository's warning sink is told about it.
    ///
    /// # Errors
    ///
    /// Propagates ref store read failures and a symbolic ref chain that loops.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> grit_lib::error::Result<()> {
    /// use grit_lib::repo::{InitOptions, Repository};
    /// let dir = tempfile::tempdir()?;
    /// let (repo, _) = Repository::init(dir.path(), &InitOptions::default())?;
    /// assert!(repo.references().dwim("main")?.is_none());
    /// # Ok(())
    /// # }
    /// ```
    pub fn dwim(&self, spec: &str) -> Result<Option<DwimMatch>> {
        let (candidates, name) = expand_ref_dwim_full_name(self.repo, spec)?;
        let Some(name) = name else {
            return Ok(None);
        };
        let Some(oid) = self.resolve_if_exists(&name)? else {
            return Ok(None);
        };
        Ok(Some(DwimMatch {
            name: RefName::from_trusted(name),
            oid,
            candidates,
        }))
    }

    /// Read `name` when it exists: its stored value and the object it resolves to.
    ///
    /// Unlike [`resolve`](Self::resolve), a missing ref is `Ok(None)` rather than an error,
    /// so read and corruption failures stay distinguishable from absence. A direct ref is
    /// read once; only a symbolic ref is followed.
    pub(crate) fn read_existing(&self, name: &str) -> Result<Option<ExistingRef>> {
        let name = RefNameRef::from_trusted(name);
        let Some(raw) = self.repo.ref_store().read_raw(name)? else {
            return Ok(None);
        };
        let oid = match &raw {
            RawRef::Direct(oid) => *oid,
            RawRef::Symbolic(_) => self.repo.resolve_ref_oid(name.as_str())?,
        };
        Ok(Some(ExistingRef { raw, oid }))
    }

    /// Resolve `name` when it exists, `Ok(None)` when it does not (see [`Self::read_existing`]).
    pub(crate) fn resolve_if_exists(&self, name: &str) -> Result<Option<ObjectId>> {
        Ok(self.read_existing(name)?.map(|existing| existing.oid))
    }

    /// Delete `name` and its reflog through this repository's ref store, provided it still
    /// has the value `existing` was read with.
    ///
    /// The delete is a compare-and-swap, so a concurrent update between the caller's checks
    /// and the delete fails instead of being lost. A symbolic ref is deleted itself, not its
    /// target.
    pub(crate) fn delete_verified(&self, name: &str, existing: &ExistingRef) -> Result<()> {
        ensure_refname_safe_for_storage(name)?;
        let name_ref = RefNameRef::from_trusted(name);
        let (expected, no_deref) = match &existing.raw {
            RawRef::Symbolic(target) => (
                Expected::Symref(RefName::from_trusted(target.clone())),
                true,
            ),
            RawRef::Direct(oid) => (Expected::Oid(*oid), false),
        };
        let store = self.store();
        commit_ref_update_on_store(
            store,
            RefUpdate {
                name: RefName::from_trusted(name.to_owned()),
                new_value: None,
                expected,
                reflog: None,
                flags: RefUpdateFlags {
                    no_deref,
                    ..RefUpdateFlags::default()
                },
            },
        )?;
        store.delete_reflog(name_ref)
    }

    /// List refs under `prefix` (for example `"refs/heads/"`), sorted by name.
    ///
    /// # Errors
    ///
    /// Propagates ref store iteration errors.
    #[inline]
    pub fn list(&self, prefix: &str) -> Result<Vec<(RefName, ObjectId)>> {
        Ok(list_refs_in(self.repo, prefix)?
            .into_iter()
            .map(|(name, oid)| (RefName::from_trusted(name), oid))
            .collect())
    }

    /// List refs whose full names match the glob `pattern` (for example `refs/heads/topic/*`
    /// or `refs/tags/v1.*`), sorted by name.
    ///
    /// The text before the first wildcard is a name prefix, so `refs/tags/v*` lists
    /// `refs/tags/v1`. A pattern without wildcards lists the refs under that directory.
    ///
    /// # Errors
    ///
    /// Propagates ref store iteration errors.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> grit_lib::error::Result<()> {
    /// use grit_lib::repo::{InitOptions, Repository};
    /// let dir = tempfile::tempdir()?;
    /// let (repo, _) = Repository::init(dir.path(), &InitOptions::default())?;
    /// assert!(repo.references().list_glob("refs/tags/v*")?.is_empty());
    /// # Ok(())
    /// # }
    /// ```
    pub fn list_glob(&self, pattern: &str) -> Result<Vec<(RefName, ObjectId)>> {
        Ok(list_refs_glob_in(self.repo, pattern)?
            .into_iter()
            .map(|(name, oid)| (RefName::from_trusted(name), oid))
            .collect())
    }

    /// List refs matching `query` (patterns, sort, limit) through this repository's ref store.
    ///
    /// # Errors
    ///
    /// Returns ref store errors when the ref store cannot be read, when creator-date sort
    /// is requested without object data, or when an object read fails.
    pub fn query(
        &self,
        query: &RefQuery,
        options: &RefQueryOptions,
    ) -> crate::error::Result<Vec<RefListing>> {
        query_refs(self.repo, query, options)
    }

    /// Point `name` at `oid`, creating parent directories as needed.
    ///
    /// Uses the [`RefStore`](crate::refs::store::RefStore) installed on this repository (including
    /// injected in-memory stores), not a fresh open from `git_dir` alone.
    ///
    /// Symbolic refs are followed: updating `HEAD` while it points at `refs/heads/main` moves
    /// `main` and leaves `HEAD` symbolic. Reflog entries are appended when
    /// [`core.logAllRefUpdates`](crate::refs::LogRefsConfig) allows (same policy as
    /// `git update-ref`). Identity comes from the repository committer signature.
    ///
    /// To rewrite `HEAD` itself (detach or replace the symref file), use
    /// [`Self::update_direct`]. To require the ref tip to match an expected oid first, use
    /// [`Self::compare_and_swap`].
    ///
    /// `oid` must be stored in this repository, and must be a commit when `name` is a branch
    /// (`refs/heads/…`) or `HEAD`. This catches a commit that a concurrent prune deleted after
    /// you wrote it, instead of leaving the ref pointing at a missing object.
    ///
    /// # Errors
    ///
    /// - [`RefStoreError::MissingObject`](crate::refs::store::RefStoreError::MissingObject)
    ///   when the repository does not store `oid`.
    /// - [`RefStoreError::NotACommit`](crate::refs::store::RefStoreError::NotACommit) when
    ///   `name` is a branch or `HEAD` and `oid` is not a commit.
    /// - Validation, locking, and I/O errors from the ref backend.
    ///
    /// The two object errors are returned as [`crate::error::RefError::Store`]. The ref is
    /// unchanged on error.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> grit_lib::error::Result<()> {
    /// use grit_lib::refs::store::{RefName, RefNameRef};
    /// use grit_lib::repo::{InitOptions, Repository};
    /// use grit_lib::ident::Signature;
    /// use grit_lib::porcelain::commit::CommitRequest;
    /// use grit_lib::progress::NullProgress;
    /// let dir = std::env::temp_dir().join("grit-refs-write-doc");
    /// let (repo, _) = Repository::init(&dir, &InitOptions::default())?;
    /// let mut req = CommitRequest::new("doc");
    /// req.author = Some(Signature::new("Doc", "doc@example.com", repo.identity_now())?);
    /// req.committer = Some(Signature::new("Doc", "doc@example.com", repo.identity_now())?);
    /// req.allow_empty = true;
    /// let commit = repo.commits().create_staged(&req, &mut NullProgress, &grit_lib::progress::CancelToken::never())?.oid;
    /// let name = RefName::try_from("refs/heads/handle-demo").expect("valid ref");
    /// repo.references().update(&name, &commit)?;
    /// assert_eq!(repo.references().resolve(&name)?, commit);
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    pub fn update(&self, name: impl AsRef<RefNameRef>, oid: &ObjectId) -> Result<()> {
        self.commit_point(name.as_ref(), oid, Expected::Any, RefUpdateFlags::default())
    }

    /// Point `name` at `oid` without following symbolic refs.
    ///
    /// Updating `HEAD` writes the object id into `.git/HEAD` (detached HEAD) instead of moving
    /// the branch `HEAD` points at. Reflog policy matches [`Self::update`].
    ///
    /// # Errors
    ///
    /// Same validation and backend errors as [`Self::update`].
    pub fn update_direct(&self, name: impl AsRef<RefNameRef>, oid: &ObjectId) -> Result<()> {
        self.commit_point(
            name.as_ref(),
            oid,
            Expected::Any,
            RefUpdateFlags {
                no_deref: true,
                ..RefUpdateFlags::default()
            },
        )
    }

    /// Point `name` at `oid` only when it currently resolves to `expected`.
    ///
    /// Symbolic refs are followed the same way as [`Self::update`]. On mismatch the ref is
    /// unchanged and the error is
    /// [`RefStoreError::ExpectedMismatch`](crate::refs::store::RefStoreError::ExpectedMismatch).
    ///
    /// # Errors
    ///
    /// Same as [`Self::update`], plus compare-and-swap mismatch.
    pub fn compare_and_swap(
        &self,
        name: impl AsRef<RefNameRef>,
        expected: &ObjectId,
        oid: &ObjectId,
    ) -> Result<()> {
        self.commit_point(
            name.as_ref(),
            oid,
            Expected::Oid(*expected),
            RefUpdateFlags::default(),
        )
    }

    /// Make `name` a symbolic ref pointing at `target` (for example `HEAD` at
    /// `refs/heads/main`), replacing whatever `name` held. No reflog entry is written.
    ///
    /// `target` does not have to exist: pointing `HEAD` at a branch with no commits yet
    /// leaves the repository on an unborn branch.
    ///
    /// # Errors
    ///
    /// [`RefError::Invalid`](crate::error::RefError::Invalid) when `name` is not safe to store, a namespace conflict with an
    /// existing ref, and lock and I/O failures from the ref backend.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> grit_lib::error::Result<()> {
    /// use grit_lib::repo::{InitOptions, Repository};
    /// let dir = tempfile::tempdir()?;
    /// let (repo, _) = Repository::init(dir.path(), &InitOptions::default())?;
    /// repo.references().update_symbolic("HEAD", "refs/heads/trunk")?;
    /// assert_eq!(repo.references().head()?.branch_name(), Some("trunk"));
    /// # Ok(())
    /// # }
    /// ```
    pub fn update_symbolic(
        &self,
        name: impl AsRef<RefNameRef>,
        target: impl AsRef<RefNameRef>,
    ) -> Result<()> {
        write_symbolic_ref_on_store(
            self.store(),
            self.repo.git_dir(),
            name.as_ref().as_str(),
            target.as_ref().as_str(),
        )
    }

    /// Delete `name` and its reflog. A symbolic ref is deleted itself, not its target.
    ///
    /// # Errors
    ///
    /// [`RefStoreError::NotFound`](crate::refs::store::RefStoreError::NotFound) (as
    /// [`RefError::Store`](crate::error::RefError::Store)) when `name` does not exist, [`RefError::Invalid`](crate::error::RefError::Invalid) when it is not
    /// safe to store, and lock and I/O failures from the ref backend.
    pub fn delete(&self, name: impl AsRef<RefNameRef>) -> Result<()> {
        delete_ref_on_store(self.store(), name.as_ref().as_str())
    }

    /// Delete `name` only when it currently resolves to `expected`.
    ///
    /// On mismatch the ref is unchanged and the error is
    /// [`RefStoreError::ExpectedMismatch`](crate::refs::store::RefStoreError::ExpectedMismatch).
    ///
    /// # Errors
    ///
    /// Same as [`Self::delete`], plus the compare-and-swap mismatch.
    pub fn compare_and_delete(
        &self,
        name: impl AsRef<RefNameRef>,
        expected: &ObjectId,
    ) -> Result<()> {
        let name = name.as_ref().as_str();
        ensure_refname_safe_for_storage(name)?;
        store_write_value_on_store(
            self.store(),
            self.repo.git_dir(),
            name,
            None,
            Expected::Oid(*expected),
            None,
        )
    }

    /// Apply `updates` as one all-or-nothing transaction through this repository's ref store.
    ///
    /// Every update is checked (compare-and-swap expectations, name conflicts, and that a
    /// direct value names a stored object, and a commit on a branch or `HEAD`) before any ref
    /// moves. Reflog lines are written only for updates that carry
    /// [`RefUpdate::reflog`](crate::refs::store::RefUpdate::reflog).
    ///
    /// # Errors
    ///
    /// [`RefStoreError`](crate::refs::store::RefStoreError) (as [`RefError::Store`](crate::error::RefError::Store)) for
    /// duplicate names, expectation mismatches, lock and name conflicts, and missing or
    /// non-commit objects; I/O and corrupt-store failures from the backend. No ref changes on
    /// error.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> grit_lib::error::Result<()> {
    /// use grit_lib::refs::store::{Expected, RawRef, RefName, RefUpdate, RefUpdateFlags};
    /// use grit_lib::repo::{InitOptions, Repository};
    /// let dir = tempfile::tempdir()?;
    /// let (repo, _) = Repository::init(dir.path(), &InitOptions::default())?;
    /// let target = RefName::try_from("refs/heads/main").expect("valid ref");
    /// repo.references().apply(&[RefUpdate {
    ///     name: RefName::try_from("refs/heads/alias").expect("valid ref"),
    ///     new_value: Some(RawRef::Symbolic(target.as_str().to_owned())),
    ///     expected: Expected::Missing,
    ///     reflog: None,
    ///     flags: RefUpdateFlags::default(),
    /// }])?;
    /// assert_eq!(repo.references().symbolic("refs/heads/alias")?, Some(target));
    /// # Ok(())
    /// # }
    /// ```
    pub fn apply(&self, updates: &[RefUpdate]) -> Result<()> {
        if updates.is_empty() {
            return Ok(());
        }
        commit_ref_updates_on_store(self.store(), updates, &[])
    }

    /// Apply `updates` one ref at a time, the way a non-atomic push is applied: deletions
    /// commit together first, then creates and updates, and a failing ref is reported in its
    /// outcome instead of failing its siblings.
    ///
    /// Outcomes are returned in input order.
    ///
    /// # Errors
    ///
    /// Only failures that stop a whole phase (for example the backend cannot be locked or
    /// read); per-ref rejections are in [`RefUpdateCommitOutcome::result`].
    pub fn apply_each(&self, updates: Vec<RefUpdate>) -> Result<Vec<RefUpdateCommitOutcome>> {
        commit_ref_updates_non_atomic_on_store(self.store(), updates)
    }

    fn commit_point(
        &self,
        name: &RefNameRef,
        oid: &ObjectId,
        expected: Expected,
        flags: RefUpdateFlags,
    ) -> Result<()> {
        let refname = name.as_str();
        ensure_refname_safe_for_storage(refname)?;
        let store = self.store();
        let config = self.repo.config().snapshot()?;
        let signature = match self
            .repo
            .identity(IdentRole::Committer, self.repo.identity_now())
        {
            Ok(sig) => Some(sig),
            Err(crate::error::Error::Commit(CommitError::Identity(_))) => None,
            Err(err) => return Err(err),
        };
        let reflog_for = |target: &str| -> Result<Option<ReflogUpdate>> {
            let Some(sig) = signature.as_ref() else {
                return Ok(None);
            };
            Ok(reflog_wanted(store, config.as_ref(), target)?
                .then(|| ReflogUpdate::from_signature(sig, "")))
        };

        // A symbolic ref whose target does not exist yet (an unborn `HEAD`) has no old tip.
        let old_tip = match self.resolve_if_exists(refname) {
            Ok(tip) => tip,
            Err(Error::Ref(crate::error::RefError::Store(RefStoreError::NotFound { .. }))) => None,
            Err(err) => return Err(err),
        };
        let mut updates = Vec::with_capacity(2);

        // Peeling `HEAD` must not attach one reflog decision to both `HEAD` and the target
        // branch: Git evaluates existing logs independently when log-all-ref-updates is off.
        let peeled_head_target = if !flags.no_deref && refname == "HEAD" {
            match store.read_raw(RefNameRef::from_trusted("HEAD"))? {
                Some(RawRef::Symbolic(target)) => Some(target),
                _ => None,
            }
        } else {
            None
        };

        if let Some(branch) = peeled_head_target {
            let branch_for_reflog = branch.clone();
            updates.push(RefUpdate {
                name: RefName::from_trusted(branch),
                new_value: Some(RawRef::Direct(*oid)),
                expected,
                reflog: reflog_for(branch_for_reflog.as_str())?,
                flags: RefUpdateFlags::default(),
            });
            if let Some(mut head_reflog) = reflog_for("HEAD")? {
                head_reflog.old_oid = old_tip;
                head_reflog.new_oid = Some(*oid);
                updates.push(RefUpdate {
                    name: RefName::from_trusted("HEAD"),
                    new_value: Some(RawRef::Direct(*oid)),
                    expected: Expected::Any,
                    reflog: Some(head_reflog),
                    flags: RefUpdateFlags {
                        log_only: true,
                        no_deref: true,
                        ..RefUpdateFlags::default()
                    },
                });
            }
        } else {
            updates.push(RefUpdate {
                name: RefName::from_trusted(refname.to_owned()),
                new_value: Some(RawRef::Direct(*oid)),
                expected,
                reflog: reflog_for(refname)?,
                flags,
            });

            let mirror_head = !flags.no_deref
                && refname.starts_with("refs/heads/")
                && matches!(
                    store.read_raw(RefNameRef::from_trusted("HEAD"))?,
                    Some(RawRef::Symbolic(head_branch)) if head_branch.as_str() == refname
                );
            if mirror_head {
                if let Some(mut head_reflog) = reflog_for("HEAD")? {
                    head_reflog.old_oid = old_tip;
                    head_reflog.new_oid = Some(*oid);
                    updates.push(RefUpdate {
                        name: RefName::from_trusted("HEAD"),
                        new_value: Some(RawRef::Direct(*oid)),
                        expected: Expected::Any,
                        reflog: Some(head_reflog),
                        flags: RefUpdateFlags {
                            log_only: true,
                            no_deref: true,
                            ..RefUpdateFlags::default()
                        },
                    });
                }
            }
        }

        commit_ref_updates_on_store_with_wait(store, &updates, || {
            LockWait::files_ref_lock(Some(config.as_ref()))
        })
    }

    /// Read reflog entries for `name` (oldest first).
    ///
    /// # Errors
    ///
    /// Propagates reflog parse and backend errors.
    #[inline]
    pub fn reflog(&self, name: impl AsRef<RefNameRef>) -> Result<Vec<ReflogEntry>> {
        let mut entries = Vec::new();
        self.repo
            .ref_store()
            .for_each_reflog_entry(name.as_ref(), false, &mut |entry| {
                entries.push(entry.clone());
                ControlFlow::Continue(())
            })?;
        Ok(entries)
    }

    /// Pack loose refs into `packed-refs` (files backend) or compact reftable tables.
    ///
    /// # Errors
    ///
    /// Propagates ref-store, locking, and I/O failures.
    pub fn pack(
        &self,
        opts: &crate::maintenance::PackRefsOptions,
    ) -> Result<crate::maintenance::PackRefsReport> {
        crate::maintenance::pack_refs(self.repo, opts)
    }
}