tak_cli/notes.rs
1//! Storage: benchmark results as git notes under `refs/notes/tak`.
2//!
3//! Why notes rather than an orphan branch or a committed file:
4//!
5//! - The data is *about a commit*, which is exactly what notes are for.
6//! - `cat_sort_uniq` resolves concurrent writers with no custom merge driver.
7//! - The notes tree is keyed by commit SHA as *path names* and does not reference
8//! the annotated commits, so a single shallow fetch of this one ref returns the
9//! entire history without cloning the repository — measured at 36ms / 124K for
10//! 100 commits × 6 benchmarks, with zero project commit objects transferred.
11//! That property is what makes a hosted dashboard cheap.
12//!
13//! All network operations shell out to `git` on purpose. `actions/checkout` sets
14//! up auth via `http.extraheader`, and users have credential helpers, SSH agents
15//! and corporate proxies; reimplementing any of that is a trap. Local object
16//! access can move to `gix` later without changing this boundary.
17
18use anyhow::{Context, Result, bail};
19use std::io::{BufRead, BufReader, Read};
20use std::process::{Command, Stdio};
21
22use crate::record::{Record, parse_note};
23
24pub const NOTES_REF: &str = "refs/notes/tak";
25
26/// Scratch ref the remote is fetched into, so a fetch never lands directly on
27/// the ref holding records that have not been pushed yet.
28const REMOTE_REF: &str = "refs/notes/tak-remote";
29
30/// Refspec for reading. Forced, which is safe because it only ever overwrites
31/// the scratch ref.
32const FETCH_REFSPEC: &str = "+refs/notes/tak:refs/notes/tak-remote";
33
34/// Refspec for writing, deliberately **not** forced.
35///
36/// A forced push always succeeds. That makes the retry-and-merge loop below
37/// unreachable and lets any writer with a stale or empty local ref replace the
38/// entire remote history in one shot. It is not a hypothetical: a CI job whose
39/// checkout had never fetched notes recorded one measurement, pushed, and
40/// destroyed 60 backfilled ones in jdx/aube.
41///
42/// Without the `+`, that push is rejected as a non-fast-forward, and the loop
43/// fetches the remote, merges it in with cat_sort_uniq, and tries again.
44const PUSH_REFSPEC: &str = "refs/notes/tak:refs/notes/tak";
45
46/// Refspec suggested to users for plain `git fetch`, which has no local records
47/// to lose because it is a read-only convenience for people who never run tak.
48const USER_FETCH_REFSPEC: &str = "+refs/notes/tak:refs/notes/tak";
49/// Number of fetch/merge/push attempts before giving up on a contended push.
50const PUSH_ATTEMPTS: u32 = 5;
51
52fn git(args: &[&str]) -> Result<String> {
53 let out = Command::new("git")
54 .args(args)
55 .output()
56 .with_context(|| format!("failed to run `git {}`", args.join(" ")))?;
57 if !out.status.success() {
58 bail!(
59 "git {} failed: {}",
60 args.join(" "),
61 String::from_utf8_lossy(&out.stderr).trim()
62 );
63 }
64 Ok(String::from_utf8_lossy(&out.stdout).trim_end().to_string())
65}
66
67/// Fallback identity arguments for commands that create a commit.
68///
69/// `git notes add` and `git notes merge` write commits, so git demands an
70/// author. Containers and fresh CI images routinely have none configured, and
71/// aborting a whole backfill for want of a name nobody will ever read is not a
72/// useful failure. Only applied when the user has not set one, so a real
73/// identity is never overridden.
74fn identity_args() -> Vec<&'static str> {
75 let configured = |key: &str| {
76 Command::new("git")
77 .args(["config", "--get", key])
78 .output()
79 .map(|o| o.status.success())
80 .unwrap_or(false)
81 };
82 // Checked independently: a machine with `user.name` set but no email would
83 // otherwise have its real name replaced by the placeholder.
84 let mut args = Vec::new();
85 if !configured("user.name") {
86 args.extend_from_slice(&["-c", "user.name=tak"]);
87 }
88 if !configured("user.email") {
89 args.extend_from_slice(&["-c", "user.email=tak@localhost"]);
90 }
91 args
92}
93
94/// Like [`git`] but prepends a fallback identity, for commands that commit.
95fn git_committing(args: &[&str]) -> Result<String> {
96 let mut full = identity_args();
97 full.extend_from_slice(args);
98 git(&full)
99}
100
101/// Like [`git`] but returns the failure instead of raising, for calls whose
102/// failure is an expected outcome (a rejected push, a missing note).
103fn git_ok(args: &[&str]) -> Result<(bool, String)> {
104 let out = Command::new("git")
105 .args(args)
106 .output()
107 .with_context(|| format!("failed to run `git {}`", args.join(" ")))?;
108 let text = if out.status.success() {
109 String::from_utf8_lossy(&out.stdout).trim_end().to_string()
110 } else {
111 String::from_utf8_lossy(&out.stderr).trim_end().to_string()
112 };
113 Ok((out.status.success(), text))
114}
115
116/// Pull the notes ref from `remote`.
117///
118/// Never fatal: a developer may be offline, or the remote may have no notes yet.
119/// Callers fall back to whatever is in the local ref.
120pub fn fetch(remote: &str) -> Result<bool> {
121 let (ok, _) = git_ok(&["fetch", "--quiet", "--depth", "1", remote, FETCH_REFSPEC])?;
122 if !ok {
123 return Ok(false);
124 }
125 absorb_remote()?;
126 Ok(true)
127}
128
129/// Fold the fetched remote notes into the local ref, keeping both sides.
130///
131/// Reading used to fetch straight onto `refs/notes/tak`, so `tak history` after
132/// a local `tak run --record` threw the local record away before it could be
133/// pushed. Merging instead of overwriting is the same choice the push path
134/// makes, for the same reason: neither side of this ref is authoritative.
135fn absorb_remote() -> Result<()> {
136 // Nothing local yet: adopt the remote wholesale. `notes merge` needs a ref
137 // to merge into and would fail here.
138 let (has_local, _) = git_ok(&["rev-parse", "--verify", "--quiet", NOTES_REF])?;
139 if !has_local {
140 git(&["update-ref", NOTES_REF, REMOTE_REF])?;
141 return Ok(());
142 }
143 git_committing(&[
144 "notes",
145 "--ref",
146 NOTES_REF,
147 "merge",
148 "-s",
149 "cat_sort_uniq",
150 REMOTE_REF,
151 ])?;
152 Ok(())
153}
154
155/// Read every record attached to `commit`, after refreshing from the remote.
156///
157/// The fetch is deliberately inside the read path. Users must never have to know
158/// that notes exist, let alone that they need a refspec — that seam is the single
159/// biggest usability risk in this design.
160pub fn read(remote: Option<&str>, commit: &str) -> Result<Vec<Record>> {
161 if let Some(r) = remote {
162 let _ = fetch(r);
163 }
164 let (ok, body) = git_ok(&["notes", "--ref", NOTES_REF, "show", commit])?;
165 if !ok {
166 // No note for this commit is a normal state, not an error.
167 return Ok(vec![]);
168 }
169 Ok(parse_note(&body))
170}
171
172/// Append records to `commit`'s note locally, preserving anything already there.
173pub fn append(commit: &str, records: &[Record]) -> Result<()> {
174 if records.is_empty() {
175 return Ok(());
176 }
177 let mut lines: Vec<String> = Vec::new();
178 let (ok, existing) = git_ok(&["notes", "--ref", NOTES_REF, "show", commit])?;
179 if ok {
180 lines.extend(existing.lines().map(str::to_string));
181 }
182 for r in records {
183 lines.push(r.to_line()?);
184 }
185 // Sort and dedupe locally so the note matches what cat_sort_uniq would
186 // produce on merge; otherwise a local write and a remote merge of the same
187 // data yield different bytes.
188 lines.sort();
189 lines.dedup();
190
191 git_committing(&[
192 "notes",
193 "--ref",
194 NOTES_REF,
195 "add",
196 "-f",
197 "-m",
198 &lines.join("\n"),
199 commit,
200 ])?;
201 Ok(())
202}
203
204/// Push the notes ref, resolving races against other CI jobs.
205///
206/// Two runners finishing at once will both try to push; the loser is rejected,
207/// re-fetches, merges with `cat_sort_uniq` and retries. Verified end-to-end: both
208/// runners' measurements survive the merge.
209pub fn push(remote: &str) -> Result<()> {
210 for attempt in 1..=PUSH_ATTEMPTS {
211 let (ok, err) = git_ok(&["push", "--quiet", remote, PUSH_REFSPEC])?;
212 if ok {
213 return Ok(());
214 }
215 if attempt == PUSH_ATTEMPTS {
216 bail!("could not push {NOTES_REF} after {PUSH_ATTEMPTS} attempts: {err}");
217 }
218 // Fetch the winner's ref to a scratch location, then merge into ours.
219 git(&["fetch", "--quiet", remote, FETCH_REFSPEC])?;
220 absorb_remote()?;
221 }
222 unreachable!()
223}
224
225/// Resolve a revision to the full SHA of the commit it names.
226///
227/// `^{commit}` matters: `git rev-parse v1.2.3` on an *annotated* tag returns the
228/// tag object, not the commit, and notes are attached to commits. Without the
229/// peel, `tak history v1.2.3` and `tak compare v1.2.3` silently find nothing on
230/// exactly the revisions people are most likely to name. Harmless for branches
231/// and raw SHAs, which peel to themselves.
232pub fn rev_parse(rev: &str) -> Result<String> {
233 git(&["rev-parse", &format!("{rev}^{{commit}}")])
234}
235
236/// The current directory relative to the repository root, as git spells it:
237/// `a/b/` in a subdirectory, empty at the root.
238pub fn prefix() -> Result<String> {
239 git(&["rev-parse", "--show-prefix"])
240}
241
242/// The contents of `path`, relative to the repository root, in `commit`'s
243/// tree, or `None` when that tree has no such file.
244///
245/// Absent and unreadable are told apart, which is why this asks `ls-tree`
246/// before reading: `cat-file` fails the same way for a path the commit does
247/// not have and for a tree this clone never fetched. A caller that falls back
248/// on absence must not fall back on the second, or a checkout missing the
249/// objects would quietly get a different answer from one that has them.
250///
251/// `cat-file blob` rather than `git show`: plumbing, so no pager, no textconv
252/// and nothing a user's config can put between the bytes and the parser.
253/// `--literal-pathspecs` because a directory name is data here, not a glob.
254///
255/// A symlink is followed, as the search on disk follows one, but only within
256/// `commit`'s own tree: its blob holds the target path, which is resolved and
257/// looked up in the same tree. A target that is absolute or climbs out of the
258/// repository is refused rather than read from the disk, because the disk is
259/// the working tree, and the working tree is what this read exists to avoid.
260/// A link that leads nowhere is an error, not an absent file: the tree says a
261/// file is there, and falling back would ignore it.
262pub fn file_at(commit: &str, path: &str) -> Result<Option<String>> {
263 let mut at = path.to_string();
264 for _ in 0..=MAX_LINKS {
265 let entry = git(&[
266 "--literal-pathspecs",
267 "ls-tree",
268 "-z",
269 "--full-tree",
270 commit,
271 "--",
272 &at,
273 ])?;
274 let Some((meta, _)) = entry.split_once('\t') else {
275 if at == path {
276 return Ok(None);
277 }
278 bail!("{path} at {commit} is a symlink to {at}, which does not exist there");
279 };
280 let blob = format!("{commit}:{at}");
281 match meta.split(' ').next() {
282 Some("100644" | "100755") => return git(&["cat-file", "blob", &blob]).map(Some),
283 Some("120000") => {
284 let target = git(&["cat-file", "blob", &blob])?;
285 at = resolve_link(&at, &target).with_context(|| {
286 format!(
287 "{path} at {commit} is a symlink to {target}, which is outside \
288 the repository"
289 )
290 })?;
291 }
292 _ => bail!("{at} at {commit} is not a regular file"),
293 }
294 }
295 bail!("{path} at {commit} goes through more than {MAX_LINKS} symlinks")
296}
297
298/// Symlinks [`file_at`] follows before giving up. A loop would otherwise never
299/// end, and a real configuration is one link deep, not nine.
300const MAX_LINKS: usize = 8;
301
302/// Where a symlink at `link` pointing at `target` leads, as a path from the
303/// repository root, or `None` when it leaves the repository.
304///
305/// Lexical, as the tree has no directories to stat: `..` pops the path built
306/// so far. Popping past the root, or an absolute target, escapes.
307fn resolve_link(link: &str, target: &str) -> Option<String> {
308 if target.starts_with('/') || target.starts_with('\\') {
309 return None;
310 }
311 let mut parts: Vec<&str> = link.split('/').collect();
312 parts.pop();
313 for part in target.split('/') {
314 match part {
315 "" | "." => {}
316 ".." => {
317 parts.pop()?;
318 }
319 name => parts.push(name),
320 }
321 }
322 // The root itself is a directory, never the file being looked for.
323 (!parts.is_empty()).then(|| parts.join("/"))
324}
325
326/// The most recent `n` commits reachable from `rev`, newest first.
327///
328/// First-parent only. A merge commit's second parent is the branch that was
329/// merged, and walking into it interleaves a feature branch's measurements with
330/// the trunk's — which makes a trend line jump around for reasons that have
331/// nothing to do with the trunk.
332pub fn rev_list(rev: &str, n: usize) -> Result<Vec<String>> {
333 let n = n.to_string();
334 let out = git(&["rev-list", "--first-parent", "-n", &n, rev])?;
335 Ok(out.lines().map(str::to_string).collect())
336}
337
338/// The values of trailer `key` on every commit in `base..head`, one line per
339/// commit: its SHA, then each value, every field NUL-separated.
340///
341/// Every commit in the range, not first-parent only — the opposite choice to
342/// [`rev_list`], for a different question. A trend follows the trunk; this asks
343/// what the change being measured declares, and under a merge-commit workflow
344/// the declaration sits on the branch commits, reachable only through the
345/// merge's second parent. Under squash-merge the range is the one squashed
346/// commit, and whatever trailers survived into its message.
347///
348/// `unfold` joins a value git wrapped onto continuation lines, and the NUL
349/// separator keeps repeated trailers on one line, so a line is always exactly
350/// one commit. NUL rather than a comma because it is the one byte a trailer
351/// value cannot hold: joining with commas made `Tak-Accept: a,b` and two
352/// trailers `a` and `b` produce the same output, so a benchmark named `a,b`
353/// could only ever be read as two others. Commits with no such trailer still
354/// print their SHA; the parser skips the empty value.
355///
356/// `--no-show-signature` for the same reason [`log`] passes it: a user's
357/// `log.showSignature` would otherwise put GPG output on stdout, between the
358/// lines this parses. `--end-of-options` and `--` keep the range a revision
359/// whatever it looks like.
360///
361/// `first_parent` narrows the range to the trunk's own commits, for `tak
362/// detect`: after a merge, what landed on main is the commit on its
363/// first-parent line — the squash, the rebased commit, or the merge itself —
364/// and that is the history a main-branch check has reviewed as merged. A
365/// branch commit behind a merge's second parent was only ever gated on its
366/// pull request.
367pub fn trailers(base: &str, head: &str, key: &str, first_parent: bool) -> Result<String> {
368 let format = format!("--format=%H%x00%(trailers:key={key},valueonly,unfold,separator=%x00)");
369 let range = format!("{base}..{head}");
370 let mut args = vec!["log", "--no-show-signature"];
371 if first_parent {
372 args.push("--first-parent");
373 }
374 args.extend([format.as_str(), "--end-of-options", &range, "--"]);
375 git(&args)
376}
377
378/// One commit on a first-parent walk, with whatever tak recorded on it.
379#[derive(Debug, Clone)]
380pub struct Logged {
381 pub sha: String,
382 /// Committer date, strict ISO 8601. The committer date rather than the
383 /// author date because a trunk timeline is about when a change landed; a
384 /// branch rebased and merged a month later was authored long before it
385 /// could have moved anything.
386 pub date: String,
387 pub subject: String,
388 /// Empty for a commit nothing was recorded on — the common case.
389 pub records: Vec<Record>,
390}
391
392/// Fields per commit in [`log`]'s output: SHA, date, subject, note.
393const LOG_FIELDS: usize = 4;
394
395/// Every commit on `rev`'s first-parent history, newest first, with its records.
396///
397/// One `git log`, with each note inlined through `%N`, rather than a
398/// `notes show` per commit: a series view wants hundreds of commits, and a
399/// subprocess each put a noticeable pause in front of what should be an
400/// instant read of local objects.
401///
402/// Every field ends in NUL (`%x00` between fields, `-z` after the last), the
403/// one byte none of them can hold: git will not store it in a commit message,
404/// and JSON escapes it. A printable-looking separator such as `\x1e` was
405/// tried first and can appear in a subject, which cut that commit in two and
406/// dropped its measurements.
407///
408/// First-parent for the same reason as [`rev_list`]. `--no-notes` first clears
409/// whatever refs `core.notesRef` and `notes.displayRef` configure, so only this
410/// ref's notes reach `%N` and are parsed as records — explicitly, rather than
411/// relying on an explicit `--notes=<ref>` happening to replace the defaults.
412///
413/// `max` bounds the walk to the newest `max` commits, for a caller that has to
414/// stop somewhere on a trunk of hundreds of thousands of commits and needs to
415/// know whether it did.
416pub fn log(rev: &str, max: Option<usize>) -> Result<Vec<Logged>> {
417 walk(rev, max, |_| false)
418}
419
420/// [`log`], stopping as soon as `done` says the commit just read is the last
421/// one needed. That commit is kept.
422///
423/// For a limit that counts something `--max-count` cannot: `tak log -n 20`
424/// wants twenty *recorded* commits, and how far back they reach is only known
425/// by reading. Collecting the whole walk first read every note on the trunk,
426/// and held all of them at once, to print twenty.
427pub fn log_until(rev: &str, done: impl FnMut(&Logged) -> bool) -> Result<Vec<Logged>> {
428 walk(rev, None, done)
429}
430
431fn walk(rev: &str, max: Option<usize>, done: impl FnMut(&Logged) -> bool) -> Result<Vec<Logged>> {
432 let notes = format!("--notes={NOTES_REF}");
433 let limit = max.map(|n| format!("--max-count={n}"));
434 let mut args = vec![
435 "log",
436 "-z",
437 "--first-parent",
438 "--no-show-signature",
439 "--no-notes",
440 ¬es,
441 "--format=%H%x00%cI%x00%s%x00%N",
442 ];
443 if let Some(limit) = &limit {
444 args.push(limit);
445 }
446 args.extend(["--end-of-options", rev, "--"]);
447 let what = || format!("`git {}`", args.join(" "));
448
449 let mut child = Command::new("git")
450 .args(&args)
451 .stdin(Stdio::null())
452 .stdout(Stdio::piped())
453 .stderr(Stdio::piped())
454 .spawn()
455 .with_context(|| format!("failed to run {}", what()))?;
456 // Drained on a thread of its own, so git blocked writing a full stderr
457 // pipe can never be waiting on us blocked reading its stdout.
458 let mut stderr = child.stderr.take().expect("stderr is piped");
459 let errors = std::thread::spawn(move || {
460 let mut text = String::new();
461 let _ = stderr.read_to_string(&mut text);
462 text
463 });
464 // `read_log` owns the pipe and drops it on return, so when it stops early
465 // git's next write fails before the kill below lands.
466 let read = read_log(
467 BufReader::new(child.stdout.take().expect("stdout is piped")),
468 done,
469 );
470
471 let stopped = matches!(read, Ok((_, true)));
472 if stopped || read.is_err() {
473 // Stopping early is the point, so how git ends afterwards — killed,
474 // or dead of a broken pipe mid-write — is not a failure to report.
475 let _ = child.kill();
476 }
477 // Reaped on every path, so no zombie outlives the walk.
478 let status = child
479 .wait()
480 .with_context(|| format!("failed to wait for {}", what()))?;
481 let (logged, _) = read.with_context(|| format!("failed to read {}", what()))?;
482 // Git's own stderr closes when it dies, killed or not, but anything it
483 // spawned can inherit the pipe and hold it open. Only a failure needs
484 // the text, so only a failure waits for it — as `Command::output` would
485 // — and an early stop leaves the thread to finish on its own.
486 if !stopped && !status.success() {
487 let errors = errors.join().unwrap_or_default();
488 bail!("{} failed: {}", what(), errors.trim());
489 }
490 Ok(logged)
491}
492
493/// Parse [`log`]'s output a commit at a time, until `done` accepts one or the
494/// output ends. The flag beside the commits says which.
495fn read_log(
496 mut out: impl BufRead,
497 mut done: impl FnMut(&Logged) -> bool,
498) -> std::io::Result<(Vec<Logged>, bool)> {
499 let mut logged = Vec::new();
500 let mut fields: Vec<String> = Vec::with_capacity(LOG_FIELDS);
501 let mut buf = Vec::new();
502 loop {
503 buf.clear();
504 if out.read_until(0, &mut buf)? == 0 {
505 // Whatever is left in `fields` is the empty piece after the final
506 // terminator, or a group git never finished; neither is a commit.
507 return Ok((logged, false));
508 }
509 if buf.last() == Some(&0) {
510 buf.pop();
511 }
512 fields.push(String::from_utf8_lossy(&buf).into_owned());
513 if fields.len() < LOG_FIELDS {
514 continue;
515 }
516 let entry = parse_entry(&fields);
517 fields.clear();
518 if let Some(c) = entry {
519 let last = done(&c);
520 logged.push(c);
521 if last {
522 return Ok((logged, true));
523 }
524 }
525 }
526}
527
528fn parse_entry(fields: &[String]) -> Option<Logged> {
529 let [sha, date, subject, note] = fields else {
530 return None;
531 };
532 // Nothing else here can come out of git misaligned, but a note is
533 // arbitrary bytes a person could have written by hand; refusing a group
534 // that does not start with a SHA stops one such note from inventing a
535 // commit.
536 if sha.is_empty() || !sha.bytes().all(|b| b.is_ascii_hexdigit()) {
537 return None;
538 }
539 Some(Logged {
540 sha: sha.clone(),
541 date: date.clone(),
542 subject: subject.clone(),
543 records: parse_note(note),
544 })
545}
546
547/// Whether `sha` is where this clone's history was cut off, so a walk that
548/// ended there ran out of *clone* rather than out of project.
549///
550/// Asked of the commit the walk ended on rather than of the repository as a
551/// whole. `rev-parse --is-shallow-repository` answers for every ref, and the
552/// notes refresh is itself a `--depth 1` fetch: after the first one, a full
553/// clone reports itself shallow because the *notes* history is, and a report
554/// built in it warned that older measurements might be missing when none were.
555///
556/// `actions/checkout` defaults to a depth of one, so a genuinely cut-off walk
557/// is the normal state of a CI checkout rather than an edge case.
558pub fn is_shallow_boundary(sha: &str) -> bool {
559 let Ok(path) = git(&["rev-parse", "--git-path", "shallow"]) else {
560 return false;
561 };
562 // No file is the common case: nothing in this clone is shallow.
563 std::fs::read_to_string(path).is_ok_and(|grafts| grafts.lines().any(|l| l.trim() == sha))
564}
565
566/// Teach plain `git fetch` about the notes ref, so the data is visible to users
567/// who never run `tak`. A convenience, not load-bearing — every `tak` read path
568/// fetches for itself.
569pub fn install_refspec(remote: &str) -> Result<()> {
570 let key = format!("remote.{remote}.fetch");
571 let (_, existing) = git_ok(&["config", "--get-all", &key])?;
572 if existing.lines().any(|l| l.trim() == USER_FETCH_REFSPEC) {
573 return Ok(());
574 }
575 git(&["config", "--add", &key, USER_FETCH_REFSPEC])?;
576 Ok(())
577}
578
579#[cfg(test)]
580mod tests {
581 use super::*;
582
583 const LINE: &str =
584 r#"{"bench":"a","metrics":{"instructions":5.0},"runner":"r","tool":"self","ts":"t","v":1}"#;
585
586 /// A link resolves from its own directory, and never out of the tree.
587 #[test]
588 fn a_link_resolves_inside_the_tree_or_not_at_all() {
589 let cases = [
590 ("tak.toml", "config/tak.toml", Some("config/tak.toml")),
591 (
592 "a/b/tak.toml",
593 "../shared/./tak.toml",
594 Some("a/shared/tak.toml"),
595 ),
596 ("a/tak.toml", "../tak.base.toml", Some("tak.base.toml")),
597 ("a/tak.toml", "../../etc/tak.toml", None),
598 ("tak.toml", "/etc/tak.toml", None),
599 ("tak.toml", ".", None),
600 ];
601 for (link, target, want) in cases {
602 assert_eq!(
603 resolve_link(link, target).as_deref(),
604 want,
605 "{link} -> {target}"
606 );
607 }
608 }
609
610 /// `%N` ends with a newline and is empty for a commit with no note; both
611 /// have to come out as a commit, the second with no records.
612 #[test]
613 fn a_log_parses_noted_and_unnoted_commits() {
614 // As `git log -z` writes it: NUL after every field, including the
615 // last, and a newline ending a note that exists.
616 let out = format!(
617 "aaa\u{0}2026-01-02T00:00:00+00:00\u{0}second\u{0}{LINE}\n\u{0}\
618 bbb\u{0}2026-01-01T00:00:00+00:00\u{0}first\u{0}\u{0}"
619 );
620 let log = read_log(out.as_bytes(), |_| false).unwrap().0;
621 assert_eq!(log.len(), 2);
622 assert_eq!(log[0].sha, "aaa");
623 assert_eq!(log[0].subject, "second");
624 assert_eq!(log[0].records.len(), 1);
625 assert_eq!(log[1].sha, "bbb");
626 assert!(log[1].records.is_empty());
627 }
628
629 /// The byte the first version of this format used as its separator.
630 #[test]
631 fn a_control_character_in_a_subject_stays_in_the_subject() {
632 let out = format!("aaa\u{0}2026-01-02T00:00:00+00:00\u{0}odd \u{1e} one\u{0}{LINE}\n\u{0}");
633 let log = read_log(out.as_bytes(), |_| false).unwrap().0;
634 assert_eq!(log.len(), 1);
635 assert_eq!(log[0].subject, "odd \u{1e} one");
636 assert_eq!(log[0].records.len(), 1);
637 }
638
639 /// Stopping is the whole saving, so nothing after the accepted commit may
640 /// be read: here the rest of the stream fails if it is touched.
641 #[test]
642 fn a_log_stops_reading_at_the_commit_that_satisfies_it() {
643 struct Poisoned;
644 impl Read for Poisoned {
645 fn read(&mut self, _: &mut [u8]) -> std::io::Result<usize> {
646 Err(std::io::Error::other("read past the stop"))
647 }
648 }
649 let head = format!(
650 "aaa\u{0}2026-01-02T00:00:00+00:00\u{0}second\u{0}\u{0}\
651 bbb\u{0}2026-01-01T00:00:00+00:00\u{0}first\u{0}{LINE}\n\u{0}"
652 );
653 // A one-byte buffer, so the reader cannot have prefetched the poison
654 // by accident and still pass.
655 let out = BufReader::with_capacity(1, head.as_bytes().chain(Poisoned));
656 let (log, stopped) = read_log(out, |c| !c.records.is_empty()).unwrap();
657 assert!(stopped);
658 assert_eq!(log.len(), 2);
659 assert_eq!(log[1].sha, "bbb");
660
661 let out = BufReader::new(head.as_bytes().chain(Poisoned));
662 assert!(read_log(out, |_| false).is_err());
663 }
664}