OXYGENHUB
# 33472ccc08cc oxygen / crates / oxy-core / src / repo / prompt.rs
36.9 KiB · Rust · last changed oxy log shows the working copy as last recorded, and takes milliseconds (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
    /// Whether the working copy was conflicted when last recorded (the
474
    /// manifest's flag), without looking at the files.
475
    pub fn recorded_conflicted(&self) -> Result<bool> {
476
        Ok(self.read_manifest()?.is_some_and(|(c, _, _)| c))
477
    }
478
479
    pub(crate) fn read_manifest(&self) -> Result<Option<(bool, bool, std::sync::Arc<Manifest>)>> {
480
        let path = self.manifest_path();
481
        let id = match fs::metadata(&path) {
482
            Ok(m) => {
483
                #[cfg(unix)]
484
                let ino = std::os::unix::fs::MetadataExt::ino(&m);
485
                #[cfg(not(unix))]
486
                let ino = 0;
487
                (m.len(), mtime_ns(&m), ino)
488
            }
489
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
490
            Err(e) => return Err(e.into()),
491
        };
492
        if let Some((cached_id, m)) = &*self.manifest_cache.borrow() {
493
            if *cached_id == id {
494
                return Ok(Some(m.clone()));
495
            }
496
        }
497
        let Some((c, u, m)) = self.parse_manifest(&path)? else {
498
            return Ok(None);
499
        };
500
        let m = (c, u, std::sync::Arc::new(m));
501
        *self.manifest_cache.borrow_mut() = Some((id, m.clone()));
502
        Ok(Some(m))
503
    }
504
505
    fn parse_manifest(&self, path: &std::path::Path) -> Result<Option<(bool, bool, Manifest)>> {
506
        let buf = match fs::read(path) {
507
            Ok(b) => b,
508
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
509
            Err(e) => return Err(e.into()),
510
        };
511
        Ok(decode_manifest(&buf))
512
    }
513
514
    /// Whether the working copy is certainly clean, known from the manifest
515
    /// alone, without loading any history (spec §12.4): the last snapshot
516
    /// or commit found no uncommitted work and no conflict, there are no
517
    /// subrepos (whose state the manifest does not hold), and no file was
518
    /// added, removed or changed since. An entry inside the racy window,
519
    /// where an equal size and time do not prove equal content, is checked
520
    /// by hashing the file. `false` means only that a snapshot must decide.
521
    pub fn clean_by_manifest(&self) -> Result<bool> {
522
        let _t = crate::timing::phase("status: check the manifest");
523
        // Why a snapshot must decide, with timings on.
524
        let not = |why: &str| {
525
            if crate::timing::enabled() {
526
                eprintln!("timing status: not clean by the manifest: {why}");
527
            }
528
            Ok(false)
529
        };
530
        let Some((conflicted, uncommitted, m)) = self.read_manifest()? else {
531
            return not("no manifest");
532
        };
533
        if conflicted || uncommitted || self.root.join(".oxymodules").exists() {
534
            return not("conflicted, uncommitted or subrepos");
535
        }
536
        if self.disk_differs(&m, true)? {
537
            return not("a file differs");
538
        }
539
        Ok(true)
540
    }
541
542
    /// A manifest entry written within the racy window whose file no
543
    /// longer matches it. Such entries are hashed, in parallel (a checkout
544
    /// just wrote them all).
545
    fn racy_change(&self, m: &Manifest) -> Option<String> {
546
        use rayon::prelude::*;
547
        let racy: Vec<(&String, &ManifestEntry)> = m
548
            .entries
549
            .iter()
550
            .filter(|(_, e)| e.mtime_ns + 2_000_000_000 >= m.written_ns)
551
            .collect();
552
        let root = &self.root;
553
        racy.par_iter()
554
            .find_any(|(rel, e)| {
555
                let path = root.join(rel.as_str());
556
                let same = match fs::symlink_metadata(&path) {
557
                    Ok(md) if md.file_type().is_symlink() => fs::read_link(&path).is_ok_and(|t| {
558
                        *blake3::hash(t.to_string_lossy().as_bytes()).as_bytes() == e.hash
559
                    }),
560
                    Ok(md) if md.is_file() => {
561
                        md.len() == e.size
562
                            && fs::read(&path).is_ok_and(|b| *blake3::hash(&b).as_bytes() == e.hash)
563
                    }
564
                    _ => false,
565
                };
566
                !same
567
            })
568
            .map(|(rel, _)| rel.to_string())
569
    }
570
571
    /// The status lines of the last snapshot, when the working copy is as
572
    /// that snapshot left it: the cache it wrote names the working-copy
573
    /// change and the manifest it recorded, and every file still matches
574
    /// that manifest. `None` when a snapshot must decide (no cache, a file
575
    /// changed, conflicts or subrepos). An empty list is a clean working
576
    /// copy.
577
    pub fn status_by_manifest(&self) -> Result<Option<Vec<PathStatus>>> {
578
        // A listing left by an earlier check describes the files as they
579
        // were then; this check makes its own.
580
        self.listing_cache.take();
581
        let Some((conflicted, uncommitted, m)) = self.read_manifest()? else {
582
            return Ok(None);
583
        };
584
        if !uncommitted {
585
            return Ok(self.clean_by_manifest()?.then(Vec::new));
586
        }
587
        let _t = crate::timing::phase("status: by the status cache");
588
        if conflicted || self.root.join(".oxymodules").exists() {
589
            return Ok(None);
590
        }
591
        let Some((wc, stamp, statuses)) = fs::read(self.status_cache_path())
592
            .ok()
593
            .and_then(|b| decode_status_cache(&b))
594
        else {
595
            return Ok(None);
596
        };
597
        let now = self.view()?.workspaces.get(&self.workspace).copied();
598
        if now != Some(wc) || self.manifest_stamp() != Some(stamp) {
599
            return Ok(None);
600
        }
601
        if self.disk_differs(&m, true)? {
602
            return Ok(None);
603
        }
604
        // Test builds check the cache against a snapshot of the files.
605
        #[cfg(test)]
606
        {
607
            let snap = self.snapshot_status("status cache check")?;
608
            let key = |v: &[PathStatus]| {
609
                let mut k: Vec<(String, u8)> = v
610
                    .iter()
611
                    .map(|p| (p.path.clone(), status_byte(p.status)))
612
                    .collect();
613
                k.sort();
614
                k
615
            };
616
            assert_eq!(
617
                key(&statuses),
618
                key(&snap.statuses),
619
                "status cache disagrees with a snapshot"
620
            );
621
        }
622
        Ok(Some(statuses))
623
    }
624
625
    fn status_cache_path(&self) -> PathBuf {
626
        self.manifest_path().with_file_name("status")
627
    }
628
629
    /// The manifest file's checksum, which names its content.
630
    fn manifest_stamp(&self) -> Option<[u8; 32]> {
631
        use std::io::Read;
632
        let mut head = [0u8; MANIFEST_SUM.end];
633
        fs::File::open(self.manifest_path())
634
            .and_then(|mut f| f.read_exact(&mut head))
635
            .ok()?;
636
        head[MANIFEST_SUM].try_into().ok()
637
    }
638
639
    /// Record `statuses` as the status of working-copy change `wc` against
640
    /// the manifest as it is now; with no uncommitted work there is nothing
641
    /// to record, and the cache goes.
642
    pub(crate) fn write_status_cache(&self, wc: Option<&ChangeHash>, statuses: &[PathStatus]) {
643
        let path = self.status_cache_path();
644
        let (Some(wc), Some(stamp)) = (wc, self.manifest_stamp()) else {
645
            let _ = fs::remove_file(&path);
646
            return;
647
        };
648
        let _ = write_cache(&path, &encode_status_cache(wc, &stamp, statuses));
649
    }
650
651
    /// Whether the working copy differs from the last manifest. Without a
652
    /// manifest the answer is `None`.
653
    pub fn quick_dirty(&self) -> Result<Option<bool>> {
654
        self.quick_dirty_keeping(false)
655
    }
656
657
    /// `quick_dirty`; with `keep`, the listing it made is left for the
658
    /// next walk of the working copy.
659
    fn quick_dirty_keeping(&self, keep: bool) -> Result<Option<bool>> {
660
        let Some((_, uncommitted, manifest)) = self.read_manifest()? else {
661
            return Ok(None);
662
        };
663
        if uncommitted {
664
            return Ok(Some(true));
665
        }
666
        Ok(Some(self.disk_differs(&manifest, keep)?))
667
    }
668
669
    /// Whether the working copy differs from `manifest`: a file added,
670
    /// gone or changed. With `keep`, the listing made is left for the next
671
    /// walk of the working copy when it does.
672
    fn disk_differs(&self, manifest: &Manifest, keep: bool) -> Result<bool> {
673
        // A file written within the racy window can change without its size
674
        // or time moving (a coarse clock): those entries are hashed. One
675
        // that changed still lets the directory check below hand its stats
676
        // to the snapshot that follows.
677
        let racy = self.racy_change(manifest).is_some();
678
        if let Some(differs) = self.disk_differs_by_dirs_keeping(manifest, keep, racy) {
679
            return Ok(differs || racy);
680
        }
681
        if racy {
682
            return Ok(true);
683
        }
684
        self.disk_differs_listing(manifest, keep)
685
    }
686
687
    /// [`Repo::disk_differs`] without listing the tree, when the manifest
688
    /// knows its directories: a directory's time moves when an entry is
689
    /// added, removed or renamed in it, so with every directory's time as
690
    /// recorded (and none within the racy window) the files are the
691
    /// manifest's, and each is checked by its stat. `None` when a
692
    /// directory changed or the manifest has none: the tree must be listed.
693
    #[cfg(test)]
694
    pub(crate) fn disk_differs_by_dirs(&self, manifest: &Manifest) -> Option<bool> {
695
        self.disk_differs_by_dirs_keeping(manifest, false, false)
696
    }
697
698
    /// [`Repo::disk_differs_by_dirs`]; with `keep`, when a file differs
699
    /// (or `racy` says one does), the stats taken become the listing of the
700
    /// snapshot that follows: no directory's entries changed, so the
701
    /// manifest's files are the tree's.
702
    fn disk_differs_by_dirs_keeping(
703
        &self,
704
        manifest: &Manifest,
705
        keep: bool,
706
        racy: bool,
707
    ) -> Option<bool> {
708
        use rayon::prelude::*;
709
        if manifest.dirs.is_empty() || !self.config.sparse_paths.is_empty() {
710
            return None;
711
        }
712
        let _t = crate::timing::phase("status: directories and files by stat");
713
        let root = &self.root;
714
        let dirs_same = manifest.dirs.par_iter().all(|(rel, t)| {
715
            *t + 2_000_000_000 < manifest.written_ns
716
                && fs::metadata(root.join(rel)).is_ok_and(|m| m.is_dir() && mtime_ns(&m) == *t)
717
        });
718
        if !dirs_same {
719
            return None;
720
        }
721
        // Each tracked path as it is now: a file's stat, a symlink's target.
722
        enum Now {
723
            File(PathBuf, fs::Metadata),
724
            Link(Vec<u8>),
725
        }
726
        let differs_from = |me: &ManifestEntry, path: &Path, now: &Now| match now {
727
            Now::Link(t) => *blake3::hash(t).as_bytes() != me.hash,
728
            Now::File(_, m) => {
729
                m.len() != me.size
730
                    || super::is_executable(m) != me.exec
731
                    || (mtime_ns(m) != me.mtime_ns
732
                        && !fs::read(path).is_ok_and(|b| *blake3::hash(&b).as_bytes() == me.hash))
733
            }
734
        };
735
        let stat = |rel: &str| -> Option<Now> {
736
            let path = root.join(rel);
737
            let m = fs::symlink_metadata(&path).ok()?;
738
            if m.file_type().is_symlink() {
739
                let t = fs::read_link(&path).ok()?;
740
                Some(Now::Link(t.to_string_lossy().as_bytes().to_vec()))
741
            } else if m.is_file() {
742
                Some(Now::File(path, m))
743
            } else {
744
                None
745
            }
746
        };
747
        let differs = if !keep {
748
            manifest
749
                .entries
750
                .par_iter()
751
                .any(|(rel, me)| match stat(rel) {
752
                    Some(now) => differs_from(me, &root.join(rel.as_str()), &now),
753
                    None => true,
754
                })
755
        } else {
756
            let now: Vec<(&String, Option<Now>)> = manifest
757
                .entries
758
                .par_iter()
759
                .map(|(rel, _)| (rel, stat(rel)))
760
                .collect();
761
            // A path gone or no longer a file: its directory moved, unless
762
            // within a clock tick; list the tree to be sure.
763
            if now.iter().any(|(_, n)| n.is_none()) {
764
                return None;
765
            }
766
            let differs = now.par_iter().any(|(rel, n)| {
767
                let me = &manifest.entries[*rel];
768
                differs_from(me, &root.join(rel.as_str()), n.as_ref().unwrap())
769
            });
770
            if differs || racy {
771
                let mut listing = super::walk::Listing {
772
                    dirs: manifest.dirs.clone(),
773
                    nested: manifest.nested.iter().map(|n| root.join(n)).collect(),
774
                    ..Default::default()
775
                };
776
                for (rel, n) in now {
777
                    match n.unwrap() {
778
                        Now::File(path, m) => listing.files.push((rel.clone(), path, m)),
779
                        Now::Link(t) => listing.symlinks.push((rel.clone(), t)),
780
                    }
781
                }
782
                *self.listing_cache.borrow_mut() = Some(listing);
783
            }
784
            differs
785
        };
786
        if !differs {
787
            // Nested repositories the manifest has no entry for are not
788
            // subrepos: nothing in them is tracked (oxygen#43).
789
            *self.untracked_nested.borrow_mut() = manifest
790
                .nested
791
                .iter()
792
                .filter(|rel| !manifest.entries.contains_key(*rel))
793
                .cloned()
794
                .collect();
795
        }
796
        Some(differs)
797
    }
798
799
    /// [`Repo::disk_differs`] by listing the tree.
800
    fn disk_differs_listing(&self, manifest: &Manifest, keep: bool) -> Result<bool> {
801
        use rayon::prelude::*;
802
        let sparse = &self.config.sparse_paths;
803
        let in_scope = |p: &str| {
804
            sparse.is_empty()
805
                || sparse
806
                    .iter()
807
                    .any(|s| p == s || p.starts_with(&format!("{s}/")))
808
        };
809
        // A working copy that cannot be listed counts as changed.
810
        // Known files are not matched against the ignore rules: with no
811
        // uncommitted work (the clean check), the manifest's files are the
812
        // base's, and a prompt's answer is the same either way.
813
        let known = |p: &str| manifest.entries.contains_key(p);
814
        let Ok(listing) = super::walk::list_knowing(&self.root, &in_scope, &known) else {
815
            return Ok(true);
816
        };
817
        let differs = || -> Result<bool> {
818
            let links_differ = listing.symlinks.iter().any(|(rel, target)| {
819
                manifest
820
                    .entries
821
                    .get(rel)
822
                    .is_none_or(|me| *blake3::hash(target).as_bytes() != me.hash)
823
            });
824
            if links_differ {
825
                return Ok(true);
826
            }
827
            // Each file is checked on its own, in parallel, stopping at the
828
            // first difference; an unreadable one counts as different.
829
            let files_differ = listing.files.par_iter().any(|(rel, path, m)| {
830
                manifest.entries.get(rel).is_none_or(|me| {
831
                    m.len() != me.size
832
                        || super::is_executable(m) != me.exec
833
                        || (mtime_ns(m) != me.mtime_ns
834
                            && !fs::read(path)
835
                                .is_ok_and(|b| *blake3::hash(&b).as_bytes() == me.hash))
836
                })
837
            });
838
            if files_differ {
839
                return Ok(true);
840
            }
841
            let seen = listing.files.len() + listing.symlinks.len();
842
            if seen == manifest.entries.len() {
843
                return Ok(false);
844
            }
845
            // Manifest entries the walk skipped: tracked files that ignore
846
            // rules hide (Linux tracks some its own .gitignore names). Found
847
            // by merging the two sorted lists; they count as present when
848
            // still on disk and unchanged, checked on every core.
849
            let mut listed: Vec<&str> = listing
850
                .files
851
                .iter()
852
                .map(|(r, _, _)| r.as_str())
853
                .chain(listing.symlinks.iter().map(|(r, _)| r.as_str()))
854
                .collect();
855
            listed.sort_unstable();
856
            let mut at = listed.iter().peekable();
857
            let skipped: Vec<(&String, &ManifestEntry)> = manifest
858
                .entries
859
                .iter()
860
                .filter(|(rel, _)| {
861
                    while at.next_if(|l| **l < rel.as_str()).is_some() {}
862
                    at.peek().is_none_or(|l| **l != rel.as_str())
863
                })
864
                .collect();
865
            let root = &self.root;
866
            Ok(skipped.par_iter().any(|(rel, me)| {
867
                let path = root.join(rel.as_str());
868
                let Ok(m) = fs::symlink_metadata(&path) else {
869
                    return true;
870
                };
871
                !m.file_type().is_symlink()
872
                    && (m.len() != me.size
873
                        || super::is_executable(&m) != me.exec
874
                        || (mtime_ns(&m) != me.mtime_ns
875
                            && !fs::read(&path)
876
                                .is_ok_and(|b| *blake3::hash(&b).as_bytes() == me.hash)))
877
            }))
878
        };
879
        let dirty = differs()?;
880
        if !dirty {
881
            // Nested repositories the manifest has no entry for are not
882
            // subrepos: nothing in them is tracked (oxygen#43).
883
            *self.untracked_nested.borrow_mut() = listing
884
                .nested
885
                .iter()
886
                .map(|d| self.rel_path(d))
887
                .filter(|rel| !manifest.entries.contains_key(rel))
888
                .collect();
889
        }
890
        if dirty && keep {
891
            *self.listing_cache.borrow_mut() = Some(listing);
892
        }
893
        Ok(dirty)
894
    }
895
896
    /// Prompt information without recording anything.
897
    pub fn quick_status(&self) -> Result<PromptInfo> {
898
        let view = self.view()?;
899
        let bookmark = self.config.bookmark.clone();
900
        let heads = self.heads_of(&view, &bookmark)?;
901
        let wc_hash = view.workspaces.get(&self.workspace).copied();
902
        let change_id = match wc_hash {
903
            Some(h) => self.store.get_change_meta(&h)?.change_id.short(8),
904
            None => String::new(),
905
        };
906
        // Conflictedness was recorded by the last snapshot; without a
907
        // manifest (never snapshotted) both flags are unknown and shown clear.
908
        let manifest = self.read_manifest()?;
909
        let conflicted = manifest.as_ref().map(|(c, _, _)| *c).unwrap_or(false);
910
        let dirty = self.quick_dirty()?.unwrap_or(false);
911
        let (ahead, behind) = match view.remotes.get("origin").and_then(|b| b.get(&bookmark)) {
912
            Some(st) => {
913
                let remote_heads = self.store.get_state(st)?.heads;
914
                let ahead = self.negotiate(&remote_heads, &heads).map(|v| v.len()).ok();
915
                let behind = self.negotiate(&heads, &remote_heads).map(|v| v.len()).ok();
916
                (ahead, behind)
917
            }
918
            None => (None, None),
919
        };
920
        Ok(PromptInfo {
921
            bookmark,
922
            change_id,
923
            heads: heads.len(),
924
            dirty,
925
            conflicted,
926
            ahead,
927
            behind,
928
        })
929
    }
930
}
931
932
#[cfg(test)]
933
mod tests {
934
    use super::*;
935
936
    #[test]
937
    fn placeholders_and_glyphs() {
938
        let clean = PromptInfo {
939
            bookmark: "main".into(),
940
            change_id: "658990aa".into(),
941
            heads: 1,
942
            dirty: false,
943
            conflicted: false,
944
            ahead: Some(0),
945
            behind: None,
946
        };
947
        assert_eq!(clean.format(DEFAULT_PROMPT_FORMAT), "main 658990aa");
948
        assert_eq!(clean.format(GLYPH_PROMPT_FORMAT), "⚛ main 658990aa ✔");
949
        let busy = PromptInfo {
950
            dirty: true,
951
            ahead: Some(2),
952
            behind: Some(3),
953
            ..clean.clone()
954
        };
955
        assert_eq!(busy.format(DEFAULT_PROMPT_FORMAT), "main 658990aa*+2-3");
956
        assert_eq!(busy.format(GLYPH_PROMPT_FORMAT), "⚛ main 658990aa ✎↑2↓3");
957
        let bad = PromptInfo {
958
            conflicted: true,
959
            ..busy.clone()
960
        };
961
        assert_eq!(bad.format("%s%x%d %h %a/%B %%"), "‼!* 1 2/3 %");
962
        assert_eq!(bad.state_color(), 31);
963
        assert_eq!(
964
            busy.format_colored("%b", ("\\[", "\\]")),
965
            "\\[\x1b[33m\\]main\\[\x1b[0m\\]"
966
        );
967
        assert_eq!(clean.format_colored("%b", ("", "")), "\x1b[36mmain\x1b[0m");
968
        assert_eq!(clean.format("%q"), "%q");
969
    }
970
}