OXYGENHUB
# eaf3e9068180 oxygen / crates / oxy-core / src / repo / prompt.rs
21.0 KiB · Rust · last changed Check the manifest with a parallel walk 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: String,
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<String>,
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
}
150
151
pub(crate) fn mtime_ns(m: &fs::Metadata) -> u128 {
152
    m.modified()
153
        .ok()
154
        .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
155
        .map(|d| d.as_nanos())
156
        .unwrap_or(0)
157
}
158
159
pub const DEFAULT_PROMPT_FORMAT: &str = "%b %c%d%x%A%D";
160
/// The repository icon for `%i` (an atom, for oxygen).
161
pub const ICON: &str = "⚛";
162
/// A format with glyphs: icon, bookmark, change id, state, ahead/behind.
163
pub const GLYPH_PROMPT_FORMAT: &str = "%i %b %c %s%U%O";
164
165
/// One manifest line per file: size, mtime in nanoseconds, hash, blob ref
166
/// or `-`, graph key or `-`, `x` when executable or `-`, path.
167
fn manifest_line(
168
    path: &str,
169
    size: u64,
170
    mtime_ns: u128,
171
    hash: &str,
172
    blob: Option<ObjectRef>,
173
    graph: Option<&str>,
174
    exec: bool,
175
) -> String {
176
    format!(
177
        "{size}\t{mtime_ns}\t{hash}\t{}\t{}\t{}\t{path}\n",
178
        blob.map(|b| b.to_hex()).unwrap_or_else(|| "-".into()),
179
        graph.unwrap_or("-"),
180
        if exec { "x" } else { "-" }
181
    )
182
}
183
184
impl Repo {
185
    pub(crate) fn manifest_path(&self) -> PathBuf {
186
        self.oxy
187
            .join("workspaces")
188
            .join(self.workspace.to_hex())
189
            .join("manifest")
190
    }
191
192
    /// Record the working copy as it is now (after a snapshot, commit, or
193
    /// checkout), with header lines saying whether the base state is
194
    /// conflicted and whether the working-copy change holds uncommitted work.
195
    pub(crate) fn write_manifest(&self, conflicted: bool, uncommitted: bool) -> Result<()> {
196
        let entries = self.walk_working_copy()?;
197
        self.write_manifest_entries(conflicted, uncommitted, &entries, &HashMap::new())
198
    }
199
200
    /// Write the manifest from entries already walked; `blobs` names the
201
    /// stored blob of each opaque path so the next walk can skip reading it.
202
    pub(crate) fn write_manifest_entries(
203
        &self,
204
        conflicted: bool,
205
        uncommitted: bool,
206
        entries: &BTreeMap<String, FsEntry>,
207
        blobs: &HashMap<String, ObjectRef>,
208
    ) -> Result<()> {
209
        let written = std::time::SystemTime::now()
210
            .duration_since(UNIX_EPOCH)
211
            .map(|d| d.as_nanos())
212
            .unwrap_or(0);
213
        let head = format!(
214
            "# conflicted={}\n# uncommitted={}\n",
215
            conflicted as u8, uncommitted as u8
216
        );
217
        let mut body = String::new();
218
        let mut newest_ns: u128 = 0;
219
        for (path, e) in entries {
220
            let full = self.root.join(path);
221
            let (size, mtime_ns) = match fs::symlink_metadata(&full) {
222
                Ok(m) => (m.len(), mtime_ns(&m)),
223
                Err(_) => (e.content.len() as u64, 0),
224
            };
225
            let hash = match &e.content_hash {
226
                Some(h) => h.clone(),
227
                None => blake3::hash(&e.content).to_hex().to_string(),
228
            };
229
            let blob = blobs.get(path).copied().or(e.blob);
230
            newest_ns = newest_ns.max(mtime_ns);
231
            body.push_str(&manifest_line(
232
                path,
233
                size,
234
                mtime_ns,
235
                &hash,
236
                blob,
237
                e.graph_key.as_deref(),
238
                e.exec,
239
            ));
240
        }
241
        let p = self.manifest_path();
242
        // Leave an unchanged manifest alone when its stamp already trusts
243
        // every entry (none is within the racy window): rewriting it would
244
        // change nothing but the file, which editors watching the tree
245
        // (and subrepos inside it) take as a change.
246
        if let Ok(old) = fs::read_to_string(&p) {
247
            let old_written: Option<u128> = old.lines().find_map(|l| {
248
                l.strip_prefix("# written=")
249
                    .and_then(|v| v.trim().parse().ok())
250
            });
251
            let old_rest: String = old
252
                .lines()
253
                .filter(|l| !l.starts_with("# written="))
254
                .map(|l| format!("{l}\n"))
255
                .collect();
256
            if let Some(w) = old_written {
257
                if old_rest == format!("{head}{body}") && newest_ns + 2_000_000_000 < w {
258
                    return Ok(());
259
                }
260
            }
261
        }
262
        let text = format!("{head}# written={written}\n{body}");
263
        fs::create_dir_all(p.parent().unwrap())?;
264
        write_atomic(&p, text.as_bytes())
265
    }
266
267
    /// Change the header flags, and set the graph key of each path in
268
    /// `keys` (after a commit, the new base's keys of the files it holds as
269
    /// they are on disk).
270
    pub(crate) fn rewrite_manifest(
271
        &self,
272
        conflicted: bool,
273
        uncommitted: bool,
274
        keys: &HashMap<String, String>,
275
    ) -> Result<()> {
276
        let p = self.manifest_path();
277
        let text = match fs::read_to_string(&p) {
278
            Ok(t) => t,
279
            Err(_) => return self.write_manifest(conflicted, uncommitted),
280
        };
281
        let mut out = String::with_capacity(text.len());
282
        for line in text.lines() {
283
            if line.starts_with("# conflicted=") {
284
                out.push_str(&format!("# conflicted={}\n", conflicted as u8));
285
            } else if line.starts_with("# uncommitted=") {
286
                out.push_str(&format!("# uncommitted={}\n", uncommitted as u8));
287
            } else {
288
                let f: Vec<&str> = line.splitn(7, '\t').collect();
289
                match (f.len() == 7).then(|| keys.get(f[6])).flatten() {
290
                    Some(k) => out.push_str(&format!(
291
                        "{}\t{}\t{}\t{}\t{k}\t{}\t{}\n",
292
                        f[0], f[1], f[2], f[3], f[5], f[6]
293
                    )),
294
                    None => {
295
                        out.push_str(line);
296
                        out.push('\n');
297
                    }
298
                }
299
            }
300
        }
301
        write_atomic(&p, out.as_bytes())
302
    }
303
304
    /// Forget the manifest after an operation that changed the working-copy
305
    /// change without a snapshot (undo, rewrites); the prompt shows blank
306
    /// markers until the next snapshot.
307
    pub(crate) fn drop_manifest(&self) {
308
        let _ = fs::remove_file(self.manifest_path());
309
    }
310
311
    pub(crate) fn read_manifest(&self) -> Result<Option<(bool, bool, Manifest)>> {
312
        let text = match fs::read_to_string(self.manifest_path()) {
313
            Ok(t) => t,
314
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
315
            Err(e) => return Err(e.into()),
316
        };
317
        let mut out = Manifest::default();
318
        let mut conflicted = false;
319
        let mut uncommitted = false;
320
        for line in text.lines() {
321
            if let Some(v) = line.strip_prefix("# conflicted=") {
322
                conflicted = v.trim() == "1";
323
                continue;
324
            }
325
            if let Some(v) = line.strip_prefix("# uncommitted=") {
326
                uncommitted = v.trim() == "1";
327
                continue;
328
            }
329
            if let Some(v) = line.strip_prefix("# written=") {
330
                out.written_ns = v.trim().parse().unwrap_or(u128::MAX);
331
                continue;
332
            }
333
            // A line of another shape (an older manifest) is no entry: the
334
            // file is then read, and the next snapshot rewrites the line.
335
            let f: Vec<&str> = line.splitn(7, '\t').collect();
336
            if f.len() == 7 {
337
                out.entries.insert(
338
                    f[6].to_string(),
339
                    ManifestEntry {
340
                        size: f[0].parse().unwrap_or(0),
341
                        mtime_ns: f[1].parse().unwrap_or(0),
342
                        hash: f[2].to_string(),
343
                        blob: ObjectRef::from_hex(f[3]),
344
                        graph: (f[4] != "-").then(|| f[4].to_string()),
345
                        exec: f[5] == "x",
346
                    },
347
                );
348
            }
349
        }
350
        Ok(Some((conflicted, uncommitted, out)))
351
    }
352
353
    /// Whether the working copy is certainly clean, known from the manifest
354
    /// alone, without loading any history (spec §12.4): the last snapshot
355
    /// or commit found no uncommitted work and no conflict, every entry is
356
    /// older than the racy window (so an equal size and time mean equal
357
    /// content), there are no subrepos (whose state the manifest does not
358
    /// hold), and no file was added, removed or changed since. `false`
359
    /// means only that a snapshot must decide.
360
    pub fn clean_by_manifest(&self) -> Result<bool> {
361
        let _t = crate::timing::phase("status: check the manifest");
362
        let Some((conflicted, uncommitted, m)) = self.read_manifest()? else {
363
            return Ok(false);
364
        };
365
        if conflicted || uncommitted || self.root.join(".oxymodules").exists() {
366
            return Ok(false);
367
        }
368
        let racy = m
369
            .entries
370
            .values()
371
            .any(|e| e.mtime_ns + 2_000_000_000 >= m.written_ns);
372
        if racy {
373
            return Ok(false);
374
        }
375
        Ok(self.quick_dirty()? == Some(false))
376
    }
377
378
    /// Whether the working copy differs from the last manifest. Without a
379
    /// manifest the answer is `None`.
380
    pub fn quick_dirty(&self) -> Result<Option<bool>> {
381
        let Some((_, uncommitted, manifest)) = self.read_manifest()? else {
382
            return Ok(None);
383
        };
384
        if uncommitted {
385
            return Ok(Some(true));
386
        }
387
        use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering::Relaxed};
388
        let nested = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
389
        let wb = self.walker(&nested);
390
        // Every file is checked on its own, so the walk runs in parallel and
391
        // stops at the first difference.
392
        let dirty = AtomicBool::new(false);
393
        let seen = AtomicUsize::new(0);
394
        let (root, sparse) = (&self.root, &self.config.sparse_paths);
395
        let in_scope = |p: &str| {
396
            sparse.is_empty()
397
                || sparse
398
                    .iter()
399
                    .any(|s| p == s || p.starts_with(&format!("{s}/")))
400
        };
401
        wb.build_parallel().run(|| {
402
            Box::new(|entry| {
403
                use ignore::WalkState;
404
                if dirty.load(Relaxed) {
405
                    return WalkState::Quit;
406
                }
407
                let Ok(entry) = entry else {
408
                    return WalkState::Continue;
409
                };
410
                let Some(ft) = entry.file_type() else {
411
                    return WalkState::Continue;
412
                };
413
                if ft.is_dir() {
414
                    return WalkState::Continue;
415
                }
416
                let rel: String = entry
417
                    .path()
418
                    .strip_prefix(root)
419
                    .unwrap()
420
                    .components()
421
                    .map(|c| c.as_os_str().to_string_lossy().to_string())
422
                    .collect::<Vec<_>>()
423
                    .join("/");
424
                if !in_scope(&rel) {
425
                    return WalkState::Continue;
426
                }
427
                // Whether this file differs from its entry; an unreadable
428
                // one counts as different.
429
                let differs = match manifest.entries.get(&rel) {
430
                    None => true,
431
                    Some(me) => {
432
                        seen.fetch_add(1, Relaxed);
433
                        match fs::symlink_metadata(entry.path()) {
434
                            Err(_) => true,
435
                            Ok(_) if ft.is_symlink() => {
436
                                !fs::read_link(entry.path()).is_ok_and(|t| {
437
                                    blake3::hash(t.to_string_lossy().as_bytes())
438
                                        .to_hex()
439
                                        .as_str()
440
                                        == me.hash
441
                                })
442
                            }
443
                            Ok(m) => {
444
                                m.len() != me.size
445
                                    || super::is_executable(&m) != me.exec
446
                                    || (mtime_ns(&m) != me.mtime_ns
447
                                        && !fs::read(entry.path()).is_ok_and(|b| {
448
                                            blake3::hash(&b).to_hex().as_str() == me.hash
449
                                        }))
450
                            }
451
                        }
452
                    }
453
                };
454
                if differs {
455
                    dirty.store(true, Relaxed);
456
                    return WalkState::Quit;
457
                }
458
                WalkState::Continue
459
            })
460
        });
461
        if dirty.load(Relaxed) {
462
            return Ok(Some(true));
463
        }
464
        let seen = seen.load(Relaxed);
465
        if seen == manifest.entries.len() {
466
            return Ok(Some(false));
467
        }
468
        // Manifest entries the walk skipped: tracked files that ignore rules
469
        // hide. They count as present when still on disk and unchanged.
470
        for (rel, me) in &manifest.entries {
471
            let path = self.root.join(rel);
472
            let Ok(m) = fs::symlink_metadata(&path) else {
473
                return Ok(Some(true));
474
            };
475
            if m.file_type().is_symlink() {
476
                continue;
477
            }
478
            if m.len() != me.size
479
                || super::is_executable(&m) != me.exec
480
                || (mtime_ns(&m) != me.mtime_ns
481
                    && blake3::hash(&fs::read(&path)?).to_hex().as_str() != me.hash)
482
            {
483
                return Ok(Some(true));
484
            }
485
        }
486
        Ok(Some(false))
487
    }
