OXYGENHUB

Coverage / crates/oxy-core/src/repo/prompt.rs 91.5%

744 of 813 lines run, 137 of 194 functions · run #251 on main · run missed

1
//! Fast, side-effect-free status for shell prompts.
2
//!
3
//! Every snapshot and checkout writes a manifest of the working copy as it
4
//! was last seen: `size`, `mtime`, and BLAKE3 of each file. `quick_status`
5
//! walks the working copy and compares against that manifest, reading a
6
//! file's content only when its size or mtime changed, and records no
7
//! operation. Ahead/behind counts come from walking the store between the
8
//! local bookmark and its `origin` tracking state.
9
10
use super::*;
11
use std::time::UNIX_EPOCH;
12
13
#[derive(Debug, Clone, Default, PartialEq, Eq)]
14
pub struct PromptInfo {
15
    pub bookmark: String,
16
    /// Working-copy ChangeId prefix.
17
    pub change_id: String,
18
    pub heads: usize,
19
    pub dirty: bool,
20
    pub conflicted: bool,
21
    /// Changes local `main` has that `origin/main` lacks, when tracking exists.
22
    pub ahead: Option<usize>,
23
    pub behind: Option<usize>,
24
}
25
26
impl PromptInfo {
27
    /// The glyph for the working copy's state: `‼` conflicted, `✎` dirty,
28
    /// `✔` clean.
293×
    pub fn state_glyph(&self) -> &'static str {
303×
        if self.conflicted {
311×
            "‼"
322×
        } else if self.dirty {
331×
            "✎"
34
        } else {
351×
            "✔"
36
        }
373×
    }
38
39
    /// The ANSI colour (SGR parameter) for the state: red, yellow, or cyan.
403×
    pub fn state_color(&self) -> u8 {
413×
        if self.conflicted {
421×
            31
432×
        } else if self.dirty {
441×
            33
45
        } else {
461×
            36
47
        }
483×
    }
49
50
    /// `format` wrapped in the state colour. `guard` is `("\\[", "\\]")` for
51
    /// bash prompts, `("%{", "%}")` for zsh, or empty for raw output.
522×
    pub fn format_colored(&self, fmt: &str, guard: (&str, &str)) -> String {
532×
        format!(
54
            "{}\x1b[{}m{}{}{}\x1b[0m{}",
55
            guard.0,
562×
            self.state_color(),
57
            guard.1,
582×
            self.format(fmt),
59
            guard.0,
60
            guard.1
61
        )
622×
    }
63
64
    /// Expand `%b` bookmark, `%c` change id, `%h` heads, `%d` dirty marker
65
    /// (`*`), `%x` conflict marker (`!`), `%a`/`%B` ahead/behind counts
66
    /// (empty when unknown), `%A`/`%D` `+n`/`-n` when non-zero, `%s` the
67
    /// state glyph, `%U`/`%O` `↑n`/`↓n` when non-zero, `%i` the repository
68
    /// icon, `%%` percent.
6911×
    pub fn format(&self, fmt: &str) -> String {
7011×
        let mut out = String::new();
7111×
        let mut chars = fmt.chars();
7281×
        while let Some(c) = chars.next() {
7370×
            if c != '%' {
7424×
                out.push(c);
7524×
                continue;
7646×
            }
7746×
            match chars.next() {
787×
                Some('b') => out.push_str(&self.bookmark),
795×
                Some('c') => out.push_str(&self.change_id),
802×
                Some('h') => out.push_str(&self.heads.to_string()),
81
                Some('d') => {
824×
                    if self.dirty {
832×
                        out.push('*');
842×
                    }
85
                }
86
                Some('x') => {
874×
                    if self.conflicted {
881×
                        out.push('!');
893×
                    }
90
                }
912×
                Some('a') => out.push_str(&self.ahead.map(|n| n.to_string()).unwrap_or_default()),
922×
                Some('B') => out.push_str(&self.behind.map(|n| n.to_string()).unwrap_or_default()),
93
                Some('A') => {
944×
                    if let Some(n) = self.ahead.filter(|n| *n > 0) {
952×
                        out.push_str(&format!("+{n}"));
962×
                    }
97
                }
98
                Some('D') => {
994×
                    if let Some(n) = self.behind.filter(|n| *n > 0) {
1002×
                        out.push_str(&format!("-{n}"));
1012×
                    }
102
                }
1033×
                Some('s') => out.push_str(self.state_glyph()),
104
                Some('U') => {
1052×
                    if let Some(n) = self.ahead.filter(|n| *n > 0) {
1061×
                        out.push_str(&format!("↑{n}"));
1071×
                    }
108
                }
109
                Some('O') => {
1102×
                    if let Some(n) = self.behind.filter(|n| *n > 0) {
1111×
                        out.push_str(&format!("↓{n}"));
1121×
                    }
113
                }
1142×
                Some('i') => out.push_str(ICON),
1152×
                Some('%') => out.push('%'),
1161×
                Some(other) => {
1171×
                    out.push('%');
1181×
                    out.push(other);
1191×
                }
1200×
                None => out.push('%'),
121
            }
122
        }
12311×
        out
12411×
    }
