OXYGENHUB
# 1966f5db15ee oxygen / crates / oxy-core / src / repo / prompt.rs
21.6 KiB · Rust · last changed Manifest as a flat binary file, hashes and graph keys as bytes (refs #41) 1 month ago source blame history raw
135212de Andy McCall ↶ 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 {
694805cc Andy McCall ↶ 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 {
75167672 Andy McCall 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
        )
694805cc Andy McCall ↶ 62
    }
63
135212de Andy McCall ↶ 64
    /// Expand `%b` bookmark, `%c` change id, `%h` heads, `%d` dirty marker
65
    /// (`*`), `%x` conflict marker (`!`), `%a`/`%B` ahead/behind counts
694805cc Andy McCall ↶ 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.
135212de Andy McCall ↶ 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
                }
694805cc Andy McCall ↶ 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),
135212de Andy McCall ↶ 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.
b7f102fc Andy McCall ↶ 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,
1966f5db Andy McCall ↶ 134
    pub hash: [u8; 32],
b7f102fc Andy McCall ↶ 135
    pub blob: Option<ObjectRef>,
cc7a0056 Andy McCall ↶ 136
    /// The graph key (`State::graph_key`) of the base file this text file
137
    /// was found equal to, rendered, byte for byte.
1966f5db Andy McCall ↶ 138
    pub graph: Option<[u8; 32]>,
da868d5d Andy McCall ↶ 139
    /// Whether the file was executable: a mode change alters neither size
140
    /// nor time.
141
    pub exec: bool,