488
489
    /// Prompt information without recording anything.
490
    pub fn quick_status(&self) -> Result<PromptInfo> {
491
        let view = self.view()?;
492
        let bookmark = self.config.bookmark.clone();
493
        let heads = self.heads_of(&view, &bookmark)?;
494
        let wc_hash = view.workspaces.get(&self.workspace).copied();
495
        let change_id = match wc_hash {
496
            Some(h) => self.store.get_change(&h)?.change_id.short(8),
497
            None => String::new(),
498
        };
499
        // Conflictedness was recorded by the last snapshot; without a
500
        // manifest (never snapshotted) both flags are unknown and shown clear.
501
        let manifest = self.read_manifest()?;
502
        let conflicted = manifest.as_ref().map(|(c, _, _)| *c).unwrap_or(false);
503
        let dirty = self.quick_dirty()?.unwrap_or(false);
504
        let (ahead, behind) = match view.remotes.get("origin").and_then(|b| b.get(&bookmark)) {
505
            Some(st) => {
506
                let remote_heads = self.store.get_state(st)?.heads;
507
                let ahead = self.negotiate(&remote_heads, &heads).map(|v| v.len()).ok();
508
                let behind = self.negotiate(&heads, &remote_heads).map(|v| v.len()).ok();
509
                (ahead, behind)
510
            }
511
            None => (None, None),
512
        };
513
        Ok(PromptInfo {
514
            bookmark,
515
            change_id,
516
            heads: heads.len(),
517
            dirty,
518
            conflicted,
519
            ahead,
520
            behind,
521
        })
522
    }
