OXYGENHUB
# cd4eb55e3b3d oxygen / crates / oxy-core / src / repo / prompt.rs
36.6 KiB · Rust · last changed Commit takes a status's snapshot from the cache; the stat check lends its stats to the snapshot (refs #41) 1 month ago source blame history raw
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.
29
    pub fn state_glyph(&self) -> &'static str {
30
        if self.conflicted {
31
            "‼"
32
        } else if self.dirty {
33
            "✎"
34
        } else {
35
            "✔"
36
        }
37
    }
38
39
    /// The ANSI colour (SGR parameter) for the state: red, yellow, or cyan.
40
    pub fn state_color(&self) -> u8 {
41
        if self.conflicted {
42
            31
43
        } else if self.dirty {
44
            33
45
        } else {
46
            36
47
        }
48
    }
49
50
    /// `format` wrapped in the state colour. `guard` is `("\\[", "\\]")` for
51
    /// bash prompts, `("%{", "%}")` for zsh, or empty for raw output.
52
    pub fn format_colored(&self, fmt: &str, guard: (&str, &str)) -> String {
53
        format!(
54
            "{}\x1b[{}m{}{}{}\x1b[0m{}",
55
            guard.0,
56
            self.state_color(),
57
            guard.1,
58
            self.format(fmt),
59
            guard.0,
60
            guard.1
61
        )
62
    }
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.
69
    pub fn format(&self, fmt: &str) -> String {
70
        let mut out = String::new();
71
        let mut chars = fmt.chars();
72
        while let Some(c) = chars.next() {
73
            if c != '%' {
74
                out.push(c);
75
                continue;
76
            }
77
            match chars.next() {
78
                Some('b') => out.push_str(&self.bookmark),
79
                Some('c') => out.push_str(&self.change_id),
80
                Some('h') => out.push_str(&self.heads.to_string()),
81
                Some('d') => {
82
                    if self.dirty {
83
                        out.push('*');
84
                    }
85
                }
86
                Some('x') => {
87
                    if self.conflicted {
88
                        out.push('!');
89
                    }
90
                }
91
                Some('a') => out.push_str(&self.ahead.map(|n| n.to_string()).unwrap_or_default()),
92
                Some('B') => out.push_str(&self.behind.map(|n| n.to_string()).unwrap_or_default()),
93
                Some('A') => {
94
                    if let Some(n) = self.ahead.filter(|n| *n > 0) {
95
                        out.push_str(&format!("+{n}"));
96
                    }
97
                }
98
                Some('D') => {
99
                    if let Some(n) = self.behind.filter(|n| *n > 0) {
100
                        out.push_str(&format!("-{n}"));
101
                    }
102
                }
103
                Some('s') => out.push_str(self.state_glyph()),
104
                Some('U') => {
105
                    if let Some(n) = self.ahead.filter(|n| *n > 0) {
106
                        out.push_str(&format!("↑{n}"));
107
                    }
108
                }
109
                Some('O') => {
110
                    if let Some(n) = self.behind.filter(|n| *n > 0) {
111
                        out.push_str(&format!("↓{n}"));
112
                    }
113
                }
114
                Some('i') => out.push_str(ICON),
115
                Some('%') => out.push('%'),
116
                Some(other) => {
117
                    out.push('%');
118
                    out.push(other);
119
                }
120
                None => out.push('%'),
121
            }
122
        }
123
        out
124
    }
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
pub(crate) fn mtime_ns(m: &fs::Metadata) -> u128 {
162
    m.modified()
163
        .ok()
164
        .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
165
        .map(|d| d.as_nanos())
166
        .unwrap_or(0)
167
}
168
169
pub const DEFAULT_PROMPT_FORMAT: &str = "%b %c%d%x%A%D";
170
/// The repository icon for `%i` (an atom, for oxygen).
171
pub const ICON: &str = "⚛";
172
/// A format with glyphs: icon, bookmark, change id, state, ahead/behind.
173
pub const GLYPH_PROMPT_FORMAT: &str = "%i %b %c %s%U%O";
174
175
/// The manifest file (oxygen#41): a flat binary layout read in one pass.
176
/// A magic number; the conflicted and uncommitted flags; when it was
177
/// written, at a fixed offset so an otherwise equal manifest can be
178
/// recognised; BLAKE3 of everything else; then each entry in path order:
179
/// path, size, mtime in nanoseconds, BLAKE3 of the content, the stored
180
/// blob of an opaque file, the graph key it was found equal to, and
181
/// whether it is executable. Format 3 puts before the entries every
182
/// directory the walk listed with its time, and the nested repositories. A file that does not check, or in any other
183
/// layout (an older manifest), reads as no manifest, and the next snapshot
184
/// writes it again: it is a cache, written without waiting for the disk.
185
const MANIFEST_MAGIC: &[u8; 8] = b"oxyman3\0";
186
/// Where the written time sits: after the magic and the two flags.
187
const MANIFEST_WRITTEN: std::ops::Range<usize> = 10..26;
188
/// Where the checksum sits, after the written time.
189
const MANIFEST_SUM: std::ops::Range<usize> = 26..58;
190
191
fn manifest_sum(buf: &[u8]) -> [u8; 32] {
192
    let mut h = blake3::Hasher::new();
193
    h.update(&buf[..MANIFEST_SUM.start]);
194
    h.update_rayon(&buf[MANIFEST_SUM.end..]);
195
    *h.finalize().as_bytes()
196
}
197
198
fn encode_manifest(
199
    conflicted: bool,
200
    uncommitted: bool,
201
    written_ns: u128,
202
    dirs: &[(String, u128)],
203
    nested: &[String],
204
    entries: &mut dyn Iterator<Item = (&str, ManifestEntry)>,
205
) -> Vec<u8> {
206
    let mut w = crate::flat::Writer::default();
207
    w.fixed(MANIFEST_MAGIC);
208
    w.u8(conflicted as u8);
209
    w.u8(uncommitted as u8);
210
    w.fixed(&written_ns.to_le_bytes());
211
    w.fixed(&[0; 32]);
212
    w.count(dirs.len());
213
    for (d, t) in dirs {
214
        w.bytes(d.as_bytes());
215
        w.fixed(&t.to_le_bytes());
216
    }
217
    w.count(nested.len());
218
    for n in nested {
219
        w.bytes(n.as_bytes());
220
    }
221
    for (path, e) in entries {
222
        w.bytes(path.as_bytes());
223
        w.u64(e.size);
224
        w.fixed(&e.mtime_ns.to_le_bytes());
225
        w.fixed(&e.hash);
226
        w.opt_object(&e.blob);
227
        match e.graph {
228
            None => w.u8(0),
229
            Some(k) => {
230
                w.u8(1);
231
                w.fixed(&k);
232
            }
233
        }
234
        w.u8(e.exec as u8);
235
    }
236
    let sum = manifest_sum(&w.0);
237
    w.0[MANIFEST_SUM].copy_from_slice(&sum);
238
    w.0
239
}
240
241
fn decode_manifest(buf: &[u8]) -> Option<(bool, bool, Manifest)> {
242
    let mut r = crate::flat::Reader::new(buf);
243
    if &r.fixed::<8>().ok()? != MANIFEST_MAGIC {
244
        return None;
245
    }
246
    let conflicted = r.u8().ok()? == 1;
247
    let uncommitted = r.u8().ok()? == 1;
248
    let written_ns = u128::from_le_bytes(r.fixed().ok()?);
249
    if r.fixed::<32>().ok()? != manifest_sum(buf) {
250
        return None;
251
    }
252
    let mut dirs = Vec::new();
253
    for _ in 0..r.count().ok()? {
254
        let d = std::str::from_utf8(r.bytes().ok()?).ok()?.to_string();
255
        dirs.push((d, u128::from_le_bytes(r.fixed().ok()?)));
256
    }
257
    let mut nested = Vec::new();
258
    for _ in 0..r.count().ok()? {
259
        nested.push(std::str::from_utf8(r.bytes().ok()?).ok()?.to_string());
260
    }
261
    let mut entries = Vec::new();
262
    while !r.at_end() {
263
        let path = std::str::from_utf8(r.bytes().ok()?).ok()?.to_string();
264
        let e = ManifestEntry {
265
            size: r.u64().ok()?,
266
            mtime_ns: u128::from_le_bytes(r.fixed().ok()?),
267
            hash: r.fixed().ok()?,
268
            blob: r.opt_object().ok()?,
269
            graph: match r.u8().ok()? {
270
                0 => None,
271
                _ => Some(r.fixed().ok()?),
272
            },
273
            exec: r.u8().ok()? == 1,
274
        };
275
        entries.push((path, e));
276
    }
277
    // Written in path order, so this builds the map without searching.
278
    let entries = entries.into_iter().collect();
279
    Some((
280
        conflicted,
281
        uncommitted,
282
        Manifest {
283
            written_ns,
284
            entries,
285
            dirs,
286
            nested,
287
        },
288
    ))
289
}
290
291
/// The status cache: a magic number, the working-copy change, the
292
/// manifest checksum, then each status line (a status byte and a path).
293
const STATUS_MAGIC: &[u8; 8] = b"oxystat1";
294
295
fn status_byte(s: ChangeStatus) -> u8 {
296
    match s {
297
        ChangeStatus::Added => 0,
298
        ChangeStatus::Modified => 1,
299
        ChangeStatus::Removed => 2,
300
        ChangeStatus::Renamed => 3,
301
        ChangeStatus::ModeChanged => 4,
302
        ChangeStatus::ConflictEdited => 5,
303
        ChangeStatus::Resolved => 6,
304
    }
305
}
306
307
fn encode_status_cache(wc: &ChangeHash, stamp: &[u8; 32], statuses: &[PathStatus]) -> Vec<u8> {
308
    let mut out = Vec::with_capacity(80 + statuses.len() * 40);
309
    out.extend_from_slice(STATUS_MAGIC);
310
    out.extend_from_slice(&wc.0);
311
    out.extend_from_slice(stamp);
312
    out.extend_from_slice(&(statuses.len() as u32).to_le_bytes());
313
    for s in statuses {
314
        out.push(status_byte(s.status));
315
        out.extend_from_slice(&(s.path.len() as u32).to_le_bytes());
316
        out.extend_from_slice(s.path.as_bytes());
317
    }
318
    out
319
}
320
321
fn decode_status_cache(b: &[u8]) -> Option<(ChangeHash, [u8; 32], Vec<PathStatus>)> {
322
    let rest = b.strip_prefix(STATUS_MAGIC)?;
323
    let wc = ObjectRef(rest.get(..32)?.try_into().ok()?);
324
    let stamp: [u8; 32] = rest.get(32..64)?.try_into().ok()?;
325
    let n = u32::from_le_bytes(rest.get(64..68)?.try_into().ok()?) as usize;
326
    let mut at = 68;
327
    let mut out = Vec::with_capacity(n.min(1 << 16));
328
    for _ in 0..n {
329
        let status = match *rest.get(at)? {
330
            0 => ChangeStatus::Added,
331
            1 => ChangeStatus::Modified,
332
            2 => ChangeStatus::Removed,
333
            3 => ChangeStatus::Renamed,
334
            4 => ChangeStatus::ModeChanged,
335
            5 => ChangeStatus::ConflictEdited,
336
            6 => ChangeStatus::Resolved,
337
            _ => return None,
338
        };
339
        let len = u32::from_le_bytes(rest.get(at + 1..at + 5)?.try_into().ok()?) as usize;
340
        let path = std::str::from_utf8(rest.get(at + 5..at + 5 + len)?)
341
            .ok()?
342
            .to_string();
343
        out.push(PathStatus { path, status });
344
        at += 5 + len;
345
    }
346
    (at == rest.len()).then_some((wc, stamp, out))
347
}
348
349
impl Repo {
350
    pub(crate) fn manifest_path(&self) -> PathBuf {
351
        self.oxy
352
            .join("workspaces")
353
            .join(self.workspace.to_hex())
354
            .join("manifest")
355
    }
356
357
    /// Record the working copy as it is now (after a snapshot, commit, or
358
    /// checkout), with header lines saying whether the base state is
359
    /// conflicted and whether the working-copy change holds uncommitted work.
360
    pub(crate) fn write_manifest(&self, conflicted: bool, uncommitted: bool) -> Result<()> {
361
        let entries = self.walk_working_copy()?;
362
        self.write_manifest_entries(conflicted, uncommitted, &entries, &HashMap::new())
363
    }
364
365
    /// Write the manifest from entries already walked; `blobs` names the
366
    /// stored blob of each opaque path so the next walk can skip reading it.
367
    pub(crate) fn write_manifest_entries(
368
        &self,
369
        conflicted: bool,
370
        uncommitted: bool,
371
        entries: &BTreeMap<String, FsEntry>,
372
        blobs: &HashMap<String, ObjectRef>,
373
    ) -> Result<()> {
374
        self.manifest_cache.take();
375
        self.listing_cache.take();
376
        let written = std::time::SystemTime::now()
377
            .duration_since(UNIX_EPOCH)
378
            .map(|d| d.as_nanos())
379
            .unwrap_or(0);
380
        let mut newest_ns: u128 = 0;
381
        let mut rows = entries.iter().map(|(path, e)| {
382
            let (size, mtime_ns) = match e.stat {
383
                Some(known) => known,
384
                None => match fs::symlink_metadata(self.root.join(path)) {
385
                    Ok(m) => (m.len(), mtime_ns(&m)),
386
                    Err(_) => (e.content.len() as u64, 0),
387
                },
388
            };
389
            newest_ns = newest_ns.max(mtime_ns);
390
            let entry = ManifestEntry {
391
                size,
392
                mtime_ns,
393
                hash: e
394
                    .content_hash
395
                    .unwrap_or_else(|| *blake3::hash(&e.content).as_bytes()),
396
                blob: blobs.get(path).copied().or(e.blob),
397
                graph: e.graph_key,
398
                exec: e.exec,
399
            };
400
            (path.as_str(), entry)
401
        });
402
        // The directories of the walk these entries came from, if any.
403
        let (dirs, nested) = self.walked_dirs.take().unwrap_or_default();
404
        let new = encode_manifest(conflicted, uncommitted, written, &dirs, &nested, &mut rows);
405
        drop(rows);
406
        let p = self.manifest_path();
407
        // Leave an unchanged manifest alone when its stamp already trusts
408
        // every entry (none is within the racy window): rewriting it would
409
        // change nothing but the file, which editors watching the tree
410
        // (and subrepos inside it) take as a change.
411
        if let Ok(old) = fs::read(&p) {
412
            let (w, sum) = (MANIFEST_WRITTEN, MANIFEST_SUM);
413
            if old.len() == new.len()
414
                && old[..w.start] == new[..w.start]
415
                && old[sum.end..] == new[sum.end..]
416
            {
417
                let old_written = u128::from_le_bytes(old[w.clone()].try_into().unwrap());
418
                if newest_ns + 2_000_000_000 < old_written {
419
                    return Ok(());
420
                }
421
            }
422
        }
423
        fs::create_dir_all(p.parent().unwrap())?;
424
        write_cache(&p, &new)
425
    }
426
427
    /// Change the header flags, and set the graph key of each path in
428
    /// `keys` (after a commit, the new base's keys of the files it holds as
429
    /// they are on disk).
430
    pub(crate) fn rewrite_manifest(
431
        &self,
432
        conflicted: bool,
433
        uncommitted: bool,
434
        keys: &HashMap<String, [u8; 32]>,
435
    ) -> Result<()> {
436
        self.manifest_cache.take();
437
        self.listing_cache.take();
438
        let p = self.manifest_path();
439
        let Some((_, _, m)) = fs::read(&p).ok().and_then(|b| decode_manifest(&b)) else {
440
            return self.write_manifest(conflicted, uncommitted);
441
        };
442
        let mut rows = m.entries.iter().map(|(path, e)| {
443
            let mut e = e.clone();
444
            if let Some(k) = keys.get(path) {
445
                e.graph = Some(*k);
446
            }
447
            (path.as_str(), e)
448
        });
449
        write_cache(
450
            &p,
451
            &encode_manifest(
452
                conflicted,
453
                uncommitted,
454
                m.written_ns,
455
                &m.dirs,
456
                &m.nested,
457
                &mut rows,
458
            ),
459
        )
460
    }
461
462
    /// Forget the manifest after an operation that changed the working-copy
463
    /// change without a snapshot (undo, rewrites); the prompt shows blank
464
    /// markers until the next snapshot.
465
    pub(crate) fn drop_manifest(&self) {
466
        self.manifest_cache.take();
467
        self.listing_cache.take();
468
        let _ = fs::remove_file(self.manifest_path());
469
    }
470
471
    /// The manifest, with whether it records a conflict and uncommitted
472
    /// work; parsed once while the file stays the same one.
473
    pub(crate) fn read_manifest(&self) -> Result<Option<(bool, bool, std::sync::Arc<Manifest>)>> {
474
        let path = self.manifest_path();
475
        let id = match fs::metadata(&path) {
476
            Ok(m) => {
477
                #[cfg(unix)]
478
                let ino = std::os::unix::fs::MetadataExt::ino(&m);
479
                #[cfg(not(unix))]
480
                let ino = 0;
481
                (m.len(), mtime_ns(&m), ino)
482
            }
483
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
484
            Err(e) => return Err(e.into()),
485
        };
486
        if let Some((cached_id, m)) = &*self.manifest_cache.borrow() {
487
            if *cached_id == id {
488
                return Ok(Some(m.clone()));
489
            }
490
        }
491
        let Some((c, u, m)) = self.parse_manifest(&path)? else {
492
            return Ok(None);
493
        };
494
        let m = (c, u, std::sync::Arc::new(m));
495
        *self.manifest_cache.borrow_mut() = Some((id, m.clone()));
496
        Ok(Some(m))
497
    }
498
499
    fn parse_manifest(&self, path: &std::path::Path) -> Result<Option<(bool, bool, Manifest)>> {
500
        let buf = match fs::read(path) {
501
            Ok(b) => b,
502
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
503
            Err(e) => return Err(e.into()),
504
        };
505
        Ok(decode_manifest(&buf))
506
    }
507
508
    /// Whether the working copy is certainly clean, known from the manifest
509
    /// alone, without loading any history (spec §12.4): the last snapshot
510
    /// or commit found no uncommitted work and no conflict, there are no
511
    /// subrepos (whose state the manifest does not hold), and no file was
512
    /// added, removed or changed since. An entry inside the racy window,
513
    /// where an equal size and time do not prove equal content, is checked
514
    /// by hashing the file. `false` means only that a snapshot must decide.
515
    pub fn clean_by_manifest(&self) -> Result<bool> {
516
        let _t = crate::timing::phase("status: check the manifest");
517
        // Why a snapshot must decide, with timings on.
518
        let not = |why: &str| {
519
            if crate::timing::enabled() {
520
                eprintln!("timing status: not clean by the manifest: {why}");
521
            }
522
            Ok(false)
523
        };
524
        let Some((conflicted, uncommitted, m)) = self.read_manifest()? else {
525
            return not("no manifest");
526
        };
527
        if conflicted || uncommitted || self.root.join(".oxymodules").exists() {
528
            return not("conflicted, uncommitted or subrepos");
529
        }
530
        if self.disk_differs(&m, true)? {
531
            return not("a file differs");
532
        }
533
        Ok(true)
534
    }
535
536
    /// A manifest entry written within the racy window whose file no
537
    /// longer matches it. Such entries are hashed, in parallel (a checkout
538
    /// just wrote them all).
539
    fn racy_change(&self, m: &Manifest) -> Option<String> {
540
        use rayon::prelude::*;
541
        let racy: Vec<(&String, &ManifestEntry)> = m
542
            .entries
543
            .iter()
544
            .filter(|(_, e)| e.mtime_ns + 2_000_000_000 >= m.written_ns)
545
            .collect();
546
        let root = &self.root;
547
        racy.par_iter()
548
            .find_any(|(rel, e)| {
549
                let path = root.join(rel.as_str());
550
                let same = match fs::symlink_metadata(&path) {
551
                    Ok(md) if md.file_type().is_symlink() => fs::read_link(&path).is_ok_and(|t| {
552
                        *blake3::hash(t.to_string_lossy().as_bytes()).as_bytes() == e.hash
553
                    }),
554
                    Ok(md) if md.is_file() => {
555
                        md.len() == e.size
556
                            && fs::read(&path).is_ok_and(|b| *blake3::hash(&b).as_bytes() == e.hash)
557
                    }
558
                    _ => false,
559
                };
560
                !same
561
            })
562
            .map(|(rel, _)| rel.to_string())
563
    }
564
565
    /// The status lines of the last snapshot, when the working copy is as
566
    /// that snapshot left it: the cache it wrote names the working-copy
567
    /// change and the manifest it recorded, and every file still matches
568
    /// that manifest. `None` when a snapshot must decide (no cache, a file
569
    /// changed, conflicts or subrepos). An empty list is a clean working
570
    /// copy.
571
    pub fn status_by_manifest(&self) -> Result<Option<Vec<PathStatus>>> {
572
        // A listing left by an earlier check describes the files as they
573
        // were then; this check makes its own.
574
        self.listing_cache.take();
575
        let Some((conflicted, uncommitted, m)) = self.read_manifest()? else {
576
            return Ok(None);
577
        };
578
        if !uncommitted {
579
            return Ok(self.clean_by_manifest()?.then(Vec::new));
580
        }
581
        let _t = crate::timing::phase("status: by the status cache");
582
        if conflicted || self.root.join(".oxymodules").exists() {
583
            return Ok(None);
584
        }
585
        let Some((wc, stamp, statuses)) = fs::read(self.status_cache_path())
586
            .ok()
587
            .and_then(|b| decode_status_cache(&b))
588
        else {
589
            return Ok(None);
590
        };
591
        let now = self.view()?.workspaces.get(&self.workspace).copied();
592
        if now != Some(wc) || self.manifest_stamp() != Some(stamp) {
593
            return Ok(None);
594
        }
595
        if self.disk_differs(&m, true)? {
596
            return Ok(None);
597
        }
598
        // Test builds check the cache against a snapshot of the files.
599
        #[cfg(test)]
600
        {
601
            let snap = self.snapshot_status("status cache check")?;
602
            let key = |v: &[PathStatus]| {
603
                let mut k: Vec<(String, u8)> = v
604
                    .iter()
605
                    .map(|p| (p.path.clone(), status_byte(p.status)))
606
                    .collect();
607
                k.sort();
608
                k
609
            };
610
            assert_eq!(
611
                key(&statuses),
612
                key(&snap.statuses),
613
                "status cache disagrees with a snapshot"
614
            );
615
        }
616
        Ok(Some(statuses))
617
    }
618
619
    fn status_cache_path(&self) -> PathBuf {
620
        self.manifest_path().with_file_name("status")
621
    }
622
623
    /// The manifest file's checksum, which names its content.
624
    fn manifest_stamp(&self) -> Option<[u8; 32]> {
625
        use std::io::Read;
626
        let mut head = [0u8; MANIFEST_SUM.end];
627
        fs::File::open(self.manifest_path())
628
            .and_then(|mut f| f.read_exact(&mut head))
629
            .ok()?;
630
        head[MANIFEST_SUM].try_into().ok()
631
    }
632
633
    /// Record `statuses` as the status of working-copy change `wc` against
634
    /// the manifest as it is now; with no uncommitted work there is nothing
635
    /// to record, and the cache goes.
636
    pub(crate) fn write_status_cache(&self, wc: Option<&ChangeHash>, statuses: &[PathStatus]) {
637
        let path = self.status_cache_path();
638
        let (Some(wc), Some(stamp)) = (wc, self.manifest_stamp()) else {
639
            let _ = fs::remove_file(&path);
640
            return;
641
        };
642
        let _ = write_cache(&path, &encode_status_cache(wc, &stamp, statuses));
643
    }
644
645
    /// Whether the working copy differs from the last manifest. Without a
646
    /// manifest the answer is `None`.
647
    pub fn quick_dirty(&self) -> Result<Option<bool>> {
648
        self.quick_dirty_keeping(false)
649
    }
650
651
    /// `quick_dirty`; with `keep`, the listing it made is left for the
652
    /// next walk of the working copy.
653
    fn quick_dirty_keeping(&self, keep: bool) -> Result<Option<bool>> {
654
        let Some((_, uncommitted, manifest)) = self.read_manifest()? else {
655
            return Ok(None);
656
        };
657
        if uncommitted {
658
            return Ok(Some(true));
659
        }
660
        Ok(Some(self.disk_differs(&manifest, keep)?))
661
    }
662
663
    /// Whether the working copy differs from `manifest`: a file added,
664
    /// gone or changed. With `keep`, the listing made is left for the next
665
    /// walk of the working copy when it does.
666
    fn disk_differs(&self, manifest: &Manifest, keep: bool) -> Result<bool> {
667
        // A file written within the racy window can change without its size
668
        // or time moving (a coarse clock): those entries are hashed. One
669
        // that changed still lets the directory check below hand its stats
670
        // to the snapshot that follows.
671
        let racy = self.racy_change(manifest).is_some();
672
        if let Some(differs) = self.disk_differs_by_dirs_keeping(manifest, keep, racy) {
673
            return Ok(differs || racy);
674
        }
675
        if racy {
676
            return Ok(true);
677
        }
678
        self.disk_differs_listing(manifest, keep)
679
    }
680
681
    /// [`Repo::disk_differs`] without listing the tree, when the manifest
682
    /// knows its directories: a directory's time moves when an entry is
683
    /// added, removed or renamed in it, so with every directory's time as
684
    /// recorded (and none within the racy window) the files are the
685
    /// manifest's, and each is checked by its stat. `None` when a
686
    /// directory changed or the manifest has none: the tree must be listed.
687
    #[cfg(test)]
688
    pub(crate) fn disk_differs_by_dirs(&self, manifest: &Manifest) -> Option<bool> {
689
        self.disk_differs_by_dirs_keeping(manifest, false, false)
690
    }
691
692
    /// [`Repo::disk_differs_by_dirs`]; with `keep`, when a file differs
693
    /// (or `racy` says one does), the stats taken become the listing of the
694
    /// snapshot that follows: no directory's entries changed, so the
695
    /// manifest's files are the tree's.
696
    fn disk_differs_by_dirs_keeping(
697
        &self,
698
        manifest: &Manifest,
699
        keep: bool,
700
        racy: bool,
701
    ) -> Option<bool> {
702
        use rayon::prelude::*;
703
        if manifest.dirs.is_empty() || !self.config.sparse_paths.is_empty() {
704
            return None;
705
        }
706
        let _t = crate::timing::phase("status: directories and files by stat");
707
        let root = &self.root;
708
        let dirs_same = manifest.dirs.par_iter().all(|(rel, t)| {
709
            *t + 2_000_000_000 < manifest.written_ns
710
                && fs::metadata(root.join(rel)).is_ok_and(|m| m.is_dir() && mtime_ns(&m) == *t)
711
        });
712
        if !dirs_same {
713
            return None;
714
        }
715
        // Each tracked path as it is now: a file's stat, a symlink's target.
716
        enum Now {
717
            File(PathBuf, fs::Metadata),
718
            Link(Vec<u8>),
719
        }
720
        let differs_from = |me: &ManifestEntry, path: &Path, now: &Now| match now {
721
            Now::Link(t) => *blake3::hash(t).as_bytes() != me.hash,
722
            Now::File(_, m) => {
723
                m.len() != me.size
724
                    || super::is_executable(m) != me.exec
725
                    || (mtime_ns(m) != me.mtime_ns
726
                        && !fs::read(path).is_ok_and(|b| *blake3::hash(&b).as_bytes() == me.hash))
727
            }
728
        };
729
        let stat = |rel: &str| -> Option<Now> {
730
            let path = root.join(rel);
731
            let m = fs::symlink_metadata(&path).ok()?;
732
            if m.file_type().is_symlink() {
733
                let t = fs::read_link(&path).ok()?;
734
                Some(Now::Link(t.to_string_lossy().as_bytes().to_vec()))
735
            } else if m.is_file() {
736
                Some(Now::File(path, m))
737
            } else {
738
                None
739
            }
740
        };
741
        let differs = if !keep {
742
            manifest
743
                .entries
744
                .par_iter()
745
                .any(|(rel, me)| match stat(rel) {
746
                    Some(now) => differs_from(me, &root.join(rel.as_str()), &now),
747
                    None => true,
748
                })
749
        } else {
750
            let now: Vec<(&String, Option<Now>)> = manifest
751
                .entries
752
                .par_iter()
753
                .map(|(rel, _)| (rel, stat(rel)))
754
                .collect();
755
            // A path gone or no longer a file: its directory moved, unless
756
            // within a clock tick; list the tree to be sure.
757
            if now.iter().any(|(_, n)| n.is_none()) {
758
                return None;
759
            }
760
            let differs = now.par_iter().any(|(rel, n)| {
761
                let me = &manifest.entries[*rel];
762
                differs_from(me, &root.join(rel.as_str()), n.as_ref().unwrap())
763
            });
764
            if differs || racy {
765
                let mut listing = super::walk::Listing {
766
                    dirs: manifest.dirs.clone(),
767
                    nested: manifest.nested.iter().map(|n| root.join(n)).collect(),
768
                    ..Default::default()
769
                };
770
                for (rel, n) in now {
771
                    match n.unwrap() {
772
                        Now::File(path, m) => listing.files.push((rel.clone(), path, m)),
773
                        Now::Link(t) => listing.symlinks.push((rel.clone(), t)),
774
                    }
775
                }
776
                *self.listing_cache.borrow_mut() = Some(listing);
777
            }
778
            differs
779
        };
780
        if !differs {
781
            // Nested repositories the manifest has no entry for are not
782
            // subrepos: nothing in them is tracked (oxygen#43).
783
            *self.untracked_nested.borrow_mut() = manifest
784
                .nested
785
                .iter()
786
                .filter(|rel| !manifest.entries.contains_key(*rel))
787
                .cloned()
788
                .collect();
789
        }
790
        Some(differs)
791
    }
792
793
    /// [`Repo::disk_differs`] by listing the tree.
794
    fn disk_differs_listing(&self, manifest: &Manifest, keep: bool) -> Result<bool> {
795
        use rayon::prelude::*;
796
        let sparse = &self.config.sparse_paths;
797
        let in_scope = |p: &str| {
798
            sparse.is_empty()
799
                || sparse
800
                    .iter()
801
                    .any(|s| p == s || p.starts_with(&format!("{s}/")))
802
        };
803
        // A working copy that cannot be listed counts as changed.
804
        // Known files are not matched against the ignore rules: with no
805
        // uncommitted work (the clean check), the manifest's files are the
806
        // base's, and a prompt's answer is the same either way.
807
        let known = |p: &str| manifest.entries.contains_key(p);
808
        let Ok(listing) = super::walk::list_knowing(&self.root, &in_scope, &known) else {
809
            return Ok(true);
810
        };
811
        let differs = || -> Result<bool> {
812
            let links_differ = listing.symlinks.iter().any(|(rel, target)| {
813
                manifest
814
                    .entries
815
                    .get(rel)
816
                    .is_none_or(|me| *blake3::hash(target).as_bytes() != me.hash)
817
            });
818
            if links_differ {
819
                return Ok(true);
820
            }
821
            // Each file is checked on its own, in parallel, stopping at the
822
            // first difference; an unreadable one counts as different.
823
            let files_differ = listing.files.par_iter().any(|(rel, path, m)| {
824
                manifest.entries.get(rel).is_none_or(|me| {
825
                    m.len() != me.size
826
                        || super::is_executable(m) != me.exec
827
                        || (mtime_ns(m) != me.mtime_ns
828
                            && !fs::read(path)
829
                                .is_ok_and(|b| *blake3::hash(&b).as_bytes() == me.hash))
830
                })
831
            });
832
            if files_differ {
833
                return Ok(true);
834
            }
835
            let seen = listing.files.len() + listing.symlinks.len();
836
            if seen == manifest.entries.len() {
837
                return Ok(false);
838
            }
839
            // Manifest entries the walk skipped: tracked files that ignore
840
            // rules hide (Linux tracks some its own .gitignore names). Found
841
            // by merging the two sorted lists; they count as present when
842
            // still on disk and unchanged, checked on every core.
843
            let mut listed: Vec<&str> = listing
844
                .files
845
                .iter()
846
                .map(|(r, _, _)| r.as_str())
847
                .chain(listing.symlinks.iter().map(|(r, _)| r.as_str()))
848
                .collect();
849
            listed.sort_unstable();
850
            let mut at = listed.iter().peekable();
851
            let skipped: Vec<(&String, &ManifestEntry)> = manifest
852
                .entries
853
                .iter()
854
                .filter(|(rel, _)| {
855
                    while at.next_if(|l| **l < rel.as_str()).is_some() {}
856
                    at.peek().is_none_or(|l| **l != rel.as_str())
857
                })
858
                .collect();
859
            let root = &self.root;
860
            Ok(skipped.par_iter().any(|(rel, me)| {
861
                let path = root.join(rel.as_str());
862
                let Ok(m) = fs::symlink_metadata(&path) else {
863
                    return true;
864
                };
865
                !m.file_type().is_symlink()
866
                    && (m.len() != me.size
867
                        || super::is_executable(&m) != me.exec
868
                        || (mtime_ns(&m) != me.mtime_ns
869
                            && !fs::read(&path)
870
                                .is_ok_and(|b| *blake3::hash(&b).as_bytes() == me.hash)))
871
            }))
872
        };
873
        let dirty = differs()?;
874
        if !dirty {
875
            // Nested repositories the manifest has no entry for are not
876
            // subrepos: nothing in them is tracked (oxygen#43).
877
            *self.untracked_nested.borrow_mut() = listing
878
                .nested
879
                .iter()
880
                .map(|d| self.rel_path(d))
881
                .filter(|rel| !manifest.entries.contains_key(rel))
882
                .collect();
883
        }
884
        if dirty && keep {
885
            *self.listing_cache.borrow_mut() = Some(listing);
886
        }
887
        Ok(dirty)
888
    }
889
890
    /// Prompt information without recording anything.
891
    pub fn quick_status(&self) -> Result<PromptInfo> {
892
        let view = self.view()?;
893
        let bookmark = self.config.bookmark.clone();
894
        let heads = self.heads_of(&view, &bookmark)?;
895
        let wc_hash = view.workspaces.get(&self.workspace).copied();
896
        let change_id = match wc_hash {
897
            Some(h) => self.store.get_change_meta(&h)?.change_id.short(8),
898
            None => String::new(),
899
        };
900
        // Conflictedness was recorded by the last snapshot; without a
901
        // manifest (never snapshotted) both flags are unknown and shown clear.
902
        let manifest = self.read_manifest()?;
903
        let conflicted = manifest.as_ref().map(|(c, _, _)| *c).unwrap_or(false);
904
        let dirty = self.quick_dirty()?.unwrap_or(false);
905
        let (ahead, behind) = match view.remotes.get("origin").and_then(|b| b.get(&bookmark)) {
906
            Some(st) => {
907
                let remote_heads = self.store.get_state(st)?.heads;
908
                let ahead = self.negotiate(&remote_heads, &heads).map(|v| v.len()).ok();
909
                let behind = self.negotiate(&heads, &remote_heads).map(|v| v.len()).ok();
910
                (ahead, behind)
911
            }
912
            None => (None, None),
913
        };
914
        Ok(PromptInfo {
915
            bookmark,
916
            change_id,
917
            heads: heads.len(),
918
            dirty,
919
            conflicted,
920
            ahead,
921
            behind,
922
        })
923
    }
924
}
925
926
#[cfg(test)]
927
mod tests {
928
    use super::*;
929
930
    #[test]
931
    fn placeholders_and_glyphs() {
932
        let clean = PromptInfo {
933
            bookmark: "main".into(),
934
            change_id: "658990aa".into(),
935
            heads: 1,
936
            dirty: false,
937
            conflicted: false,
938
            ahead: Some(0),
939
            behind: None,
940
        };
941
        assert_eq!(clean.format(DEFAULT_PROMPT_FORMAT), "main 658990aa");
942
        assert_eq!(clean.format(GLYPH_PROMPT_FORMAT), "⚛ main 658990aa ✔");
943
        let busy = PromptInfo {
944
            dirty: true,
945
            ahead: Some(2),
946
            behind: Some(3),
947
            ..clean.clone()
948
        };
949
        assert_eq!(busy.format(DEFAULT_PROMPT_FORMAT), "main 658990aa*+2-3");
950
        assert_eq!(busy.format(GLYPH_PROMPT_FORMAT), "⚛ main 658990aa ✎↑2↓3");
951
        let bad = PromptInfo {
952
            conflicted: true,
953
            ..busy.clone()
954
        };
955
        assert_eq!(bad.format("%s%x%d %h %a/%B %%"), "‼!* 1 2/3 %");
956
        assert_eq!(bad.state_color(), 31);
957
        assert_eq!(
958
            busy.format_colored("%b", ("\\[", "\\]")),
959
            "\\[\x1b[33m\\]main\\[\x1b[0m\\]"
960
        );
961
        assert_eq!(clean.format_colored("%b", ("", "")), "\x1b[36mmain\x1b[0m");
962
        assert_eq!(clean.format("%q"), "%q");
963
    }
964
}