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