Skip to main content

fallow_engine/
flag_age.rs

1//! Flag age from git history for `fallow flags --retirement`.
2//!
3//! `blame` mode runs one `git blame --porcelain` per file with flag sites and
4//! asks for the lines of those sites only. The oldest commit is a lower bound
5//! on the age of the flag, because a rewrite of the line resets it. `pickaxe`
6//! mode also runs one `git log -S<name>` per flag name, which gives the first
7//! commit that added the name. Both modes count days against the
8//! [`AnalysisClock`], so two runs over one commit give the same ages.
9//!
10//! Results are cached under the cache directory for the current HEAD. A blame
11//! entry is also keyed by the file content, because blame reads the working
12//! tree.
13
14use std::collections::BTreeMap;
15use std::path::Path;
16use std::process::Stdio;
17use std::sync::atomic::{AtomicUsize, Ordering};
18
19use fallow_types::flag_retirement::{FlagAgeMode, FlagCommit, RetirementFlag};
20use fallow_types::path_guard::CacheTarget;
21use fallow_types::workspace::WorkspaceDiagnosticKind;
22use rayon::prelude::*;
23use rustc_hash::{FxHashMap, FxHashSet};
24use serde::{Deserialize, Serialize};
25
26use crate::clock::{AnalysisClock, utc_date, utc_timestamp};
27
28/// Cache file name under the cache directory.
29const CACHE_FILE: &str = "flag-age.json";
30
31/// Cache format version. Bump it when the cached shape or meaning changes.
32const CACHE_VERSION: u32 = 1;
33
34/// Length of the abbreviated commit hash in the report.
35const SHORT_SHA_LEN: usize = 12;
36
37/// Seconds in one day.
38const SECS_PER_DAY: u64 = 86_400;
39
40/// Number of pickaxe runs between two progress reports.
41const PICKAXE_PROGRESS_STEP: usize = 10;
42
43/// Pickaxe progress: flag names read so far, and the flag names to read.
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
45pub struct PickaxeProgress {
46    /// Flag names read so far.
47    pub done: usize,
48    /// Flag names this run reads.
49    pub total: usize,
50}
51
52/// Inputs of one flag-age measurement.
53#[derive(Clone, Copy)]
54pub struct FlagAgeRequest<'a> {
55    /// Project root. Git runs here, and site paths are relative to it.
56    pub root: &'a Path,
57    /// How to measure the age.
58    pub mode: FlagAgeMode,
59    /// Directory for the age cache, or `None` to run without the cache.
60    pub cache_dir: Option<&'a Path>,
61    /// Receives pickaxe progress: once at the start, then every few names.
62    pub progress: Option<&'a (dyn Fn(PickaxeProgress) + Sync)>,
63}
64
65/// What a flag-age measurement did.
66#[derive(Debug, Default)]
67pub struct FlagAgeOutcome {
68    /// The analysis clock as an RFC 3339 timestamp, when ages were measured.
69    pub generated_at_clock: Option<String>,
70    /// Why ages are missing, when history was not available.
71    pub diagnostics: Vec<WorkspaceDiagnosticKind>,
72    /// `git blame` subprocesses this run started.
73    pub blame_calls: usize,
74    /// `git log -S` subprocesses this run started.
75    pub pickaxe_calls: usize,
76}
77
78/// A commit and its committer time.
79#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
80struct CommitStamp {
81    sha: String,
82    time: u64,
83}
84
85#[derive(Debug, Default, Serialize, Deserialize)]
86struct AgeCache {
87    version: u32,
88    head: String,
89    files: BTreeMap<String, FileBlame>,
90    pickaxe: BTreeMap<String, Option<CommitStamp>>,
91}
92
93#[derive(Debug, Default, Serialize, Deserialize)]
94struct FileBlame {
95    content_hash: u64,
96    lines: BTreeMap<u32, Option<CommitStamp>>,
97}
98
99/// Fill the age fields of `rows` from git history.
100///
101/// A missing repository, a branch without commits and a shallow clone leave
102/// every age `None` and return the matching diagnostic.
103pub(crate) fn apply_flag_ages(
104    rows: &mut [RetirementFlag],
105    request: &FlagAgeRequest<'_>,
106) -> FlagAgeOutcome {
107    let mut outcome = FlagAgeOutcome::default();
108    if request.mode == FlagAgeMode::Off {
109        return outcome;
110    }
111    let head = match probe_history(request.root) {
112        Ok(head) => head,
113        Err(diagnostic) => {
114            outcome.diagnostics.push(diagnostic);
115            return outcome;
116        }
117    };
118    let clock = AnalysisClock::for_repo(request.root);
119    outcome.generated_at_clock = Some(utc_timestamp(clock.epoch_secs()));
120
121    let mut cache = request
122        .cache_dir
123        .and_then(|dir| load_cache(dir, &head))
124        .unwrap_or_else(|| AgeCache {
125            version: CACHE_VERSION,
126            head: head.clone(),
127            ..AgeCache::default()
128        });
129
130    outcome.blame_calls = refresh_blame(&mut cache, rows, request.root);
131    if request.mode == FlagAgeMode::Pickaxe {
132        outcome.pickaxe_calls = refresh_pickaxe(&mut cache, rows, request);
133    }
134    if let Some(dir) = request.cache_dir
135        && (outcome.blame_calls > 0 || outcome.pickaxe_calls > 0)
136    {
137        save_cache(CacheTarget::new(request.root, dir), &cache);
138    }
139
140    for row in rows.iter_mut() {
141        fill_row(row, &cache, request.mode, clock);
142    }
143    outcome
144}
145
146/// HEAD's commit hash, or the diagnostic that explains why no history is
147/// available.
148fn probe_history(root: &Path) -> Result<String, WorkspaceDiagnosticKind> {
149    let shallow = run_git(root, &["rev-parse", "--is-shallow-repository"]).ok_or_else(|| {
150        WorkspaceDiagnosticKind::FlagAgeUnavailable {
151            cause: "not-a-repository".to_string(),
152        }
153    })?;
154    if shallow.trim().eq_ignore_ascii_case("true") {
155        return Err(WorkspaceDiagnosticKind::FlagAgeShallowClone);
156    }
157    let head = run_git(root, &["rev-parse", "--verify", "--quiet", "HEAD"]).ok_or_else(|| {
158        WorkspaceDiagnosticKind::FlagAgeUnavailable {
159            cause: "no-commits".to_string(),
160        }
161    })?;
162    Ok(head.trim().to_string())
163}
164
165fn run_git(root: &Path, args: &[&str]) -> Option<String> {
166    let output = crate::git_env::git_command(root)
167        .args(args)
168        .current_dir(root)
169        .stderr(Stdio::null())
170        .output()
171        .ok()?;
172    output
173        .status
174        .success()
175        .then(|| String::from_utf8_lossy(&output.stdout).into_owned())
176}
177
178/// Blame every file whose site lines the cache does not hold for the current
179/// file content. Returns the number of blame subprocesses.
180fn refresh_blame(cache: &mut AgeCache, rows: &[RetirementFlag], root: &Path) -> usize {
181    let mut lines_by_file: BTreeMap<&str, FxHashSet<u32>> = BTreeMap::new();
182    for site in rows.iter().flat_map(|row| &row.sites) {
183        lines_by_file
184            .entry(site.path.as_str())
185            .or_default()
186            .insert(site.line);
187    }
188    let stale: Vec<(String, u64, Vec<u32>)> = lines_by_file
189        .into_iter()
190        .filter_map(|(path, lines)| {
191            let bytes = std::fs::read(root.join(path)).ok()?;
192            let content_hash = xxhash_rust::xxh3::xxh3_64(&bytes);
193            let cached = cache.files.get(path).is_some_and(|entry| {
194                entry.content_hash == content_hash
195                    && lines.iter().all(|line| entry.lines.contains_key(line))
196            });
197            if cached {
198                return None;
199            }
200            let mut lines: Vec<u32> = lines.into_iter().collect();
201            lines.sort_unstable();
202            Some((path.to_string(), content_hash, lines))
203        })
204        .collect();
205
206    let calls = AtomicUsize::new(0);
207    let blamed: Vec<(String, u64, FxHashMap<u32, Option<CommitStamp>>)> = stale
208        .into_par_iter()
209        .map(|(path, content_hash, lines)| {
210            calls.fetch_add(1, Ordering::Relaxed);
211            let stamps = blame_lines(root, &path, &lines);
212            (path, content_hash, stamps)
213        })
214        .collect();
215
216    for (path, content_hash, stamps) in blamed {
217        let entry = cache.files.entry(path).or_default();
218        if entry.content_hash != content_hash {
219            entry.lines.clear();
220            entry.content_hash = content_hash;
221        }
222        entry.lines.extend(stamps);
223    }
224    calls.into_inner()
225}
226
227/// Commit of each of `lines` in `path`. A line that no commit holds (an
228/// uncommitted change, or an untracked file) maps to `None`.
229fn blame_lines(root: &Path, path: &str, lines: &[u32]) -> FxHashMap<u32, Option<CommitStamp>> {
230    let mut args: Vec<String> = vec!["blame".to_string(), "--porcelain".to_string()];
231    for line in lines {
232        args.push("-L".to_string());
233        args.push(format!("{line},{line}"));
234    }
235    args.push("--".to_string());
236    args.push(path.to_string());
237    let arg_refs: Vec<&str> = args.iter().map(String::as_str).collect();
238    let mut stamps: FxHashMap<u32, Option<CommitStamp>> =
239        lines.iter().map(|&line| (line, None)).collect();
240    if let Some(output) = run_git(root, &arg_refs) {
241        stamps.extend(parse_blame_porcelain(&output));
242    }
243    stamps
244}
245
246/// Parse `git blame --porcelain` into the commit of each final line.
247fn parse_blame_porcelain(output: &str) -> FxHashMap<u32, Option<CommitStamp>> {
248    let mut times: FxHashMap<&str, u64> = FxHashMap::default();
249    let mut line_shas: Vec<(u32, &str)> = Vec::new();
250    let mut current: Option<(&str, u32)> = None;
251    for line in output.lines() {
252        if line.starts_with('\t') {
253            if let Some((sha, final_line)) = current.take() {
254                line_shas.push((final_line, sha));
255            }
256            continue;
257        }
258        if let Some(time) = line.strip_prefix("committer-time ") {
259            if let (Some((sha, _)), Ok(time)) = (current, time.trim().parse::<u64>()) {
260                times.insert(sha, time);
261            }
262            continue;
263        }
264        let mut fields = line.split(' ');
265        let Some(first) = fields.next() else {
266            continue;
267        };
268        if is_object_id(first)
269            && let Some(Ok(final_line)) = fields.nth(1).map(str::parse::<u32>)
270        {
271            current = Some((first, final_line));
272        }
273    }
274    line_shas
275        .into_iter()
276        .map(|(line, sha)| {
277            let stamp = (!sha.bytes().all(|byte| byte == b'0'))
278                .then(|| times.get(sha))
279                .flatten()
280                .map(|&time| CommitStamp {
281                    sha: sha.to_string(),
282                    time,
283                });
284            (line, stamp)
285        })
286        .collect()
287}
288
289fn is_object_id(token: &str) -> bool {
290    matches!(token.len(), 40 | 64) && token.bytes().all(|byte| byte.is_ascii_hexdigit())
291}
292
293/// Run `git log -S` for every flag name the cache does not hold. Returns the
294/// number of pickaxe subprocesses.
295fn refresh_pickaxe(
296    cache: &mut AgeCache,
297    rows: &[RetirementFlag],
298    request: &FlagAgeRequest<'_>,
299) -> usize {
300    let mut names: Vec<&str> = rows
301        .iter()
302        .map(|row| row.flag_name.as_str())
303        .filter(|name| !name.is_empty() && !cache.pickaxe.contains_key(*name))
304        .collect();
305    names.sort_unstable();
306    names.dedup();
307    if names.is_empty() {
308        return 0;
309    }
310    let total = names.len();
311    let report = |done: usize| {
312        if let Some(progress) = request.progress {
313            progress(PickaxeProgress { done, total });
314        }
315    };
316    report(0);
317    let done = AtomicUsize::new(0);
318    let found: Vec<(String, Option<CommitStamp>)> = names
319        .into_par_iter()
320        .map(|name| {
321            let stamp = first_commit_with(request.root, name);
322            let finished = done.fetch_add(1, Ordering::Relaxed) + 1;
323            if finished < total && finished.is_multiple_of(PICKAXE_PROGRESS_STEP) {
324                report(finished);
325            }
326            (name.to_string(), stamp)
327        })
328        .collect();
329    cache.pickaxe.extend(found);
330    total
331}
332
333/// The oldest commit under the root that changed the number of times `name`
334/// occurs.
335fn first_commit_with(root: &Path, name: &str) -> Option<CommitStamp> {
336    let pickaxe = format!("-S{name}");
337    let output = run_git(
338        root,
339        &[
340            "log",
341            pickaxe.as_str(),
342            "--reverse",
343            "--format=%H %ct",
344            "--",
345            ".",
346        ],
347    )?;
348    let first = output.lines().next()?;
349    let (sha, time) = first.split_once(' ')?;
350    Some(CommitStamp {
351        sha: sha.to_string(),
352        time: time.trim().parse().ok()?,
353    })
354}
355
356fn fill_row(row: &mut RetirementFlag, cache: &AgeCache, mode: FlagAgeMode, clock: AnalysisClock) {
357    let stamps: Vec<&CommitStamp> = row
358        .sites
359        .iter()
360        .filter_map(|site| {
361            cache
362                .files
363                .get(&site.path)
364                .and_then(|entry| entry.lines.get(&site.line))
365                .and_then(Option::as_ref)
366        })
367        .collect();
368    let oldest = stamps
369        .iter()
370        .min_by(|a, b| a.time.cmp(&b.time).then(a.sha.cmp(&b.sha)))
371        .copied();
372    let newest = stamps
373        .iter()
374        .max_by(|a, b| a.time.cmp(&b.time).then(b.sha.cmp(&a.sha)))
375        .copied();
376    let first_seen = (mode == FlagAgeMode::Pickaxe)
377        .then(|| cache.pickaxe.get(&row.flag_name))
378        .flatten()
379        .and_then(Option::as_ref);
380
381    row.oldest_surviving_site = oldest.map(flag_commit);
382    row.last_touched = newest.map(flag_commit);
383    row.first_seen = first_seen.map(flag_commit);
384    row.age_days = first_seen
385        .or(oldest)
386        .map(|stamp| clock.epoch_secs().saturating_sub(stamp.time) / SECS_PER_DAY);
387}
388
389fn flag_commit(stamp: &CommitStamp) -> FlagCommit {
390    FlagCommit {
391        commit: stamp.sha.chars().take(SHORT_SHA_LEN).collect(),
392        date: utc_date(stamp.time),
393    }
394}
395
396fn load_cache(dir: &Path, head: &str) -> Option<AgeCache> {
397    let bytes = std::fs::read(dir.join(CACHE_FILE)).ok()?;
398    let cache: AgeCache = serde_json::from_slice(&bytes).ok()?;
399    (cache.version == CACHE_VERSION && cache.head == head).then_some(cache)
400}
401
402/// Write the cache through a temporary file, so a reader never sees a
403/// partial file. A failed write only costs the next run its warm cache. A
404/// symlink that leaves the base of `target` skips the save.
405fn save_cache(target: CacheTarget<'_>, cache: &AgeCache) {
406    if let Ok(bytes) = serde_json::to_vec(cache) {
407        let _ = target.write_file(CACHE_FILE, &bytes);
408    }
409}
410
411#[cfg(test)]
412mod tests {
413    use std::path::PathBuf;
414
415    use fallow_types::flag_retirement::{FlagSiteRole, RetirementFlagKind, RetirementSite};
416
417    use super::*;
418
419    /// 2023-11-14T22:13:20Z.
420    const BASE_EPOCH: u64 = 1_700_000_000;
421
422    #[test]
423    #[cfg(unix)]
424    fn a_linked_cache_dir_gets_no_age_cache() {
425        let dir = tempfile::tempdir().expect("temp dir");
426        let root = dir.path().join("project");
427        let outside = dir.path().join("outside");
428        std::fs::create_dir_all(&root).expect("root");
429        std::fs::create_dir_all(&outside).expect("outside");
430        std::os::unix::fs::symlink(&outside, root.join(".fallow")).expect("link");
431        let cache_dir = root.join(".fallow");
432        save_cache(CacheTarget::new(&root, &cache_dir), &AgeCache::default());
433        assert_eq!(std::fs::read_dir(&outside).expect("outside").count(), 0);
434        save_cache(CacheTarget::inside(&outside), &AgeCache::default());
435        assert!(
436            outside.join(CACHE_FILE).exists(),
437            "a plain directory gets the cache"
438        );
439    }
440
441    fn git(root: &Path, args: &[&str], epoch: Option<u64>) {
442        let mut command = crate::git_fixture::fixture_git_command_with_identity(
443            root,
444            crate::git_fixture::FixtureIdentity::RepositoryConfig,
445        );
446        command.args(args).stdout(Stdio::null());
447        if let Some(epoch) = epoch {
448            let stamp = format!("{epoch} +0000");
449            command
450                .env("GIT_AUTHOR_DATE", &stamp)
451                .env("GIT_COMMITTER_DATE", &stamp);
452        }
453        let status = command.status().expect("run git");
454        assert!(status.success(), "git {args:?} failed");
455    }
456
457    fn init_repo(root: &Path) {
458        git(root, &["init", "--quiet", "--initial-branch=main"], None);
459        git(root, &["config", "user.name", "Flag Fixture"], None);
460        git(root, &["config", "user.email", "fixture@example.com"], None);
461        git(root, &["config", "commit.gpgsign", "false"], None);
462    }
463
464    fn commit_file(root: &Path, path: &str, contents: &str, epoch: u64) {
465        let file = root.join(path);
466        std::fs::create_dir_all(file.parent().expect("parent")).expect("dirs");
467        std::fs::write(&file, contents).expect("write");
468        git(root, &["add", path], None);
469        git(root, &["commit", "--quiet", "-m", path], Some(epoch));
470    }
471
472    fn row(name: &str, sites: &[(&str, u32)]) -> RetirementFlag {
473        RetirementFlag {
474            flag_name: name.to_string(),
475            kind: RetirementFlagKind::EnvironmentVariable,
476            sdk_name: None,
477            workspace: None,
478            sites: sites
479                .iter()
480                .map(|&(path, line)| RetirementSite {
481                    path: path.to_string(),
482                    line,
483                    col: 0,
484                    role: FlagSiteRole::Read,
485                    in_test: false,
486                })
487                .collect(),
488            read_sites: sites.len(),
489            test_only: false,
490            first_seen: None,
491            oldest_surviving_site: None,
492            last_touched: None,
493            age_days: None,
494            reasons: Vec::new(),
495            evidence: Vec::new(),
496            actions: Vec::new(),
497            vendor: None,
498        }
499    }
500
501    /// A repository where `FEATURE_A` first appears at day 0, is rewritten
502    /// on day 10 in `a.ts`, and gets a second site in `b.ts` on day 40. HEAD
503    /// is at day 100.
504    fn fixture() -> (tempfile::TempDir, PathBuf) {
505        let dir = tempfile::tempdir().expect("temp dir");
506        let root = dir.path().to_path_buf();
507        init_repo(&root);
508        let day = |n: u64| BASE_EPOCH + n * SECS_PER_DAY;
509        commit_file(&root, "a.ts", "x\nif (process.env.FEATURE_A) {}\n", day(0));
510        commit_file(
511            &root,
512            "a.ts",
513            "x\nif (process.env.FEATURE_A === '1') {}\n",
514            day(10),
515        );
516        commit_file(&root, "b.ts", "if (process.env.FEATURE_A) {}\n", day(40));
517        commit_file(&root, "c.ts", "// unrelated\n", day(100));
518        (dir, root)
519    }
520
521    fn measure(
522        root: &Path,
523        mode: FlagAgeMode,
524        cache_dir: Option<&Path>,
525    ) -> (Vec<RetirementFlag>, FlagAgeOutcome) {
526        let mut rows = vec![row("FEATURE_A", &[("a.ts", 2), ("b.ts", 1)])];
527        let outcome = apply_flag_ages(
528            &mut rows,
529            &FlagAgeRequest {
530                root,
531                mode,
532                cache_dir,
533                progress: None,
534            },
535        );
536        (rows, outcome)
537    }
538
539    #[test]
540    fn blame_ages_count_from_the_oldest_surviving_line() {
541        let (_dir, root) = fixture();
542        let (rows, outcome) = measure(&root, FlagAgeMode::Blame, None);
543        let row = &rows[0];
544        assert!(outcome.diagnostics.is_empty());
545        assert_eq!(outcome.blame_calls, 2, "one blame per file with sites");
546        assert_eq!(outcome.pickaxe_calls, 0);
547        assert_eq!(
548            outcome.generated_at_clock.as_deref(),
549            Some("2024-02-22T22:13:20Z")
550        );
551        assert_eq!(row.age_days, Some(90), "day 100 minus the day-10 rewrite");
552        assert_eq!(
553            row.oldest_surviving_site.as_ref().map(|c| c.date.as_str()),
554            Some("2023-11-24")
555        );
556        assert_eq!(
557            row.last_touched.as_ref().map(|c| c.date.as_str()),
558            Some("2023-12-24")
559        );
560        assert!(row.first_seen.is_none(), "blame does not read first_seen");
561        assert_eq!(
562            row.oldest_surviving_site.as_ref().map(|c| c.commit.len()),
563            Some(SHORT_SHA_LEN)
564        );
565    }
566
567    #[test]
568    fn pickaxe_ages_count_from_the_first_commit_with_the_name() {
569        let (_dir, root) = fixture();
570        let (rows, outcome) = measure(&root, FlagAgeMode::Pickaxe, None);
571        let row = &rows[0];
572        assert_eq!(outcome.pickaxe_calls, 1, "one pickaxe per flag name");
573        assert_eq!(row.age_days, Some(100));
574        assert_eq!(
575            row.first_seen.as_ref().map(|c| c.date.as_str()),
576            Some("2023-11-14")
577        );
578    }
579
580    #[test]
581    fn a_warm_cache_starts_no_git_history_subprocess() {
582        let (_dir, root) = fixture();
583        let cache = tempfile::tempdir().expect("cache dir");
584        let (cold_rows, cold) = measure(&root, FlagAgeMode::Pickaxe, Some(cache.path()));
585        assert_eq!((cold.blame_calls, cold.pickaxe_calls), (2, 1));
586        let (warm_rows, warm) = measure(&root, FlagAgeMode::Pickaxe, Some(cache.path()));
587        assert_eq!((warm.blame_calls, warm.pickaxe_calls), (0, 0));
588        assert_eq!(cold_rows, warm_rows);
589    }
590
591    #[test]
592    fn an_edited_file_is_blamed_again() {
593        let (_dir, root) = fixture();
594        let cache = tempfile::tempdir().expect("cache dir");
595        let _ = measure(&root, FlagAgeMode::Blame, Some(cache.path()));
596        std::fs::write(
597            root.join("b.ts"),
598            "if (process.env.FEATURE_A) { edit(); }\n",
599        )
600        .expect("edit");
601        let (rows, outcome) = measure(&root, FlagAgeMode::Blame, Some(cache.path()));
602        assert_eq!(outcome.blame_calls, 1);
603        assert_eq!(
604            rows[0].last_touched.as_ref().map(|c| c.date.as_str()),
605            Some("2023-11-24"),
606            "an uncommitted line has no commit"
607        );
608    }
609
610    #[test]
611    fn off_mode_starts_no_git_subprocess() {
612        let (_dir, root) = fixture();
613        let (rows, outcome) = measure(&root, FlagAgeMode::Off, None);
614        assert_eq!((outcome.blame_calls, outcome.pickaxe_calls), (0, 0));
615        assert!(outcome.generated_at_clock.is_none());
616        assert_eq!(rows[0].age_days, None);
617    }
618
619    #[test]
620    fn no_repository_gives_no_age_and_a_diagnostic() {
621        let dir = tempfile::tempdir().expect("temp dir");
622        std::fs::write(dir.path().join("a.ts"), "x\n").expect("write");
623        let (rows, outcome) = measure(dir.path(), FlagAgeMode::Blame, None);
624        assert_eq!(rows[0].age_days, None);
625        assert_eq!(
626            outcome.diagnostics,
627            vec![WorkspaceDiagnosticKind::FlagAgeUnavailable {
628                cause: "not-a-repository".to_string()
629            }]
630        );
631    }
632
633    #[test]
634    fn a_branch_without_commits_gives_no_age_and_a_diagnostic() {
635        let dir = tempfile::tempdir().expect("temp dir");
636        init_repo(dir.path());
637        let (_, outcome) = measure(dir.path(), FlagAgeMode::Blame, None);
638        assert_eq!(
639            outcome.diagnostics,
640            vec![WorkspaceDiagnosticKind::FlagAgeUnavailable {
641                cause: "no-commits".to_string()
642            }]
643        );
644    }
645
646    #[test]
647    fn a_shallow_clone_gives_no_age_and_a_diagnostic() {
648        let (_dir, root) = fixture();
649        let clone = tempfile::tempdir().expect("clone dir");
650        let source = format!("file://{}", root.display());
651        git(
652            clone.path(),
653            &["clone", "--quiet", "--depth", "1", &source, "."],
654            None,
655        );
656        let (rows, outcome) = measure(clone.path(), FlagAgeMode::Blame, None);
657        assert_eq!(rows[0].age_days, None);
658        assert_eq!(
659            outcome.diagnostics,
660            vec![WorkspaceDiagnosticKind::FlagAgeShallowClone]
661        );
662    }
663
664    #[test]
665    fn porcelain_parser_reads_repeated_commits_and_uncommitted_lines() {
666        let sha = "a".repeat(40);
667        let zero = "0".repeat(40);
668        let output = format!(
669            "{sha} 1 3 1\nauthor A\ncommitter-time 100\nsummary s\nfilename a.ts\n\tline three\n\
670             {sha} 2 5 1\n\tline five\n\
671             {zero} 7 7 1\ncommitter-time 900\n\tline seven\n"
672        );
673        let stamps = parse_blame_porcelain(&output);
674        assert_eq!(stamps[&3].as_ref().map(|s| s.time), Some(100));
675        assert_eq!(stamps[&5].as_ref().map(|s| s.time), Some(100));
676        assert_eq!(stamps[&7], None);
677    }
678}