125
}
126
127
/// Path → (size, mtime in nanoseconds, BLAKE3 hex) as last seen.
128
/// One manifest entry: the file's stat, its content hash, and the stored
129
/// blob for an opaque file.
130
#[derive(Clone, Debug)]
131
pub(crate) struct ManifestEntry {
132
    pub size: u64,
133
    pub mtime_ns: u128,
134
    pub hash: [u8; 32],
135
    pub blob: Option<ObjectRef>,
136
    /// The graph key (`State::graph_key`) of the base file this text file
137
    /// was found equal to, rendered, byte for byte.
138
    pub graph: Option<[u8; 32]>,
139
    /// Whether the file was executable: a mode change alters neither size
140
    /// nor time.
141
    pub exec: bool,
142
}
143
144
#[derive(Clone, Debug, Default)]
145
pub(crate) struct Manifest {
146
    /// When the manifest was written, for the racy-stat guard.
147
    pub written_ns: u128,
148
    pub entries: BTreeMap<String, ManifestEntry>,
149
    /// Every directory the walk listed, with its time then; empty when the
150
    /// manifest was not written from a walk (a checkout), and then the
151
    /// check lists the tree.
152
    pub dirs: Vec<(String, u128)>,
153
    /// Directories holding a repository of their own, as the walk found.
154
    pub nested: Vec<String>,
155
}
156
157
/// A parsed manifest and the identity (size, time, inode) of the file it
158
/// came from: reused while the file is the same one.
159
pub(crate) type CachedManifest = ((u64, u128, u64), (bool, bool, std::sync::Arc<Manifest>));
160
161
/// Now, in nanoseconds since the epoch.
1622067×
pub(crate) fn now_ns() -> u128 {
1632067×
    std::time::SystemTime::now()
1642067×
        .duration_since(UNIX_EPOCH)
1652067×
        .map(|d| d.as_nanos())
1662067×
        .unwrap_or(0)
1672067×
}
168
16928542×
pub(crate) fn mtime_ns(m: &fs::Metadata) -> u128 {
17028542×
    m.modified()
17128542×
        .ok()
17228542×
        .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
17328542×
        .map(|d| d.as_nanos())
17428542×
        .unwrap_or(0)
17528542×
}
176
177
pub const DEFAULT_PROMPT_FORMAT: &str = "%b %c%d%x%A%D";
178
/// The repository icon for `%i` (an atom, for oxygen).
179
pub const ICON: &str = "⚛";
180
/// A format with glyphs: icon, bookmark, change id, state, ahead/behind.
181
pub const GLYPH_PROMPT_FORMAT: &str = "%i %b %c %s%U%O";
182
183
/// The manifest file (oxygen#41): a flat binary layout read in one pass.
184
/// A magic number; the conflicted and uncommitted flags; when it was
185
/// written, at a fixed offset so an otherwise equal manifest can be
186
/// recognised; BLAKE3 of everything else; then each entry in path order:
187
/// path, size, mtime in nanoseconds, BLAKE3 of the content, the stored
188
/// blob of an opaque file, the graph key it was found equal to, and
189
/// whether it is executable. Format 3 puts before the entries every
190
/// directory the walk listed with its time, and the nested repositories. A file that does not check, or in any other
191
/// layout (an older manifest), reads as no manifest, and the next snapshot
192
/// writes it again: it is a cache, written without waiting for the disk.
193
const MANIFEST_MAGIC: &[u8; 8] = b"oxyman3\0";
194
/// Where the written time sits: after the magic and the two flags.
195
const MANIFEST_WRITTEN: std::ops::Range<usize> = 10..26;
196
/// Where the checksum sits, after the written time.
197
const MANIFEST_SUM: std::ops::Range<usize> = 26..58;
198
1993821×
fn manifest_sum(buf: &[u8]) -> [u8; 32] {
2003821×
    let mut h = blake3::Hasher::new();
2013821×
    h.update(&buf[..MANIFEST_SUM.start]);
2023821×
    h.update_rayon(&buf[MANIFEST_SUM.end..]);
2033821×
    *h.finalize().as_bytes()
2043821×
}
205
2061980×
fn encode_manifest(
2071980×
    conflicted: bool,
2081980×
    uncommitted: bool,
2091980×
    written_ns: u128,
2101980×
    dirs: &[(String, u128)],
2111980×
    nested: &[String],
2121980×
    entries: &mut dyn Iterator<Item = (&str, ManifestEntry)>,
2131980×
) -> Vec<u8> {
2141980×
    let mut w = crate::flat::Writer::default();
2151980×
    w.fixed(MANIFEST_MAGIC);
2161980×
    w.u8(conflicted as u8);
2171980×
    w.u8(uncommitted as u8);
2181980×
    w.fixed(&written_ns.to_le_bytes());
2191980×
    w.fixed(&[0; 32]);
2201980×
    w.count(dirs.len());
2212943×
    for (d, t) in dirs {
2222943×
        w.bytes(d.as_bytes());
2232943×
        w.fixed(&t.to_le_bytes());
2242943×
    }
2251980×
    w.count(nested.len());
2261980×
    for n in nested {
22730×
        w.bytes(n.as_bytes());
22830×
    }
22930598×
    for (path, e) in entries {
23030598×
        w.bytes(path.as_bytes());
23130598×
        w.u64(e.size);
23230598×
        w.fixed(&e.mtime_ns.to_le_bytes());
23330598×
        w.fixed(&e.hash);
23430598×
        w.opt_object(&e.blob);
23530598×
        match e.graph {
2361299×
            None => w.u8(0),
23729299×
            Some(k) => {
23829299×
                w.u8(1);
23929299×
                w.fixed(&k);
24029299×
            }
241
        }
24230598×
        w.u8(e.exec as u8);
243
    }
2441980×
    let sum = manifest_sum(&w.0);
2451980×
    w.0[MANIFEST_SUM].copy_from_slice(&sum);
2461980×
    w.0
2471980×
}
248
2491841×
fn decode_manifest(buf: &[u8]) -> Option<(bool, bool, Manifest)> {
2501841×
    let mut r = crate::flat::Reader::new(buf);
2511841×
    if &r.fixed::<8>().ok()? != MANIFEST_MAGIC {
2520×
        return None;
2531841×
    }
2541841×
    let conflicted = r.u8().ok()? == 1;
2551841×
    let uncommitted = r.u8().ok()? == 1;
2561841×
    let written_ns = u128::from_le_bytes(r.fixed().ok()?);
2571841×
    if r.fixed::<32>().ok()? != manifest_sum(buf) {
2583×
        return None;
2591838×
    }
2601838×
    let mut dirs = Vec::new();
2611838×
    for _ in 0..r.count().ok()? {
2622766×
        let d = std::str::from_utf8(r.bytes().ok()?).ok()?.to_string();
2632766×
        dirs.push((d, u128::from_le_bytes(r.fixed().ok()?)));
264
    }
2651838×
    let mut nested = Vec::new();
2661838×
    for _ in 0..r.count().ok()? {
26724×
        nested.push(std::str::from_utf8(r.bytes().ok()?).ok()?.to_string());
268
    }
2691838×
    let mut entries = Vec::new();
27027482×
    while !r.at_end() {
27125644×
        let path = std::str::from_utf8(r.bytes().ok()?).ok()?.to_string();
27225644×
        let e = ManifestEntry {
27325644×
            size: r.u64().ok()?,
27425644×
            mtime_ns: u128::from_le_bytes(r.fixed().ok()?),
27525644×
            hash: r.fixed().ok()?,
27625644×
            blob: r.opt_object().ok()?,
27725644×
            graph: match r.u8().ok()? {
2781395×
                0 => None,
27924249×
                _ => Some(r.fixed().ok()?),
280
            },
28125644×
            exec: r.u8().ok()? == 1,
282
        };
28325644×
        entries.push((path, e));
284
    }
285
    // Written in path order, so this builds the map without searching.
2861838×
    let entries = entries.into_iter().collect();
2871838×
    Some((
2881838×
        conflicted,
2891838×
        uncommitted,
2901838×
        Manifest {
2911838×
            written_ns,
2921838×
            entries,
2931838×
            dirs,
2941838×
            nested,
2951838×
        },
2961838×
    ))
2971841×
}
298
299
/// A tracked path as it is now: a file's stat, or a symlink's target.
300
enum Tracked {
301
    File(super::walk::Stat),
302
    Link(Vec<u8>),
303
}
304
305
/// The stat of every path in `rels` (relative to `root`; `None` for one
306
/// gone or neither a file nor a symlink), in the same order. Paths are
307
/// grouped by directory and each directory is opened once: a stat relative
308
/// to it resolves one name, where a stat by full path walks every
309
/// component from the root again (most of a clean status's time, in the
310
/// kernel's path lookup, on the Linux tree).
3116×
fn stat_tracked(root: &Path, rels: &[&String]) -> Vec<Option<Tracked>> {
312
    use rayon::prelude::*;
3136×
    let mut by_dir: HashMap<&str, Vec<(usize, &str)>> = HashMap::new();
3144208×
    for (i, rel) in rels.iter().enumerate() {
3154208×
        let (dir, name) = rel.rsplit_once('/').unwrap_or(("", rel.as_str()));
3164208×
        by_dir.entry(dir).or_default().push((i, name));
3174208×
    }
3186×
    let groups: Vec<(&str, Vec<(usize, &str)>)> = by_dir.into_iter().collect();
3196×
    let found: Vec<(usize, Option<Tracked>)> = groups
3206×
        .par_iter()
32110×
        .flat_map_iter(|(dir, names)| {
32210×
            let handle = fs::File::open(root.join(dir)).ok();
32310×
            names
32410×
                .iter()
3254208×
                .map(|(i, name)| {
3264208×
                    let rel = rels[*i];
3274208×
                    let now = match &handle {
3284208×
                        Some(d) => stat_in(d, name, || root.join(rel)),
3290×
                        None => None,
330
                    };
3314208×
                    (*i, now)
3324208×
                })
33310×
                .collect::<Vec<_>>()
33410×
        })
3356×
        .collect();
3366×
    let mut out: Vec<Option<Tracked>> = (0..rels.len()).map(|_| None).collect();
3374208×
    for (i, now) in found {
3384208×
        out[i] = now;
3394208×
    }
3406×
    out
3416×
}
342
343
/// One entry of the open directory `dir`; `path` builds its full path,
344
/// needed only for a symlink's target.
345
#[cfg(unix)]
3464208×
fn stat_in(dir: &fs::File, name: &str, path: impl Fn() -> PathBuf) -> Option<Tracked> {
347
    use std::os::fd::AsRawFd;
3484208×
    let c = std::ffi::CString::new(name).ok()?;
3494208×
    let mut st: libc::stat = unsafe { std::mem::zeroed() };
350
    // SAFETY: a valid directory descriptor, a NUL-terminated name, and a
351
    // stat buffer of the right type that outlives the call.
3524208×
    let r = unsafe {
3534208×
        libc::fstatat(
3544208×
            dir.as_raw_fd(),
3554208×
            c.as_ptr(),
3564208×
            &mut st,
357
            libc::AT_SYMLINK_NOFOLLOW,
358
        )
359
    };
3604208×
    if r != 0 {
3610×
        return None;
3624208×
    }
3634208×
    match st.st_mode & libc::S_IFMT {
364
        libc::S_IFREG => Some(Tracked::File(super::walk::Stat {
3654208×
            size: st.st_size as u64,
366
            // As `mtime_ns` reads it: nanoseconds since the epoch, 0 before it.
3674208×
            mtime_ns: if st.st_mtime < 0 {
3680×
                0
369
            } else {
3704208×
                st.st_mtime as u128 * 1_000_000_000 + st.st_mtime_nsec as u128
371
            },
3724208×
            exec: st.st_mode & 0o111 != 0,
373
        })),
374
        libc::S_IFLNK => {
3750×
            let t = fs::read_link(path()).ok()?;
3760×
            Some(Tracked::Link(t.to_string_lossy().as_bytes().to_vec()))
377
        }
3780×
        _ => None,
379
    }
3804208×
}
381
382
#[cfg(not(unix))]
383
fn stat_in(_dir: &fs::File, _name: &str, path: impl Fn() -> PathBuf) -> Option<Tracked> {
384
    let p = path();
385
    let m = fs::symlink_metadata(&p).ok()?;
386
    if m.file_type().is_symlink() {
387
        let t = fs::read_link(&p).ok()?;
388
        Some(Tracked::Link(t.to_string_lossy().as_bytes().to_vec()))
389
    } else if m.is_file() {
390
        Some(Tracked::File(super::walk::Stat::of(&m)))
391
    } else {
392
        None
393
    }
394
}
395
396
/// The status cache: a magic number, the working-copy change, the
397
/// manifest checksum, then each status line (a status byte and a path).
398
const STATUS_MAGIC: &[u8; 8] = b"oxystat1";
399
400713×
fn status_byte(s: ChangeStatus) -> u8 {
401713×
    match s {
402246×
        ChangeStatus::Added => 0,
403372×
        ChangeStatus::Modified => 1,
40479×
        ChangeStatus::Removed => 2,
4059×
        ChangeStatus::Renamed => 3,
4067×
        ChangeStatus::ModeChanged => 4,
4070×
        ChangeStatus::ConflictEdited => 5,
4080×
        ChangeStatus::Resolved => 6,
409
    }
410713×
}
411
412332×
fn encode_status_cache(wc: &ChangeHash, stamp: &[u8; 32], statuses: &[PathStatus]) -> Vec<u8> {
413332×
    let mut out = Vec::with_capacity(80 + statuses.len() * 40);
414332×
    out.extend_from_slice(STATUS_MAGIC);
415332×
    out.extend_from_slice(&wc.0);
416332×
    out.extend_from_slice(stamp);
417332×
    out.extend_from_slice(&(statuses.len() as u32).to_le_bytes());
418573×
    for s in statuses {
419573×
        out.push(status_byte(s.status));
420573×
        out.extend_from_slice(&(s.path.len() as u32).to_le_bytes());
421573×
        out.extend_from_slice(s.path.as_bytes());
422573×
    }
423332×
    out
424332×
}
425
426228×
fn decode_status_cache(b: &[u8]) -> Option<(ChangeHash, [u8; 32], Vec<PathStatus>)> {
427228×
    let rest = b.strip_prefix(STATUS_MAGIC)?;
428228×
    let wc = ObjectRef(rest.get(..32)?.try_into().ok()?);
429228×
    let stamp: [u8; 32] = rest.get(32..64)?.try_into().ok()?;
430228×
    let n = u32::from_le_bytes(rest.get(64..68)?.try_into().ok()?) as usize;
431228×
    let mut at = 68;
432228×
    let mut out = Vec::with_capacity(n.min(1 << 16));
433228×
    for _ in 0..n {
434409×
        let status = match *rest.get(at)? {
435112×
            0 => ChangeStatus::Added,
436260×
            1 => ChangeStatus::Modified,
43731×
            2 => ChangeStatus::Removed,
4383×
            3 => ChangeStatus::Renamed,
4393×
            4 => ChangeStatus::ModeChanged,
4400×
            5 => ChangeStatus::ConflictEdited,
4410×
            6 => ChangeStatus::Resolved,
4420×
            _ => return None,
443
        };
444409×
        let len = u32::from_le_bytes(rest.get(at + 1..at + 5)?.try_into().ok()?) as usize;
445409×
        let path = std::str::from_utf8(rest.get(at + 5..at + 5 + len)?)
446409×
            .ok()?
447409×
            .to_string();
448409×
        out.push(PathStatus { path, status });
449409×
        at += 5 + len;
450
    }
451228×
    (at == rest.len()).then_some((wc, stamp, out))
452228×
}
453
454
impl Repo {
4558447×
    pub(crate) fn manifest_path(&self) -> PathBuf {
4568447×
        self.oxy
4578447×
            .join("workspaces")
4588447×
            .join(self.workspace.to_hex())
4598447×
            .join("manifest")
4608447×
    }
461
462
    /// Record the working copy as it is now (after a snapshot, commit, or
463
    /// checkout), with header lines saying whether the base state is
464
    /// conflicted and whether the working-copy change holds uncommitted work.
4651×
    pub(crate) fn write_manifest(&self, conflicted: bool, uncommitted: bool) -> Result<()> {
4661×
        let entries = self.walk_working_copy()?;
4671×
        self.write_manifest_entries(conflicted, uncommitted, &entries, &HashMap::new())
4681×
    }
469
470
    /// Write the manifest from entries already walked; `blobs` names the
471
    /// stored blob of each opaque path so the next walk can skip reading it.
4721182×
    pub(crate) fn write_manifest_entries(
4731182×
        &self,
4741182×
        conflicted: bool,
4751182×
        uncommitted: bool,
4761182×
        entries: &BTreeMap<String, FsEntry>,
4771182×
        blobs: &HashMap<String, ObjectRef>,
4781182×
    ) -> Result<()> {
4791182×
        let dirs = self.walked_dirs.take().unwrap_or_default();
4801182×
        self.write_manifest_entries_as_of(conflicted, uncommitted, entries, blobs, now_ns(), dirs)
4811182×
    }
482
483
    /// `write_manifest_entries` stamped `written` (when the entries were
484
    /// read), with the directories of the walk they came from.
4851564×
    pub(crate) fn write_manifest_entries_as_of(
4861564×
        &self,
4871564×
        conflicted: bool,
4881564×
        uncommitted: bool,
4891564×
        entries: &BTreeMap<String, FsEntry>,
4901564×
        blobs: &HashMap<String, ObjectRef>,
4911564×
        written: u128,
4921564×
        (dirs, nested): WalkedDirs,
4931564×
    ) -> Result<()> {
4941564×
        self.manifest_cache.take();
4951564×
        self.listing_cache.take();
4961564×
        let mut newest_ns: u128 = 0;
49722218×
        let mut rows = entries.iter().map(|(path, e)| {
49822218×
            let (size, mtime_ns) = match e.stat {
49916299×
                Some(known) => known,
5005919×
                None => match fs::symlink_metadata(self.root.join(path)) {
5015917×
                    Ok(m) => (m.len(), mtime_ns(&m)),
5022×
                    Err(_) => (e.content.len() as u64, 0),
503
                },
504
            };
50522218×
            newest_ns = newest_ns.max(mtime_ns);
50622218×
            let entry = ManifestEntry {
50722218×
                size,
50822218×
                mtime_ns,
50922218×
                hash: e
51022218×
                    .content_hash
51122218×
                    .unwrap_or_else(|| *blake3::hash(&e.content).as_bytes()),
51222218×
                blob: blobs.get(path).copied().or(e.blob),
51322218×
                graph: e.graph_key,
51422218×
                exec: e.exec,
515
            };
51622218×
            (path.as_str(), entry)
51722218×
        });
5181564×
        let encoding = crate::timing::phase("manifest: rows and encoding");
5191564×
        let new = encode_manifest(conflicted, uncommitted, written, &dirs, &nested, &mut rows);
5201564×
        drop(rows);
5211564×
        drop(encoding);
5221564×
        if crate::timing::enabled() {
5235×
            let unstated = entries.values().filter(|e| e.stat.is_none()).count();
5242×
            let unhashed = entries
5252×
                .values()
5265×
                .filter(|e| e.content_hash.is_none())
5272×
                .count();
5282×
            eprintln!(
529
                "timing manifest: {} rows, {unstated} without a stat, {unhashed} without a hash",
5302×
                entries.len()
531
            );
5321562×
        }
5331564×
        let _t = crate::timing::phase("manifest: compare and write");
5341564×
        let p = self.manifest_path();
535
        // Leave an unchanged manifest alone when its stamp already trusts
536
        // every entry (none is within the racy window): rewriting it would
537
        // change nothing but the file, which editors watching the tree
538
        // (and subrepos inside it) take as a change.
5391564×
        if let Ok(old) = fs::read(&p) {
5401183×
            let (w, sum) = (MANIFEST_WRITTEN, MANIFEST_SUM);
5411183×
            if old.len() == new.len()
542359×
                && old[..w.start] == new[..w.start]
543314×
                && old[sum.end..] == new[sum.end..]
544
            {
545221×
                let old_written = u128::from_le_bytes(old[w.clone()].try_into().unwrap());
546221×
                if newest_ns + 2_000_000_000 < old_written {
54774×
                    return Ok(());
548147×
                }
549962×
            }
550381×
        }
5511490×
        fs::create_dir_all(p.parent().unwrap())?;
5521490×
        write_cache(&p, &new)
5531564×
    }
554
555
    /// Change the header flags, and set the graph key of each path in
556
    /// `keys` (after a commit, the new base's keys of the files it holds as
557
    /// they are on disk).
558210×
    pub(crate) fn rewrite_manifest(
559210×
        &self,
560210×
        conflicted: bool,
561210×
        uncommitted: bool,
562210×
        keys: &HashMap<String, [u8; 32]>,
563210×
    ) -> Result<()> {
564210×
        self.manifest_cache.take();
565210×
        self.listing_cache.take();
566210×
        let p = self.manifest_path();
567210×
        let Some((_, _, m)) = fs::read(&p).ok().and_then(|b| decode_manifest(&b)) else {
5680×
            return self.write_manifest(conflicted, uncommitted);
569
        };
570681×
        let mut rows = m.entries.iter().map(|(path, e)| {
571681×
            let mut e = e.clone();
572681×
            if let Some(k) = keys.get(path) {
573108×
                e.graph = Some(*k);
574573×
            }
575681×
            (path.as_str(), e)
576681×
        });
577210×
        write_cache(
578210×
            &p,
579210×
            &encode_manifest(
580210×
                conflicted,
581210×
                uncommitted,
582210×
                m.written_ns,
583210×
                &m.dirs,
584210×
                &m.nested,
585210×
                &mut rows,
586210×
            ),
587
        )
588210×
    }
589
590
    /// Forget the manifest after an operation that changed the working-copy
591
    /// change without a snapshot (undo, rewrites); the prompt shows blank
592
    /// markers until the next snapshot.
59341×
    pub(crate) fn drop_manifest(&self) {
59441×
        self.manifest_cache.take();
59541×
        self.listing_cache.take();
59641×
        let _ = fs::remove_file(self.manifest_path());
59741×
    }
598
599
    /// The manifest, with whether it records a conflict and uncommitted
600
    /// work; parsed once while the file stays the same one.
601
    /// Whether the working copy was conflicted when last recorded (the
602
    /// manifest's flag), without looking at the files.
6037×
    pub fn recorded_conflicted(&self) -> Result<bool> {
6047×
        Ok(self.read_manifest()?.is_some_and(|(c, _, _)| c))
6057×
    }
606
6074416×
    pub(crate) fn read_manifest(&self) -> Result<Option<(bool, bool, std::sync::Arc<Manifest>)>> {
6084416×
        let path = self.manifest_path();
6094416×
        let id = match fs::metadata(&path) {
6103306×
            Ok(m) => {
611
                #[cfg(unix)]
6123306×
                let ino = std::os::unix::fs::MetadataExt::ino(&m);
613
                #[cfg(not(unix))]
614
                let ino = 0;
6153306×
                (m.len(), mtime_ns(&m), ino)
616
            }
6171110×
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
6180×
            Err(e) => return Err(e.into()),
619
        };
6203306×
        if let Some((cached_id, m)) = &*self.manifest_cache.borrow() {
6211675×
            if *cached_id == id {
6221675×
                return Ok(Some(m.clone()));
6230×
            }
6241631×
        }
6251631×
        let Some((c, u, m)) = self.parse_manifest(&path)? else {
6263×
            return Ok(None);
627
        };
6281628×
        let m = (c, u, std::sync::Arc::new(m));
6291628×
        *self.manifest_cache.borrow_mut() = Some((id, m.clone()));
6301628×
        Ok(Some(m))
6314416×
    }
632
6331631×
    fn parse_manifest(&self, path: &std::path::Path) -> Result<Option<(bool, bool, Manifest)>> {
6341631×
        let buf = match fs::read(path) {
6351631×
            Ok(b) => b,
6360×
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
6370×
            Err(e) => return Err(e.into()),
638
        };
6391631×
        Ok(decode_manifest(&buf))
6401631×
    }
641
642
    /// Whether the working copy is certainly clean, known from the manifest
643
    /// alone, without loading any history (spec §12.4): the last snapshot
644
    /// or commit found no uncommitted work and no conflict, there are no
645
    /// subrepos (whose state the manifest does not hold), and no file was
646
    /// added, removed or changed since. An entry inside the racy window,
647
    /// where an equal size and time do not prove equal content, is checked
648
    /// by hashing the file. `false` means only that a snapshot must decide.
649757×
    pub fn clean_by_manifest(&self) -> Result<bool> {
650757×
        let _t = crate::timing::phase("status: check the manifest");
651
        // Why a snapshot must decide, with timings on.
652757×
        let not = |why: &str| {
653550×
            if crate::timing::enabled() {
6541×
                eprintln!("timing status: not clean by the manifest: {why}");
655549×
            }
656550×
            Ok(false)
657550×
        };
658757×
        let Some((conflicted, uncommitted, m)) = self.read_manifest()? else {
659245×
            return not("no manifest");
660
        };
661512×
        if conflicted || uncommitted || self.root.join(".oxymodules").exists() {
66217×
            return not("conflicted, uncommitted or subrepos");
663495×
        }
664495×
        let started = now_ns();
665495×
        if self.disk_differs(&m, true)? {
666288×
            return not("a file differs");
667207×
        }
668
        // Verified clean. Entries or directories within the racy window of
669
        // the manifest's time were hashed or listed just now; restamped with
670
        // the time this check began, the next check can trust them, as
671
        // Git restamps its index (anything changed within two seconds of
672
        // that time is still racy by the same rule).
673
        // A check that had to list the tree leaves the directories it
674
        // listed: kept, the next check need not list.
675207×
        let window = 2_000_000_000;
676207×
        let listed = self.listed_dirs.take();
677210×
        let racy = m.dirs.iter().any(|(_, t)| t + window >= m.written_ns)
6782×
            || m.entries
6792×
                .values()
68010×
                .any(|e| e.mtime_ns + window >= m.written_ns);
681207×
        if (racy || (m.dirs.is_empty() && listed.is_some())) && started > m.written_ns {
682206×
            let (dirs, nested) = listed.unwrap_or_else(|| (m.dirs.clone(), m.nested.clone()));
683206×
            self.restamp_manifest(&m, conflicted, uncommitted, started, &dirs, &nested);
6841×
        }
685207×
        Ok(true)
686757×
    }
687
688
    /// Rewrite the manifest with a new time and directory list, its entries
689
    /// unchanged.
690206×
    fn restamp_manifest(
691206×
        &self,
692206×
        m: &Manifest,
693206×
        conflicted: bool,
694206×
        uncommitted: bool,
695206×
        written_ns: u128,
696206×
        dirs: &[(String, u128)],
697206×
        nested: &[String],
698206×
    ) {
699206×
        let _t = crate::timing::phase("status: restamp the manifest");
7007699×
        let mut rows = m.entries.iter().map(|(p, e)| (p.as_str(), e.clone()));
701206×
        let bytes = encode_manifest(conflicted, uncommitted, written_ns, dirs, nested, &mut rows);
702206×
        self.manifest_cache.take();
703206×
        let _ = write_cache(&self.manifest_path(), &bytes);
704206×
    }
705
706
    /// A manifest entry written within the racy window whose file no
707
    /// longer matches it. Such entries are hashed, in parallel (a checkout
708
    /// just wrote them all).
709735×
    fn racy_change(&self, m: &Manifest) -> Option<String> {
710
        use rayon::prelude::*;
711735×
        let racy: Vec<(&String, &ManifestEntry)> = m
712735×
            .entries
713735×
            .iter()
71411186×
            .filter(|(_, e)| e.mtime_ns + 2_000_000_000 >= m.written_ns)
715735×
            .collect();
716735×
        let root = &self.root;
717735×
        racy.par_iter()
7184717×
            .find_any(|(rel, e)| {
7194717×
                let path = root.join(rel.as_str());
7204717×
                let same = match fs::symlink_metadata(&path) {
7214713×
                    Ok(md) if md.file_type().is_symlink() => fs::read_link(&path).is_ok_and(|t| {
7220×
                        *blake3::hash(t.to_string_lossy().as_bytes()).as_bytes() == e.hash
7230×
                    }),
7244713×
                    Ok(md) if md.is_file() => {
7254713×
                        md.len() == e.size
7264590×
                            && fs::read(&path).is_ok_and(|b| *blake3::hash(&b).as_bytes() == e.hash)
727
                    }
7284×
                    _ => false,
729
                };
7304717×
                !same
7314717×
            })
732735×
            .map(|(rel, _)| rel.to_string())
733735×
    }
734
735
    /// The status lines of the last snapshot, when the working copy is as
736
    /// that snapshot left it: the cache it wrote names the working-copy
737
    /// change and the manifest it recorded, and every file still matches
738
    /// that manifest. `None` when a snapshot must decide (no cache, a file
739
    /// changed, conflicts or subrepos). An empty list is a clean working
740
    /// copy.
741626×
    pub fn status_by_manifest(&self) -> Result<Option<Vec<PathStatus>>> {
742
        // A listing left by an earlier check describes the files as they
743
        // were then; this check makes its own.
744626×
        self.listing_cache.take();
745626×
        let Some((conflicted, uncommitted, m)) = self.read_manifest()? else {
746101×
            return Ok(None);
747
        };
748525×
        if !uncommitted {
749293×
            return Ok(self.clean_by_manifest()?.then(Vec::new));
750232×
        }
751232×
        let _t = crate::timing::phase("status: by the status cache");
752232×
        if conflicted || self.root.join(".oxymodules").exists() {
7534×
            return Ok(None);
754228×
        }
755228×
        let Some((wc, stamp, statuses)) = fs::read(self.status_cache_path())
756228×
            .ok()
757228×
            .and_then(|b| decode_status_cache(&b))
758
        else {
7590×
            return Ok(None);
760
        };
761228×
        let now = self.view()?.workspaces.get(&self.workspace).copied();
762228×
        if now != Some(wc) || self.manifest_stamp() != Some(stamp) {
7630×
            return Ok(None);
764228×
        }
765228×
        if self.disk_differs(&m, true)? {
7667×
            return Ok(None);
767221×
        }
768
        // Test builds check the cache against a snapshot of the files.
769
        #[cfg(test)]
770
        {
77141×
            let snap = self.snapshot_status("status cache check")?;
77282×
            let key = |v: &[PathStatus]| {
77382×
                let mut k: Vec<(String, u8)> = v
77482×
                    .iter()
775140×
                    .map(|p| (p.path.clone(), status_byte(p.status)))
77682×
                    .collect();
77782×
                k.sort();
77882×
                k
77982×
            };
78041×
            assert_eq!(
78141×
                key(&statuses),
78241×
                key(&snap.statuses),
783
                "status cache disagrees with a snapshot"
784
            );
785
        }
786221×
        Ok(Some(statuses))
787626×
    }
788
7891004×
    fn status_cache_path(&self) -> PathBuf {
7901004×
        self.manifest_path().with_file_name("status")
7911004×
    }
792
793
    /// The manifest file's checksum, which names its content.
7941004×
    fn manifest_stamp(&self) -> Option<[u8; 32]> {
795
        use std::io::Read;
7961004×
        let mut head = [0u8; MANIFEST_SUM.end];
7971004×
        fs::File::open(self.manifest_path())
7981004×
            .and_then(|mut f| f.read_exact(&mut head))
7991004×
            .ok()?;
8001004×
        head[MANIFEST_SUM].try_into().ok()
8011004×
    }
802
803
    /// Record `statuses` as the status of working-copy change `wc` against
804
    /// the manifest as it is now; with no uncommitted work there is nothing
805
    /// to record, and the cache goes.
806776×
    pub(crate) fn write_status_cache(&self, wc: Option<&ChangeHash>, statuses: &[PathStatus]) {
807776×
        let path = self.status_cache_path();
808776×
        let (Some(wc), Some(stamp)) = (wc, self.manifest_stamp()) else {
809444×
            let _ = fs::remove_file(&path);
810444×
            return;
811
        };
812332×
        let _ = write_cache(&path, &encode_status_cache(wc, &stamp, statuses));
813776×
    }
814
815
    /// Whether the working copy differs from the last manifest. Without a
816
    /// manifest the answer is `None`.
81713×
    pub fn quick_dirty(&self) -> Result<Option<bool>> {
81813×
        self.quick_dirty_keeping(false)
81913×
    }
820
821
    /// `quick_dirty`; with `keep`, the listing it made is left for the
822
    /// next walk of the working copy.
82313×
    fn quick_dirty_keeping(&self, keep: bool) -> Result<Option<bool>> {
82413×
        let Some((_, uncommitted, manifest)) = self.read_manifest()? else {
8250×
            return Ok(None);
826
        };
82713×
        if uncommitted {
8281×
            return Ok(Some(true));
82912×
        }
83012×
        Ok(Some(self.disk_differs(&manifest, keep)?))
83113×
    }
832
833
    /// Whether the working copy differs from `manifest`: a file added,
834
    /// gone or changed. With `keep`, the listing made is left for the next
835
    /// walk of the working copy when it does.
836735×
    fn disk_differs(&self, manifest: &Manifest, keep: bool) -> Result<bool> {
837
        // A file written within the racy window can change without its size
838
        // or time moving (a coarse clock): those entries are hashed. One
839
        // that changed still lets the directory check below hand its stats
840
        // to the snapshot that follows.
841735×
        let racy = self.racy_change(manifest).is_some();
842735×
        if let Some(differs) = self.disk_differs_by_dirs_keeping(manifest, keep, racy) {
8433×
            return Ok(differs || racy);
844732×
        }
845732×
        if racy {
846156×
            return Ok(true);
847576×
        }
848576×
        self.disk_differs_listing(manifest, keep)
849735×
    }
850
851
    /// [`Repo::disk_differs`] without listing the tree, when the manifest
852
    /// knows its directories: a directory's time moves when an entry is
853
    /// added, removed or renamed in it, so with every directory's time as
854
    /// recorded (and none within the racy window) the files are the
855
    /// manifest's, and each is checked by its stat. `None` when a
856
    /// directory changed or the manifest has none: the tree must be listed.
857
    #[cfg(test)]
8585×
    pub(crate) fn disk_differs_by_dirs(&self, manifest: &Manifest) -> Option<bool> {
8595×
        self.disk_differs_by_dirs_keeping(manifest, false, false)
8605×
    }
861
862
    /// [`Repo::disk_differs_by_dirs`]; with `keep`, when a file differs
863
    /// (or `racy` says one does), the stats taken become the listing of the
864
    /// snapshot that follows: no directory's entries changed, so the
865
    /// manifest's files are the tree's.
866740×
    fn disk_differs_by_dirs_keeping(
867740×
        &self,
868740×
        manifest: &Manifest,
869740×
        keep: bool,
870740×
        racy: bool,
871740×
    ) -> Option<bool> {
872
        use rayon::prelude::*;
873740×
        if manifest.dirs.is_empty() || !self.config.sparse_paths.is_empty() {
8743×
            return None;
875737×
        }
876737×
        let _t = crate::timing::phase("status: directories and files by stat");
877737×
        let root = &self.root;
878813×
        let dirs_same = manifest.dirs.par_iter().all(|(rel, t)| {
879813×
            *t + 2_000_000_000 < manifest.written_ns
88024×
                && fs::metadata(root.join(rel)).is_ok_and(|m| m.is_dir() && mtime_ns(&m) == *t)
881813×
        });
882737×
        if !dirs_same {
883731×
            return None;
8846×
        }
8856×
        let rels: Vec<&String> = manifest.entries.keys().collect();
8866×
        let now = stat_tracked(root, &rels);
8872116×
        let differs_from = |me: &ManifestEntry, rel: &str, now: &Tracked| match now {
8880×
            Tracked::Link(t) => *blake3::hash(t).as_bytes() != me.hash,
8892116×
            Tracked::File(m) => {
8902116×
                m.size != me.size
8912115×
                    || m.exec != me.exec
8922115×
                    || (m.mtime_ns != me.mtime_ns
8931×
                        && !fs::read(root.join(rel))
8941×
                            .is_ok_and(|b| *blake3::hash(&b).as_bytes() == me.hash))
895
            }
8962116×
        };
897
        // A path gone or no longer a file: its directory moved, unless
898
        // within a clock tick; list the tree to be sure.
8996×
        if now.iter().any(Option::is_none) {
9000×
            return None;
9016×
        }
902
        // The entries in the order `rels` was taken in: no lookup by path.
9036×
        let entries: Vec<&ManifestEntry> = manifest.entries.values().collect();
9046×
        let differs = rels
9056×
            .par_iter()
9066×
            .zip(entries.par_iter())
9076×
            .zip(now.par_iter())
9082116×
            .any(|((rel, me), n)| differs_from(me, rel, n.as_ref().unwrap()));
9096×
        if keep && (differs || racy) {
9101×
            let mut listing = super::walk::Listing {
9111×
                dirs: manifest.dirs.clone(),
9121×
                nested: manifest.nested.iter().map(|n| root.join(n)).collect(),
9131×
                ..Default::default()
914
            };
9152100×
            for (rel, n) in rels.into_iter().zip(now) {
9162100×
                match n.unwrap() {
9172100×
                    Tracked::File(m) => listing.files.push((rel.clone(), root.join(rel), m)),
9180×
                    Tracked::Link(t) => listing.symlinks.push((rel.clone(), t)),
919
                }
920
            }
9211×
            *self.listing_cache.borrow_mut() = Some(listing);
9225×
        }
9236×
        if !differs {
924
            // Nested repositories the manifest has no entry for are not
925
            // subrepos: nothing in them is tracked (oxygen#43).
9264×
            *self.untracked_nested.borrow_mut() = manifest
9274×
                .nested
9284×
                .iter()
9294×
                .filter(|rel| !manifest.entries.contains_key(*rel))
9304×
                .cloned()
9314×
                .collect();
9322×
        }
9336×
        Some(differs)
934740×
    }
935
936
    /// [`Repo::disk_differs`] by listing the tree.
937576×
    fn disk_differs_listing(&self, manifest: &Manifest, keep: bool) -> Result<bool> {
938
        use rayon::prelude::*;
939576×
        let sparse = &self.config.sparse_paths;
9407138×
        let in_scope = |p: &str| {
9417138×
            sparse.is_empty()
9425×
                || sparse
9435×
                    .iter()
9446×
                    .any(|s| p == s || p.starts_with(&format!("{s}/")))
9457138×
        };
946
        // A working copy that cannot be listed counts as changed.
947
        // Known files are not matched against the ignore rules: with no
948
        // uncommitted work (the clean check), the manifest's files are the
949
        // base's, and a prompt's answer is the same either way.
9507150×
        let known = |p: &str| manifest.entries.contains_key(p);
951576×
        let Ok(listing) = super::walk::list_knowing(&self.root, &in_scope, &known) else {
9520×
            return Ok(true);
953
        };
954576×
        let differs = || -> Result<bool> {
955576×
            let links_differ = listing.symlinks.iter().any(|(rel, target)| {
9561×
                manifest
9571×
                    .entries
9581×
                    .get(rel)
9591×
                    .is_none_or(|me| *blake3::hash(target).as_bytes() != me.hash)
9601×
            });
961576×
            if links_differ {
9621×
                return Ok(true);
963575×
            }
964
            // Each file is checked on its own, in parallel, stopping at the
965
            // first difference; an unreadable one counts as different.
9666671×
            let files_differ = listing.files.par_iter().any(|(rel, path, m)| {
9676671×
                manifest.entries.get(rel).is_none_or(|me| {
9686535×
                    m.size != me.size
9696534×
                        || m.exec != me.exec
9706531×
                        || (m.mtime_ns != me.mtime_ns
9713×
                            && !fs::read(path)
9723×
                                .is_ok_and(|b| *blake3::hash(&b).as_bytes() == me.hash))
9736535×
                })
9746671×
            });
975575×
            if files_differ {
976140×
                return Ok(true);
977435×
            }
978435×
            let seen = listing.files.len() + listing.symlinks.len();
979435×
            if seen == manifest.entries.len() {
980435×
                return Ok(false);
9810×
            }
982
            // Manifest entries the walk skipped: tracked files that ignore
983
            // rules hide (Linux tracks some its own .gitignore names). Found
984
            // by merging the two sorted lists; they count as present when
985
            // still on disk and unchanged, checked on every core.
9860×
            let mut listed: Vec<&str> = listing
9870×
                .files
9880×
                .iter()
9890×
                .map(|(r, _, _)| r.as_str())
9900×
                .chain(listing.symlinks.iter().map(|(r, _)| r.as_str()))
9910×
                .collect();
9920×
            listed.sort_unstable();
9930×
            let mut at = listed.iter().peekable();
9940×
            let skipped: Vec<(&String, &ManifestEntry)> = manifest
9950×
                .entries
9960×
                .iter()
9970×
                .filter(|(rel, _)| {
9980×
                    while at.next_if(|l| **l < rel.as_str()).is_some() {}
9990×
                    at.peek().is_none_or(|l| **l != rel.as_str())
10000×
                })
10010×
                .collect();
10020×
            let root = &self.root;
10030×
            Ok(skipped.par_iter().any(|(rel, me)| {
10040×
                let path = root.join(rel.as_str());
10050×
                let Ok(m) = fs::symlink_metadata(&path) else {
10060×
                    return true;
1007
                };
10080×
                !m.file_type().is_symlink()
10090×
                    && (m.len() != me.size
10100×
                        || super::is_executable(&m) != me.exec
10110×
                        || (mtime_ns(&m) != me.mtime_ns
10120×
                            && !fs::read(&path)
10130×
                                .is_ok_and(|b| *blake3::hash(&b).as_bytes() == me.hash)))
10140×
            }))
1015576×
        };
1016576×
        let dirty = differs()?;
1017576×
        if !dirty {
1018
            // Nested repositories the manifest has no entry for are not
1019
            // subrepos: nothing in them is tracked (oxygen#43).
1020435×
            let mut nested: Vec<String> = listing
1021435×
                .nested
1022435×
                .iter()
1023435×
                .map(|d| self.rel_path(d))
1024435×
                .filter(|rel| !manifest.entries.contains_key(rel))
1025435×
                .collect();
1026435×
            nested.sort();
1027435×
            *self.untracked_nested.borrow_mut() = nested;
1028
            // A complete list of the directories, each timed before it was
1029
            // read, for a restamp to keep (see `clean_by_manifest`).
1030435×
            *self.listed_dirs.borrow_mut() = Some((
1031435×
                listing.dirs.clone(),
1032435×
                listing.nested.iter().map(|d| self.rel_path(d)).collect(),
1033
            ));
1034141×
        }
1035576×
        if dirty && keep {
1036140×
            *self.listing_cache.borrow_mut() = Some(listing);
1037436×
        }
1038576×
        Ok(dirty)
1039576×
    }
1040
1041
    /// Prompt information without recording anything.
104211×
    pub fn quick_status(&self) -> Result<PromptInfo> {
104311×
        let view = self.view()?;
104411×
        let bookmark = self.config.bookmark.clone();
104511×
        let heads = self.heads_of(&view, &bookmark)?;
104611×
        let wc_hash = view.workspaces.get(&self.workspace).copied();
104711×
        let change_id = match wc_hash {
104811×
            Some(h) => self.store.get_change_meta(&h)?.change_id.short(8),
10490×
            None => String::new(),
1050
        };
1051
        // Conflictedness was recorded by the last snapshot; without a
1052
        // manifest (never snapshotted) both flags are unknown and shown clear.
105311×
        let manifest = self.read_manifest()?;
105411×
        let conflicted = manifest.as_ref().map(|(c, _, _)| *c).unwrap_or(false);
105511×
        let dirty = self.quick_dirty()?.unwrap_or(false);
105611×
        let (ahead, behind) = match view
105711×
            .remotes
105811×
            .get(&self.default_remote())
105911×
            .and_then(|b| b.get(&bookmark))
1060
        {
106110×
            Some(st) => {
106210×
                let remote_heads = self.store.get_state(st)?.heads;
106310×
                let ahead = self.negotiate(&remote_heads, &heads).map(|v| v.len()).ok();
106410×
                let behind = self.negotiate(&heads, &remote_heads).map(|v| v.len()).ok();
106510×
                (ahead, behind)
1066
            }
10671×
            None => (None, None),
1068
        };
106911×
        Ok(PromptInfo {
107011×
            bookmark,
107111×
            change_id,
107211×
            heads: heads.len(),
107311×
            dirty,
107411×
            conflicted,
107511×
            ahead,
107611×
            behind,
107711×
        })
107811×
    }
1079
}
1080
1081
#[cfg(test)]
1082
mod tests {
1083
    use super::*;
1084
1085
    #[test]
10861×
    fn placeholders_and_glyphs() {
10871×
        let clean = PromptInfo {
10881×
            bookmark: "main".into(),
10891×
            change_id: "658990aa".into(),
10901×
            heads: 1,
10911×
            dirty: false,
10921×
            conflicted: false,
10931×
            ahead: Some(0),
10941×
            behind: None,
10951×
        };
10961×
        assert_eq!(clean.format(DEFAULT_PROMPT_FORMAT), "main 658990aa");
10971×
        assert_eq!(clean.format(GLYPH_PROMPT_FORMAT), "⚛ main 658990aa ✔");
10981×
        let busy = PromptInfo {
10991×
            dirty: true,
11001×
            ahead: Some(2),
11011×
            behind: Some(3),
11021×
            ..clean.clone()
11031×
        };
11041×
        assert_eq!(busy.format(DEFAULT_PROMPT_FORMAT), "main 658990aa*+2-3");
11051×
        assert_eq!(busy.format(GLYPH_PROMPT_FORMAT), "⚛ main 658990aa ✎↑2↓3");
11061×
        let bad = PromptInfo {
11071×
            conflicted: true,
11081×
            ..busy.clone()
11091×
        };
11101×
        assert_eq!(bad.format("%s%x%d %h %a/%B %%"), "‼!* 1 2/3 %");
11111×
        assert_eq!(bad.state_color(), 31);
11121×
        assert_eq!(
11131×
            busy.format_colored("%b", ("\\[", "\\]")),
1114
            "\\[\x1b[33m\\]main\\[\x1b[0m\\]"
1115
        );
11161×
        assert_eq!(clean.format_colored("%b", ("", "")), "\x1b[36mmain\x1b[0m");
11171×
        assert_eq!(clean.format("%q"), "%q");
11181×
    }
1119
}