OXYGENHUB
# b35df36b7dc5 oxygen / crates / oxy-core / src / repo / prompt.rs
39.4 KiB · Rust · last changed Fetch reports how each bookmark stands against the remote's copy 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
/// A tracked path as it is now: a file's stat, or a symlink's target.
292
enum Tracked {
293
    File(super::walk::Stat),
294
    Link(Vec<u8>),
295
}
296
297
/// The stat of every path in `rels` (relative to `root`; `None` for one
298
/// gone or neither a file nor a symlink), in the same order. Paths are
299
/// grouped by directory and each directory is opened once: a stat relative
300
/// to it resolves one name, where a stat by full path walks every
301
/// component from the root again (most of a clean status's time, in the
302
/// kernel's path lookup, on the Linux tree).
303
fn stat_tracked(root: &Path, rels: &[&String]) -> Vec<Option<Tracked>> {
304
    use rayon::prelude::*;
305
    let mut by_dir: HashMap<&str, Vec<(usize, &str)>> = HashMap::new();
306
    for (i, rel) in rels.iter().enumerate() {
307
        let (dir, name) = rel.rsplit_once('/').unwrap_or(("", rel.as_str()));
308
        by_dir.entry(dir).or_default().push((i, name));
309
    }
310
    let groups: Vec<(&str, Vec<(usize, &str)>)> = by_dir.into_iter().collect();
311
    let found: Vec<(usize, Option<Tracked>)> = groups
312
        .par_iter()
313
        .flat_map_iter(|(dir, names)| {
314
            let handle = fs::File::open(root.join(dir)).ok();
315
            names
316
                .iter()
317
                .map(|(i, name)| {
318
                    let rel = rels[*i];
319
                    let now = match &handle {
320
                        Some(d) => stat_in(d, name, || root.join(rel)),
321
                        None => None,
322
                    };
323
                    (*i, now)
324
                })
325
                .collect::<Vec<_>>()
326
        })
327
        .collect();
328
    let mut out: Vec<Option<Tracked>> = (0..rels.len()).map(|_| None).collect();
329
    for (i, now) in found {
330
        out[i] = now;
331
    }
332
    out
333
}
334
335
/// One entry of the open directory `dir`; `path` builds its full path,
336
/// needed only for a symlink's target.
337
#[cfg(unix)]
338
fn stat_in(dir: &fs::File, name: &str, path: impl Fn() -> PathBuf) -> Option<Tracked> {
339
    use std::os::fd::AsRawFd;
340
    let c = std::ffi::CString::new(name).ok()?;
341
    let mut st: libc::stat = unsafe { std::mem::zeroed() };
342
    // SAFETY: a valid directory descriptor, a NUL-terminated name, and a
343
    // stat buffer of the right type that outlives the call.
344
    let r = unsafe {
345
        libc::fstatat(
346
            dir.as_raw_fd(),
347
            c.as_ptr(),
348
            &mut st,
349
            libc::AT_SYMLINK_NOFOLLOW,
350
        )
351
    };
352
    if r != 0 {
353
        return None;
354
    }
355
    match st.st_mode & libc::S_IFMT {
356
        libc::S_IFREG => Some(Tracked::File(super::walk::Stat {
357
            size: st.st_size as u64,
358
            // As `mtime_ns` reads it: nanoseconds since the epoch, 0 before it.
359
            mtime_ns: if st.st_mtime < 0 {
360
                0
361
            } else {
362
                st.st_mtime as u128 * 1_000_000_000 + st.st_mtime_nsec as u128
363
            },
364
            exec: st.st_mode & 0o111 != 0,
365
        })),
366
        libc::S_IFLNK => {
367
            let t = fs::read_link(path()).ok()?;
368
            Some(Tracked::Link(t.to_string_lossy().as_bytes().to_vec()))
369
        }
370
        _ => None,
371
    }
372
}
373
374
#[cfg(not(unix))]
375
fn stat_in(_dir: &fs::File, _name: &str, path: impl Fn() -> PathBuf) -> Option<Tracked> {
376
    let p = path();
377
    let m = fs::symlink_metadata(&p).ok()?;
378
    if m.file_type().is_symlink() {
379
        let t = fs::read_link(&p).ok()?;
380
        Some(Tracked::Link(t.to_string_lossy().as_bytes().to_vec()))
381
    } else if m.is_file() {
382
        Some(Tracked::File(super::walk::Stat::of(&m)))
383
    } else {
384
        None
385
    }
386
}
387
388
/// The status cache: a magic number, the working-copy change, the
389
/// manifest checksum, then each status line (a status byte and a path).
390
const STATUS_MAGIC: &[u8; 8] = b"oxystat1";
391
392
fn status_byte(s: ChangeStatus) -> u8 {
393
    match s {
394
        ChangeStatus::Added => 0,
395
        ChangeStatus::Modified => 1,
396
        ChangeStatus::Removed => 2,
397
        ChangeStatus::Renamed => 3,
398
        ChangeStatus::ModeChanged => 4,
399
        ChangeStatus::ConflictEdited => 5,
400
        ChangeStatus::Resolved => 6,
401
    }
402
}
403
404
fn encode_status_cache(wc: &ChangeHash, stamp: &[u8; 32], statuses: &[PathStatus]) -> Vec<u8> {
405
    let mut out = Vec::with_capacity(80 + statuses.len() * 40);
406
    out.extend_from_slice(STATUS_MAGIC);
407
    out.extend_from_slice(&wc.0);
408
    out.extend_from_slice(stamp);
409
    out.extend_from_slice(&(statuses.len() as u32).to_le_bytes());
410
    for s in statuses {
411
        out.push(status_byte(s.status));
412
        out.extend_from_slice(&(s.path.len() as u32).to_le_bytes());
413
        out.extend_from_slice(s.path.as_bytes());
414
    }
415
    out
416
}
417
418
fn decode_status_cache(b: &[u8]) -> Option<(ChangeHash, [u8; 32], Vec<PathStatus>)> {
419
    let rest = b.strip_prefix(STATUS_MAGIC)?;
420
    let wc = ObjectRef(rest.get(..32)?.try_into().ok()?);
421
    let stamp: [u8; 32] = rest.get(32..64)?.try_into().ok()?;
422
    let n = u32::from_le_bytes(rest.get(64..68)?.try_into().ok()?) as usize;
423
    let mut at = 68;
424
    let mut out = Vec::with_capacity(n.min(1 << 16));
425
    for _ in 0..n {
426
        let status = match *rest.get(at)? {
427
            0 => ChangeStatus::Added,
428
            1 => ChangeStatus::Modified,
429
            2 => ChangeStatus::Removed,
430
            3 => ChangeStatus::Renamed,
431
            4 => ChangeStatus::ModeChanged,
432
            5 => ChangeStatus::ConflictEdited,
433
            6 => ChangeStatus::Resolved,
434
            _ => return None,
435
        };
436
        let len = u32::from_le_bytes(rest.get(at + 1..at + 5)?.try_into().ok()?) as usize;
437
        let path = std::str::from_utf8(rest.get(at + 5..at + 5 + len)?)
438
            .ok()?
439
            .to_string();
440
        out.push(PathStatus { path, status });
441
        at += 5 + len;
442
    }
443
    (at == rest.len()).then_some((wc, stamp, out))
444
}
445
446
impl Repo {
447
    pub(crate) fn manifest_path(&self) -> PathBuf {
448
        self.oxy
449
            .join("workspaces")
450
            .join(self.workspace.to_hex())
451
            .join("manifest")
452
    }
453
454
    /// Record the working copy as it is now (after a snapshot, commit, or
455
    /// checkout), with header lines saying whether the base state is
456
    /// conflicted and whether the working-copy change holds uncommitted work.
457
    pub(crate) fn write_manifest(&self, conflicted: bool, uncommitted: bool) -> Result<()> {
458
        let entries = self.walk_working_copy()?;
459
        self.write_manifest_entries(conflicted, uncommitted, &entries, &HashMap::new())
460
    }
461
462
    /// Write the manifest from entries already walked; `blobs` names the
463
    /// stored blob of each opaque path so the next walk can skip reading it.
464
    pub(crate) fn write_manifest_entries(
465
        &self,
466
        conflicted: bool,
467
        uncommitted: bool,
468
        entries: &BTreeMap<String, FsEntry>,
469
        blobs: &HashMap<String, ObjectRef>,
470
    ) -> Result<()> {
471
        self.manifest_cache.take();
472
        self.listing_cache.take();
473
        let written = std::time::SystemTime::now()
474
            .duration_since(UNIX_EPOCH)
475
            .map(|d| d.as_nanos())
476
            .unwrap_or(0);
477
        let mut newest_ns: u128 = 0;
478
        let mut rows = entries.iter().map(|(path, e)| {
479
            let (size, mtime_ns) = match e.stat {
480
                Some(known) => known,
481
                None => match fs::symlink_metadata(self.root.join(path)) {
482
                    Ok(m) => (m.len(), mtime_ns(&m)),
483
                    Err(_) => (e.content.len() as u64, 0),
484
                },
485
            };
486
            newest_ns = newest_ns.max(mtime_ns);
487
            let entry = ManifestEntry {
488
                size,
489
                mtime_ns,
490
                hash: e
491
                    .content_hash
492
                    .unwrap_or_else(|| *blake3::hash(&e.content).as_bytes()),
493
                blob: blobs.get(path).copied().or(e.blob),
494
                graph: e.graph_key,
495
                exec: e.exec,
496
            };
497
            (path.as_str(), entry)
498
        });
499
        // The directories of the walk these entries came from, if any.
500
        let (dirs, nested) = self.walked_dirs.take().unwrap_or_default();
501
        let new = encode_manifest(conflicted, uncommitted, written, &dirs, &nested, &mut rows);
502
        drop(rows);
503
        let p = self.manifest_path();
504
        // Leave an unchanged manifest alone when its stamp already trusts
505
        // every entry (none is within the racy window): rewriting it would
506
        // change nothing but the file, which editors watching the tree
507
        // (and subrepos inside it) take as a change.
508
        if let Ok(old) = fs::read(&p) {
509
            let (w, sum) = (MANIFEST_WRITTEN, MANIFEST_SUM);
510
            if old.len() == new.len()
511
                && old[..w.start] == new[..w.start]
512
                && old[sum.end..] == new[sum.end..]
513
            {
514
                let old_written = u128::from_le_bytes(old[w.clone()].try_into().unwrap());
515
                if newest_ns + 2_000_000_000 < old_written {
516
                    return Ok(());
517
                }
518
            }
519
        }
520
        fs::create_dir_all(p.parent().unwrap())?;
521
        write_cache(&p, &new)
522
    }
523
524
    /// Change the header flags, and set the graph key of each path in
525
    /// `keys` (after a commit, the new base's keys of the files it holds as
526
    /// they are on disk).
527
    pub(crate) fn rewrite_manifest(
528
        &self,
529
        conflicted: bool,
530
        uncommitted: bool,
531
        keys: &HashMap<String, [u8; 32]>,
532
    ) -> Result<()> {
533
        self.manifest_cache.take();
534
        self.listing_cache.take();
535
        let p = self.manifest_path();
536
        let Some((_, _, m)) = fs::read(&p).ok().and_then(|b| decode_manifest(&b)) else {
537
            return self.write_manifest(conflicted, uncommitted);
538
        };
539
        let mut rows = m.entries.iter().map(|(path, e)| {
540
            let mut e = e.clone();
541
            if let Some(k) = keys.get(path) {
542
                e.graph = Some(*k);
543
            }
544
            (path.as_str(), e)
545
        });
546
        write_cache(
547
            &p,
548
            &encode_manifest(
549
                conflicted,
550
                uncommitted,
551
                m.written_ns,
552
                &m.dirs,
553
                &m.nested,
554
                &mut rows,
555
            ),
556
        )
557
    }
558
559
    /// Forget the manifest after an operation that changed the working-copy
560
    /// change without a snapshot (undo, rewrites); the prompt shows blank
561
    /// markers until the next snapshot.
562
    pub(crate) fn drop_manifest(&self) {
563
        self.manifest_cache.take();
564
        self.listing_cache.take();
565
        let _ = fs::remove_file(self.manifest_path());
566
    }
567
568
    /// The manifest, with whether it records a conflict and uncommitted
569
    /// work; parsed once while the file stays the same one.
570
    /// Whether the working copy was conflicted when last recorded (the
571
    /// manifest's flag), without looking at the files.
572
    pub fn recorded_conflicted(&self) -> Result<bool> {
573
        Ok(self.read_manifest()?.is_some_and(|(c, _, _)| c))
574
    }
575
576
    pub(crate) fn read_manifest(&self) -> Result<Option<(bool, bool, std::sync::Arc<Manifest>)>> {
577
        let path = self.manifest_path();
578
        let id = match fs::metadata(&path) {
579
            Ok(m) => {
580
                #[cfg(unix)]
581
                let ino = std::os::unix::fs::MetadataExt::ino(&m);
582
                #[cfg(not(unix))]
583
                let ino = 0;
584
                (m.len(), mtime_ns(&m), ino)
585
            }
586
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
587
            Err(e) => return Err(e.into()),
588
        };
589
        if let Some((cached_id, m)) = &*self.manifest_cache.borrow() {
590
            if *cached_id == id {
591
                return Ok(Some(m.clone()));
592
            }
593
        }
594
        let Some((c, u, m)) = self.parse_manifest(&path)? else {
595
            return Ok(None);
596
        };
597
        let m = (c, u, std::sync::Arc::new(m));
598
        *self.manifest_cache.borrow_mut() = Some((id, m.clone()));
599
        Ok(Some(m))
600
    }
601
602
    fn parse_manifest(&self, path: &std::path::Path) -> Result<Option<(bool, bool, Manifest)>> {
603
        let buf = match fs::read(path) {
604
            Ok(b) => b,
605
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
606
            Err(e) => return Err(e.into()),
607
        };
608
        Ok(decode_manifest(&buf))
609
    }
610
611
    /// Whether the working copy is certainly clean, known from the manifest
612
    /// alone, without loading any history (spec §12.4): the last snapshot
613
    /// or commit found no uncommitted work and no conflict, there are no
614
    /// subrepos (whose state the manifest does not hold), and no file was
615
    /// added, removed or changed since. An entry inside the racy window,
616
    /// where an equal size and time do not prove equal content, is checked
617
    /// by hashing the file. `false` means only that a snapshot must decide.
618
    pub fn clean_by_manifest(&self) -> Result<bool> {
619
        let _t = crate::timing::phase("status: check the manifest");
620
        // Why a snapshot must decide, with timings on.
621
        let not = |why: &str| {
622
            if crate::timing::enabled() {
623
                eprintln!("timing status: not clean by the manifest: {why}");
624
            }
625
            Ok(false)
626
        };
627
        let Some((conflicted, uncommitted, m)) = self.read_manifest()? else {
628
            return not("no manifest");
629
        };
630
        if conflicted || uncommitted || self.root.join(".oxymodules").exists() {
631
            return not("conflicted, uncommitted or subrepos");
632
        }
633
        if self.disk_differs(&m, true)? {
634
            return not("a file differs");
635
        }
636
        Ok(true)
637
    }
638
639
    /// A manifest entry written within the racy window whose file no
640
    /// longer matches it. Such entries are hashed, in parallel (a checkout
641
    /// just wrote them all).
642
    fn racy_change(&self, m: &Manifest) -> Option<String> {
643
        use rayon::prelude::*;
644
        let racy: Vec<(&String, &ManifestEntry)> = m
645
            .entries
646
            .iter()
647
            .filter(|(_, e)| e.mtime_ns + 2_000_000_000 >= m.written_ns)
648
            .collect();
649
        let root = &self.root;
650
        racy.par_iter()
651
            .find_any(|(rel, e)| {
652
                let path = root.join(rel.as_str());
653
                let same = match fs::symlink_metadata(&path) {
654
                    Ok(md) if md.file_type().is_symlink() => fs::read_link(&path).is_ok_and(|t| {
655
                        *blake3::hash(t.to_string_lossy().as_bytes()).as_bytes() == e.hash
656
                    }),
657
                    Ok(md) if md.is_file() => {
658
                        md.len() == e.size
659
                            && fs::read(&path).is_ok_and(|b| *blake3::hash(&b).as_bytes() == e.hash)
660
                    }
661
                    _ => false,
662
                };
663
                !same
664
            })
665
            .map(|(rel, _)| rel.to_string())
666
    }
667
668
    /// The status lines of the last snapshot, when the working copy is as
669
    /// that snapshot left it: the cache it wrote names the working-copy
670
    /// change and the manifest it recorded, and every file still matches
671
    /// that manifest. `None` when a snapshot must decide (no cache, a file
672
    /// changed, conflicts or subrepos). An empty list is a clean working
673
    /// copy.
674
    pub fn status_by_manifest(&self) -> Result<Option<Vec<PathStatus>>> {
675
        // A listing left by an earlier check describes the files as they
676
        // were then; this check makes its own.
677
        self.listing_cache.take();
678
        let Some((conflicted, uncommitted, m)) = self.read_manifest()? else {
679
            return Ok(None);
680
        };
681
        if !uncommitted {
682
            return Ok(self.clean_by_manifest()?.then(Vec::new));
683
        }
684
        let _t = crate::timing::phase("status: by the status cache");
685
        if conflicted || self.root.join(".oxymodules").exists() {
686
            return Ok(None);
687
        }
688
        let Some((wc, stamp, statuses)) = fs::read(self.status_cache_path())
689
            .ok()
690
            .and_then(|b| decode_status_cache(&b))
691
        else {
692
            return Ok(None);
693
        };
694
        let now = self.view()?.workspaces.get(&self.workspace).copied();
695
        if now != Some(wc) || self.manifest_stamp() != Some(stamp) {
696
            return Ok(None);
697
        }
698
        if self.disk_differs(&m, true)? {
699
            return Ok(None);
700
        }
701
        // Test builds check the cache against a snapshot of the files.
702
        #[cfg(test)]
703
        {
704
            let snap = self.snapshot_status("status cache check")?;
705
            let key = |v: &[PathStatus]| {
706
                let mut k: Vec<(String, u8)> = v
707
                    .iter()
708
                    .map(|p| (p.path.clone(), status_byte(p.status)))
709
                    .collect();
710
                k.sort();
711
                k
712
            };
713
            assert_eq!(
714
                key(&statuses),
715
                key(&snap.statuses),
716
                "status cache disagrees with a snapshot"
717
            );
718
        }
719
        Ok(Some(statuses))
720
    }
721
722
    fn status_cache_path(&self) -> PathBuf {
723
        self.manifest_path().with_file_name("status")
724
    }
725
726
    /// The manifest file's checksum, which names its content.
727
    fn manifest_stamp(&self) -> Option<[u8; 32]> {
728
        use std::io::Read;
729
        let mut head = [0u8; MANIFEST_SUM.end];
730
        fs::File::open(self.manifest_path())
731
            .and_then(|mut f| f.read_exact(&mut head))
732
            .ok()?;
733
        head[MANIFEST_SUM].try_into().ok()
734
    }
735
736
    /// Record `statuses` as the status of working-copy change `wc` against
737
    /// the manifest as it is now; with no uncommitted work there is nothing
738
    /// to record, and the cache goes.
739
    pub(crate) fn write_status_cache(&self, wc: Option<&ChangeHash>, statuses: &[PathStatus]) {
740
        let path = self.status_cache_path();
741
        let (Some(wc), Some(stamp)) = (wc, self.manifest_stamp()) else {
742
            let _ = fs::remove_file(&path);
743
            return;
744
        };
745
        let _ = write_cache(&path, &encode_status_cache(wc, &stamp, statuses));
746
    }
747
748
    /// Whether the working copy differs from the last manifest. Without a
749
    /// manifest the answer is `None`.
750
    pub fn quick_dirty(&self) -> Result<Option<bool>> {
751
        self.quick_dirty_keeping(false)
752
    }
753
754
    /// `quick_dirty`; with `keep`, the listing it made is left for the
755
    /// next walk of the working copy.
756
    fn quick_dirty_keeping(&self, keep: bool) -> Result<Option<bool>> {
757
        let Some((_, uncommitted, manifest)) = self.read_manifest()? else {
758
            return Ok(None);
759
        };
760
        if uncommitted {
761
            return Ok(Some(true));
762
        }
763
        Ok(Some(self.disk_differs(&manifest, keep)?))
764
    }
765
766
    /// Whether the working copy differs from `manifest`: a file added,
767
    /// gone or changed. With `keep`, the listing made is left for the next
768
    /// walk of the working copy when it does.
769
    fn disk_differs(&self, manifest: &Manifest, keep: bool) -> Result<bool> {
770
        // A file written within the racy window can change without its size
771
        // or time moving (a coarse clock): those entries are hashed. One
772
        // that changed still lets the directory check below hand its stats
773
        // to the snapshot that follows.
774
        let racy = self.racy_change(manifest).is_some();
775
        if let Some(differs) = self.disk_differs_by_dirs_keeping(manifest, keep, racy) {
776
            return Ok(differs || racy);
777
        }
778
        if racy {
779
            return Ok(true);
780
        }
781
        self.disk_differs_listing(manifest, keep)
782
    }
783
784
    /// [`Repo::disk_differs`] without listing the tree, when the manifest
785
    /// knows its directories: a directory's time moves when an entry is
786
    /// added, removed or renamed in it, so with every directory's time as
787
    /// recorded (and none within the racy window) the files are the
788
    /// manifest's, and each is checked by its stat. `None` when a
789
    /// directory changed or the manifest has none: the tree must be listed.
790
    #[cfg(test)]
791
    pub(crate) fn disk_differs_by_dirs(&self, manifest: &Manifest) -> Option<bool> {
792
        self.disk_differs_by_dirs_keeping(manifest, false, false)
793
    }
794
795
    /// [`Repo::disk_differs_by_dirs`]; with `keep`, when a file differs
796
    /// (or `racy` says one does), the stats taken become the listing of the
797
    /// snapshot that follows: no directory's entries changed, so the
798
    /// manifest's files are the tree's.
799
    fn disk_differs_by_dirs_keeping(
800
        &self,
801
        manifest: &Manifest,
802
        keep: bool,
803
        racy: bool,
804
    ) -> Option<bool> {
805
        use rayon::prelude::*;
806
        if manifest.dirs.is_empty() || !self.config.sparse_paths.is_empty() {
807
            return None;
808
        }
809
        let _t = crate::timing::phase("status: directories and files by stat");
810
        let root = &self.root;
811
        let dirs_same = manifest.dirs.par_iter().all(|(rel, t)| {
812
            *t + 2_000_000_000 < manifest.written_ns
813
                && fs::metadata(root.join(rel)).is_ok_and(|m| m.is_dir() && mtime_ns(&m) == *t)
814
        });
815
        if !dirs_same {
816
            return None;
817
        }
818
        let rels: Vec<&String> = manifest.entries.keys().collect();
819
        let now = stat_tracked(root, &rels);
820
        let differs_from = |me: &ManifestEntry, rel: &str, now: &Tracked| match now {
821
            Tracked::Link(t) => *blake3::hash(t).as_bytes() != me.hash,
822
            Tracked::File(m) => {
823
                m.size != me.size
824
                    || m.exec != me.exec
825
                    || (m.mtime_ns != me.mtime_ns
826
                        && !fs::read(root.join(rel))
827
                            .is_ok_and(|b| *blake3::hash(&b).as_bytes() == me.hash))
828
            }
829
        };
830
        // A path gone or no longer a file: its directory moved, unless
831
        // within a clock tick; list the tree to be sure.
832
        if now.iter().any(Option::is_none) {
833
            return None;
834
        }
835
        // The entries in the order `rels` was taken in: no lookup by path.
836
        let entries: Vec<&ManifestEntry> = manifest.entries.values().collect();
837
        let differs = rels
838
            .par_iter()
839
            .zip(entries.par_iter())
840
            .zip(now.par_iter())
841
            .any(|((rel, me), n)| differs_from(me, rel, n.as_ref().unwrap()));
842
        if keep && (differs || racy) {
843
            let mut listing = super::walk::Listing {
844
                dirs: manifest.dirs.clone(),
845
                nested: manifest.nested.iter().map(|n| root.join(n)).collect(),
846
                ..Default::default()
847
            };
848
            for (rel, n) in rels.into_iter().zip(now) {
849
                match n.unwrap() {
850
                    Tracked::File(m) => listing.files.push((rel.clone(), root.join(rel), m)),
851
                    Tracked::Link(t) => listing.symlinks.push((rel.clone(), t)),
852
                }
853
            }
854
            *self.listing_cache.borrow_mut() = Some(listing);
855
        }
856
        if !differs {
857
            // Nested repositories the manifest has no entry for are not
858
            // subrepos: nothing in them is tracked (oxygen#43).
859
            *self.untracked_nested.borrow_mut() = manifest
860
                .nested
861
                .iter()
862
                .filter(|rel| !manifest.entries.contains_key(*rel))
863
                .cloned()
864
                .collect();
865
        }
866
        Some(differs)
867
    }
868
869
    /// [`Repo::disk_differs`] by listing the tree.
870
    fn disk_differs_listing(&self, manifest: &Manifest, keep: bool) -> Result<bool> {
871
        use rayon::prelude::*;
872
        let sparse = &self.config.sparse_paths;
873
        let in_scope = |p: &str| {
874
            sparse.is_empty()
875
                || sparse
876
                    .iter()
877
                    .any(|s| p == s || p.starts_with(&format!("{s}/")))
878
        };
879
        // A working copy that cannot be listed counts as changed.
880
        // Known files are not matched against the ignore rules: with no
881
        // uncommitted work (the clean check), the manifest's files are the
882
        // base's, and a prompt's answer is the same either way.
883
        let known = |p: &str| manifest.entries.contains_key(p);
884
        let Ok(listing) = super::walk::list_knowing(&self.root, &in_scope, &known) else {
885
            return Ok(true);
886
        };
887
        let differs = || -> Result<bool> {
888
            let links_differ = listing.symlinks.iter().any(|(rel, target)| {
889
                manifest
890
                    .entries
891
                    .get(rel)
892
                    .is_none_or(|me| *blake3::hash(target).as_bytes() != me.hash)
893
            });
894
            if links_differ {
895
                return Ok(true);
896
            }
897
            // Each file is checked on its own, in parallel, stopping at the
898
            // first difference; an unreadable one counts as different.
899
            let files_differ = listing.files.par_iter().any(|(rel, path, m)| {
900
                manifest.entries.get(rel).is_none_or(|me| {
901
                    m.size != me.size
902
                        || m.exec != me.exec
903
                        || (m.mtime_ns != me.mtime_ns
904
                            && !fs::read(path)
905
                                .is_ok_and(|b| *blake3::hash(&b).as_bytes() == me.hash))
906
                })
907
            });
908
            if files_differ {
909
                return Ok(true);
910
            }
911
            let seen = listing.files.len() + listing.symlinks.len();
912
            if seen == manifest.entries.len() {
913
                return Ok(false);
914
            }
915
            // Manifest entries the walk skipped: tracked files that ignore
916
            // rules hide (Linux tracks some its own .gitignore names). Found
917
            // by merging the two sorted lists; they count as present when
918
            // still on disk and unchanged, checked on every core.
919
            let mut listed: Vec<&str> = listing
920
                .files
921
                .iter()
922
                .map(|(r, _, _)| r.as_str())
923
                .chain(listing.symlinks.iter().map(|(r, _)| r.as_str()))
924
                .collect();
925
            listed.sort_unstable();
926
            let mut at = listed.iter().peekable();
927
            let skipped: Vec<(&String, &ManifestEntry)> = manifest
928
                .entries
929
                .iter()
930
                .filter(|(rel, _)| {
931
                    while at.next_if(|l| **l < rel.as_str()).is_some() {}
932
                    at.peek().is_none_or(|l| **l != rel.as_str())
933
                })
934
                .collect();
935
            let root = &self.root;
936
            Ok(skipped.par_iter().any(|(rel, me)| {
937
                let path = root.join(rel.as_str());
938
                let Ok(m) = fs::symlink_metadata(&path) else {
939
                    return true;
940
                };
941
                !m.file_type().is_symlink()
942
                    && (m.len() != me.size
943
                        || super::is_executable(&m) != me.exec
944
                        || (mtime_ns(&m) != me.mtime_ns
945
                            && !fs::read(&path)
946
                                .is_ok_and(|b| *blake3::hash(&b).as_bytes() == me.hash)))
947
            }))
948
        };
949
        let dirty = differs()?;
950
        if !dirty {
951
            // Nested repositories the manifest has no entry for are not
952
            // subrepos: nothing in them is tracked (oxygen#43).
953
            *self.untracked_nested.borrow_mut() = listing
954
                .nested
955
                .iter()
956
                .map(|d| self.rel_path(d))
957
                .filter(|rel| !manifest.entries.contains_key(rel))
958
                .collect();
959
        }
960
        if dirty && keep {
961
            *self.listing_cache.borrow_mut() = Some(listing);
962
        }
963
        Ok(dirty)
964
    }
965
966
    /// Prompt information without recording anything.
967
    pub fn quick_status(&self) -> Result<PromptInfo> {
968
        let view = self.view()?;
969
        let bookmark = self.config.bookmark.clone();
970
        let heads = self.heads_of(&view, &bookmark)?;
971
        let wc_hash = view.workspaces.get(&self.workspace).copied();
972
        let change_id = match wc_hash {
973
            Some(h) => self.store.get_change_meta(&h)?.change_id.short(8),
974
            None => String::new(),
975
        };
976
        // Conflictedness was recorded by the last snapshot; without a
977
        // manifest (never snapshotted) both flags are unknown and shown clear.
978
        let manifest = self.read_manifest()?;
979
        let conflicted = manifest.as_ref().map(|(c, _, _)| *c).unwrap_or(false);
980
        let dirty = self.quick_dirty()?.unwrap_or(false);
981
        let (ahead, behind) = match view
982
            .remotes
983
            .get(&self.default_remote())
984
            .and_then(|b| b.get(&bookmark))
985
        {
986
            Some(st) => {
987
                let remote_heads = self.store.get_state(st)?.heads;
988
                let ahead = self.negotiate(&remote_heads, &heads).map(|v| v.len()).ok();
989
                let behind = self.negotiate(&heads, &remote_heads).map(|v| v.len()).ok();
990
                (ahead, behind)
991
            }
992
            None => (None, None),
993
        };
994
        Ok(PromptInfo {
995
            bookmark,
996
            change_id,
997
            heads: heads.len(),
998
            dirty,
999
            conflicted,
1000
            ahead,
1001
            behind,
1002
        })
1003
    }
1004
}
1005
1006
#[cfg(test)]
1007
mod tests {
1008
    use super::*;
1009
1010
    #[test]
1011
    fn placeholders_and_glyphs() {
1012
        let clean = PromptInfo {
1013
            bookmark: "main".into(),
1014
            change_id: "658990aa".into(),
1015
            heads: 1,
1016
            dirty: false,
1017
            conflicted: false,
1018
            ahead: Some(0),
1019
            behind: None,
1020
        };
1021
        assert_eq!(clean.format(DEFAULT_PROMPT_FORMAT), "main 658990aa");
1022
        assert_eq!(clean.format(GLYPH_PROMPT_FORMAT), "⚛ main 658990aa ✔");
1023
        let busy = PromptInfo {
1024
            dirty: true,
1025
            ahead: Some(2),
1026
            behind: Some(3),
1027
            ..clean.clone()
1028
        };
1029
        assert_eq!(busy.format(DEFAULT_PROMPT_FORMAT), "main 658990aa*+2-3");
1030
        assert_eq!(busy.format(GLYPH_PROMPT_FORMAT), "⚛ main 658990aa ✎↑2↓3");
1031
        let bad = PromptInfo {
1032
            conflicted: true,
1033
            ..busy.clone()
1034
        };
1035
        assert_eq!(bad.format("%s%x%d %h %a/%B %%"), "‼!* 1 2/3 %");
1036
        assert_eq!(bad.state_color(), 31);
1037
        assert_eq!(
1038
            busy.format_colored("%b", ("\\[", "\\]")),
1039
            "\\[\x1b[33m\\]main\\[\x1b[0m\\]"
1040
        );
1041
        assert_eq!(clean.format_colored("%b", ("", "")), "\x1b[36mmain\x1b[0m");
1042
        assert_eq!(clean.format("%q"), "%q");
1043
    }
1044
}