Skip to main content

ostrya/
refs.rs

1//! Ref resolution, listing, and writes.
2//!
3//! A ref is a file under `refs/` that names a commit by its checksum. The
4//! entry points are:
5//!
6//! - [`Repo::resolve_rev`] resolves a revision string to a commit. Its doc
7//!   gives the revision syntax.
8//! - [`Repo::resolve_ref_tip`] reads one [`Ref`] from the ref store: a local
9//!   ref, a remote ref, or a collection ref.
10//! - [`Repo::list_refs`], [`Repo::list_remote_refs`],
11//!   [`Repo::list_mirror_refs`], [`Repo::list_collection_refs`],
12//!   [`Repo::list_collection_refs_in`], and [`Repo::list_ref_aliases`] list
13//!   refs.
14//! - [`Repo::set_ref_immediate`] writes one ref outside a transaction. Its doc
15//!   gives the ref file format and the durability rules.
16//! - [`Transaction::set_ref`] queues a ref write for the transaction commit.
17
18use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
19use std::io::{Read, Write};
20use std::os::fd::{AsFd, BorrowedFd, OwnedFd};
21#[cfg(feature = "receive")]
22use std::sync::Arc;
23
24use ostrya_core::{Checksum, Ref, RefPattern, RefSelector, RepoMode};
25use rustix::fs::{AtFlags, FileType, Mode, OFlags};
26use rustix::io::Errno;
27
28use crate::access::{AccessRules, Namespace, ReadAccess};
29use crate::archive::{Walked, resolve_alias, walk};
30use crate::config::valid_remote_name;
31use crate::error::{Error, Result};
32use crate::perm;
33use crate::repo::Repo;
34use crate::staging::{REF_TEMP_PREFIX, TempEntry, open_tmp_dir};
35use crate::summary::SelectionFloor;
36use crate::transaction::Transaction;
37use crate::traverse::read_dir_names;
38
39/// One collection-qualified ref of a repository.
40///
41/// [`Repo::list_collection_refs`] returns these entries. The refs of the
42/// `[core] collection-id` of the repository are the local refs, under
43/// `refs/heads`. The refs of another collection id are under `refs/mirrors`
44/// or under `refs/remotes`.
45#[derive(Debug, Clone, PartialEq, Eq)]
46pub struct CollectionRefEntry {
47    /// The collection id that qualifies the ref.
48    pub collection: String,
49    /// The ref name.
50    ///
51    /// For a local ref, this is its refspec.
52    pub name: String,
53    /// The commit that the ref names.
54    pub commit: Checksum,
55    /// `true` for a ref under `refs/heads`, `false` for a ref under
56    /// `refs/mirrors` or `refs/remotes`.
57    ///
58    /// The collection id of the repository qualifies a ref under `refs/heads`.
59    pub local: bool,
60    /// The remote whose `collection-id` qualifies a ref under
61    /// `refs/remotes/R/`, or `None` for a ref under `refs/heads` or
62    /// `refs/mirrors`.
63    pub remote: Option<String>,
64}
65
66/// A ref stored as an alias: a relative symlink to the file of another ref.
67#[derive(Debug, Clone, PartialEq, Eq)]
68pub struct RefAlias {
69    /// The refspec of the alias itself.
70    pub refspec: String,
71    /// The symlink target, as stored.
72    pub target: String,
73}
74
75/// The state of one ref path, as the receive path reads it under its lock.
76#[cfg(feature = "receive")]
77#[derive(Debug, Clone, Copy, PartialEq, Eq)]
78pub(crate) enum RefFileState {
79    /// No file stands at the path.
80    Absent,
81    /// A ref file, and the commit it names.
82    Commit(Checksum),
83    /// A symlink: an alias of another ref.
84    Alias,
85    /// Something a ref write cannot replace: a directory, a path that passes
86    /// through a file, or a special file.
87    NotARef,
88}
89
90/// One queued ref write: a target and the checksum to point it at (`None`
91/// removes the ref).
92pub(crate) struct RefWrite {
93    target: Ref,
94    checksum: Option<Checksum>,
95}
96
97/// Methods that queue ref writes for the transaction commit.
98impl Transaction {
99    /// Queues a ref write for the transaction commit.
100    ///
101    /// [`commit`](Transaction::commit) writes the ref after it publishes the
102    /// objects. If `checksum` is `None`, the commit removes the ref.
103    ///
104    /// The ref gives the path, as
105    /// [`set_ref_immediate`](Repo::set_ref_immediate) states. A collection
106    /// ref of the `[core] collection-id` of the repository is at
107    /// `refs/heads/<name>`, so the commit writes or removes that file, and it
108    /// does not touch `refs/mirrors/<collection>/`.
109    ///
110    /// The call itself does not check the ref. If the ref fails
111    /// [`Ref::validate`], the commit fails with [`Error::InvalidRefspec`],
112    /// which holds the text of the ref. The commit then publishes no object
113    /// and writes no ref.
114    ///
115    /// If a directory of `refs/mirrors/` has a name that fails the rule, a
116    /// ref under it cannot be written or removed through this call. Remove
117    /// such a ref by hand.
118    pub fn set_ref(&self, r: &Ref, checksum: Option<&Checksum>) {
119        self.refs.lock().unwrap().push(RefWrite {
120            target: r.clone(),
121            checksum: checksum.copied(),
122        });
123    }
124
125    /// Maps each queued ref to its path under the repository. A malformed
126    /// ref fails the call. [`commit`](Transaction::commit) calls it first,
127    /// so a malformed ref fails before the commit publishes any object.
128    pub(crate) fn resolve_ref_queue(&self) -> Result<Vec<(String, Option<Checksum>)>> {
129        let own = self.repo().config().collection_id();
130        let queue = self.refs.lock().unwrap();
131        queue
132            .iter()
133            .map(|w| Ok((ref_relpath(own, &w.target)?, w.checksum)))
134            .collect()
135    }
136}
137
138/// Writes the resolved refs of a transaction, each one atomically, on the
139/// blocking pool.
140///
141/// The call uses the fsync policy that the transaction resolved, so the
142/// object writes, the publication step, and the ref writes read one value.
143///
144/// The durability invariant: with fsync on, each ref file is `fdatasync`-ed
145/// before its rename. After the last rename, each directory that gained or
146/// lost a name is `fsync`-ed once, deepest first, before the call returns.
147///
148/// Before the call, the caller made durable the objects and the detached
149/// metadata that the refs name. So no ref is durable before what it names. A
150/// write that fails still syncs the directories of the refs written before
151/// it.
152///
153/// `tmp_fd` is the open `tmp/` of the repository. Each ref write creates its
154/// temp file there.
155pub(crate) fn write_resolved_refs_blocking(
156    repo_fd: BorrowedFd<'_>,
157    tmp_fd: BorrowedFd<'_>,
158    refs: &[(String, Option<Checksum>)],
159    fsync: bool,
160    repo_mode: RepoMode,
161) -> Result<()> {
162    let mut dirs = Vec::new();
163    let written = refs
164        .iter()
165        .try_for_each(|(relpath, checksum)| match checksum {
166            Some(checksum) => put_ref_file_blocking(
167                repo_fd, tmp_fd, relpath, *checksum, fsync, repo_mode, &mut dirs,
168            ),
169            None => remove_ref_blocking(repo_fd, relpath, fsync, &mut dirs),
170        });
171    if !fsync {
172        return written;
173    }
174    let synced = sync_ref_dirs(repo_fd, dirs);
175    written.and(synced)
176}
177
178/// The largest ref file that the reader loads. A ref file is 65 bytes.
179const REF_READ_CAP: u64 = 4096;
180
181/// Methods that resolve, list, and write refs.
182impl Repo {
183    /// Resolves a revision string to a commit checksum.
184    ///
185    /// If the revision names no ref, `allow_noent` selects the result:
186    /// `Ok(None)` if it is `true`, and [`Error::RefNotFound`] if it is
187    /// `false`. No other failure depends on `allow_noent`.
188    ///
189    /// # Revision syntax
190    ///
191    /// A revision is a base, followed by zero or more `^` characters. The call
192    /// tries these forms of the base in this order:
193    ///
194    /// 1. A full checksum: 64 lowercase hex characters. It resolves to itself.
195    ///    The call does not check that the commit object exists.
196    /// 2. An abbreviated checksum: 1 to 63 lowercase hex characters. It
197    ///    resolves to the one commit object whose checksum starts with it.
198    /// 3. A ref in a text form of [`Ref`]: `NAME`, `REMOTE:NAME`, or
199    ///    `@ID:NAME`. It resolves to the commit that the ref names, read at
200    ///    the path that [`resolve_ref_tip`](Repo::resolve_ref_tip) reads.
201    ///    `@ID:NAME` reads `refs/mirrors/ID/NAME`, or `refs/heads/NAME` when
202    ///    `ID` is the `[core] collection-id` of the repository. A ref path
203    ///    that names a directory, or that passes through a file, fails with
204    ///    [`Error::Io`].
205    ///
206    /// A checksum is in lowercase hex only. A 64-character name with an
207    /// uppercase character is a refspec.
208    ///
209    /// Only commit objects match an abbreviated checksum. A `dirtree`, a
210    /// `dirmeta`, or a file object with the same prefix does not match.
211    ///
212    /// An abbreviated checksum comes before the ref store. If a hex name is
213    /// also a ref, and a commit checksum starts with that name, the name
214    /// resolves to the commit. If no commit checksum starts with the name,
215    /// the name resolves as a refspec.
216    ///
217    /// Each `^` steps one generation back along the `parent` field of the
218    /// commit.
219    ///
220    /// # Errors
221    ///
222    /// - [`Error::RefNotFound`] if the base names no ref and `allow_noent` is
223    ///   `false`.
224    /// - [`Error::InvalidRefspec`] if the base is not a checksum and not a
225    ///   valid ref.
226    /// - [`Error::AmbiguousRefspec`] if more than one commit checksum starts
227    ///   with the abbreviated checksum.
228    /// - [`Error::NoParentCommit`] if a `^` steps back from a commit with no
229    ///   parent.
230    /// - [`Error::ObjectNotFound`] if a `^` step reads a commit that is not in
231    ///   the repository.
232    /// - [`Error::InvalidFormat`] if a ref file is not UTF-8.
233    /// - [`Error::Core`] if a ref file holds no checksum, or a commit object
234    ///   does not parse.
235    /// - [`Error::Io`] if a read from the file system fails, or if the ref
236    ///   path of the base names a directory or passes through a file.
237    pub async fn resolve_rev(&self, rev: &str, allow_noent: bool) -> Result<Option<Checksum>> {
238        Ok(self
239            .resolve_rev_kind(rev, allow_noent)
240            .await?
241            .map(|(checksum, _)| checksum))
242    }
243
244    /// Resolves a revision as [`resolve_rev`](Repo::resolve_rev) does, and
245    /// also returns the kind of its base.
246    ///
247    /// The kind is the kind of name that the base of `rev` resolved as: a
248    /// full or an abbreviated checksum, or a ref.
249    pub(crate) async fn resolve_rev_kind(
250        &self,
251        rev: &str,
252        allow_noent: bool,
253    ) -> Result<Option<(Checksum, RevKind)>> {
254        let (base, generations) = split_ancestry(rev);
255        let Some((mut checksum, kind)) = self.resolve_base_rev(base, allow_noent).await? else {
256            return Ok(None);
257        };
258        for _ in 0..generations {
259            let (commit, _) = self.load_commit(&checksum).await?;
260            checksum = commit.parent.ok_or(Error::NoParentCommit(checksum))?;
261        }
262        Ok(Some((checksum, kind)))
263    }
264
265    /// Resolves a revision with no ancestry suffix: a full checksum, an
266    /// abbreviated checksum, or a refspec, tried in that order. The result
267    /// holds the kind that the revision resolved as.
268    ///
269    /// A 64-character name is a checksum only in lowercase hex, so an
270    /// uppercase or mixed-case name of that length is a refspec. The checksum
271    /// parser keeps its case tolerance where it reads a checksum from stored
272    /// bytes: ref file content and delta metadata.
273    ///
274    /// A shorter run of lowercase hex is an abbreviated checksum, and it comes
275    /// before the ref store. If the store also holds a ref of that name, the
276    /// name resolves to the commit that it prefixes. The call does not read
277    /// the ref target.
278    ///
279    /// A prefix that no commit object has falls through to the ref store. So
280    /// a hex name is a ref name while no commit starts with it.
281    async fn resolve_base_rev(
282        &self,
283        rev: &str,
284        allow_noent: bool,
285    ) -> Result<Option<(Checksum, RevKind)>> {
286        if let Ok(checksum) = Checksum::from_hex_lower(rev) {
287            return Ok(Some((checksum, RevKind::Checksum)));
288        }
289
290        if is_abbreviated_checksum(rev) {
291            let repo = self.clone();
292            let prefix = rev.to_owned();
293            match ostrya_rt::unblock(move || match_abbreviated(repo.objects_fd(), &prefix)).await? {
294                AbbrevMatch::One(checksum) => return Ok(Some((checksum, RevKind::Checksum))),
295                AbbrevMatch::Ambiguous => return Err(Error::AmbiguousRefspec(rev.to_owned())),
296                AbbrevMatch::None => {}
297            }
298        }
299
300        let r: Ref = rev.parse()?;
301        let relpath = ref_relpath(self.config().collection_id(), &r)?;
302        match self.resolve_relpath_tip(relpath).await? {
303            Some(checksum) => Ok(Some((checksum, RevKind::Ref))),
304            None if allow_noent => Ok(None),
305            None => Err(Error::RefNotFound(rev.to_owned())),
306        }
307    }
308
309    /// Returns the commit that a ref names, read from the ref store only.
310    ///
311    /// The ref selects the path, as
312    /// [`set_ref_immediate`](Repo::set_ref_immediate) states. A collection
313    /// ref of the `[core] collection-id` of the repository reads
314    /// `refs/heads/NAME`, and the call does not read `refs/mirrors/ID/`. The
315    /// call reads `[core] collection-id` from the config that the handle read
316    /// at the open.
317    ///
318    /// The call does not read the name as a checksum, as an abbreviated
319    /// checksum, or with a `^` suffix. If the ref is an alias, the call
320    /// follows the link. An alias whose target is absent reads as an absent
321    /// ref. A ref path that names a directory, or that passes through a
322    /// file, holds no ref. The result is `None` if the store holds no such
323    /// ref. A caller that needs an error for an absent ref gives
324    /// [`Error::RefNotFound`] with the text of the ref.
325    ///
326    /// Callers that hold a ref name and not a revision use this call. These
327    /// are a media export and a media import for their refs, a summary for
328    /// the metadata ref that it chains, and the CLI for its alias-target
329    /// check. An alias records a name, so the CLI uses this call.
330    ///
331    /// A symlink that the port does not write can make the call and the ref
332    /// listing give different results. Examples are a symlink to a directory
333    /// in the mirror tree, an alias loop, and an absolute alias. The listing
334    /// does not follow a symlink to a directory, and it reads an alias by its
335    /// own rule. The call follows each link through the file system.
336    ///
337    /// The call takes no lock. It does not wait for an
338    /// [`UpdateGuard`](crate::UpdateGuard) or for a transaction. A ref write
339    /// renames a complete file over the ref, so the read gives the old commit
340    /// or the new commit.
341    ///
342    /// # Errors
343    ///
344    /// - [`Error::InvalidRefspec`] if the ref fails [`Ref::validate`]. The
345    ///   error holds the text of the ref, and the call reads no file.
346    /// - [`Error::InvalidFormat`] if the ref file is not UTF-8.
347    /// - [`Error::Core`] if the ref file holds no checksum.
348    /// - [`Error::Io`] if the read fails, for example on an alias loop or on
349    ///   a ref file that the process cannot read.
350    pub async fn resolve_ref_tip(&self, r: &Ref) -> Result<Option<Checksum>> {
351        match self
352            .resolve_relpath_tip(ref_relpath(self.config().collection_id(), r)?)
353            .await
354        {
355            Err(Error::Io(e)) if is_not_a_ref_path(&e) => Ok(None),
356            other => other,
357        }
358    }
359
360    /// Returns the commit that the ref file at `relpath` names. The call
361    /// follows an alias. The result is `None` if no file is at the path. A
362    /// path that names a directory, or that passes through a file, fails
363    /// with [`Error::Io`].
364    ///
365    /// The read and the parse run in one call on the blocking pool.
366    pub(crate) async fn resolve_relpath_tip(&self, relpath: String) -> Result<Option<Checksum>> {
367        let repo = self.clone();
368        ostrya_rt::unblock(move || repo.resolve_relpath_tip_blocking(&relpath)).await
369    }
370
371    /// Runs [`resolve_relpath_tip`](Repo::resolve_relpath_tip) on the calling
372    /// thread.
373    pub(crate) fn resolve_relpath_tip_blocking(&self, relpath: &str) -> Result<Option<Checksum>> {
374        match read_ref_file(self.repo_fd(), relpath)? {
375            Some(bytes) => Ok(Some(parse_ref_content(&bytes)?)),
376            None => Ok(None),
377        }
378    }
379
380    /// Returns the commits of the ref files at several paths under `refs/`,
381    /// each read as [`resolve_ref_tip`](Repo::resolve_ref_tip) reads a
382    /// refspec, in one pass on the blocking pool. The result holds one entry
383    /// for each path, in order. A ref path that names a directory, or that
384    /// passes through a file, holds no ref and reads as absent.
385    #[cfg(feature = "receive")]
386    pub(crate) async fn resolve_relpath_tips(
387        &self,
388        relpaths: Arc<[String]>,
389    ) -> Result<Vec<Option<Checksum>>> {
390        let repo = self.clone();
391        let contents = ostrya_rt::unblock(move || {
392            relpaths
393                .iter()
394                .map(|p| match read_ref_file(repo.repo_fd(), p) {
395                    Err(e) if is_not_a_ref_path(&e) => Ok(None),
396                    other => other,
397                })
398                .collect::<std::io::Result<Vec<_>>>()
399        })
400        .await?;
401        contents
402            .into_iter()
403            .map(|bytes| bytes.map(|b| parse_ref_content(&b)).transpose())
404            .collect()
405    }
406
407    /// Returns the state of the ref file at each of several paths under
408    /// `refs/`, and the commit of the refspec `tip`, in one pass on the
409    /// blocking pool. The result holds one state for each path, in order.
410    ///
411    /// The call reads each ref path with `lstat` first. It then opens a
412    /// regular file with `O_NOFOLLOW` and parses it. A ref that does not parse
413    /// fails the call.
414    ///
415    /// If `tip` is given, the call reads it at the path where
416    /// [`resolve_ref_tip`](Repo::resolve_ref_tip) reads it. A path that names
417    /// a directory, or that passes through a file, fails `tip` with
418    /// [`Error::Io`]. The result holds the failure of `tip` separately, so
419    /// the caller decides if it needs the value.
420    #[cfg(feature = "receive")]
421    #[allow(clippy::type_complexity)]
422    pub(crate) async fn read_ref_states(
423        &self,
424        relpaths: Arc<[String]>,
425        tip: Option<&str>,
426    ) -> Result<(Vec<RefFileState>, Option<Result<Option<Checksum>>>)> {
427        let tip = tip.map(refspec_to_relpath);
428        let repo = self.clone();
429        ostrya_rt::unblock(move || {
430            let states = relpaths
431                .iter()
432                .map(|p| ref_file_state(repo.repo_fd(), p))
433                .collect::<Result<Vec<_>>>()?;
434            let tip = tip.map(|relpath| match read_ref_file(repo.repo_fd(), &relpath?)? {
435                Some(bytes) => Ok(Some(parse_ref_content(&bytes)?)),
436                None => Ok(None),
437            });
438            Ok((states, tip))
439        })
440        .await
441    }
442
443    /// Returns the local refs as `(name, commit)` pairs, sorted by name.
444    ///
445    /// The local refs are under `refs/heads`. If `prefix` is given, the result
446    /// holds only the ref named `prefix` and the refs below `prefix/`. The call
447    /// follows each alias. An alias whose target names no ref is not in the
448    /// result.
449    ///
450    /// # Errors
451    ///
452    /// - [`Error::InvalidFormat`] if a ref file is not UTF-8.
453    /// - [`Error::Core`] if a ref file holds no checksum.
454    /// - [`Error::Io`] if a read from the file system fails, for example for
455    ///   an alias that names a directory.
456    pub async fn list_refs(&self, prefix: Option<&str>) -> Result<Vec<(String, Checksum)>> {
457        let repo = self.clone();
458        let mut refs = ostrya_rt::unblock(move || collect_heads(&repo)).await?;
459        if let Some(prefix) = prefix {
460            refs.retain(|(name, _)| ref_prefixes(name).any(|part| part == prefix));
461        }
462        refs.sort_by(|a, b| a.0.cmp(&b.0));
463        Ok(refs)
464    }
465
466    /// Returns the refs that `refs` and `collections` select and `access`
467    /// reads, for a ref listing.
468    ///
469    /// # Local refs
470    ///
471    /// The local refs are the refs of `refs/heads`. The call does not read
472    /// `refs/mirrors/ID/` of the `[core] collection-id` of the config.
473    /// `refs` selects the local refs by name, and `access`
474    /// reads them in the local namespace.
475    ///
476    /// A ref is selected when the selector has no positive pattern or a
477    /// positive pattern matches its name, and no negative pattern matches it.
478    /// The walk reads only the directories that the literal leading parts of
479    /// a positive pattern name, and below them only the directories that the
480    /// pattern can match. It applies the negative patterns to a name before
481    /// it reads the ref file, so a ref that no entry selects is never read.
482    /// The walk drops a positive pattern that another positive pattern
483    /// covers: if `q` is literal parts and a final `**`, a pattern that
484    /// starts with the same literal parts and has at least one more part
485    /// selects only names that `q` selects. The walk does not read a
486    /// directory that a negative pattern covers: a negative pattern of
487    /// literal or `*` parts and a final `**` matches each name below a
488    /// directory whose path starts with these parts.
489    /// With no positive pattern, the patterns of the allow items that give
490    /// `r` in the group of the namespace take the place of the positive
491    /// patterns in the walk, and the walk does not read a directory that a
492    /// deny item of the group covers. The walk enumerates a name that the
493    /// ref-name rule refuses, and a wildcard selects it.
494    ///
495    /// The result holds a ref only when `access` reads its name. The call
496    /// checks the name before it reads the ref file, so a ref file that
497    /// `access` does not read is never read. When `access` reads no local
498    /// ref, or when a negative pattern of `refs` is `**`, the call does not
499    /// open `refs/heads/`. The call opens `refs/heads/` and `refs/mirrors/`
500    /// by their paths from the repository. Below these
501    /// two directories, it opens each ref file and each directory with no
502    /// symlink followed. An alias resolves by the rule of
503    /// the archive view: its body is relative, it names a regular file under
504    /// `refs/` by one link, and `access` reads the target path. The call
505    /// opens the target with no symlink followed. An alias that breaks one
506    /// of these rules, and an alias whose target names no regular file, are
507    /// not in the result. A ref entry that is a FIFO or a socket at the open
508    /// is not in the result, and its open does not wait for a writer.
509    ///
510    /// # Collection refs
511    ///
512    /// With `collections`, the call reads the top level of `refs/mirrors/`
513    /// one time. `collections` selects the refs of each other collection by
514    /// `ID/NAME`, with the rules above, and `access` reads them with the
515    /// group of the item in the namespace of `ID`. The call skips a
516    /// collection whose group gives no `r` before it reads the directory. It
517    /// also skips a name that is not UTF-8, and an entry that is no
518    /// directory. A directory whose name fails the collection-id rule goes to
519    /// `invalid_dirs`, and the call reads no entry in it. The call skips the
520    /// directory of an id that no positive pattern can reach, or that a
521    /// negative pattern covers, before it reads the rights of the id. The
522    /// own collection id is not a collection of the result. With `None`, the
523    /// call does not open `refs/mirrors/`.
524    ///
525    /// # Size
526    ///
527    /// With `cap`, the call keeps the lower bound of the size of the listing
528    /// that the first size check of
529    /// [`build_ref_listing`](Repo::build_ref_listing) computes, and adds each
530    /// ref that it selects. When the bound passes `cap`, the call stops and
531    /// fails with the error of that check, and it reads no more ref file.
532    /// With `None`, the selection has no cap.
533    ///
534    /// The call runs on the blocking pool.
535    ///
536    /// # Errors
537    ///
538    /// - The errors of [`list_refs`](Repo::list_refs), for a selected ref.
539    /// - [`Error::Remote`] with
540    ///   [`LimitExceeded`](crate::remote::Error::LimitExceeded) if the lower
541    ///   bound passes `cap`.
542    pub(crate) async fn select_refs(
543        &self,
544        refs: &RefSelector,
545        collections: Option<&RefSelector>,
546        access: &ReadAccess,
547        cap: Option<u64>,
548    ) -> Result<RefSelection> {
549        let repo = self.clone();
550        let refs = refs.clone();
551        let collections = collections.cloned();
552        let access = access.clone();
553        ostrya_rt::unblock(move || {
554            let mut floor = SelectionFloor::new(cap);
555            let mut selection = RefSelection::default();
556            collect_local_selected(&repo, &refs, &access, &mut floor, &mut selection)?;
557            if let Some(collections) = &collections
558                && let Some(mirrors) = open_refs_dir(&repo, MIRRORS_DIR)?
559            {
560                collect_collections_selected(
561                    &repo,
562                    mirrors.as_fd(),
563                    collections,
564                    &access,
565                    &mut floor,
566                    &mut selection,
567                )?;
568            }
569            Ok(selection)
570        })
571        .await
572    }
573
574    /// Returns the remote refs as `(refspec, commit)` pairs, sorted by refspec.
575    ///
576    /// The remote refs are under `refs/remotes`. The first path component
577    /// below `refs/remotes` is the remote name, so the refspec of each ref is
578    /// `remote:name`. A file directly under `refs/remotes` names no remote,
579    /// and the result does not hold it.
580    ///
581    /// # Errors
582    ///
583    /// - [`Error::InvalidFormat`] if a ref file is not UTF-8.
584    /// - [`Error::Core`] if a ref file holds no checksum.
585    /// - [`Error::Io`] if a read from the file system fails.
586    pub async fn list_remote_refs(&self) -> Result<Vec<(String, Checksum)>> {
587        let repo = self.clone();
588        let mut refs = ostrya_rt::unblock(move || collect_remotes(&repo)).await?;
589        refs.sort_by(|a, b| a.0.cmp(&b.0));
590        Ok(refs)
591    }
592
593    /// Returns the mirror refs as `(collection_id, ref_name, commit)` triples.
594    ///
595    /// The mirror refs are under `refs/mirrors`. The first path component
596    /// below `refs/mirrors` is the collection id. The rest of the path is the
597    /// ref name, which can contain `/`. A file directly under `refs/mirrors`
598    /// has no collection id, and the result does not hold it.
599    ///
600    /// The result holds the refs of `refs/mirrors/ID/` of the
601    /// `[core] collection-id` of the repository. The ref resolve, the
602    /// collection ref listings, and the summary ignore that directory.
603    ///
604    /// The result is not sorted. A caller that needs a stable order sorts it.
605    ///
606    /// # Errors
607    ///
608    /// - [`Error::InvalidFormat`] if a ref file is not UTF-8.
609    /// - [`Error::Core`] if a ref file holds no checksum.
610    /// - [`Error::Io`] if a read from the file system fails.
611    pub async fn list_mirror_refs(&self) -> Result<Vec<(String, String, Checksum)>> {
612        let repo = self.clone();
613        ostrya_rt::unblock(move || collect_mirrors(&repo, None)).await
614    }
615
616    /// Returns the collection-qualified refs, sorted by collection id and ref
617    /// name.
618    ///
619    /// The result holds:
620    ///
621    /// - The local refs, qualified by the `[core] collection-id` of the
622    ///   repository, if the config sets one.
623    /// - Each ref under `refs/mirrors`, which holds its collection id in its
624    ///   path, except the refs of `refs/mirrors/ID/` of the
625    ///   `[core] collection-id` of the repository. The call does not read
626    ///   that directory.
627    /// - Each ref under `refs/remotes/R/` of a remote R whose config sets a
628    ///   `collection-id`, qualified by that id. The call skips a remote
629    ///   whose `collection-id` holds a malformed escape sequence, fails
630    ///   [`is_valid_collection_id`](crate::is_valid_collection_id), or is the
631    ///   `[core] collection-id` of the repository, and a remote name that
632    ///   [`valid_remote_name`] refuses. A directory under `refs/remotes` with
633    ///   no remote group in the config gives no ref. If no remote qualifies,
634    ///   the call does not read `refs/remotes`.
635    ///
636    /// The result holds each pair of a collection id and a ref name one
637    /// time. A ref under `refs/mirrors` wins over a ref of a remote with the
638    /// same pair. Among remotes with the same pair, the first remote in the
639    /// byte order of the names wins.
640    ///
641    /// [`list_collection_refs_in`](Repo::list_collection_refs_in) lists the
642    /// refs of one collection that a selector selects. It does not read
643    /// `refs/remotes`.
644    ///
645    /// # Errors
646    ///
647    /// - [`Error::InvalidFormat`] if a ref file is not UTF-8.
648    /// - [`Error::Core`] if a ref file holds no checksum.
649    /// - [`Error::Io`] if a read from the file system fails.
650    pub async fn list_collection_refs(&self) -> Result<Vec<CollectionRefEntry>> {
651        let config = self.config();
652        let own = config.collection_id();
653        // The remotes whose refs the listing holds, each with its collection
654        // id, sorted by name.
655        let mut remotes = BTreeMap::new();
656        for name in config.remotes() {
657            if !valid_remote_name(name) {
658                continue;
659            }
660            let Some(remote) = config.remote(name) else {
661                continue;
662            };
663            // A value with a malformed escape sequence gives no row.
664            if let Ok(Some(id)) = remote.collection_id()
665                && ostrya_core::is_valid_collection_id(&id)
666                && Some(id.as_str()) != own
667            {
668                remotes.insert(name.to_owned(), id);
669            }
670        }
671        let heads = match own {
672            Some(_) => self.list_refs(None).await?,
673            None => Vec::new(),
674        };
675        let mut all = self.collection_refs_over(&heads, own).await?;
676        if remotes.is_empty() {
677            return Ok(all);
678        }
679        let repo = self.clone();
680        let refs = ostrya_rt::unblock(move || collect_remote_collections(&repo, &remotes)).await?;
681        // The refs of the remotes come after the mirror refs, in the byte
682        // order of the remote names. The sort is stable, and `dedup_by` keeps
683        // the first entry of each pair, so a mirror ref wins over a ref of a
684        // remote, and the first remote by name wins over the others.
685        all.extend(
686            refs.into_iter()
687                .map(|(remote, collection, name, commit)| CollectionRefEntry {
688                    collection,
689                    name,
690                    commit,
691                    local: false,
692                    remote: Some(remote),
693                }),
694        );
695        all.sort_by(|a, b| (&a.collection, &a.name).cmp(&(&b.collection, &b.name)));
696        all.dedup_by(|a, b| a.collection == b.collection && a.name == b.name);
697        Ok(all)
698    }
699
700    /// Returns the refs of the collection `collection_id` that `refs`
701    /// selects, as `(name, commit)` pairs, sorted byte-wise by name, each
702    /// name one time.
703    ///
704    /// `refs` selects a ref by its name in the collection, with the rules of
705    /// [`RefSelector`]. An empty selector selects each ref of the collection.
706    ///
707    /// The collection id selects the directories that the call lists:
708    ///
709    /// - The `[core] collection-id` of the repository lists the refs of
710    ///   `refs/heads/`. The call does not read `refs/mirrors/ID/`. The
711    ///   summary and the ref listing apply the same rule.
712    /// - Each other collection id lists the refs of `refs/mirrors/ID/` alone.
713    ///   With no directory `refs/mirrors/ID/`, the result is an empty vector.
714    ///
715    /// The call opens `refs/mirrors/ID` with no symlink followed. An entry
716    /// `ID` that is absent, a regular file, or a symlink is no directory
717    /// `refs/mirrors/ID/`, and so is each entry `ID` when `refs/mirrors` is
718    /// absent. When the call opens `refs/mirrors`, a `refs/mirrors` that is a
719    /// regular file gives an error. The call reads `[core] collection-id`
720    /// from the config that the handle read at the open.
721    ///
722    /// An alias resolves by the rule of the ref listing: its body is a
723    /// relative path, and it names a regular file under `refs/heads/` or
724    /// under `refs/mirrors/ID/` of a valid collection id other than `[core]
725    /// collection-id` with one link. The result holds the alias by its own
726    /// name, with the commit of the target. An alias whose target is absent,
727    /// is outside these directories, or is an alias is not in the result.
728    /// A ref entry that is a FIFO or a socket at the open is not in the
729    /// result, and its open does not wait for a writer.
730    ///
731    /// The call does not check a name that it finds against the ref-name
732    /// rule. A wildcard of `refs` selects a name that the rule refuses.
733    ///
734    /// # Reads
735    ///
736    /// The call reads only the directories that the literal leading parts of
737    /// a positive pattern name, and below them only the directories that the
738    /// pattern can match. It does not read a directory that a negative
739    /// pattern covers: a negative pattern of literal or `*` parts and a
740    /// final `**` matches each name below a directory whose path starts with
741    /// these parts. It applies the negative patterns to a name before it
742    /// reads the ref file. A negative pattern `**` selects no ref, and the
743    /// call then opens no directory. The call opens each directory that
744    /// literal leading parts name one time, also when more than one pattern
745    /// starts with these parts.
746    ///
747    /// For each other collection id, the call opens `refs/mirrors/` and
748    /// `refs/mirrors/ID/`, and below `refs/mirrors/ID/` the directories that
749    /// the rules above give. It does not read the names at the top level of
750    /// `refs/mirrors/`. Except to read the target of an alias, it does not
751    /// open the directory of another collection, and it does not open
752    /// `refs/heads/`.
753    ///
754    /// The call takes no lock. It does not wait for an
755    /// [`UpdateGuard`](crate::UpdateGuard) or for a transaction. A ref write
756    /// renames a complete file over the ref, so each ref in the result has
757    /// the old commit or the new commit. Writes during the call can give a
758    /// result that the store did not hold at one time.
759    ///
760    /// No client group applies: the `[ex-ostrya client]` groups of the
761    /// config do not limit the result. The result has no size limit.
762    ///
763    /// # Errors
764    ///
765    /// - [`Error::InvalidRefspec`] if the collection id does not pass
766    ///   [`is_collection_id`](crate::is_collection_id) or is longer than 255
767    ///   bytes. The error holds the collection id. The call reads no file.
768    /// - [`Error::InvalidFormat`] if a selected ref file is not UTF-8.
769    /// - [`Error::Core`] if a selected ref file holds no checksum.
770    /// - [`Error::Io`] if a read fails, for example if `refs/mirrors` that
771    ///   the call opens is a regular file, or if a directory that the call
772    ///   reads gives no read permission.
773    pub async fn list_collection_refs_in(
774        &self,
775        collection_id: &str,
776        refs: &RefSelector,
777    ) -> Result<Vec<(String, Checksum)>> {
778        if !ostrya_core::is_valid_collection_id(collection_id) {
779            return Err(Error::InvalidRefspec(collection_id.to_owned()));
780        }
781        if selects_no_name(refs) {
782            return Ok(Vec::new());
783        }
784        let own = self.config().collection_id();
785        if own == Some(collection_id) {
786            let selection = self
787                .select_refs(refs, None, self.implicit_reads(), None)
788                .await?;
789            return Ok(selection.local);
790        }
791        // The selector of `ID/NAME` paths. With no positive pattern, `ID/**`
792        // keeps the walk inside the directory of the collection.
793        let mut entries: Vec<String> = refs
794            .positive()
795            .iter()
796            .map(|pattern| format!("{collection_id}/{}", pattern.as_str()))
797            .collect();
798        if entries.is_empty() {
799            entries.push(format!("{collection_id}/**"));
800        }
801        entries.extend(
802            refs.negative()
803                .iter()
804                .map(|pattern| format!("!{collection_id}/{}", pattern.as_str())),
805        );
806        let collections = RefSelector::parse(entries.iter().map(String::as_str))?;
807        let repo = self.clone();
808        let id = collection_id.to_owned();
809        ostrya_rt::unblock(move || {
810            let everyone = repo.implicit_reads();
811            let Some(rules) = everyone.collection_rules(&id) else {
812                return Ok(Vec::new());
813            };
814            // The walk opens `refs/mirrors/ID` by its name, so the call does
815            // not read the names of `refs/mirrors`.
816            let Some(mirrors) = open_refs_dir(&repo, MIRRORS_DIR)? else {
817                return Ok(Vec::new());
818            };
819            let mut floor = SelectionFloor::new(None);
820            let mut selection = RefSelection::default();
821            collect_collection_selected(
822                &repo,
823                mirrors.as_fd(),
824                &CollectionWalk::new(&collections),
825                &id,
826                rules,
827                everyone,
828                &mut floor,
829                &mut selection,
830            )?;
831            Ok(selection.collections.remove(&id).unwrap_or_default())
832        })
833        .await
834    }
835
836    /// Returns the collection-qualified refs, made over a `refs/heads` listing
837    /// that the caller read before, sorted by collection id and ref name. A
838    /// repository with no `[core] collection-id` qualifies no local ref, and
839    /// the call then ignores `heads`. The result holds each ref under
840    /// `refs/mirrors`, except the refs of `refs/mirrors/skip/`. The call does
841    /// not read that directory.
842    pub(crate) async fn collection_refs_over(
843        &self,
844        heads: &[(String, Checksum)],
845        skip: Option<&str>,
846    ) -> Result<Vec<CollectionRefEntry>> {
847        let mut all = Vec::new();
848        if let Some(collection) = self.config().collection_id().map(str::to_owned) {
849            for (name, commit) in heads {
850                all.push(CollectionRefEntry {
851                    collection: collection.clone(),
852                    name: name.clone(),
853                    commit: *commit,
854                    local: true,
855                    remote: None,
856                });
857            }
858        }
859        let repo = self.clone();
860        let skip = skip.map(str::to_owned);
861        let mirrors = ostrya_rt::unblock(move || collect_mirrors(&repo, skip.as_deref())).await?;
862        for (collection, name, commit) in mirrors {
863            all.push(CollectionRefEntry {
864                collection,
865                name,
866                commit,
867                local: false,
868                remote: None,
869            });
870        }
871        all.sort_by(|a, b| (&a.collection, &a.name).cmp(&(&b.collection, &b.name)));
872        Ok(all)
873    }
874
875    /// Returns the local and remote refs that are aliases, sorted by refspec.
876    ///
877    /// The result holds an alias whose target names no ref, because the call
878    /// reads the link and not the ref behind it. An alias whose target is not
879    /// UTF-8 is not in the result.
880    ///
881    /// # Errors
882    ///
883    /// - [`Error::Io`] if a read from the file system fails.
884    pub async fn list_ref_aliases(&self) -> Result<Vec<RefAlias>> {
885        let repo = self.clone();
886        let mut aliases = ostrya_rt::unblock(move || collect_aliases(&repo)).await?;
887        aliases.sort_by(|a, b| a.refspec.cmp(&b.refspec));
888        Ok(aliases)
889    }
890
891    /// Checks a path below `refs/` for a component that is not a directory.
892    ///
893    /// `relpath` is relative to `refs/`, as a listing prefix names it. The
894    /// call fails for one condition only: a component before the last one is
895    /// not a directory (`ENOTDIR`). This condition ends a listing.
896    ///
897    /// If the path names nothing, the call returns `Ok(())`, because a prefix
898    /// that matches no ref lists nothing. Each other failure of the check also
899    /// returns `Ok(())`, and the prefix then filters the listing. The call
900    /// does not follow the last component, so a path that names an alias is
901    /// the link itself.
902    ///
903    /// # Errors
904    ///
905    /// - [`Error::Io`] with `ENOTDIR` if a component before the last one is
906    ///   not a directory.
907    pub async fn check_refs_path(&self, relpath: &str) -> Result<()> {
908        let path = format!("refs/{relpath}");
909        let repo = self.clone();
910        ostrya_rt::unblock(move || {
911            match rustix::fs::statat(repo.repo_fd(), &path, AtFlags::SYMLINK_NOFOLLOW) {
912                Err(Errno::NOTDIR) => Err(Error::Io(Errno::NOTDIR.into())),
913                _ => Ok(()),
914            }
915        })
916        .await
917    }
918
919    /// Writes one ref outside a transaction.
920    ///
921    /// If `checksum` is `None`, the call removes the ref file. The removal of
922    /// an absent ref file is not an error. The call reads `[core] fsync` from
923    /// the config. A transaction writes its queued refs in the same way, under
924    /// its own fsync policy (see [`Transaction::commit`]).
925    ///
926    /// # Ref files
927    ///
928    /// A ref is a file under `refs/`. It holds a 64-character hex checksum and
929    /// a newline, 65 bytes in all. The file mode is `0644`, independent of the
930    /// umask. The [`Ref`] gives the path:
931    ///
932    /// - The local ref `name` is at `refs/heads/name`.
933    /// - The remote ref `remote:name` is at `refs/remotes/remote/name`.
934    /// - The collection ref `@collection:name` is at
935    ///   `refs/mirrors/collection/name`. A collection ref of the `[core]
936    ///   collection-id` of the repository is at `refs/heads/name`, so
937    ///   `@collection:name` and `name` name the same file there. The call
938    ///   reads `[core] collection-id` from the config that the handle read at
939    ///   the open.
940    ///
941    /// A ref can also be an alias: a relative symlink to the file of another
942    /// ref. A read follows the link and reads the checksum of the target ref.
943    /// [`Ref::validate`] checks each component of the ref against the
944    /// ref-name rule, so a ref path stays inside `refs/`. If a directory of
945    /// `refs/mirrors/` has a name that fails the rule, a ref under it cannot
946    /// be written or removed through this call. Remove such a ref by hand.
947    ///
948    /// The call creates the missing parent directories of a name with `/` in
949    /// it. It requests mode `0777` for them, which the umask reduces. In a
950    /// `bare-user-shared` repository, each directory that the call creates
951    /// gets mode `02770`.
952    ///
953    /// # Durability
954    ///
955    /// The write is atomic. The call writes the content to a new temp file in
956    /// the `tmp/` directory of the repository. Then it renames the temp file
957    /// over the ref file. No temp entry is under `refs/`, so a listing never
958    /// reads one.
959    ///
960    /// If `tmp/` is on a different file system, the rename fails with
961    /// `EXDEV`, and the call removes the temp file.
962    ///
963    /// If `[core] fsync` is on:
964    ///
965    /// - The call runs `fdatasync` on the temp file before the rename.
966    /// - After the rename, the call runs `fsync` on the directory that holds
967    ///   the ref, so the name is durable together with the content.
968    /// - If the call created parent directories, it also runs `fsync` on the
969    ///   directory that holds each created directory, deepest first. So the
970    ///   full path of the name is durable, and not only the last entry.
971    ///
972    /// A removal and an alias write have no content of their own, so they sync
973    /// directories only. A write that fails still syncs the directories that it
974    /// changed before the failure.
975    ///
976    /// # Locks
977    ///
978    /// The call takes the repository lock
979    /// [`Shared`](crate::LockKind::Shared) and then the update lock, as
980    /// [`begin_update`](Repo::begin_update) does, and writes under both. A
981    /// caller that holds an [`UpdateGuard`](crate::UpdateGuard) of this
982    /// repository must write through the guard, with
983    /// [`UpdateGuard::set_ref`](crate::UpdateGuard::set_ref). If `[core]
984    /// locking` is on and the caller holds the repository lock exclusive, the
985    /// call waits for that lock. [`LockKind`](crate::LockKind) states the
986    /// result of this wait.
987    ///
988    /// # Errors
989    ///
990    /// - [`Error::InvalidRefspec`] if the ref fails [`Ref::validate`]. The
991    ///   error holds the text of the ref, and the call writes nothing.
992    /// - [`Error::Core`] if `[core] fsync`, `[core] locking`, or `[core]
993    ///   lock-timeout-secs` does not parse.
994    /// - [`Error::InvalidFormat`] if `[core] lock-timeout-secs` is below `-1`.
995    /// - [`Error::LockTimeout`] if the wait for a lock passes `[core]
996    ///   lock-timeout-secs`.
997    /// - [`Error::Io`] if a file system operation fails.
998    pub async fn set_ref_immediate(&self, r: &Ref, checksum: Option<&Checksum>) -> Result<()> {
999        let relpath = ref_relpath(self.config().collection_id(), r)?;
1000        self.write_ref_relpath(relpath, checksum).await
1001    }
1002
1003    async fn write_ref_relpath(&self, relpath: String, checksum: Option<&Checksum>) -> Result<()> {
1004        let fsync = self.config().fsync()?;
1005        let repo_mode = self.mode();
1006        let checksum = checksum.copied();
1007        self.write_locked(move |repo| {
1008            write_ref_blocking(repo.repo_fd(), &relpath, checksum, fsync, repo_mode)
1009        })
1010        .await
1011    }
1012
1013    /// Writes one ref as an alias of another ref, outside a transaction.
1014    ///
1015    /// The alias is a relative symlink from the file of `refspec` to the file
1016    /// of `target`. It replaces the ref or the alias that `refspec` named
1017    /// before. The call checks both refspecs. The call does not require
1018    /// either ref to exist, because the link records a name and not a
1019    /// checksum.
1020    ///
1021    /// The write is atomic: the call creates the link under a temp name in
1022    /// `tmp/` and renames it over the ref path. If `[core] fsync` is on, the
1023    /// call runs `fsync` on the directory that holds the link. It also runs
1024    /// `fsync` on the directory that holds each parent directory that the
1025    /// call created. The locks are those of
1026    /// [`set_ref_immediate`](Repo::set_ref_immediate).
1027    ///
1028    /// # Errors
1029    ///
1030    /// - [`Error::InvalidRefspec`] if `refspec` or `target` is not a valid
1031    ///   refspec.
1032    /// - [`Error::Core`] if `[core] fsync`, `[core] locking`, or `[core]
1033    ///   lock-timeout-secs` does not parse.
1034    /// - [`Error::InvalidFormat`] if `[core] lock-timeout-secs` is below `-1`.
1035    /// - [`Error::LockTimeout`] if the wait for a lock passes `[core]
1036    ///   lock-timeout-secs`.
1037    /// - [`Error::Io`] if a file system operation fails.
1038    pub async fn set_ref_alias_immediate(&self, refspec: &str, target: &str) -> Result<()> {
1039        let fsync = self.config().fsync()?;
1040        let repo_mode = self.mode();
1041        let relpath = refspec_to_relpath(refspec)?;
1042        let link = relative_link(&relpath, &refspec_to_relpath(target)?);
1043        self.write_locked(move |repo| {
1044            write_alias_blocking(repo.repo_fd(), &relpath, &link, fsync, repo_mode)
1045        })
1046        .await
1047    }
1048}
1049
1050/// The kind of name the base of a revision resolved as.
1051#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1052pub(crate) enum RevKind {
1053    /// A full checksum, or an abbreviated checksum of a commit object.
1054    Checksum,
1055    /// A ref of the ref store.
1056    Ref,
1057}
1058
1059/// Splits a revision string into its base and the number of trailing `^`
1060/// characters. Each `^` asks for one more generation of ancestry.
1061fn split_ancestry(rev: &str) -> (&str, usize) {
1062    let base = rev.trim_end_matches('^');
1063    (base, rev.len() - base.len())
1064}
1065
1066/// Returns `true` if a revision names a commit by an abbreviated checksum: a
1067/// run of 1 to 63 lowercase hex characters. A 64-character run is the
1068/// checksum itself. One uppercase character makes the name a refspec, the
1069/// case rule of a full checksum.
1070fn is_abbreviated_checksum(rev: &str) -> bool {
1071    !rev.is_empty()
1072        && rev.len() < 64
1073        && rev
1074            .bytes()
1075            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
1076}
1077
1078/// What an abbreviated checksum matched among the commit objects present.
1079enum AbbrevMatch {
1080    /// No commit object has a checksum that starts with the prefix.
1081    None,
1082    /// Exactly one does.
1083    One(Checksum),
1084    /// More than one does.
1085    Ambiguous,
1086}
1087
1088/// Scans the loose commit objects for the ones whose checksum starts with
1089/// `prefix`.
1090///
1091/// Only commit objects match. A `dirtree`, a `dirmeta`, or a file object with
1092/// the same prefix does not match. A prefix that only such an object has
1093/// matches nothing.
1094///
1095/// The `objects/<xx>/` fanout holds the first two characters
1096/// of a checksum. A prefix of two or more characters names one fanout with its
1097/// first two characters, and the call opens that directory by name. A
1098/// one-character prefix scans the sixteen fanouts whose name starts with it,
1099/// found from a listing of `objects/`.
1100fn match_abbreviated(objects_fd: BorrowedFd<'_>, prefix: &str) -> Result<AbbrevMatch> {
1101    let mut found: Option<Checksum> = None;
1102    if prefix.len() >= 2 {
1103        let (fanout, within) = prefix.split_at(2);
1104        if scan_fanout(objects_fd, fanout, within, &mut found)? {
1105            return Ok(AbbrevMatch::Ambiguous);
1106        }
1107    } else {
1108        for fanout in read_dir_names(objects_fd)? {
1109            // The name of an object fanout directory is two hex characters.
1110            // Each other entry under `objects/` is not a loose-object fanout.
1111            if fanout.len() != 2 || !fanout.bytes().all(|b| b.is_ascii_hexdigit()) {
1112                continue;
1113            }
1114            if !fanout.starts_with(prefix) {
1115                continue;
1116            }
1117            if scan_fanout(objects_fd, &fanout, "", &mut found)? {
1118                return Ok(AbbrevMatch::Ambiguous);
1119            }
1120        }
1121    }
1122    Ok(match found {
1123        Some(checksum) => AbbrevMatch::One(checksum),
1124        None => AbbrevMatch::None,
1125    })
1126}
1127
1128/// Scans one `objects/<fanout>/` directory for the commit objects whose name
1129/// starts with `within`, and records each match in `found`. An absent fanout
1130/// directory holds no match. Returns `true` if the prefix is ambiguous.
1131fn scan_fanout(
1132    objects_fd: BorrowedFd<'_>,
1133    fanout: &str,
1134    within: &str,
1135    found: &mut Option<Checksum>,
1136) -> Result<bool> {
1137    let dir = match rustix::fs::openat(
1138        objects_fd,
1139        fanout,
1140        OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
1141        Mode::empty(),
1142    ) {
1143        Ok(fd) => fd,
1144        Err(Errno::NOENT) => return Ok(false),
1145        Err(e) => return Err(Error::Io(e.into())),
1146    };
1147    for entry in read_dir_names(dir.as_fd())? {
1148        let Some(checksum) = matching_commit(fanout, &entry, within) else {
1149            continue;
1150        };
1151        // The fanout holds the first two characters of a checksum, so two
1152        // entries are two commits, and a second match makes the prefix
1153        // ambiguous.
1154        if found.replace(checksum).is_some() {
1155            return Ok(true);
1156        }
1157    }
1158    Ok(false)
1159}
1160
1161/// Returns the checksum of one `objects/<fanout>/<rest>.commit` entry whose
1162/// name starts with `within`, or `None` for each other entry.
1163fn matching_commit(fanout: &str, entry: &str, within: &str) -> Option<Checksum> {
1164    let (rest, ext) = entry.rsplit_once('.')?;
1165    if ext != "commit" || rest.len() != 62 || !rest.starts_with(within) {
1166        return None;
1167    }
1168    Checksum::from_hex_lower(&format!("{fanout}{rest}")).ok()
1169}
1170
1171/// Returns the symlink body that an alias at `from_relpath` needs to point at
1172/// `to_relpath`.
1173///
1174/// Both paths are relative to the repository root. The body drops the shared
1175/// leading components. It then has one `..` for each further component of
1176/// the directory of the alias. It ends with the other components of the
1177/// target.
1178pub(crate) fn relative_link(from_relpath: &str, to_relpath: &str) -> String {
1179    let from: Vec<&str> = from_relpath.split('/').collect();
1180    let to: Vec<&str> = to_relpath.split('/').collect();
1181    // The name of the alias is not part of the directory that the link is
1182    // read in. The name of the target is never a shared component.
1183    let from_dir = &from[..from.len() - 1];
1184    let common = from_dir
1185        .iter()
1186        .zip(&to[..to.len() - 1])
1187        .take_while(|(a, b)| a == b)
1188        .count();
1189    let mut parts = vec![".."; from_dir.len() - common];
1190    parts.extend_from_slice(&to[common..]);
1191    parts.join("/")
1192}
1193
1194/// Collects each ref under `refs/heads` and its subdirectories.
1195fn collect_heads(repo: &Repo) -> Result<Vec<(String, Checksum)>> {
1196    let Some(heads) = open_refs_dir(repo, "refs/heads")? else {
1197        return Ok(Vec::new());
1198    };
1199    let mut out = Vec::new();
1200    walk_ref_dir(heads.as_fd(), "", &mut |entry| push_head(&mut out, &entry))?;
1201    Ok(out)
1202}
1203
1204/// The directory of the local refs.
1205pub(crate) const HEADS_DIR: &str = "refs/heads";
1206
1207/// The directory of the mirror refs, one subdirectory for each collection id.
1208pub(crate) const MIRRORS_DIR: &str = "refs/mirrors";
1209
1210/// The refs of one ref listing, which [`Repo::select_refs`] returns.
1211#[derive(Default)]
1212pub(crate) struct RefSelection {
1213    /// The local refs, sorted byte-wise by name, each one time.
1214    pub(crate) local: Vec<(String, Checksum)>,
1215    /// The refs of each collection other than the own collection, by
1216    /// collection id, each list sorted byte-wise by name. A collection with
1217    /// no selected ref is not in the map.
1218    pub(crate) collections: BTreeMap<String, Vec<(String, Checksum)>>,
1219    /// The names of the directories under `refs/mirrors/` that fail the
1220    /// collection-id rule, sorted byte-wise, each one time.
1221    pub(crate) invalid_dirs: Vec<String>,
1222    /// The target path of each alias of `local`, by name.
1223    pub(crate) local_aliases: HashMap<String, String>,
1224    /// The target path of each alias of `collections`, by collection id and
1225    /// name.
1226    pub(crate) collection_aliases: BTreeMap<String, HashMap<String, String>>,
1227}
1228
1229impl RefSelection {
1230    /// Returns the refs of the selection that `access` reads.
1231    ///
1232    /// The selection comes from [`Repo::select_refs`] with an access that
1233    /// reads each ref that `access` reads. The result holds the refs that
1234    /// `select_refs` with the same selectors and `access` gives for the same
1235    /// state of the repository. A ref is in the result when `access` reads
1236    /// its name, and, for an alias, its target path. The result holds no
1237    /// alias target and no invalid directory.
1238    pub(crate) fn readable(&self, access: &ReadAccess) -> RefSelection {
1239        let mut out = RefSelection::default();
1240        if access.reads_local_refs() {
1241            for (name, commit) in &self.local {
1242                if !access.can_read(&Namespace::Local, name) {
1243                    continue;
1244                }
1245                if let Some(target) = self.local_aliases.get(name)
1246                    && !access.can_read_path(target)
1247                {
1248                    continue;
1249                }
1250                out.local.push((name.clone(), *commit));
1251            }
1252        }
1253        for (id, refs) in &self.collections {
1254            let Some(rules) = access.collection_rules(id) else {
1255                continue;
1256            };
1257            if !rules.gives_read() {
1258                continue;
1259            }
1260            let aliases = self.collection_aliases.get(id);
1261            let names: Vec<(String, Checksum)> = refs
1262                .iter()
1263                .filter(|(name, _)| {
1264                    crate::access::reads(rules, name)
1265                        && aliases
1266                            .and_then(|aliases| aliases.get(name))
1267                            .is_none_or(|target| access.can_read_path(target))
1268                })
1269                .cloned()
1270                .collect();
1271            if !names.is_empty() {
1272                out.collections.insert(id.clone(), names);
1273            }
1274        }
1275        out
1276    }
1277}
1278
1279/// Returns the local refs that `selector` selects and `access` reads, sorted
1280/// by name, each one time: the refs of `refs/heads`. When `access` reads no
1281/// local ref, or when `selector` selects no name, the call does not open
1282/// `refs/heads`. The call adds each ref to `floor`, and the refs and their
1283/// alias targets to `selection`.
1284fn collect_local_selected(
1285    repo: &Repo,
1286    selector: &RefSelector,
1287    access: &ReadAccess,
1288    floor: &mut SelectionFloor,
1289    selection: &mut RefSelection,
1290) -> Result<()> {
1291    if selects_no_name(selector) || !access.reads_local_refs() {
1292        return Ok(());
1293    }
1294    let mut local = BTreeMap::new();
1295    if let Some(heads) = open_refs_dir(repo, HEADS_DIR)? {
1296        collect_dir_selected(
1297            repo,
1298            HEADS_DIR,
1299            heads.as_fd(),
1300            selector,
1301            access,
1302            floor,
1303            &mut local,
1304            selection,
1305        )?;
1306    }
1307    selection.local = local.into_iter().collect();
1308    Ok(())
1309}
1310
1311/// Adds to `out` each ref of `dir`, the directory `root` under `refs/`, that
1312/// `selector` selects and `access` reads in the local namespace, each one
1313/// time, and adds it to `floor`. A ref that no entry selects, that `access`
1314/// does not read, or that is in `out` already is not read, and a directory
1315/// that a negative pattern covers is not read. With no positive pattern, the
1316/// walk reads only the directories that an allow item of the local rules of
1317/// `access` that gives `r` can match, and no directory that a deny item of
1318/// these rules covers. The target path of each alias goes to
1319/// `selection.local_aliases`.
1320#[allow(clippy::too_many_arguments)]
1321fn collect_dir_selected(
1322    repo: &Repo,
1323    root: &str,
1324    dir: BorrowedFd<'_>,
1325    selector: &RefSelector,
1326    access: &ReadAccess,
1327    floor: &mut SelectionFloor,
1328    out: &mut BTreeMap<String, Checksum>,
1329    selection: &mut RefSelection,
1330) -> Result<()> {
1331    // Reads the ref of `entry` unless it is in `out` already, a negative
1332    // pattern matches it, or `access` does not read it. The positive match
1333    // is the duty of the walk.
1334    let mut take = |entry: RefEntry<'_>| -> Result<()> {
1335        if out.contains_key(entry.path)
1336            || selector.negative().iter().any(|p| p.matches(entry.path))
1337            || !access.can_read(&Namespace::Local, entry.path)
1338        {
1339            return Ok(());
1340        }
1341        if let Some((bytes, target)) = read_listed_ref(repo, root, &entry, access)? {
1342            let commit = parse_ref_content(&bytes)?;
1343            floor.add_ref(entry.path)?;
1344            out.insert(entry.path.to_owned(), commit);
1345            if let Some(target) = target {
1346                selection
1347                    .local_aliases
1348                    .insert(entry.path.to_owned(), target);
1349            }
1350        }
1351        Ok(())
1352    };
1353    match access.local_rules() {
1354        Some(rules) if selector.positive().is_empty() => {
1355            let covers = negative_covers(selector);
1356            walk_readable(dir, rules, &|dir| dir_is_covered(&covers, dir), &mut take)
1357        }
1358        _ => walk_selected(dir, selector, &mut take),
1359    }
1360}
1361
1362/// Adds to `selection` the collection refs that `selector` selects by
1363/// `ID/NAME` and `access` reads, and the names of the directories under
1364/// `mirrors`, the open `refs/mirrors`, that fail the collection-id rule. The
1365/// call adds each ref and each collection of the map to `floor`.
1366///
1367/// The call reads the top level of `mirrors` one time. Then it walks the
1368/// directory of each collection that a positive pattern can reach and whose
1369/// group gives `r`, and no other directory. The own collection id is not a
1370/// collection of the map. A name that is not UTF-8 and an entry at the top
1371/// level that is no directory are skipped.
1372fn collect_collections_selected(
1373    repo: &Repo,
1374    mirrors: BorrowedFd<'_>,
1375    selector: &RefSelector,
1376    access: &ReadAccess,
1377    floor: &mut SelectionFloor,
1378    selection: &mut RefSelection,
1379) -> Result<()> {
1380    let own = repo.config().collection_id();
1381    let walk = CollectionWalk::new(selector);
1382    // The rules of each collection that the walk can reach and the client
1383    // can read, computed one time for the listing.
1384    let mut readable = BTreeMap::new();
1385    for name in read_dir_names(mirrors)? {
1386        if Some(name.as_str()) == own {
1387            continue;
1388        }
1389        if !ostrya_core::is_valid_collection_id(&name) {
1390            if ref_entry_type(mirrors, &name)? == Some(FileType::Directory) {
1391                selection.invalid_dirs.push(name);
1392            }
1393            continue;
1394        }
1395        // The walk opens the directory of each id of `readable` with no
1396        // symlink followed, and skips an entry that is no directory, so the
1397        // loop reads no type of the entry.
1398        if !walk.reaches(&name) {
1399            continue;
1400        }
1401        if let Some(rules) = access.collection_rules(&name)
1402            && rules.gives_read()
1403        {
1404            readable.insert(name, rules);
1405        }
1406    }
1407    selection.invalid_dirs.sort();
1408    selection.invalid_dirs.dedup();
1409    for (id, rules) in &readable {
1410        collect_collection_selected(repo, mirrors, &walk, id, rules, access, floor, selection)?;
1411    }
1412    Ok(())
1413}
1414
1415/// Adds to `selection` the refs of the collection `id` that `walk` selects by
1416/// `ID/NAME` and that `rules`, the rules of the collection, read, with the
1417/// target paths of their aliases. The call walks the directory `id` of
1418/// `mirrors`, the open `refs/mirrors`, with [`CollectionWalk::walk`]. Except
1419/// to read the target of an alias, it opens no other directory of `mirrors`.
1420/// It applies the negative patterns of the walk and `rules` to a name before
1421/// it reads the ref file. An alias resolves only when `access` reads its
1422/// target path. The call adds each ref to `floor`, and the collection when it
1423/// gives its first ref. A collection with no ref is not in `selection`.
1424#[allow(clippy::too_many_arguments)]
1425fn collect_collection_selected(
1426    repo: &Repo,
1427    mirrors: BorrowedFd<'_>,
1428    walk: &CollectionWalk<'_>,
1429    id: &str,
1430    rules: &AccessRules,
1431    access: &ReadAccess,
1432    floor: &mut SelectionFloor,
1433    selection: &mut RefSelection,
1434) -> Result<()> {
1435    let mut names: BTreeMap<String, Checksum> = BTreeMap::new();
1436    let mut aliases = HashMap::new();
1437    let mut take = |entry: RefEntry<'_>| -> Result<()> {
1438        // The walk gives each entry of the directory of `id` as `id/NAME`.
1439        let Some((_, name)) = entry.path.split_once('/') else {
1440            return Ok(());
1441        };
1442        if names.contains_key(name)
1443            || walk
1444                .selector
1445                .negative()
1446                .iter()
1447                .any(|p| p.matches(entry.path))
1448            || !crate::access::reads(rules, name)
1449        {
1450            return Ok(());
1451        }
1452        if let Some((bytes, target)) = read_listed_ref(repo, MIRRORS_DIR, &entry, access)? {
1453            let commit = parse_ref_content(&bytes)?;
1454            if names.is_empty() {
1455                floor.add_collection(id)?;
1456            }
1457            floor.add_ref(name)?;
1458            names.insert(name.to_owned(), commit);
1459            if let Some(target) = target {
1460                aliases.insert(name.to_owned(), target);
1461            }
1462        }
1463        Ok(())
1464    };
1465    walk.walk(mirrors, id, rules, &mut take)?;
1466    if !aliases.is_empty() {
1467        selection.collection_aliases.insert(id.to_owned(), aliases);
1468    }
1469    if !names.is_empty() {
1470        selection
1471            .collections
1472            .insert(id.to_owned(), names.into_iter().collect());
1473    }
1474    Ok(())
1475}
1476
1477/// Walks the ref tree of `dir` for `selector`, and gives `take` each entry
1478/// whose path a positive pattern can match. With no positive pattern, `take`
1479/// gets each entry. The walk does not read a directory that a negative
1480/// pattern covers. `take` applies the negative patterns.
1481fn walk_selected(
1482    dir: BorrowedFd<'_>,
1483    selector: &RefSelector,
1484    take: &mut dyn FnMut(RefEntry<'_>) -> Result<()>,
1485) -> Result<()> {
1486    let covers = negative_covers(selector);
1487    let skip = |dir: &str| dir_is_covered(&covers, dir);
1488    if selector.positive().is_empty() {
1489        walk_ref_dir_skipping(dir, "", &skip, &mut &mut *take)?;
1490    } else {
1491        let split: Vec<(&RefPattern, Vec<&str>)> = uncovered_patterns(selector.positive())
1492            .into_iter()
1493            .map(|pattern| (pattern, pattern.as_str().split('/').collect()))
1494            .collect();
1495        let patterns: Vec<(&RefPattern, &[&str])> = split
1496            .iter()
1497            .map(|(pattern, parts)| (*pattern, parts.as_slice()))
1498            .collect();
1499        walk_ref_patterns(dir, "", &patterns, &skip, take)?;
1500    }
1501    Ok(())
1502}
1503
1504/// Walks the ref tree of `dir` for the allow items of `rules` that give `r`,
1505/// as [`walk_selected`] walks for positive patterns, and gives `take` each
1506/// entry whose path such an item can match. The walk does not read a
1507/// directory that a deny item of `rules` covers, or for whose path `skip`
1508/// returns `true`. `take` applies the rules.
1509fn walk_readable(
1510    dir: BorrowedFd<'_>,
1511    rules: &AccessRules,
1512    skip: &dyn Fn(&str) -> bool,
1513    take: &mut dyn FnMut(RefEntry<'_>) -> Result<()>,
1514) -> Result<()> {
1515    let positive: Vec<RefPattern> = rules
1516        .allow
1517        .iter()
1518        .filter(|item| item.gives_read())
1519        .map(|item| item.pattern.clone())
1520        .collect();
1521    let covers: Vec<Vec<&str>> = rules
1522        .deny
1523        .iter()
1524        .filter_map(|pattern| covering_lead(pattern.as_str()))
1525        .collect();
1526    let skip = |dir: &str| skip(dir) || dir_is_covered(&covers, dir);
1527    for pattern in uncovered_patterns(&positive) {
1528        let parts: Vec<&str> = pattern.as_str().split('/').collect();
1529        walk_ref_pattern(dir, "", &parts, pattern, &skip, take)?;
1530    }
1531    Ok(())
1532}
1533
1534/// The walk of the collection directories under `refs/mirrors` for a
1535/// selector of `ID/NAME` paths, with each pattern split one time.
1536///
1537/// The first part of a pattern names collection ids: a literal names one id,
1538/// and `*` and `**` name each id. A pattern of one part other than `**`
1539/// selects no ref. Below the directory of an id, `**` as the first part takes
1540/// each entry whose whole path the pattern matches, and each other first
1541/// part takes the rest of the parts.
1542struct CollectionWalk<'a> {
1543    /// The selector of the walk.
1544    selector: &'a RefSelector,
1545    /// The leading parts of each negative pattern that covers a directory.
1546    covers: Vec<Vec<&'a str>>,
1547    /// The positive patterns that no other positive pattern covers, each
1548    /// with its parts.
1549    patterns: Vec<(&'a RefPattern, Vec<&'a str>)>,
1550    /// The ids that the first parts name, when no first part is a wildcard.
1551    literal_ids: Option<BTreeSet<&'a str>>,
1552}
1553
1554impl<'a> CollectionWalk<'a> {
1555    /// Returns the walk of `selector`.
1556    fn new(selector: &'a RefSelector) -> CollectionWalk<'a> {
1557        let patterns: Vec<(&RefPattern, Vec<&str>)> = uncovered_patterns(selector.positive())
1558            .into_iter()
1559            .map(|pattern| (pattern, pattern.as_str().split('/').collect()))
1560            .collect();
1561        let literal = patterns
1562            .iter()
1563            .all(|(_, parts)| parts[0] != "*" && parts[0] != "**");
1564        let literal_ids = literal.then(|| {
1565            patterns
1566                .iter()
1567                .filter(|(_, parts)| parts.len() > 1)
1568                .map(|(_, parts)| parts[0])
1569                .collect()
1570        });
1571        CollectionWalk {
1572            selector,
1573            covers: negative_covers(selector),
1574            patterns,
1575            literal_ids,
1576        }
1577    }
1578
1579    /// Returns `true` if a positive pattern can select a ref of the
1580    /// collection `id` and no negative pattern covers its directory. With no
1581    /// positive pattern, each id that no negative pattern covers is reached.
1582    fn reaches(&self, id: &str) -> bool {
1583        if dir_is_covered(&self.covers, id) {
1584            return false;
1585        }
1586        if self.selector.positive().is_empty() {
1587            return true;
1588        }
1589        match &self.literal_ids {
1590            Some(ids) => ids.contains(id),
1591            None => self
1592                .patterns
1593                .iter()
1594                .any(|(_, parts)| first_part_reaches(parts, id)),
1595        }
1596    }
1597
1598    /// Walks the directory `id` of `mirrors`, the open `refs/mirrors`, as
1599    /// [`walk_selected`] walks a directory, and gives `take` each entry as
1600    /// `id/NAME`. The walk does not read the top level of `mirrors`. With no
1601    /// positive pattern, it walks as [`walk_readable`] walks for `rules`, the
1602    /// rules of the collection.
1603    fn walk(
1604        &self,
1605        mirrors: BorrowedFd<'_>,
1606        id: &str,
1607        rules: &AccessRules,
1608        take: &mut dyn FnMut(RefEntry<'_>) -> Result<()>,
1609    ) -> Result<()> {
1610        let skip = |dir: &str| dir_is_covered(&self.covers, dir);
1611        let Some(sub) = open_ref_subdir(mirrors, id)? else {
1612            return Ok(());
1613        };
1614        if self.selector.positive().is_empty() {
1615            let skip = |dir: &str| skip(&format!("{id}/{dir}"));
1616            return walk_readable(sub.as_fd(), rules, &skip, &mut |entry| {
1617                let path = format!("{id}/{}", entry.path);
1618                take(RefEntry {
1619                    path: &path,
1620                    ..entry
1621                })
1622            });
1623        }
1624        // The patterns whose first part names `id`, with the parts below it.
1625        let mut below: Vec<(&RefPattern, &[&str])> = Vec::new();
1626        for (pattern, parts) in &self.patterns {
1627            if !first_part_reaches(parts, id) {
1628                continue;
1629            }
1630            match parts.split_first() {
1631                Some((&"**", _)) => {
1632                    walk_ref_dir_skipping(sub.as_fd(), id, &skip, &mut |entry| {
1633                        if pattern.matches(entry.path) {
1634                            take(entry)
1635                        } else {
1636                            Ok(())
1637                        }
1638                    })?;
1639                }
1640                Some((_, rest)) => below.push((*pattern, rest)),
1641                None => {}
1642            }
1643        }
1644        walk_ref_patterns(sub.as_fd(), id, &below, &skip, take)
1645    }
1646}
1647
1648/// Returns `true` if the pattern of the parts `parts` can select a ref of the
1649/// collection `id`: its first part is `**`, or it has more than one part and
1650/// its first part is `*` or `id`.
1651fn first_part_reaches(parts: &[&str], id: &str) -> bool {
1652    match parts.split_first() {
1653        Some((&"**", _)) => true,
1654        Some((first, rest)) => !rest.is_empty() && (*first == "*" || *first == id),
1655        None => false,
1656    }
1657}
1658
1659/// Returns `true` if a negative pattern of `selector` is `**`. That pattern
1660/// matches each name, so `selector` selects no name.
1661fn selects_no_name(selector: &RefSelector) -> bool {
1662    selector.negative().iter().any(|p| p.as_str() == "**")
1663}
1664
1665/// Returns the leading parts of each negative pattern of `selector` that
1666/// covers a directory, for [`dir_is_covered`].
1667fn negative_covers(selector: &RefSelector) -> Vec<Vec<&str>> {
1668    selector
1669        .negative()
1670        .iter()
1671        .filter_map(|pattern| covering_lead(pattern.as_str()))
1672        .collect()
1673}
1674
1675/// Reads the ref of the entry `entry` of a ref-tree walk of the directory
1676/// `root` under `refs/` for the listing of `access`, or returns `None`.
1677///
1678/// The result holds the bytes of the ref file, and the target path of an
1679/// alias. An alias goes to [`read_alias_ref`]. The call opens each other
1680/// entry with [`walk`], so the open follows no symlink and does not wait for
1681/// a writer. An entry that is an alias at the open goes to `read_alias_ref`,
1682/// as the ref-tree walk sends an alias. An entry removed after the ref-tree
1683/// walk read its type gives `None`. An entry that is a FIFO or a socket at
1684/// the open gives `None`.
1685fn read_listed_ref(
1686    repo: &Repo,
1687    root: &str,
1688    entry: &RefEntry<'_>,
1689    access: &ReadAccess,
1690) -> Result<Option<(Vec<u8>, Option<String>)>> {
1691    let alias = || -> Result<Option<(Vec<u8>, Option<String>)>> {
1692        Ok(read_alias_ref(repo, root, entry, access)?.map(|(bytes, target)| (bytes, Some(target))))
1693    };
1694    if entry.file_type == FileType::Symlink {
1695        return alias();
1696    }
1697    match walk(entry.dir, entry.name, false)? {
1698        Walked::File(file, _) => {
1699            let mut buf = Vec::with_capacity(REF_READ_CAP as usize);
1700            file.take(REF_READ_CAP).read_to_end(&mut buf)?;
1701            Ok(Some((buf, None)))
1702        }
1703        Walked::NotFound => Ok(None),
1704        Walked::Refused | Walked::Alias(_) => alias(),
1705    }
1706}
1707
1708/// Reads the ref that the alias `entry` of a walk of the directory `root`
1709/// under `refs/` names, or returns `None`. The result holds the bytes of the
1710/// ref file and the target path.
1711///
1712/// The body of the alias resolves by the rule of the archive view. The
1713/// result is `None` when the body breaks that rule, when `access` does not
1714/// read the target path, and when the target is no regular file. The path of
1715/// the target gives its namespace. The read of the target follows no
1716/// symlink.
1717fn read_alias_ref(
1718    repo: &Repo,
1719    root: &str,
1720    entry: &RefEntry<'_>,
1721    access: &ReadAccess,
1722) -> Result<Option<(Vec<u8>, String)>> {
1723    let body = match rustix::fs::readlinkat(entry.dir, entry.name, Vec::new()) {
1724        Ok(body) => body,
1725        // The entry was removed after the walk read its type.
1726        Err(Errno::NOENT) => return Ok(None),
1727        Err(e) => return Err(Error::Io(e.into())),
1728    };
1729    let link_dir = match entry.path.rsplit_once('/') {
1730        Some((dir, _)) => format!("{root}/{dir}"),
1731        None => root.to_owned(),
1732    };
1733    let Some(target) = resolve_alias(&link_dir, body.as_bytes()) else {
1734        return Ok(None);
1735    };
1736    if !access.can_read_path(&target) {
1737        return Ok(None);
1738    }
1739    match walk(repo.repo_fd(), &target, false)? {
1740        Walked::File(file, _) => {
1741            let mut buf = Vec::with_capacity(REF_READ_CAP as usize);
1742            file.take(REF_READ_CAP).read_to_end(&mut buf)?;
1743            Ok(Some((buf, target)))
1744        }
1745        Walked::NotFound | Walked::Refused | Walked::Alias(_) => Ok(None),
1746    }
1747}
1748
1749/// Reads the ref entry `entry` of a walk of `refs/heads` and adds it to
1750/// `out`. An alias resolves to the commit of its target, and a dangling alias
1751/// adds nothing.
1752fn push_head(out: &mut Vec<(String, Checksum)>, entry: &RefEntry<'_>) -> Result<()> {
1753    if let Some(bytes) = read_ref_file(entry.dir, entry.name)? {
1754        out.push((entry.path.to_owned(), parse_ref_content(&bytes)?));
1755    }
1756    Ok(())
1757}
1758
1759/// Collects each ref under `refs/remotes`, named by its `remote:name`
1760/// refspec. The first path component is the remote, and the rest is the ref
1761/// name.
1762fn collect_remotes(repo: &Repo) -> Result<Vec<(String, Checksum)>> {
1763    let Some(remotes) = open_refs_dir(repo, "refs/remotes")? else {
1764        return Ok(Vec::new());
1765    };
1766    let mut out = Vec::new();
1767    walk_ref_dir(remotes.as_fd(), "", &mut |entry| {
1768        let Some(bytes) = read_ref_file(entry.dir, entry.name)? else {
1769            return Ok(());
1770        };
1771        let checksum = parse_ref_content(&bytes)?;
1772        // A file directly under refs/remotes names no remote. The walk skips
1773        // it, as collect_mirrors skips a file that names no collection.
1774        if let Some((remote, ref_name)) = entry.path.split_once('/') {
1775            out.push((format!("{remote}:{ref_name}"), checksum));
1776        }
1777        Ok(())
1778    })?;
1779    Ok(out)
1780}
1781
1782/// Collects each ref under `refs/remotes/R/` of each remote R of `remotes`,
1783/// as `(remote, collection_id, ref_name, commit)` tuples. `remotes` maps a
1784/// remote name to its collection id. The refs come in the order of the remotes in
1785/// the map. A directory `R` that is absent, a regular file, or a symlink
1786/// gives no ref.
1787fn collect_remote_collections(
1788    repo: &Repo,
1789    remotes: &BTreeMap<String, String>,
1790) -> Result<Vec<(String, String, String, Checksum)>> {
1791    let Some(dir) = open_refs_dir(repo, "refs/remotes")? else {
1792        return Ok(Vec::new());
1793    };
1794    let mut out = Vec::new();
1795    for (remote, collection) in remotes {
1796        let Some(sub) = open_ref_subdir(dir.as_fd(), remote)? else {
1797            continue;
1798        };
1799        walk_ref_dir(sub.as_fd(), "", &mut |entry| {
1800            if let Some(bytes) = read_ref_file(entry.dir, entry.name)? {
1801                let checksum = parse_ref_content(&bytes)?;
1802                out.push((
1803                    remote.clone(),
1804                    collection.clone(),
1805                    entry.path.to_owned(),
1806                    checksum,
1807                ));
1808            }
1809            Ok(())
1810        })?;
1811    }
1812    Ok(out)
1813}
1814
1815/// Collects the aliases under `refs/heads` and `refs/remotes`. Each alias
1816/// gets the name that the listing of its directory gives a ref.
1817fn collect_aliases(repo: &Repo) -> Result<Vec<RefAlias>> {
1818    let mut out = Vec::new();
1819    if let Some(heads) = open_refs_dir(repo, "refs/heads")? {
1820        walk_ref_dir(heads.as_fd(), "", &mut |entry| {
1821            if let Some(target) = read_alias_target(&entry)? {
1822                out.push(RefAlias {
1823                    refspec: entry.path.to_owned(),
1824                    target,
1825                });
1826            }
1827            Ok(())
1828        })?;
1829    }
1830    if let Some(remotes) = open_refs_dir(repo, "refs/remotes")? {
1831        walk_ref_dir(remotes.as_fd(), "", &mut |entry| {
1832            if let Some(target) = read_alias_target(&entry)?
1833                && let Some((remote, ref_name)) = entry.path.split_once('/')
1834            {
1835                out.push(RefAlias {
1836                    refspec: format!("{remote}:{ref_name}"),
1837                    target,
1838                });
1839            }
1840            Ok(())
1841        })?;
1842    }
1843    Ok(out)
1844}
1845
1846/// Opens one directory under `refs/`. Returns `None` if it does not exist.
1847fn open_refs_dir(repo: &Repo, relpath: &str) -> Result<Option<OwnedFd>> {
1848    match rustix::fs::openat(
1849        repo.repo_fd(),
1850        relpath,
1851        OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
1852        Mode::empty(),
1853    ) {
1854        Ok(fd) => Ok(Some(fd)),
1855        Err(Errno::NOENT) => Ok(None),
1856        Err(e) => Err(Error::Io(e.into())),
1857    }
1858}
1859
1860/// Collects each ref under `refs/mirrors`, split into its collection id (the
1861/// first path component) and its ref name (the rest of the path). The walk
1862/// does not read the directory `refs/mirrors/skip/`.
1863fn collect_mirrors(repo: &Repo, skip: Option<&str>) -> Result<Vec<(String, String, Checksum)>> {
1864    let Some(mirrors) = open_refs_dir(repo, "refs/mirrors")? else {
1865        return Ok(Vec::new());
1866    };
1867    let mut out = Vec::new();
1868    let skip = |path: &str| Some(path) == skip;
1869    walk_ref_dir_skipping(mirrors.as_fd(), "", &skip, &mut |entry| {
1870        let Some(bytes) = read_ref_file(entry.dir, entry.name)? else {
1871            return Ok(());
1872        };
1873        let checksum = parse_ref_content(&bytes)?;
1874        // A mirror ref is <collection>/<ref>. The collection id is one
1875        // component, and the ref name is the path after the first slash. A
1876        // file directly under refs/mirrors has no collection component. The
1877        // walk skips it, which matches the collection-qualified layout of the
1878        // `ostree` command.
1879        if let Some((collection, ref_name)) = entry.path.split_once('/') {
1880            out.push((collection.to_owned(), ref_name.to_owned(), checksum));
1881        }
1882        Ok(())
1883    })?;
1884    Ok(out)
1885}
1886
1887/// One entry a ref-tree walk reports.
1888pub(crate) struct RefEntry<'a> {
1889    /// The open directory holding the entry.
1890    pub(crate) dir: BorrowedFd<'a>,
1891    /// The name of the entry in that directory.
1892    pub(crate) name: &'a str,
1893    /// The path from the root of the walk to the entry.
1894    pub(crate) path: &'a str,
1895    /// The type of the entry, read with no symlink followed.
1896    pub(crate) file_type: FileType,
1897}
1898
1899/// Walks a directory under `refs/`. The walk descends into each subdirectory
1900/// and reports each other entry to `visit`.
1901///
1902/// The walk classifies entries with `SYMLINK_NOFOLLOW`, so it descends only
1903/// into a real directory, and an alias has [`FileType::Symlink`] whatever it
1904/// names. The walk reports a link that names a directory and does not
1905/// descend into it. A caller that reads it as a ref fails the read with
1906/// `EISDIR`, and a caller that reads it as an alias reads the link. The walk
1907/// skips a name that is not UTF-8, and a name removed between the directory
1908/// read and the classification.
1909///
1910/// The walk opens a subdirectory with no symlink followed. When the entry is
1911/// no directory at the open, the walk reads its type again and reports it
1912/// with that type. When the entry is removed, or is a directory again, the
1913/// walk skips it.
1914pub(crate) fn walk_ref_dir(
1915    dir: BorrowedFd<'_>,
1916    prefix: &str,
1917    visit: &mut impl FnMut(RefEntry<'_>) -> Result<()>,
1918) -> Result<()> {
1919    walk_ref_dir_skipping(dir, prefix, &|_| false, visit)
1920}
1921
1922/// Walks a directory as [`walk_ref_dir`] does, and does not read a
1923/// subdirectory when `skip` returns `true` for its path below the top.
1924fn walk_ref_dir_skipping(
1925    dir: BorrowedFd<'_>,
1926    prefix: &str,
1927    skip: &dyn Fn(&str) -> bool,
1928    visit: &mut impl FnMut(RefEntry<'_>) -> Result<()>,
1929) -> Result<()> {
1930    for name in read_dir_names(dir)? {
1931        // A name removed between the directory read and the classification
1932        // has no type.
1933        let Some(mut file_type) = ref_entry_type(dir, &name)? else {
1934            continue;
1935        };
1936        let path = if prefix.is_empty() {
1937            name.clone()
1938        } else {
1939            format!("{prefix}/{name}")
1940        };
1941        if file_type == FileType::Directory {
1942            if skip(&path) {
1943                continue;
1944            }
1945            if let Some(sub) = open_ref_subdir(dir, &name)? {
1946                walk_ref_dir_skipping(sub.as_fd(), &path, skip, visit)?;
1947                continue;
1948            }
1949            // The entry changed after its classification. It takes the type
1950            // that it has now.
1951            match ref_entry_type(dir, &name)? {
1952                Some(now) if now != FileType::Directory => file_type = now,
1953                _ => continue,
1954            }
1955        }
1956        visit(RefEntry {
1957            dir,
1958            name: &name,
1959            path: &path,
1960            file_type,
1961        })?;
1962    }
1963    Ok(())
1964}
1965
1966/// Walks the parts of a ref tree that the patterns `patterns` can match, as
1967/// [`walk_ref_pattern`] walks for each pattern. Each item holds a pattern and
1968/// its parts that remain below `dir`, and `prefix` is the path of `dir` below
1969/// the top, or empty for the top.
1970///
1971/// The patterns whose first part is the same literal share the read of the
1972/// type of that entry and the open of that directory. So the walk opens each
1973/// directory of the literal leading parts one time, whatever the number of
1974/// patterns below it. Each pattern whose first part is `*` or `**` goes to
1975/// `walk_ref_pattern`.
1976fn walk_ref_patterns(
1977    dir: BorrowedFd<'_>,
1978    prefix: &str,
1979    patterns: &[(&RefPattern, &[&str])],
1980    skip: &dyn Fn(&str) -> bool,
1981    visit: &mut dyn FnMut(RefEntry<'_>) -> Result<()>,
1982) -> Result<()> {
1983    // The patterns of each literal first part, with the parts after it.
1984    let mut literal: BTreeMap<&str, Vec<(&RefPattern, &[&str])>> = BTreeMap::new();
1985    for &(pattern, parts) in patterns {
1986        match parts.split_first() {
1987            Some((first, rest)) if *first != "*" && *first != "**" => {
1988                literal.entry(first).or_default().push((pattern, rest));
1989            }
1990            Some(_) => walk_ref_pattern(dir, prefix, parts, pattern, skip, visit)?,
1991            None => {}
1992        }
1993    }
1994    for (name, group) in literal {
1995        // A missing entry, or a name longer than a file name can be, has no
1996        // type.
1997        let Some(file_type) = ref_entry_type(dir, name)? else {
1998            continue;
1999        };
2000        let path = if prefix.is_empty() {
2001            name.to_owned()
2002        } else {
2003            format!("{prefix}/{name}")
2004        };
2005        if file_type == FileType::Directory {
2006            let below: Vec<(&RefPattern, &[&str])> = group
2007                .into_iter()
2008                .filter(|(_, rest)| !rest.is_empty())
2009                .collect();
2010            // An entry that is no directory at the open matches no pattern
2011            // with more parts.
2012            if !below.is_empty()
2013                && !skip(&path)
2014                && let Some(sub) = open_ref_subdir(dir, name)?
2015            {
2016                walk_ref_patterns(sub.as_fd(), &path, &below, skip, visit)?;
2017            }
2018        } else if group.iter().any(|(_, rest)| rest.is_empty()) {
2019            visit(RefEntry {
2020                dir,
2021                name,
2022                path: &path,
2023                file_type,
2024            })?;
2025        }
2026    }
2027    Ok(())
2028}
2029
2030/// Walks the part of a ref tree that `pattern` can match. `parts` are the
2031/// parts of the pattern that remain below `dir`, and `prefix` is the path of
2032/// `dir` below the top, or empty for the top. `visit` gets each entry that
2033/// [`walk_ref_dir`] gives from the top with a path that `pattern` matches,
2034/// and no other entry. The call does not read a subdirectory when `skip`
2035/// returns `true` for its path.
2036///
2037/// The call classifies each entry with `SYMLINK_NOFOLLOW`, and opens a
2038/// subdirectory with no symlink followed, as `walk_ref_dir` does, so it
2039/// descends only into a real directory. It reads no ref file
2040/// outside the literal leading parts of the pattern and the matches. A
2041/// leading wildcard lists the directories at its level. For the first of
2042/// `parts`:
2043///
2044/// - A literal part names one entry. If the entry is missing, or is longer
2045///   than a file name can be, the pattern selects nothing. If more parts
2046///   follow, the entry must be a real directory, and the call goes down into
2047///   it. If the part is the last, the entry goes to `visit` unless it is a
2048///   directory. A symlink that names a directory is such an entry.
2049/// - `*` reads `dir` and takes each entry as a literal part does.
2050/// - `**` walks `dir` with `walk_ref_dir`. If no part follows it, each entry
2051///   goes to `visit`. Otherwise `visit` gets each entry whose whole path the
2052///   pattern matches.
2053fn walk_ref_pattern(
2054    dir: BorrowedFd<'_>,
2055    prefix: &str,
2056    parts: &[&str],
2057    pattern: &RefPattern,
2058    skip: &dyn Fn(&str) -> bool,
2059    visit: &mut dyn FnMut(RefEntry<'_>) -> Result<()>,
2060) -> Result<()> {
2061    let Some((first, rest)) = parts.split_first() else {
2062        return Ok(());
2063    };
2064    if *first == "**" {
2065        return walk_ref_dir_skipping(dir, prefix, skip, &mut |entry| {
2066            if rest.is_empty() || pattern.matches(entry.path) {
2067                visit(entry)
2068            } else {
2069                Ok(())
2070            }
2071        });
2072    }
2073    let names = if *first == "*" {
2074        read_dir_names(dir)?
2075    } else {
2076        vec![(*first).to_owned()]
2077    };
2078    for name in names {
2079        // A name removed after the directory read has no type.
2080        let Some(file_type) = ref_entry_type(dir, &name)? else {
2081            continue;
2082        };
2083        let path = if prefix.is_empty() {
2084            name.clone()
2085        } else {
2086            format!("{prefix}/{name}")
2087        };
2088        match (file_type == FileType::Directory, rest.is_empty()) {
2089            (true, false) if !skip(&path) => {
2090                // An entry that is no directory at the open matches no
2091                // pattern with more parts.
2092                if let Some(sub) = open_ref_subdir(dir, &name)? {
2093                    walk_ref_pattern(sub.as_fd(), &path, rest, pattern, skip, visit)?;
2094                }
2095            }
2096            (false, true) => visit(RefEntry {
2097                dir,
2098                name: &name,
2099                path: &path,
2100                file_type,
2101            })?,
2102            _ => {}
2103        }
2104    }
2105    Ok(())
2106}
2107
2108/// Returns the leading parts of the negative pattern `text` when the
2109/// pattern is these parts, each a literal or `*`, followed by a final `**`.
2110/// Such a pattern matches each name below a directory whose path starts with
2111/// the parts. `**` alone has no leading part.
2112fn covering_lead(text: &str) -> Option<Vec<&str>> {
2113    let lead = if text == "**" {
2114        ""
2115    } else {
2116        text.strip_suffix("/**")?
2117    };
2118    let parts: Vec<&str> = if lead.is_empty() {
2119        Vec::new()
2120    } else {
2121        lead.split('/').collect()
2122    };
2123    if parts.contains(&"**") {
2124        return None;
2125    }
2126    Some(parts)
2127}
2128
2129/// Returns `true` if a negative pattern with one of the leading parts
2130/// `covers` matches each name below the directory `dir`. That holds when
2131/// `dir` has at least as many parts as the lead, and each lead part is `*` or
2132/// equals the part of `dir` at its place.
2133fn dir_is_covered(covers: &[Vec<&str>], dir: &str) -> bool {
2134    covers.iter().any(|lead| {
2135        let mut parts = dir.split('/');
2136        lead.iter()
2137            .all(|l| parts.next().is_some_and(|part| *l == "*" || *l == part))
2138    })
2139}
2140
2141/// Returns the patterns of `patterns` that no other pattern of the slice
2142/// covers, in order. A pattern `q` covers a pattern `p` when `q` is literal
2143/// parts followed by a final `**`, and `p` starts with the same literal
2144/// parts and has at least one more part: each name that `p` matches is below
2145/// the literal parts, and `q` matches it. Of two patterns with the same text
2146/// the first stays. A pattern that only a combination of patterns covers
2147/// stays.
2148fn uncovered_patterns(patterns: &[RefPattern]) -> Vec<&RefPattern> {
2149    // The text of each pattern that has the shape of `q`, up to its `**`.
2150    let leads: Vec<(usize, &str)> = patterns
2151        .iter()
2152        .enumerate()
2153        .filter_map(|(i, q)| {
2154            let text = q.as_str();
2155            let lead = if text == "**" {
2156                ""
2157            } else {
2158                &text[..text.strip_suffix("/**")?.len() + 1]
2159            };
2160            let literal = lead.split('/').all(|part| part != "*" && part != "**");
2161            literal.then_some((i, lead))
2162        })
2163        .collect();
2164    // The texts of the patterns before the current one.
2165    let mut seen: HashSet<&str> = HashSet::new();
2166    patterns
2167        .iter()
2168        .filter(|p| {
2169            let text = p.as_str();
2170            let repeat = !seen.insert(text);
2171            !repeat
2172                && !leads.iter().any(|(j, lead)| {
2173                    patterns[*j].as_str() != text
2174                        && text.len() > lead.len()
2175                        && text.starts_with(lead)
2176                })
2177        })
2178        .collect()
2179}
2180
2181/// Returns the type of the entry `name` of `dir`, read with no symlink
2182/// followed, or `None` if the entry does not exist.
2183///
2184/// A name longer than the file system permits (`ENAMETOOLONG`) names no
2185/// entry, so it also gives `None`.
2186fn ref_entry_type(dir: BorrowedFd<'_>, name: &str) -> Result<Option<FileType>> {
2187    match rustix::fs::statat(dir, name, AtFlags::SYMLINK_NOFOLLOW) {
2188        Ok(stat) => Ok(Some(FileType::from_raw_mode(stat.st_mode))),
2189        Err(Errno::NOENT | Errno::NAMETOOLONG) => Ok(None),
2190        Err(e) => Err(Error::Io(e.into())),
2191    }
2192}
2193
2194/// Opens the subdirectory `name` of `dir` in a ref-tree walk, with no
2195/// symlink followed. Returns `None` if the entry is removed or is no
2196/// directory, a symlink included.
2197fn open_ref_subdir(dir: BorrowedFd<'_>, name: &str) -> Result<Option<OwnedFd>> {
2198    match rustix::fs::openat(
2199        dir,
2200        name,
2201        OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
2202        Mode::empty(),
2203    ) {
2204        Ok(fd) => Ok(Some(fd)),
2205        Err(Errno::NOENT | Errno::NOTDIR | Errno::LOOP) => Ok(None),
2206        Err(e) => Err(Error::Io(e.into())),
2207    }
2208}
2209
2210/// Returns the symlink target of an alias entry, as stored. Returns `None`
2211/// for an entry that is not a symlink and for a target that is not UTF-8.
2212fn read_alias_target(entry: &RefEntry<'_>) -> Result<Option<String>> {
2213    if entry.file_type != FileType::Symlink {
2214        return Ok(None);
2215    }
2216    let target = rustix::fs::readlinkat(entry.dir, entry.name, Vec::new())
2217        .map_err(|e| Error::Io(e.into()))?;
2218    Ok(target.into_string().ok())
2219}
2220
2221/// Reads a ref file relative to `dir`, and follows alias symlinks. Returns
2222/// `None` if the file does not exist.
2223fn read_ref_file(
2224    dir: rustix::fd::BorrowedFd<'_>,
2225    relpath: &str,
2226) -> std::io::Result<Option<Vec<u8>>> {
2227    let fd = match rustix::fs::openat(
2228        dir,
2229        relpath,
2230        OFlags::RDONLY | OFlags::CLOEXEC,
2231        Mode::empty(),
2232    ) {
2233        Ok(fd) => fd,
2234        Err(Errno::NOENT) => return Ok(None),
2235        Err(e) => return Err(e.into()),
2236    };
2237    // The buffer holds the whole cap before the read, so a ref file takes
2238    // one read and the read that finds its end.
2239    let mut buf = Vec::with_capacity(REF_READ_CAP as usize);
2240    std::fs::File::from(fd)
2241        .take(REF_READ_CAP)
2242        .read_to_end(&mut buf)?;
2243    Ok(Some(buf))
2244}
2245
2246/// Returns `true` if `e` is the error of a read of a ref path that names a
2247/// directory, or that passes through a file. Such a path holds no ref.
2248fn is_not_a_ref_path(e: &std::io::Error) -> bool {
2249    matches!(
2250        e.kind(),
2251        std::io::ErrorKind::IsADirectory | std::io::ErrorKind::NotADirectory
2252    )
2253}
2254
2255/// Returns the state of the ref path `relpath`, read with `lstat` and then an
2256/// `O_NOFOLLOW` open of a regular file. A path that passes through a file
2257/// (`ENOTDIR`) is [`RefFileState::NotARef`].
2258#[cfg(feature = "receive")]
2259fn ref_file_state(dir: BorrowedFd<'_>, relpath: &str) -> Result<RefFileState> {
2260    let stat = match rustix::fs::statat(dir, relpath, AtFlags::SYMLINK_NOFOLLOW) {
2261        Ok(stat) => stat,
2262        Err(Errno::NOENT) => return Ok(RefFileState::Absent),
2263        Err(Errno::NOTDIR) => return Ok(RefFileState::NotARef),
2264        Err(e) => return Err(e.into()),
2265    };
2266    match FileType::from_raw_mode(stat.st_mode) {
2267        FileType::Symlink => return Ok(RefFileState::Alias),
2268        FileType::RegularFile => {}
2269        _ => return Ok(RefFileState::NotARef),
2270    }
2271    let fd = match rustix::fs::openat(
2272        dir,
2273        relpath,
2274        OFlags::RDONLY | OFlags::CLOEXEC | OFlags::NOFOLLOW,
2275        Mode::empty(),
2276    ) {
2277        Ok(fd) => fd,
2278        Err(Errno::NOENT) => return Ok(RefFileState::Absent),
2279        Err(Errno::LOOP) => return Ok(RefFileState::Alias),
2280        Err(e) => return Err(e.into()),
2281    };
2282    let mut buf = Vec::with_capacity(REF_READ_CAP as usize);
2283    std::fs::File::from(fd)
2284        .take(REF_READ_CAP)
2285        .read_to_end(&mut buf)?;
2286    Ok(RefFileState::Commit(parse_ref_content(&buf)?))
2287}
2288
2289/// Parses the content of a ref file: a hex checksum with trailing white
2290/// space.
2291fn parse_ref_content(bytes: &[u8]) -> Result<Checksum> {
2292    let text = std::str::from_utf8(bytes)
2293        .map_err(|_| Error::InvalidFormat("ref content is not valid UTF-8".into()))?;
2294    Ok(Checksum::from_hex(text.trim())?)
2295}
2296
2297/// Checks that a refspec names a path under `refs/`.
2298///
2299/// A refspec is a ref name, with an optional `<remote>:` prefix.
2300/// [`ostrya_core::is_refspec`] holds the rule. Each component of the name, and
2301/// the remote, is not empty, does not start with `-` or `.`, and holds only
2302/// ASCII alphanumerics, `-`, `.`, `_`, and alphanumeric characters that are
2303/// not ASCII. So the name holds no `:`, no space, and no wildcard, and the
2304/// remote holds no `/`, no space, and no wildcard.
2305///
2306/// # Errors
2307///
2308/// - [`Error::InvalidRefspec`] if `refspec` does not obey the rule, for
2309///   example if it names a path outside `refs/` or holds a character that
2310///   the rule refuses. The error holds the refspec as given.
2311pub fn validate_refspec(refspec: &str) -> Result<()> {
2312    if ostrya_core::is_refspec(refspec) {
2313        Ok(())
2314    } else {
2315        Err(Error::InvalidRefspec(refspec.to_owned()))
2316    }
2317}
2318
2319/// Maps a refspec to its path under `refs/`. Refuses a refspec that
2320/// [`validate_refspec`] refuses.
2321pub(crate) fn refspec_to_relpath(refspec: &str) -> Result<String> {
2322    validate_refspec(refspec)?;
2323    Ok(match refspec.split_once(':') {
2324        Some((remote, name)) => format!("refs/remotes/{remote}/{name}"),
2325        None => format!("refs/heads/{refspec}"),
2326    })
2327}
2328
2329/// Returns `true` if the name that a listing gave a ref addresses the file
2330/// that the listing read: if [`refspec_to_relpath`] maps `name` to exactly
2331/// `<top>/<path>`. `top` is the directory of `refs/` that the listing walked,
2332/// and `path` is the path of the ref file below it.
2333///
2334/// Prune classifies a ref below `refs/heads` or `refs/remotes` only where
2335/// this returns `true`. So each such ref that the classifier sees reads and
2336/// deletes through the file that the listing read. A name that the mapping
2337/// refuses gives `false`.
2338///
2339/// The name alone decides this for a ref below `refs/heads`. There, a `:` in
2340/// the name sends the mapping to `refs/remotes` and so to a different file.
2341///
2342/// For a ref below `refs/remotes`, the path must be `<remote>/<rest>`, where
2343/// the name is `<remote>:<rest>`. A listing names such a ref with a `:` in
2344/// place of the first `/` of its path.
2345///
2346/// A name that the ref-name rule refuses is not addressable, so prune never
2347/// classifies it as weak. Only an out-of-band write can put such a name on
2348/// disk. The rule refuses a `:` in the name part, so a name that a listing
2349/// gives for a file below `refs/remotes` addresses that file alone.
2350///
2351/// No refspec maps to a path below `refs/mirrors`, so a mirror ref always
2352/// gives `false`. Prune classifies a mirror ref by its own rule: the path
2353/// must split into a valid collection id and a valid ref name, which
2354/// [`ref_relpath`] with no own id maps back to the same file.
2355///
2356/// The body mirrors [`refspec_to_relpath`] branch for branch and allocates
2357/// nothing, because prune calls it once for each ref in the repository.
2358pub(crate) fn listed_name_addresses_it(name: &str, top: &str, path: &str) -> bool {
2359    match name.split_once(':') {
2360        Some((remote, rest)) => {
2361            top == "refs/remotes"
2362                && ostrya_core::is_ref_name_component(remote)
2363                && is_ref_path(rest)
2364                && path
2365                    .split_once('/')
2366                    .is_some_and(|(dir, below)| dir == remote && below == rest)
2367        }
2368        None => top == "refs/heads" && is_ref_path(name) && path == name,
2369    }
2370}
2371
2372/// Checks a bare ref name with the ref-name rule of [`validate_refspec`], and
2373/// fails with [`Error::InvalidRefspec`].
2374///
2375/// An HTTP pull applies it before a ref name becomes a request path. A
2376/// component that the rule refuses, such as a traversal component, asks the
2377/// server for a different resource, as it names a different file in the
2378/// repository.
2379pub(crate) fn check_ref_path(name: &str) -> Result<()> {
2380    if is_ref_path(name) {
2381        Ok(())
2382    } else {
2383        Err(Error::InvalidRefspec(name.to_owned()))
2384    }
2385}
2386
2387/// Returns each prefix that selects the ref `name`: each leading part of
2388/// `name` that ends before a `/`, and then `name` itself.
2389///
2390/// The prefix `a/b` selects the ref `a/b` and each ref below `a/b/`. It does
2391/// not select `a/bc`. [`Repo::list_refs`] applies this rule.
2392pub(crate) fn ref_prefixes(name: &str) -> impl Iterator<Item = &str> {
2393    name.match_indices('/')
2394        .map(|(end, _)| &name[..end])
2395        .chain(std::iter::once(name))
2396}
2397
2398// A ref name can contain `/`. A component of a ref name, and a remote, is not
2399// empty, does not start with `-` or `.`, and holds ASCII alphanumerics, `-`,
2400// `.`, `_`, and alphanumeric characters that are not ASCII. `is_component` is
2401// the wider one-component rule that the remote part of a receive pattern uses
2402// (`receive/pattern.rs`): not empty, not `.` or `..`, no slash, no NUL.
2403// `ostrya-core` holds the rules, and a collection id takes
2404// `ostrya_core::is_valid_collection_id`.
2405#[cfg(feature = "receive")]
2406pub(crate) use ostrya_core::is_ref_component as is_component;
2407pub(crate) use ostrya_core::is_ref_name as is_ref_path;
2408
2409/// Maps a ref to the path under the repository that the ref store reads and
2410/// writes, in a repository whose `[core] collection-id` is `own`.
2411///
2412/// A local ref gives `refs/heads/<name>`, and a remote ref gives
2413/// `refs/remotes/<remote>/<name>`. A collection ref gives
2414/// `refs/mirrors/<id>/<name>`, or `refs/heads/<name>` when `id` is `own`. A
2415/// caller that needs the mirror path of each id passes `None`. The ref must
2416/// pass [`Ref::validate`]. A failure gives [`Error::InvalidRefspec`] with the
2417/// text of the ref, and the caller writes nothing.
2418pub(crate) fn ref_relpath(own: Option<&str>, r: &Ref) -> Result<String> {
2419    r.validate()?;
2420    Ok(match r {
2421        Ref::Local { name } => format!("{HEADS_DIR}/{name}"),
2422        Ref::Remote { remote, name } => format!("refs/remotes/{remote}/{name}"),
2423        Ref::Collection { id, name } if Some(id.as_str()) == own => {
2424            format!("{HEADS_DIR}/{name}")
2425        }
2426        Ref::Collection { id, name } => format!("{MIRRORS_DIR}/{id}/{name}"),
2427    })
2428}
2429
2430/// Reads a refspec as a [`Ref`] with no check: `REMOTE:NAME`, split at the
2431/// first `:`, is a remote ref, and other text is a local ref.
2432///
2433/// The ref store checks the result where it maps it to a path, so a refspec
2434/// that fails the rule fails there with [`Error::InvalidRefspec`].
2435pub(crate) fn refspec_ref(refspec: &str) -> Ref {
2436    match refspec.split_once(':') {
2437        Some((remote, name)) => Ref::remote(remote, name),
2438        None => Ref::local(refspec),
2439    }
2440}
2441
2442/// The permission bits forced on a ref file, independent of the umask. The
2443/// `ostree` command writes its ref files with mode `0644`.
2444const REF_FILE_MODE: u32 = 0o644;
2445/// The request mode for a created ref parent directory, reduced by the umask.
2446/// The ref subdirectories of the `ostree` command are `0755` under a `022`
2447/// umask. In a `bare-user-shared` repository, the write then forces a parent
2448/// directory that it creates to [`perm::SHARED_DIR_MODE`]. So each member of
2449/// the repository group can publish a ref under it.
2450const REF_DIR_MODE: u32 = 0o777;
2451
2452/// Writes or removes one ref file relative to `repo_fd`, atomically.
2453///
2454/// For `Some(checksum)`, the call:
2455///
2456/// 1. Opens `tmp/`, and creates it if it is missing.
2457/// 2. Creates the missing parent directories of the target.
2458/// 3. Writes the 65-byte `<hex>\n` content to a new temp file in `tmp/`.
2459/// 4. Runs `fdatasync` on the temp file if `fsync` is set.
2460/// 5. Renames the temp file over the target.
2461///
2462/// If `tmp/` is on a different file system, the rename fails with `EXDEV`,
2463/// and the call removes the temp file. `None` unlinks the ref and does not
2464/// use `tmp/`. An absent file is success.
2465///
2466/// Under `fsync`, the call runs `fsync` on the directory that holds the ref
2467/// after the rename or the unlink. So the name that the operation created or
2468/// removed is durable, and not only the content of the file. The call also
2469/// makes the name of each parent directory that it created durable, deepest
2470/// first. A write that fails still syncs the directories that it changed
2471/// before the failure.
2472fn write_ref_blocking(
2473    repo_fd: BorrowedFd<'_>,
2474    relpath: &str,
2475    checksum: Option<Checksum>,
2476    fsync: bool,
2477    repo_mode: RepoMode,
2478) -> Result<()> {
2479    let mut dirs = Vec::new();
2480    let written = put_ref_blocking(repo_fd, relpath, checksum, fsync, repo_mode, &mut dirs);
2481    written.and(sync_ref_dirs(repo_fd, dirs))
2482}
2483
2484/// Runs the body of [`write_ref_blocking`], and leaves the directory syncs to
2485/// the caller.
2486///
2487/// Under `fsync`, the call adds each directory that gained or lost a name to
2488/// `dirs`, for [`sync_ref_dirs`]. These are the directory that holds the ref,
2489/// and the directory that holds each parent that this write created. The
2490/// call adds a created parent when it creates it, so a write that fails after
2491/// that step still adds it.
2492pub(crate) fn put_ref_blocking(
2493    repo_fd: BorrowedFd<'_>,
2494    relpath: &str,
2495    checksum: Option<Checksum>,
2496    fsync: bool,
2497    repo_mode: RepoMode,
2498    dirs: &mut Vec<String>,
2499) -> Result<()> {
2500    match checksum {
2501        Some(checksum) => {
2502            let tmp_fd = open_tmp_dir(repo_fd, repo_mode)?;
2503            put_ref_file_blocking(
2504                repo_fd,
2505                tmp_fd.as_fd(),
2506                relpath,
2507                checksum,
2508                fsync,
2509                repo_mode,
2510                dirs,
2511            )
2512        }
2513        None => remove_ref_blocking(repo_fd, relpath, fsync, dirs),
2514    }
2515}
2516
2517/// Unlinks the ref file `relpath`. An absent file is success. Under `fsync`,
2518/// the call adds the directory that holds the ref to `dirs`.
2519fn remove_ref_blocking(
2520    repo_fd: BorrowedFd<'_>,
2521    relpath: &str,
2522    fsync: bool,
2523    dirs: &mut Vec<String>,
2524) -> Result<()> {
2525    match rustix::fs::unlinkat(repo_fd, relpath, AtFlags::empty()) {
2526        Ok(()) => {
2527            if fsync {
2528                dirs.push(ref_parent(relpath).to_owned());
2529            }
2530            Ok(())
2531        }
2532        Err(Errno::NOENT) => Ok(()),
2533        Err(e) => Err(e.into()),
2534    }
2535}
2536
2537/// Writes the ref file `relpath` through a temp file in the open `tmp/` at
2538/// `tmp_fd`, as [`put_ref_blocking`] writes a `Some` checksum.
2539fn put_ref_file_blocking(
2540    repo_fd: BorrowedFd<'_>,
2541    tmp_fd: BorrowedFd<'_>,
2542    relpath: &str,
2543    checksum: Checksum,
2544    fsync: bool,
2545    repo_mode: RepoMode,
2546    dirs: &mut Vec<String>,
2547) -> Result<()> {
2548    create_ref_parents(repo_fd, relpath, repo_mode, fsync, dirs)?;
2549    let content = format!("{}\n", checksum.to_hex());
2550    let (temp, fd) = TempEntry::create_file(tmp_fd, REF_TEMP_PREFIX, REF_FILE_MODE)?;
2551    let mut file = std::fs::File::from(fd);
2552    file.write_all(content.as_bytes())?;
2553    file.flush()?;
2554    rustix::fs::fchmod(file.as_fd(), Mode::from_raw_mode(REF_FILE_MODE))?;
2555    if fsync {
2556        rustix::fs::fdatasync(file.as_fd())?;
2557    }
2558    drop(file);
2559    temp.rename_into(repo_fd, relpath)?;
2560    if fsync {
2561        dirs.push(ref_parent(relpath).to_owned());
2562    }
2563    Ok(())
2564}
2565
2566/// Sorts `dirs` deepest first, then by name, and drops the repeats.
2567fn sort_dirs_deepest_first(dirs: &mut Vec<String>) {
2568    let depth = |dir: &str| {
2569        if dir == "." {
2570            0
2571        } else {
2572            dir.split('/').count()
2573        }
2574    };
2575    dirs.sort_by(|a, b| depth(b).cmp(&depth(a)).then_with(|| a.cmp(b)));
2576    dirs.dedup();
2577}
2578
2579/// Runs `fsync` once on each distinct directory of `dirs`, deepest first. The
2580/// names are relative to the repository root.
2581///
2582/// The call syncs a deeper directory before the directory above it. The
2583/// first sync records the name of the ref file. The next records the name of
2584/// the directory that holds it, and the next the name of the directory above
2585/// that. The object fanout uses the same order.
2586///
2587/// So a crash part way through leaves a prefix of each path recorded. It
2588/// never leaves a directory entry that names a directory with unrecorded
2589/// contents.
2590fn sync_ref_dirs(repo_fd: BorrowedFd<'_>, mut dirs: Vec<String>) -> Result<()> {
2591    sort_dirs_deepest_first(&mut dirs);
2592    for dir in &dirs {
2593        sync_dir(repo_fd, dir)?;
2594    }
2595    Ok(())
2596}
2597
2598/// Runs `fsync` once on each distinct directory of `dirs`, in the order of
2599/// [`sync_ref_dirs`], and returns the first error. A failed sync does not stop
2600/// the syncs after it.
2601pub(crate) fn sync_dirs_all(repo_fd: BorrowedFd<'_>, mut dirs: Vec<String>) -> Result<()> {
2602    sort_dirs_deepest_first(&mut dirs);
2603    let mut first = Ok(());
2604    for dir in &dirs {
2605        let synced = sync_dir(repo_fd, dir);
2606        #[cfg(test)]
2607        test_syncs::record(repo_fd);
2608        if first.is_ok() {
2609            first = synced;
2610        }
2611    }
2612    first
2613}
2614
2615/// The directory syncs that [`sync_dirs_all`] made, for the unit tests. Each
2616/// sync has one entry. The entry holds the `(device, inode)` of the
2617/// repository root, and a flag. The flag is `true` if a guard of this process
2618/// held the update lock of that repository when the sync ran.
2619#[cfg(test)]
2620pub(crate) mod test_syncs {
2621    use std::os::fd::BorrowedFd;
2622    use std::sync::Mutex;
2623
2624    type Record = ((u64, u64), bool);
2625
2626    static SYNCS: Mutex<Vec<Record>> = Mutex::new(Vec::new());
2627
2628    pub(crate) fn record(repo_fd: BorrowedFd<'_>) {
2629        let held = crate::lock::update_lock_held_in_process(repo_fd);
2630        if let Ok(stat) = rustix::fs::fstat(repo_fd) {
2631            SYNCS
2632                .lock()
2633                .unwrap()
2634                .push(((stat.st_dev, stat.st_ino), held));
2635        }
2636    }
2637
2638    fn syncs(root: &std::path::Path) -> Vec<bool> {
2639        use std::os::unix::fs::MetadataExt;
2640        let meta = std::fs::metadata(root).unwrap();
2641        let key = (meta.dev(), meta.ino());
2642        let syncs = SYNCS.lock().unwrap();
2643        syncs
2644            .iter()
2645            .filter(|(k, _)| *k == key)
2646            .map(|(_, held)| *held)
2647            .collect()
2648    }
2649
2650    /// The number of syncs made under the repository root `root`.
2651    pub(crate) fn count(root: &std::path::Path) -> usize {
2652        syncs(root).len()
2653    }
2654
2655    /// The number of syncs made under the repository root `root` while no
2656    /// guard of this process held its update lock.
2657    pub(crate) fn unlocked(root: &std::path::Path) -> usize {
2658        syncs(root).into_iter().filter(|held| !held).count()
2659    }
2660}
2661
2662/// Writes one alias symlink relative to `repo_fd`, atomically.
2663///
2664/// The call:
2665///
2666/// 1. Opens `tmp/`, and creates it if it is missing.
2667/// 2. Creates the missing parent directories of the target.
2668/// 3. Creates the link under a new temp name in `tmp/`.
2669/// 4. Renames the link over the target.
2670///
2671/// So the call replaces an existing ref file or an existing alias in one
2672/// step. A symlink has no content of its own to sync. So `fsync` reaches the
2673/// directory that holds the link, and the directory that holds each parent
2674/// that this write created.
2675///
2676/// A write that fails still syncs the directories that it changed before the
2677/// failure.
2678fn write_alias_blocking(
2679    repo_fd: BorrowedFd<'_>,
2680    relpath: &str,
2681    link: &str,
2682    fsync: bool,
2683    repo_mode: RepoMode,
2684) -> Result<()> {
2685    let mut dirs = Vec::new();
2686    let written = put_alias_blocking(repo_fd, relpath, link, fsync, repo_mode, &mut dirs);
2687    written.and(sync_ref_dirs(repo_fd, dirs))
2688}
2689
2690/// Runs the body of [`write_alias_blocking`], and leaves the directory syncs
2691/// to the caller. Under `fsync`, the call adds to `dirs` the directory that
2692/// holds the link, and the directory that holds each parent that this write
2693/// created. It adds each parent when it creates it.
2694pub(crate) fn put_alias_blocking(
2695    repo_fd: BorrowedFd<'_>,
2696    relpath: &str,
2697    link: &str,
2698    fsync: bool,
2699    repo_mode: RepoMode,
2700    dirs: &mut Vec<String>,
2701) -> Result<()> {
2702    let tmp_fd = open_tmp_dir(repo_fd, repo_mode)?;
2703    create_ref_parents(repo_fd, relpath, repo_mode, fsync, dirs)?;
2704    TempEntry::create_symlink(tmp_fd.as_fd(), REF_TEMP_PREFIX, link)?
2705        .rename_into(repo_fd, relpath)?;
2706    if fsync {
2707        dirs.push(ref_parent(relpath).to_owned());
2708    }
2709    Ok(())
2710}
2711
2712/// Removes each ref that still names the checksum that the caller recorded
2713/// for it, relative to `repo_fd`, in one blocking pass.
2714///
2715/// The call maps each key to its path with `relpath`. The caller passes the
2716/// path rule of the asynchronous writes, for example [`refspec_to_relpath`]
2717/// for a refspec or [`ref_relpath`] for a [`Ref`]. So
2718/// the read and the unlink address the same file as the rest of the library.
2719/// One pass can hold keys of more than one space under `refs/`.
2720///
2721/// Each read comes immediately before its own unlink. The call leaves a ref
2722/// that now names a different commit where it is. This covers a repository
2723/// whose `[core] locking` is false, and a caller that moved the ref after it
2724/// recorded the checksum.
2725///
2726/// A read that finds no file unlinks all the same. The name that the caller
2727/// recorded is gone or dangles. `unlinkat` removes a symlink and not the file
2728/// that it names, and an absent name is success.
2729///
2730/// Under `fsync`, after the last unlink, the call runs `fsync` once on each
2731/// directory from which an unlink removed a name. So each removed name is
2732/// durable. The call records a directory only if its own unlink reported
2733/// success. A recorded directory that is gone when the pass reaches it holds
2734/// no entry to make durable, so its absence is success as well.
2735///
2736/// A hash set holds the membership test. A vector holds the order of the
2737/// `fsync` calls, which is the order of the first unlink in each directory. The
2738/// membership test reads the borrowed path, so a parent that the set already
2739/// holds costs no allocation.
2740///
2741/// Returns the keys that it removed, in the order that it got them.
2742pub(crate) fn delete_matching_refs_blocking<K>(
2743    repo_fd: BorrowedFd<'_>,
2744    refs: Vec<(K, Checksum)>,
2745    relpath: impl Fn(&K) -> Result<String>,
2746    fsync: bool,
2747) -> Result<Vec<K>> {
2748    let mut removed = Vec::with_capacity(refs.len());
2749    let mut parents: Vec<String> = Vec::new();
2750    let mut held: HashSet<String> = HashSet::new();
2751    for (key, target) in refs {
2752        let relpath = relpath(&key)?;
2753        if let Some(bytes) = read_ref_file(repo_fd, &relpath)?
2754            && parse_ref_content(&bytes)? != target
2755        {
2756            continue;
2757        }
2758        match rustix::fs::unlinkat(repo_fd, relpath.as_str(), AtFlags::empty()) {
2759            Ok(()) => {
2760                if fsync {
2761                    let parent = ref_parent(&relpath);
2762                    if !held.contains(parent) {
2763                        held.insert(parent.to_owned());
2764                        parents.push(parent.to_owned());
2765                    }
2766                }
2767            }
2768            Err(Errno::NOENT) => {}
2769            Err(e) => return Err(Error::Io(e.into())),
2770        }
2771        removed.push(key);
2772    }
2773    for parent in &parents {
2774        sync_dir_present(repo_fd, parent)?;
2775    }
2776    Ok(removed)
2777}
2778
2779/// Returns the directory that holds the ref at `relpath`. A refspec and a
2780/// collection ref always map below `refs/`, so the path has a parent. For a
2781/// bare name, the result is the repository root.
2782fn ref_parent(relpath: &str) -> &str {
2783    relpath.rsplit_once('/').map_or(".", |(dir, _)| dir)
2784}
2785
2786/// Runs `fsync` on one directory, named relative to the repository root, if
2787/// the directory still exists. A directory that is gone holds no entry to make
2788/// durable, so its absence is success.
2789fn sync_dir_present(repo_fd: BorrowedFd<'_>, path: &str) -> Result<()> {
2790    match sync_dir(repo_fd, path) {
2791        Err(Error::Io(e)) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
2792        other => other,
2793    }
2794}
2795
2796/// Runs `fsync` on one directory, named relative to the repository root.
2797pub(crate) fn sync_dir(repo_fd: BorrowedFd<'_>, path: &str) -> Result<()> {
2798    let dir = rustix::fs::openat(
2799        repo_fd,
2800        path,
2801        OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
2802        Mode::empty(),
2803    )?;
2804    rustix::fs::fsync(dir.as_fd())?;
2805    Ok(())
2806}
2807
2808/// Creates the parent directories of a ref path, idempotently.
2809///
2810/// The call creates each component except the last, and leaves existing
2811/// directories in place. Under `fsync`, the call adds the directory that holds
2812/// each created directory to `dirs` when the `mkdirat` returns, before any
2813/// step that can fail. So a write that fails later still leaves the new name
2814/// to a sync.
2815///
2816/// A `mkdirat` adds a name to the directory that it is called in. So to make
2817/// a created `refs/heads/deep/nest` durable, a caller syncs `refs/heads/deep`,
2818/// which holds the `nest` entry: the [`ref_parent`] of the created path. A
2819/// directory that was already in place needs no sync, because its name is
2820/// already durable.
2821///
2822/// In a `bare-user-shared` repository, the call forces each directory that it
2823/// creates to [`perm::SHARED_DIR_MODE`]. A directory that already exists
2824/// keeps its mode and its group.
2825fn create_ref_parents(
2826    repo_fd: BorrowedFd<'_>,
2827    relpath: &str,
2828    repo_mode: RepoMode,
2829    fsync: bool,
2830    dirs: &mut Vec<String>,
2831) -> Result<()> {
2832    let mut acc = String::new();
2833    let mut components: Vec<&str> = relpath.split('/').collect();
2834    components.pop(); // the final component is the ref file itself
2835    for component in components {
2836        if !acc.is_empty() {
2837            acc.push('/');
2838        }
2839        acc.push_str(component);
2840        match rustix::fs::mkdirat(repo_fd, acc.as_str(), Mode::from_raw_mode(REF_DIR_MODE)) {
2841            Ok(()) => {
2842                if fsync {
2843                    dirs.push(ref_parent(&acc).to_owned());
2844                }
2845                perm::force_created_dir(repo_fd, acc.as_str(), repo_mode)?;
2846            }
2847            Err(Errno::EXIST) => {}
2848            Err(e) => return Err(e.into()),
2849        }
2850    }
2851    Ok(())
2852}
2853
2854#[cfg(test)]
2855mod tests {
2856    use super::*;
2857
2858    #[test]
2859    fn refspec_maps_local_and_remote() {
2860        assert_eq!(
2861            refspec_to_relpath("test/main").unwrap(),
2862            "refs/heads/test/main"
2863        );
2864        assert_eq!(
2865            refspec_to_relpath("origin:test/main").unwrap(),
2866            "refs/remotes/origin/test/main"
2867        );
2868    }
2869
2870    #[test]
2871    fn refspec_rejects_traversal() {
2872        // The error names the whole refspec, which a caller that reports a
2873        // refused name has in hand. It does not name the failed component.
2874        for bad in [
2875            "",
2876            "..",
2877            "a/../b",
2878            "/a",
2879            "a/",
2880            "a//b",
2881            "a/..",
2882            "origin:../escape",
2883            // A name outside the ref-name rule.
2884            "a b",
2885            "a*",
2886            "-a",
2887            "a/.b",
2888            "a^b",
2889            "a~b",
2890            "origin:a:b",
2891            "origin:a b",
2892            // A remote outside the ref-name rule.
2893            "o r:main",
2894            "o*:main",
2895            "-o:main",
2896            ".o:main",
2897            "o~:main",
2898            // A remote is one component, so a `/` in it names no remote.
2899            "a/b:x",
2900            ":x",
2901            "origin:",
2902        ] {
2903            let err = refspec_to_relpath(bad).unwrap_err();
2904            assert!(
2905                matches!(&err, Error::InvalidRefspec(name) if name == bad),
2906                "should reject {bad:?}, got {err}"
2907            );
2908        }
2909        assert!(validate_refspec("test/main").is_ok());
2910        assert!(validate_refspec("origin:test/main").is_ok());
2911        for good in [
2912            "a.",
2913            "a..b",
2914            "_a",
2915            "a_b",
2916            "1a",
2917            "A",
2918            "\u{e9}",
2919            "a/\u{e9}b",
2920            "\u{e9}:main",
2921        ] {
2922            assert!(validate_refspec(good).is_ok(), "should accept {good:?}");
2923        }
2924    }
2925
2926    fn patterns(texts: &[&str]) -> Vec<RefPattern> {
2927        texts
2928            .iter()
2929            .map(|text| RefPattern::parse(text).unwrap())
2930            .collect()
2931    }
2932
2933    /// A pattern below the literal parts of a `lit/**` pattern is dropped,
2934    /// and a duplicate stays one time. A pattern that is not below the
2935    /// literal parts, one with a wildcard before the `**`, and `a/**` against
2936    /// `a` stay.
2937    #[test]
2938    fn a_covered_pattern_is_dropped() {
2939        let kept = |texts: &[&str]| -> Vec<String> {
2940            let all = patterns(texts);
2941            uncovered_patterns(&all)
2942                .iter()
2943                .map(|p| p.as_str().to_owned())
2944                .collect()
2945        };
2946        assert_eq!(
2947            kept(&["a/b", "a/**", "a/*/c", "ab", "a"]),
2948            ["a/**", "ab", "a"]
2949        );
2950        assert_eq!(kept(&["a/b", "a/b", "a/**", "a/**"]), ["a/**"]);
2951        assert_eq!(kept(&["x/y", "x/y"]), ["x/y"]);
2952        assert_eq!(kept(&["a/b/**", "a/**", "a/b/c"]), ["a/**"]);
2953        assert_eq!(kept(&["a/*/**", "a/b/c"]), ["a/*/**", "a/b/c"]);
2954        assert_eq!(kept(&["a/**/c", "a/**", "a/**/c"]), ["a/**"]);
2955        assert_eq!(kept(&["a/**/c", "b/**/c"]), ["a/**/c", "b/**/c"]);
2956        assert_eq!(kept(&["**", "a", "b/*"]), ["**"]);
2957        assert_eq!(kept(&["*", "a/b"]), ["*", "a/b"]);
2958    }
2959
2960    /// A negative pattern covers a directory when it is `lead/**` and the
2961    /// directory path starts with the lead parts, where `*` stands for any
2962    /// part.
2963    #[test]
2964    fn a_negative_pattern_covers_a_directory() {
2965        let covers: Vec<Vec<&str>> = ["a/c/**", "*/x/**", "**/q", "a/**/**", "k/**"]
2966            .iter()
2967            .filter_map(|text| covering_lead(text))
2968            .collect();
2969        assert_eq!(covers, [vec!["a", "c"], vec!["*", "x"], vec!["k"]]);
2970        for dir in ["a/c", "a/c/d", "z/x", "k", "k/j/i"] {
2971            assert!(dir_is_covered(&covers, dir), "{dir}");
2972        }
2973        for dir in ["a", "a/b", "b/c", "z", "kk", "z/y"] {
2974            assert!(!dir_is_covered(&covers, dir), "{dir}");
2975        }
2976        assert!(dir_is_covered(&[Vec::new()], "any"));
2977    }
2978
2979    #[test]
2980    fn ref_relpath_names_the_ref_it_rejects() {
2981        for (r, label) in [
2982            (
2983                Ref::collection("org.example.Foo", "a/../b"),
2984                "@org.example.Foo:a/../b",
2985            ),
2986            (Ref::collection("a", "main"), "@a:main"),
2987            (Ref::local("a/../b"), "a/../b"),
2988            (Ref::local("origin:main"), "origin:main"),
2989            (Ref::remote("o/r", "main"), "o/r:main"),
2990            (
2991                Ref::collection("org.example.B", "-bad"),
2992                "@org.example.B:-bad",
2993            ),
2994        ] {
2995            let err = ref_relpath(None, &r).unwrap_err();
2996            assert!(
2997                matches!(&err, Error::InvalidRefspec(name) if name == label),
2998                "{err}"
2999            );
3000        }
3001        let longest = format!("org.{}", "a".repeat(251));
3002        assert_eq!(longest.len(), ostrya_core::MAX_COLLECTION_ID_LEN);
3003        assert!(ref_relpath(None, &Ref::collection(longest.as_str(), "main")).is_ok());
3004        let too_long = format!("org.{}", "a".repeat(252));
3005        let err = ref_relpath(None, &Ref::collection(too_long.as_str(), "main")).unwrap_err();
3006        assert!(
3007            matches!(&err, Error::InvalidRefspec(name) if *name == format!("@{too_long}:main")),
3008            "{err}"
3009        );
3010    }
3011
3012    #[test]
3013    fn a_refspec_reads_as_a_ref_with_no_check() {
3014        assert_eq!(refspec_ref("a/b"), Ref::local("a/b"));
3015        assert_eq!(refspec_ref("origin:a/b"), Ref::remote("origin", "a/b"));
3016        assert_eq!(refspec_ref("o:a:b"), Ref::remote("o", "a:b"));
3017        let at = refspec_ref("@org.example.A:x");
3018        assert_eq!(at, Ref::remote("@org.example.A", "x"));
3019        assert!(at.validate().is_err());
3020    }
3021
3022    #[test]
3023    fn splits_the_ancestry_suffix() {
3024        assert_eq!(split_ancestry("test/main"), ("test/main", 0));
3025        assert_eq!(split_ancestry("test/main^"), ("test/main", 1));
3026        assert_eq!(split_ancestry("test/main^^^"), ("test/main", 3));
3027        assert_eq!(split_ancestry("^"), ("", 1));
3028    }
3029
3030    #[test]
3031    fn builds_the_alias_link_body() {
3032        // A sibling alias names the target directly.
3033        assert_eq!(
3034            relative_link("refs/heads/alias", "refs/heads/test/main"),
3035            "test/main"
3036        );
3037        // A nested alias climbs out of its own directory first.
3038        assert_eq!(relative_link("refs/heads/p/q", "refs/heads/one"), "../one");
3039        // A target one level up from the directory of the alias.
3040        assert_eq!(relative_link("refs/heads/a/b", "refs/heads/a"), "../a");
3041        // Across the two ref roots.
3042        assert_eq!(
3043            relative_link("refs/heads/alias", "refs/remotes/origin/main"),
3044            "../remotes/origin/main"
3045        );
3046    }
3047
3048    /// Every case the addressability predicate is checked against, as
3049    /// `(name, top, path, expected)`.
3050    const ADDRESSABILITY_CASES: &[(&str, &str, &str, bool)] = &[
3051        // A local name addresses its own file where the mapping accepts it.
3052        ("main", "refs/heads", "main", true),
3053        ("test/main", "refs/heads", "test/main", true),
3054        // A `:` reads as the separator of a remote name, so the mapping gives
3055        // a path under `refs/remotes`.
3056        ("foo:bar", "refs/heads", "foo:bar", false),
3057        ("a/b:c", "refs/heads", "a/b:c", false),
3058        // A local name the mapping accepts still has to match the path it was
3059        // listed at.
3060        ("main", "refs/heads", "other", false),
3061        // A name the mapping refuses answers false as well.
3062        ("a/../b", "refs/heads", "a/../b", false),
3063        ("", "refs/heads", "", false),
3064        // A remote name addresses its own file where the first `/` of the path
3065        // is the `:` of the name.
3066        ("origin:main", "refs/remotes", "origin/main", true),
3067        ("a:pool/x", "refs/remotes", "a:pool/x", false),
3068        ("a:pool/x", "refs/remotes", "a/pool/x", true),
3069        // A `:` in the name part is outside the ref-name rule, so neither of
3070        // the two files that list as this name is addressable.
3071        ("origin:foo:bar", "refs/remotes", "origin/foo:bar", false),
3072        ("a:b:main", "refs/remotes", "a:b/main", false),
3073        ("a:b:main", "refs/remotes", "a/b:main", false),
3074        // A name outside the rule is not addressable, wherever its file is.
3075        ("a b", "refs/heads", "a b", false),
3076        ("-a", "refs/heads", "-a", false),
3077        ("a/.b", "refs/heads", "a/.b", false),
3078        ("a*", "refs/heads", "a*", false),
3079        ("origin:a b", "refs/remotes", "origin/a b", false),
3080        ("o r:main", "refs/remotes", "o r/main", false),
3081        ("-o:main", "refs/remotes", "-o/main", false),
3082        (".o:main", "refs/remotes", ".o/main", false),
3083        ("o~:main", "refs/remotes", "o~/main", false),
3084        ("\u{e9}:main", "refs/remotes", "\u{e9}/main", true),
3085        // A file directly under `refs/remotes` names no remote, so its name
3086        // maps under `refs/heads`.
3087        ("stray", "refs/remotes", "stray", false),
3088        // An empty remote component is refused.
3089        (":x:main", "refs/remotes", ":x/main", false),
3090        // So is a traversal, in the remote component and in the name below it.
3091        ("..:main", "refs/remotes", "../main", false),
3092        ("origin:a/../b", "refs/remotes", "origin/a/../b", false),
3093        // No refspec maps below `refs/mirrors`.
3094        (
3095            "org.example.Coll/mm",
3096            "refs/mirrors",
3097            "org.example.Coll/mm",
3098            false,
3099        ),
3100        // A remote refspec at the path that it takes under another top gives
3101        // false, because the mapping names one top alone.
3102        ("origin:main", "refs/mirrors", "origin/main", false),
3103    ];
3104
3105    #[test]
3106    fn a_listed_name_addresses_its_own_file_only_where_the_mapping_returns_it() {
3107        for (name, top, path, expected) in ADDRESSABILITY_CASES {
3108            assert_eq!(
3109                listed_name_addresses_it(name, top, path),
3110                *expected,
3111                "{name:?} under {top:?} at {path:?}"
3112            );
3113        }
3114    }
3115
3116    #[test]
3117    fn the_addressability_predicate_agrees_with_the_refspec_mapping() {
3118        // The predicate reads the name in place, so this holds it to the
3119        // mapping it mirrors.
3120        for (name, top, path, _) in ADDRESSABILITY_CASES {
3121            assert_eq!(
3122                listed_name_addresses_it(name, top, path),
3123                refspec_to_relpath(name).ok() == Some(format!("{top}/{path}")),
3124                "{name:?} under {top:?} at {path:?}"
3125            );
3126        }
3127    }
3128
3129    #[test]
3130    fn parses_ref_content_with_newline() {
3131        let hex = "b3c8e8525e8a5c3409bf6e6db5f5d656da77ae76d08cbc4f8b75b71879757a89";
3132        let checksum = parse_ref_content(format!("{hex}\n").as_bytes()).unwrap();
3133        assert_eq!(checksum.to_hex(), hex);
3134        assert!(parse_ref_content(b"not-a-checksum\n").is_err());
3135    }
3136
3137    /// A scratch directory with `refs/heads` in it, removed when the value
3138    /// drops.
3139    struct Root {
3140        dir: std::path::PathBuf,
3141        fd: std::os::fd::OwnedFd,
3142    }
3143
3144    impl Root {
3145        fn new(label: &str) -> Root {
3146            let dir = std::env::temp_dir().join(format!(
3147                "ostrya-refs-{label}-{}-{}",
3148                std::process::id(),
3149                crate::write::unique()
3150            ));
3151            std::fs::create_dir_all(dir.join("refs/heads")).unwrap();
3152            let fd = std::fs::File::open(&dir).unwrap().into();
3153            Root { dir, fd }
3154        }
3155
3156        fn fd(&self) -> BorrowedFd<'_> {
3157            self.fd.as_fd()
3158        }
3159    }
3160
3161    impl Drop for Root {
3162        fn drop(&mut self) {
3163            let _ = std::fs::remove_dir_all(&self.dir);
3164        }
3165    }
3166
3167    /// A ref-tree walk opens a subdirectory with no symlink followed: a
3168    /// symlink to a directory, a regular file, and an absent entry give no
3169    /// directory.
3170    #[test]
3171    fn a_ref_subdirectory_opens_with_no_symlink_followed() {
3172        let root = Root::new("subdir-nofollow");
3173        let heads = root.dir.join("refs/heads");
3174        std::fs::create_dir(heads.join("real")).unwrap();
3175        std::os::unix::fs::symlink("real", heads.join("link")).unwrap();
3176        std::fs::write(heads.join("file"), b"").unwrap();
3177        let dir = std::fs::File::open(&heads).unwrap();
3178        assert!(open_ref_subdir(dir.as_fd(), "real").unwrap().is_some());
3179        for name in ["link", "file", "absent"] {
3180            let sub = open_ref_subdir(dir.as_fd(), name).unwrap();
3181            assert!(sub.is_none(), "{name}");
3182        }
3183    }
3184
3185    /// The listing opens an entry that the walk found as a ref file with no
3186    /// symlink followed. An entry that is an alias at the open takes the
3187    /// alias rule, so an alias to a ref that the client does not read gives
3188    /// no ref. The same entry gives the ref of its target to a client that
3189    /// reads the target.
3190    #[test]
3191    fn a_listed_ref_file_that_is_an_alias_at_the_open_takes_the_alias_rule() {
3192        let root = Root::new("listed-alias");
3193        ostrya_rt::block_on(async {
3194            let repo = Repo::create(
3195                &root.dir.join("repo"),
3196                crate::CreateOptions::new(RepoMode::Archive),
3197            )
3198            .await
3199            .unwrap();
3200            let commit = Checksum::from_bytes([7; 32]);
3201            let heads = root.dir.join("repo/refs/heads");
3202            std::fs::write(heads.join("secret"), format!("{}\n", commit.to_hex())).unwrap();
3203            std::fs::create_dir(heads.join("pub")).unwrap();
3204            std::os::unix::fs::symlink("../secret", heads.join("pub/a")).unwrap();
3205            let dir = std::fs::File::open(heads.join("pub")).unwrap();
3206            let entry = RefEntry {
3207                dir: dir.as_fd(),
3208                name: "a",
3209                path: "pub/a",
3210                file_type: FileType::RegularFile,
3211            };
3212            let reader = |allow: &str| {
3213                let text = format!(
3214                    "[core]\nrepo_version=1\nmode=archive-z2\n\
3215                     [ex-ostrya client \"c\"]\nauth=anonymous\nallow={allow}\n"
3216                );
3217                let config = crate::RepoConfig::parse(&text).unwrap();
3218                let access = crate::access::ClientAccess::from_config(&config, &root.dir).unwrap();
3219                ReadAccess::new(
3220                    std::sync::Arc::new(access),
3221                    crate::access::AuthItem::Anonymous,
3222                    None,
3223                )
3224            };
3225            let hidden = read_listed_ref(&repo, HEADS_DIR, &entry, &reader("r:pub/**")).unwrap();
3226            assert_eq!(hidden, None);
3227            let (read, target) = read_listed_ref(&repo, HEADS_DIR, &entry, &reader("r:**"))
3228                .unwrap()
3229                .unwrap();
3230            assert_eq!(parse_ref_content(&read).unwrap(), commit);
3231            assert_eq!(target.as_deref(), Some("refs/heads/secret"));
3232        });
3233    }
3234
3235    /// The listing gives no ref for an entry that is a FIFO at the open, and
3236    /// the open does not wait for a writer. This holds when the walk read the
3237    /// entry as a FIFO, and when the walk read a regular file that a FIFO
3238    /// replaced.
3239    #[test]
3240    fn a_listed_ref_entry_that_is_a_fifo_at_the_open_gives_no_ref() {
3241        let root = Root::new("listed-fifo");
3242        let repo = ostrya_rt::block_on(Repo::create(
3243            &root.dir.join("repo"),
3244            crate::CreateOptions::new(RepoMode::Archive),
3245        ))
3246        .unwrap();
3247        let heads = root.dir.join("repo/refs/heads");
3248        let fifo = heads.join("fifo");
3249        rustix::fs::mknodat(
3250            rustix::fs::CWD,
3251            &fifo,
3252            FileType::Fifo,
3253            Mode::from_raw_mode(0o644),
3254            0,
3255        )
3256        .unwrap();
3257        for file_type in [FileType::Fifo, FileType::RegularFile] {
3258            let (tx, rx) = std::sync::mpsc::channel();
3259            let (repo, heads) = (repo.clone(), heads.clone());
3260            std::thread::spawn(move || {
3261                let dir = std::fs::File::open(&heads).unwrap();
3262                let entry = RefEntry {
3263                    dir: dir.as_fd(),
3264                    name: "fifo",
3265                    path: "fifo",
3266                    file_type,
3267                };
3268                let reads = repo.implicit_reads();
3269                let _ =
3270                    tx.send(read_listed_ref(&repo, HEADS_DIR, &entry, reads).map(|r| r.is_none()));
3271            });
3272            let timeout = std::time::Duration::from_secs(10);
3273            let Ok(result) = rx.recv_timeout(timeout) else {
3274                // A writer releases the blocked open, so the thread ends.
3275                let _ = rustix::fs::open(
3276                    &fifo,
3277                    OFlags::WRONLY | OFlags::NONBLOCK | OFlags::CLOEXEC,
3278                    Mode::empty(),
3279                );
3280                let _ = rx.recv_timeout(timeout);
3281                panic!("{file_type:?}: the open waits on the FIFO");
3282            };
3283            assert!(result.unwrap(), "{file_type:?}");
3284        }
3285    }
3286
3287    /// The collection id of the repositories of the own-collection tests.
3288    const OWN: &str = "org.example.Os";
3289    /// The ref name of the own-collection tests.
3290    const NAME: &str = "os/stable";
3291
3292    /// Creates an archive repository at `path` with the collection id
3293    /// [`OWN`].
3294    async fn own_repo(path: &std::path::Path) -> Repo {
3295        Repo::create(
3296            path,
3297            crate::CreateOptions::new(RepoMode::Archive).collection_id(OWN),
3298        )
3299        .await
3300        .unwrap()
3301    }
3302
3303    /// The implicit read access of a handle takes the collection id of the
3304    /// repository as the local namespace. It reads the local path of a ref
3305    /// of that id, and no mirror path of that id.
3306    #[test]
3307    fn the_implicit_read_access_takes_the_collection_id_of_the_repository() {
3308        let root = Root::new("implicit-reads");
3309        ostrya_rt::block_on(async {
3310            let repo = own_repo(&root.dir.join("repo")).await;
3311            let reads = repo.implicit_reads();
3312            assert_eq!(reads.access().namespace(Some(OWN)), Namespace::Local);
3313            assert!(reads.can_read_path(&format!("refs/heads/{NAME}")));
3314            assert!(!reads.can_read_path(&format!("refs/mirrors/{OWN}/{NAME}")));
3315        });
3316    }
3317
3318    /// A collection ref of the collection id of the repository maps to the
3319    /// local path, and a ref of each other id maps to the mirror path. A pair
3320    /// that fails the rule fails the call with its label.
3321    #[test]
3322    fn a_collection_ref_of_the_own_id_maps_to_the_local_path() {
3323        let path = |own, id, name| ref_relpath(own, &Ref::collection(id, name));
3324        assert_eq!(
3325            path(Some(OWN), OWN, NAME).unwrap(),
3326            format!("refs/heads/{NAME}")
3327        );
3328        assert_eq!(
3329            path(Some(OWN), "org.example.Other", NAME).unwrap(),
3330            format!("refs/mirrors/org.example.Other/{NAME}")
3331        );
3332        assert_eq!(
3333            path(None, OWN, NAME).unwrap(),
3334            format!("refs/mirrors/{OWN}/{NAME}")
3335        );
3336        assert_eq!(
3337            ref_relpath(Some(OWN), &Ref::local(NAME)).unwrap(),
3338            format!("refs/heads/{NAME}")
3339        );
3340        assert_eq!(
3341            ref_relpath(Some(OWN), &Ref::remote("origin", NAME)).unwrap(),
3342            format!("refs/remotes/origin/{NAME}")
3343        );
3344        for name in ["../x", "origin:x"] {
3345            let err = path(Some(OWN), OWN, name).unwrap_err();
3346            assert!(
3347                matches!(&err, Error::InvalidRefspec(label) if *label == format!("@{OWN}:{name}")),
3348                "{err:?}"
3349            );
3350        }
3351    }
3352
3353    #[test]
3354    fn sync_dirs_all_runs_each_sync_past_a_failure() {
3355        let root = Root::new("sync-all");
3356        // The deepest entry sorts first, and it is a file, so its sync fails.
3357        std::fs::create_dir_all(root.dir.join("refs/heads/a")).unwrap();
3358        std::fs::write(root.dir.join("refs/heads/a/file"), b"").unwrap();
3359        let dirs = vec![
3360            ".".to_owned(),
3361            "refs/heads".to_owned(),
3362            "refs/heads/a/file".to_owned(),
3363            "refs/heads/a".to_owned(),
3364        ];
3365        let before = test_syncs::count(&root.dir);
3366        let err = sync_dirs_all(root.fd(), dirs).unwrap_err();
3367        assert!(
3368            matches!(&err, Error::Io(e) if e.raw_os_error() == Some(Errno::NOTDIR.raw_os_error())),
3369            "{err:?}"
3370        );
3371        assert_eq!(test_syncs::count(&root.dir), before + 4);
3372    }
3373
3374    /// A write that fails after it created parent directories still records
3375    /// the directories that hold them, and leaves no temp entry in `tmp/`.
3376    #[test]
3377    fn a_failed_write_records_the_parents_it_created() {
3378        let root = Root::new("created");
3379        // A ref name of 256 bytes is longer than a file name can be. The temp
3380        // file in `tmp/` is created, and the rename over the ref name fails.
3381        let long = "r".repeat(256);
3382        let mut dirs = Vec::new();
3383        let relpath = format!("refs/heads/new/deep/{long}");
3384        let checksum = Some(Checksum::from_bytes([7; 32]));
3385        put_ref_blocking(
3386            root.fd(),
3387            &relpath,
3388            checksum,
3389            true,
3390            RepoMode::BareUser,
3391            &mut dirs,
3392        )
3393        .unwrap_err();
3394        dirs.sort();
3395        assert_eq!(dirs, ["refs/heads", "refs/heads/new"]);
3396        let tmp = root.dir.join("tmp");
3397        assert!(tmp.is_dir());
3398        assert_eq!(std::fs::read_dir(&tmp).unwrap().count(), 0);
3399
3400        // A link body longer than a path can be fails the `symlinkat`.
3401        let mut dirs = Vec::new();
3402        let link = "x".repeat(5000);
3403        let relpath = "refs/heads/other/deep/alias";
3404        put_alias_blocking(
3405            root.fd(),
3406            relpath,
3407            &link,
3408            true,
3409            RepoMode::BareUser,
3410            &mut dirs,
3411        )
3412        .unwrap_err();
3413        dirs.sort();
3414        assert_eq!(dirs, ["refs/heads", "refs/heads/other"]);
3415        assert_eq!(std::fs::read_dir(&tmp).unwrap().count(), 0);
3416    }
3417}