b7f102fc Andy McCall ↶ 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
}
135212de Andy McCall ↶ 150
d0990c2b Andy McCall ↶ 151
/// A parsed manifest and the identity (size, time, inode) of the file it
152
/// came from: reused while the file is the same one.
153
pub(crate) type CachedManifest = ((u64, u128, u64), (bool, bool, std::sync::Arc<Manifest>));
154
b7f102fc Andy McCall ↶ 155
pub(crate) fn mtime_ns(m: &fs::Metadata) -> u128 {
75167672 Andy McCall 156
    m.modified()
157
        .ok()
158
        .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
159
        .map(|d| d.as_nanos())
160
        .unwrap_or(0)
b7f102fc Andy McCall ↶ 161
}
162
135212de Andy McCall ↶ 163
pub const DEFAULT_PROMPT_FORMAT: &str = "%b %c%d%x%A%D";
694805cc Andy McCall ↶ 164
/// The repository icon for `%i` (an atom, for oxygen).
165
pub const ICON: &str = "⚛";
166
/// A format with glyphs: icon, bookmark, change id, state, ahead/behind.
167
pub const GLYPH_PROMPT_FORMAT: &str = "%i %b %c %s%U%O";
135212de Andy McCall ↶ 168
1966f5db Andy McCall ↶ 169
/// The manifest file (oxygen#41): a flat binary layout read in one pass.
170
/// A magic number; the conflicted and uncommitted flags; when it was
171
/// written, at a fixed offset so an otherwise equal manifest can be
172
/// recognised; then each entry in path order: path, size, mtime in
173
/// nanoseconds, BLAKE3 of the content, the stored blob of an opaque file,
174
/// the graph key it was found equal to, and whether it is executable. A
175
/// file in any other layout (an older text manifest) reads as no manifest,
176
/// and the next snapshot writes it again.
177
const MANIFEST_MAGIC: &[u8; 8] = b"oxyman1\0";
178
/// Where the written time sits: after the magic and the two flags.
179
const MANIFEST_WRITTEN: std::ops::Range<usize> = 10..26;
180
181
fn encode_manifest(
182
    conflicted: bool,
183
    uncommitted: bool,
184
    written_ns: u128,
185
    entries: &mut dyn Iterator<Item = (&str, ManifestEntry)>,
186
) -> Vec<u8> {
187
    let mut w = crate::flat::Writer::default();
188
    w.fixed(MANIFEST_MAGIC);
189
    w.u8(conflicted as u8);
190
    w.u8(uncommitted as u8);
191
    w.fixed(&written_ns.to_le_bytes());
192
    for (path, e) in entries {
193
        w.bytes(path.as_bytes());
194
        w.u64(e.size);
195
        w.fixed(&e.mtime_ns.to_le_bytes());
196
        w.fixed(&e.hash);
197
        w.opt_object(&e.blob);
198
        match e.graph {
199
            None => w.u8(0),
200
            Some(k) => {
201
                w.u8(1);
202
                w.fixed(&k);
203
            }
204
        }
205
        w.u8(e.exec as u8);
206
    }
207
    w.0
135212de Andy McCall ↶ 208
}
209
1966f5db Andy McCall ↶ 210
fn decode_manifest(buf: &[u8]) -> Option<(bool, bool, Manifest)> {
211
    let mut r = crate::flat::Reader::new(buf);
212
    if &r.fixed::<8>().ok()? != MANIFEST_MAGIC {
213
        return None;
214
    }
215
    let conflicted = r.u8().ok()? == 1;
216
    let uncommitted = r.u8().ok()? == 1;
217
    let written_ns = u128::from_le_bytes(r.fixed().ok()?);
218
    let mut entries = Vec::new();
219
    while !r.at_end() {
220
        let path = std::str::from_utf8(r.bytes().ok()?).ok()?.to_string();
221
        let e = ManifestEntry {
222
            size: r.u64().ok()?,
223
            mtime_ns: u128::from_le_bytes(r.fixed().ok()?),
224
            hash: r.fixed().ok()?,
225
            blob: r.opt_object().ok()?,
226
            graph: match r.u8().ok()? {
227
                0 => None,
228
                _ => Some(r.fixed().ok()?),
229
            },
230
            exec: r.u8().ok()? == 1,
231
        };
232
        entries.push((path, e));
233
    }
234
    // Written in path order, so this builds the map without searching.
235
    let entries = entries.into_iter().collect();
236
    Some((
237
        conflicted,
238
        uncommitted,
239
        Manifest {
240
            written_ns,
241
            entries,
242
        },
243
    ))
244
}
245
135212de Andy McCall ↶ 246
impl Repo {
dfb23a3a Andy McCall ↶ 247
    pub(crate) fn manifest_path(&self) -> PathBuf {
75167672 Andy McCall 248
        self.oxy
249
            .join("workspaces")
250
            .join(self.workspace.to_hex())
251
            .join("manifest")
135212de Andy McCall ↶ 252
    }
253
254
    /// Record the working copy as it is now (after a snapshot, commit, or
255
    /// checkout), with header lines saying whether the base state is
256
    /// conflicted and whether the working-copy change holds uncommitted work.
257
    pub(crate) fn write_manifest(&self, conflicted: bool, uncommitted: bool) -> Result<()> {
b7f102fc Andy McCall ↶ 258
        let entries = self.walk_working_copy()?;
259
        self.write_manifest_entries(conflicted, uncommitted, &entries, &HashMap::new())
260
    }
261
262
    /// Write the manifest from entries already walked; `blobs` names the
263
    /// stored blob of each opaque path so the next walk can skip reading it.
75167672 Andy McCall 264
    pub(crate) fn write_manifest_entries(
265
        &self,
266
        conflicted: bool,
267
        uncommitted: bool,
268
        entries: &BTreeMap<String, FsEntry>,
269
        blobs: &HashMap<String, ObjectRef>,
270
    ) -> Result<()> {
d0990c2b Andy McCall ↶ 271
        self.manifest_cache.take();
76740263 Andy McCall ↶ 272
        self.listing_cache.take();
75167672 Andy McCall 273
        let written = std::time::SystemTime::now()
274
            .duration_since(UNIX_EPOCH)
275
            .map(|d| d.as_nanos())
276
            .unwrap_or(0);
dfb23a3a Andy McCall ↶ 277
        let mut newest_ns: u128 = 0;
1966f5db Andy McCall ↶ 278
        let mut rows = entries.iter().map(|(path, e)| {
0554aaa7 Andy McCall ↶ 279
            let (size, mtime_ns) = match e.stat {
280
                Some(known) => known,
1966f5db Andy McCall ↶ 281
                None => match fs::symlink_metadata(self.root.join(path)) {
0554aaa7 Andy McCall ↶ 282
                    Ok(m) => (m.len(), mtime_ns(&m)),
283
                    Err(_) => (e.content.len() as u64, 0),
284
                },
135212de Andy McCall ↶ 285
            };
dfb23a3a Andy McCall ↶ 286
            newest_ns = newest_ns.max(mtime_ns);
1966f5db Andy McCall ↶ 287
            let entry = ManifestEntry {
cc7a0056 Andy McCall ↶ 288
                size,
289
                mtime_ns,
1966f5db Andy McCall ↶ 290
                hash: e
291
                    .content_hash
292
                    .unwrap_or_else(|| *blake3::hash(&e.content).as_bytes()),
293
                blob: blobs.get(path).copied().or(e.blob),
294
                graph: e.graph_key,
295
                exec: e.exec,
296
            };
297
            (path.as_str(), entry)
298
        });
299
        let new = encode_manifest(conflicted, uncommitted, written, &mut rows);
300
        drop(rows);
135212de Andy McCall ↶ 301
        let p = self.manifest_path();
dfb23a3a Andy McCall ↶ 302
        // Leave an unchanged manifest alone when its stamp already trusts
303
        // every entry (none is within the racy window): rewriting it would
304
        // change nothing but the file, which editors watching the tree
305
        // (and subrepos inside it) take as a change.
1966f5db Andy McCall ↶ 306
        if let Ok(old) = fs::read(&p) {
307
            let w = MANIFEST_WRITTEN;
308
            if old.len() == new.len()
309
                && old[..w.start] == new[..w.start]
310
                && old[w.end..] == new[w.end..]
311
            {
312
                let old_written = u128::from_le_bytes(old[w.clone()].try_into().unwrap());
313
                if newest_ns + 2_000_000_000 < old_written {
dfb23a3a Andy McCall ↶ 314
                    return Ok(());
315
                }
316
            }
317
        }
135212de Andy McCall ↶ 318
        fs::create_dir_all(p.parent().unwrap())?;
1966f5db Andy McCall ↶ 319
        write_atomic(&p, &new)
135212de Andy McCall ↶ 320
    }
321
86e1824f Andy McCall ↶ 322
    /// Change the header flags, and set the graph key of each path in
323
    /// `keys` (after a commit, the new base's keys of the files it holds as
324
    /// they are on disk).
325
    pub(crate) fn rewrite_manifest(
326
        &self,
327
        conflicted: bool,
328
        uncommitted: bool,
1966f5db Andy McCall ↶ 329
        keys: &HashMap<String, [u8; 32]>,
86e1824f Andy McCall ↶ 330
    ) -> Result<()> {
d0990c2b Andy McCall ↶ 331
        self.manifest_cache.take();
76740263 Andy McCall ↶ 332
        self.listing_cache.take();
b7f102fc Andy McCall ↶ 333
        let p = self.manifest_path();
1966f5db Andy McCall ↶ 334
        let Some((_, _, m)) = fs::read(&p).ok().and_then(|b| decode_manifest(&b)) else {
335
            return self.write_manifest(conflicted, uncommitted);
b7f102fc Andy McCall ↶ 336
        };
1966f5db Andy McCall ↶ 337
        let mut rows = m.entries.iter().map(|(path, e)| {
338
            let mut e = e.clone();
339
            if let Some(k) = keys.get(path) {
340
                e.graph = Some(*k);
b7f102fc Andy McCall ↶ 341
            }
1966f5db Andy McCall ↶ 342
            (path.as_str(), e)
343
        });
344
        write_atomic(
345
            &p,
346
            &encode_manifest(conflicted, uncommitted, m.written_ns, &mut rows),
347
        )
b7f102fc Andy McCall ↶ 348
    }
349
135212de Andy McCall ↶ 350
    /// Forget the manifest after an operation that changed the working-copy
351
    /// change without a snapshot (undo, rewrites); the prompt shows blank
352
    /// markers until the next snapshot.
353
    pub(crate) fn drop_manifest(&self) {
d0990c2b Andy McCall ↶ 354
        self.manifest_cache.take();
76740263 Andy McCall ↶ 355
        self.listing_cache.take();
135212de Andy McCall ↶ 356
        let _ = fs::remove_file(self.manifest_path());
d0990c2b Andy McCall ↶ 357
    }
358
359
    /// The manifest, with whether it records a conflict and uncommitted
360
    /// work; parsed once while the file stays the same one.
361
    pub(crate) fn read_manifest(&self) -> Result<Option<(bool, bool, std::sync::Arc<Manifest>)>> {
362
        let path = self.manifest_path();
363
        let id = match fs::metadata(&path) {
364
            Ok(m) => {
365
                #[cfg(unix)]
366
                let ino = std::os::unix::fs::MetadataExt::ino(&m);
367
                #[cfg(not(unix))]
368
                let ino = 0;
369
                (m.len(), mtime_ns(&m), ino)
370
            }
371
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
372
            Err(e) => return Err(e.into()),
373
        };
374
        if let Some((cached_id, m)) = &*self.manifest_cache.borrow() {
375
            if *cached_id == id {
376
                return Ok(Some(m.clone()));
377
            }
378
        }
379
        let Some((c, u, m)) = self.parse_manifest(&path)? else {
380
            return Ok(None);
381
        };
382
        let m = (c, u, std::sync::Arc::new(m));
383
        *self.manifest_cache.borrow_mut() = Some((id, m.clone()));
384
        Ok(Some(m))
135212de Andy McCall ↶ 385
    }
386
d0990c2b Andy McCall ↶ 387
    fn parse_manifest(&self, path: &std::path::Path) -> Result<Option<(bool, bool, Manifest)>> {
1966f5db Andy McCall ↶ 388
        let buf = match fs::read(path) {
389
            Ok(b) => b,
135212de Andy McCall ↶ 390
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
391
            Err(e) => return Err(e.into()),
392
        };
1966f5db Andy McCall ↶ 393
        Ok(decode_manifest(&buf))
135212de Andy McCall ↶ 394
    }
395
da868d5d Andy McCall ↶ 396
    /// Whether the working copy is certainly clean, known from the manifest
397
    /// alone, without loading any history (spec §12.4): the last snapshot
d3cd7ef9 Andy McCall ↶ 398
    /// or commit found no uncommitted work and no conflict, there are no
399
    /// subrepos (whose state the manifest does not hold), and no file was
400
    /// added, removed or changed since. An entry inside the racy window,
401
    /// where an equal size and time do not prove equal content, is checked
402
    /// by hashing the file. `false` means only that a snapshot must decide.
da868d5d Andy McCall ↶ 403
    pub fn clean_by_manifest(&self) -> Result<bool> {
404
        let _t = crate::timing::phase("status: check the manifest");
405
        let Some((conflicted, uncommitted, m)) = self.read_manifest()? else {
406
            return Ok(false);
407
        };
408
        if conflicted || uncommitted || self.root.join(".oxymodules").exists() {
409
            return Ok(false);
410
        }
d3cd7ef9 Andy McCall ↶ 411
        for (rel, e) in &m.entries {
412
            if e.mtime_ns + 2_000_000_000 < m.written_ns {
413
                continue;
414
            }
415
            let path = self.root.join(rel);
416
            let same = match fs::symlink_metadata(&path) {
417
                Ok(md) if md.file_type().is_symlink() => fs::read_link(&path).is_ok_and(|t| {
1966f5db Andy McCall ↶ 418
                    *blake3::hash(t.to_string_lossy().as_bytes()).as_bytes() == e.hash
d3cd7ef9 Andy McCall ↶ 419
                }),
420
                Ok(md) if md.is_file() => {
421
                    md.len() == e.size
1966f5db Andy McCall ↶ 422
                        && fs::read(&path).is_ok_and(|b| *blake3::hash(&b).as_bytes() == e.hash)
d3cd7ef9 Andy McCall ↶ 423
                }
424
                _ => false,
425
            };
426
            if !same {
427
                return Ok(false);
428
            }
da868d5d Andy McCall ↶ 429
        }
76740263 Andy McCall ↶ 430
        Ok(self.quick_dirty_keeping(true)? == Some(false))
da868d5d Andy McCall ↶ 431
    }
432
135212de Andy McCall ↶ 433
    /// Whether the working copy differs from the last manifest. Without a
434
    /// manifest the answer is `None`.
435
    pub fn quick_dirty(&self) -> Result<Option<bool>> {
76740263 Andy McCall ↶ 436
        self.quick_dirty_keeping(false)
437
    }
438
439
    /// `quick_dirty`; with `keep`, the listing it made is left for the
440
    /// next walk of the working copy.
441
    fn quick_dirty_keeping(&self, keep: bool) -> Result<Option<bool>> {
75167672 Andy McCall 442
        let Some((_, uncommitted, manifest)) = self.read_manifest()? else {
443
            return Ok(None);
444
        };
135212de Andy McCall ↶ 445
        if uncommitted {
446
            return Ok(Some(true));
447
        }
76740263 Andy McCall ↶ 448
        use rayon::prelude::*;
449
        let sparse = &self.config.sparse_paths;
eaf3e906 Andy McCall ↶ 450
        let in_scope = |p: &str| {
451
            sparse.is_empty()
452
                || sparse
453
                    .iter()
454
                    .any(|s| p == s || p.starts_with(&format!("{s}/")))
76740263 Andy McCall ↶ 455
        };
456
        // A working copy that cannot be listed counts as changed.
457
        let Ok(listing) = super::walk::list(&self.root, &in_scope) else {
458
            return Ok(Some(true));
eaf3e906 Andy McCall ↶ 459
        };
76740263 Andy McCall ↶ 460
        let differs = || -> Result<bool> {
461
            let links_differ = listing.symlinks.iter().any(|(rel, target)| {
462
                manifest
463
                    .entries
464
                    .get(rel)
1966f5db Andy McCall ↶ 465
                    .is_none_or(|me| *blake3::hash(target).as_bytes() != me.hash)
76740263 Andy McCall ↶ 466
            });
467
            if links_differ {
468
                return Ok(true);
469
            }
470
            // Each file is checked on its own, in parallel, stopping at the
471
            // first difference; an unreadable one counts as different.
472
            let files_differ = listing.files.par_iter().any(|(rel, path, m)| {
473
                manifest.entries.get(rel).is_none_or(|me| {
474
                    m.len() != me.size
475
                        || super::is_executable(m) != me.exec
476
                        || (mtime_ns(m) != me.mtime_ns
477
                            && !fs::read(path)
1966f5db Andy McCall ↶ 478
                                .is_ok_and(|b| *blake3::hash(&b).as_bytes() == me.hash))
76740263 Andy McCall ↶ 479
                })
480
            });
481
            if files_differ {
482
                return Ok(true);
483
            }
484
            let seen = listing.files.len() + listing.symlinks.len();
485
            if seen == manifest.entries.len() {
486
                return Ok(false);
487
            }
488
            // Manifest entries the walk skipped: tracked files that ignore rules
489
            // hide. They count as present when still on disk and unchanged.
490
            for (rel, me) in &manifest.entries {
491
                let path = self.root.join(rel);
492
                let Ok(m) = fs::symlink_metadata(&path) else {
493
                    return Ok(true);
eaf3e906 Andy McCall ↶ 494
                };
76740263 Andy McCall ↶ 495
                if m.file_type().is_symlink() {
496
                    continue;
eaf3e906 Andy McCall ↶ 497
                }
76740263 Andy McCall ↶ 498
                if m.len() != me.size
499
                    || super::is_executable(&m) != me.exec
500
                    || (mtime_ns(&m) != me.mtime_ns
1966f5db Andy McCall ↶ 501
                        && *blake3::hash(&fs::read(&path)?).as_bytes() != me.hash)
76740263 Andy McCall ↶ 502
                {
503
                    return Ok(true);
135212de Andy McCall ↶ 504
                }
9ac1fbe2 Andy McCall ↶ 505
            }
76740263 Andy McCall ↶ 506
            Ok(false)
507
        };
508
        let dirty = differs()?;
509
        if dirty && keep {
510
            *self.listing_cache.borrow_mut() = Some(listing);
9ac1fbe2 Andy McCall ↶ 511
        }
76740263 Andy McCall ↶ 512
        Ok(Some(dirty))
135212de Andy McCall ↶ 513
    }
514
515
    /// Prompt information without recording anything.
516
    pub fn quick_status(&self) -> Result<PromptInfo> {
517
        let view = self.view()?;
518
        let bookmark = self.config.bookmark.clone();
519
        let heads = self.heads_of(&view, &bookmark)?;
520
        let wc_hash = view.workspaces.get(&self.workspace).copied();
521
        let change_id = match wc_hash {
69816d68 Andy McCall ↶ 522
            Some(h) => self.store.get_change_meta(&h)?.change_id.short(8),
135212de Andy McCall ↶ 523
            None => String::new(),
524
        };
525
        // Conflictedness was recorded by the last snapshot; without a
526
        // manifest (never snapshotted) both flags are unknown and shown clear.
527
        let manifest = self.read_manifest()?;
528
        let conflicted = manifest.as_ref().map(|(c, _, _)| *c).unwrap_or(false);
529
        let dirty = self.quick_dirty()?.unwrap_or(false);
530
        let (ahead, behind) = match view.remotes.get("origin").and_then(|b| b.get(&bookmark)) {
531
            Some(st) => {
532
                let remote_heads = self.store.get_state(st)?.heads;
533
                let ahead = self.negotiate(&remote_heads, &heads).map(|v| v.len()).ok();
534
                let behind = self.negotiate(&heads, &remote_heads).map(|v| v.len()).ok();
535
                (ahead, behind)
536
            }
537
            None => (None, None),
538
        };
75167672 Andy McCall 539
        Ok(PromptInfo {
540
            bookmark,
541
            change_id,
542
            heads: heads.len(),
543
            dirty,
544
            conflicted,
545
            ahead,
546
            behind,
547
        })
135212de Andy McCall ↶ 548
    }
549
}
694805cc Andy McCall ↶ 550
551
#[cfg(test)]
552
mod tests {
553
    use super::*;
554
555
    #[test]
556
    fn placeholders_and_glyphs() {
75167672 Andy McCall 557
        let clean = PromptInfo {
558
            bookmark: "main".into(),
559
            change_id: "658990aa".into(),
560
            heads: 1,
561
            dirty: false,
562
            conflicted: false,
563
            ahead: Some(0),
564
            behind: None,
565
        };
694805cc Andy McCall ↶ 566
        assert_eq!(clean.format(DEFAULT_PROMPT_FORMAT), "main 658990aa");
567
        assert_eq!(clean.format(GLYPH_PROMPT_FORMAT), "⚛ main 658990aa ✔");
75167672 Andy McCall 568
        let busy = PromptInfo {
569
            dirty: true,
570
            ahead: Some(2),
571
            behind: Some(3),
572
            ..clean.clone()
573
        };
694805cc Andy McCall ↶ 574
        assert_eq!(busy.format(DEFAULT_PROMPT_FORMAT), "main 658990aa*+2-3");
575
        assert_eq!(busy.format(GLYPH_PROMPT_FORMAT), "⚛ main 658990aa ✎↑2↓3");
75167672 Andy McCall 576
        let bad = PromptInfo {
577
            conflicted: true,
578
            ..busy.clone()
579
        };
694805cc Andy McCall ↶ 580
        assert_eq!(bad.format("%s%x%d %h %a/%B %%"), "‼!* 1 2/3 %");
581
        assert_eq!(bad.state_color(), 31);
75167672 Andy McCall 582
        assert_eq!(
583
            busy.format_colored("%b", ("\\[", "\\]")),
584
            "\\[\x1b[33m\\]main\\[\x1b[0m\\]"
585
        );
694805cc Andy McCall ↶ 586
        assert_eq!(clean.format_colored("%b", ("", "")), "\x1b[36mmain\x1b[0m");
587
        assert_eq!(clean.format("%q"), "%q");
588
    }
589
}