523
}
524
525
#[cfg(test)]
526
mod tests {
527
    use super::*;
528
529
    #[test]
530
    fn placeholders_and_glyphs() {
531
        let clean = PromptInfo {
532
            bookmark: "main".into(),
533
            change_id: "658990aa".into(),
534
            heads: 1,
535
            dirty: false,
536
            conflicted: false,
537
            ahead: Some(0),
538
            behind: None,
539
        };
540
        assert_eq!(clean.format(DEFAULT_PROMPT_FORMAT), "main 658990aa");
541
        assert_eq!(clean.format(GLYPH_PROMPT_FORMAT), "⚛ main 658990aa ✔");
542
        let busy = PromptInfo {
543
            dirty: true,
544
            ahead: Some(2),
545
            behind: Some(3),
546
            ..clean.clone()
547
        };
548
        assert_eq!(busy.format(DEFAULT_PROMPT_FORMAT), "main 658990aa*+2-3");
549
        assert_eq!(busy.format(GLYPH_PROMPT_FORMAT), "⚛ main 658990aa ✎↑2↓3");
550
        let bad = PromptInfo {
551
            conflicted: true,
552
            ..busy.clone()
553
        };
554
        assert_eq!(bad.format("%s%x%d %h %a/%B %%"), "‼!* 1 2/3 %");
555
        assert_eq!(bad.state_color(), 31);
556
        assert_eq!(
557
            busy.format_colored("%b", ("\\[", "\\]")),
558
            "\\[\x1b[33m\\]main\\[\x1b[0m\\]"
559
        );
560
        assert_eq!(clean.format_colored("%b", ("", "")), "\x1b[36mmain\x1b[0m");
561
        assert_eq!(clean.format("%q"), "%q");
562
    }
563
}