| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright (c) 2026 UtopiaIA |
| 3 | |
| 4 | //! The commands answered with derived data: `log -- <path>`, `blame` and |
| 5 | //! `derive`. |
| 6 | |
| 7 | use std::collections::HashMap; |
| 8 | use std::io::{self, Write}; |
| 9 | use std::process::ExitCode; |
| 10 | |
| 11 | use anyhow::{Result, bail}; |
| 12 | use braid_format::{Changeset, ObjectId, validate_path}; |
| 13 | use braid_repo::Repo; |
| 14 | use serde_json::{Value, json}; |
| 15 | |
| 16 | use crate::{ |
| 17 | Cli, agent_of, format_signature_time, open_repo, print_json, read_changeset, resolve_changeset, |
| 18 | }; |
| 19 | |
| 20 | /// The long help of `blame`. |
| 21 | pub(crate) const BLAME_HELP: &str = |
| 22 | "Show, for each line of a file, the changeset that last changed it, |
| 23 | following first parents from the revision: a merge on the first-parent |
| 24 | chain owns the lines it brought in. Renames are not followed: the lines of |
| 25 | a file are new where the path appeared. |
| 26 | |
| 27 | Each line prints the changeset's short id, its agent (or author when it |
| 28 | names no agent), the author's date, the line number and the line. With |
| 29 | --json, blame prints changeset, the full id of the revision, path, and |
| 30 | lines: one per line, with line (counted from 1), changeset, agent (or |
| 31 | null), author, time and content. |
| 32 | |
| 33 | The path is given from the repository's root. Blame data is derived and |
| 34 | kept in the store, so blaming the file again, at this revision or a later |
| 35 | one, reuses it."; |
| 36 | |
| 37 | /// The long help of `derive`. |
| 38 | pub(crate) const DERIVE_HELP: &str = |
| 39 | "Compute the derived data of every changeset reachable from the revisions |
| 40 | (main when none is given, every ref with --all): its generation number and |
| 41 | first-parent skip pointer, which make ancestry queries and merge bases |
| 42 | cheap, and its changed-path filter, which lets log -- <path> and blame skip |
| 43 | changesets. Blame data, per file, is computed by blame itself. |
| 44 | |
| 45 | Derived data is computed when a command first needs it, so this is only a |
| 46 | way to pay that cost ahead of time, after a large import for example. |
| 47 | With --json, derive prints changesets, how many are reachable, and |
| 48 | computed, how many records were missing and computed."; |
| 49 | |
| 50 | /// A path given on the command line, as the repository names it: from the |
| 51 | /// root, without `./` in front or `/` at the end. `.` and the empty path are |
| 52 | /// the root. |
| 53 | pub(crate) fn repo_path(text: &str) -> Result<Vec<u8>> { |
| 54 | let mut path = text.trim_end_matches('/'); |
| 55 | while let Some(rest) = path.strip_prefix("./") { |
| 56 | path = rest.trim_start_matches('/'); |
| 57 | } |
| 58 | if path.is_empty() || path == "." { |
| 59 | return Ok(Vec::new()); |
| 60 | } |
| 61 | if let Err(err) = validate_path(path.as_bytes()) { |
| 62 | bail!("{text:?} is not a path in the repository: {err}"); |
| 63 | } |
| 64 | Ok(path.as_bytes().to_vec()) |
| 65 | } |
| 66 | |
| 67 | /// The changesets on the first-parent chain of `head` that touch one of |
| 68 | /// `paths`, newest first, at most `limit`. |
| 69 | pub(crate) fn path_log( |
| 70 | repo: &Repo, |
| 71 | head: ObjectId, |
| 72 | paths: &[String], |
| 73 | limit: usize, |
| 74 | ) -> Result<Vec<ObjectId>> { |
| 75 | let paths = paths |
| 76 | .iter() |
| 77 | .map(|path| repo_path(path)) |
| 78 | .collect::<Result<Vec<_>>>()?; |
| 79 | let paths: Vec<&[u8]> = paths.iter().map(Vec::as_slice).collect(); |
| 80 | let mut history = repo.history(); |
| 81 | let found = history.path_log(head, &paths, limit)?; |
| 82 | history.flush()?; |
| 83 | Ok(found) |
| 84 | } |
| 85 | |
| 86 | pub(crate) fn blame(cli: &Cli, revision: &str, path: &str) -> Result<ExitCode> { |
| 87 | let repo = open_repo(cli)?; |
| 88 | let at = resolve_changeset(&repo, revision)?; |
| 89 | let file = repo_path(path)?; |
| 90 | let mut history = repo.history(); |
| 91 | let blame = history.blame(at, &file)?; |
| 92 | history.flush()?; |
| 93 | let Some(blame) = blame else { |
| 94 | bail!("{path:?} is not a file at {}", at.short()); |
| 95 | }; |
| 96 | |
| 97 | // Each changeset that owns lines, read once. |
| 98 | let mut changesets: HashMap<ObjectId, Changeset> = HashMap::new(); |
| 99 | for origin in &blame.origins { |
| 100 | if !changesets.contains_key(origin) { |
| 101 | changesets.insert(*origin, read_changeset(&repo, origin)?); |
| 102 | } |
| 103 | } |
| 104 | let who = |id: &ObjectId| { |
| 105 | let changeset = &changesets[id]; |
| 106 | agent_of(changeset) |
| 107 | .unwrap_or_else(|| String::from_utf8_lossy(&changeset.author.name).into_owned()) |
| 108 | }; |
| 109 | let text = |line: &[u8]| { |
| 110 | let line = line.strip_suffix(b"\n").unwrap_or(line); |
| 111 | String::from_utf8_lossy(line).into_owned() |
| 112 | }; |
| 113 | |
| 114 | if cli.json { |
| 115 | let lines: Vec<Value> = blame |
| 116 | .lines() |
| 117 | .enumerate() |
| 118 | .map(|(n, (line, origin))| { |
| 119 | let changeset = &changesets[&origin]; |
| 120 | json!({ |
| 121 | "line": n + 1, |
| 122 | "changeset": origin.to_hex(), |
| 123 | "agent": agent_of(changeset), |
| 124 | "author": String::from_utf8_lossy(&changeset.author.name), |
| 125 | "time": format_signature_time(&changeset.author), |
| 126 | "content": text(line), |
| 127 | }) |
| 128 | }) |
| 129 | .collect(); |
| 130 | print_json(&json!({ |
| 131 | "changeset": at.to_hex(), |
| 132 | "path": String::from_utf8_lossy(&file), |
| 133 | "lines": lines, |
| 134 | }))?; |
| 135 | return Ok(ExitCode::SUCCESS); |
| 136 | } |
| 137 | |
| 138 | let width = blame |
| 139 | .origins |
| 140 | .iter() |
| 141 | .map(|origin| who(origin).chars().count()) |
| 142 | .max() |
| 143 | .unwrap_or(0); |
| 144 | let digits = blame.origins.len().to_string().len(); |
| 145 | let mut out = io::stdout().lock(); |
| 146 | for (n, (line, origin)) in blame.lines().enumerate() { |
| 147 | writeln!( |
| 148 | out, |
| 149 | "{} {:<width$} {} {:>digits$} {}", |
| 150 | origin.short(), |
| 151 | who(&origin), |
| 152 | format_signature_time(&changesets[&origin].author), |
| 153 | n + 1, |
| 154 | text(line), |
| 155 | )?; |
| 156 | } |
| 157 | Ok(ExitCode::SUCCESS) |
| 158 | } |
| 159 | |
| 160 | pub(crate) fn derive(cli: &Cli, all: bool, revisions: &[String]) -> Result<ExitCode> { |
| 161 | let repo = open_repo(cli)?; |
| 162 | let mut heads = Vec::new(); |
| 163 | for revision in revisions { |
| 164 | heads.push(resolve_changeset(&repo, revision)?); |
| 165 | } |
| 166 | if all { |
| 167 | heads.extend(repo.ref_changesets()?); |
| 168 | } else if revisions.is_empty() { |
| 169 | heads.push(resolve_changeset(&repo, "main")?); |
| 170 | } |
| 171 | let mut history = repo.history(); |
| 172 | let report = history.derive(&heads)?; |
| 173 | if cli.json { |
| 174 | print_json(&json!({ |
| 175 | "changesets": report.changesets, |
| 176 | "computed": report.computed, |
| 177 | }))?; |
| 178 | } else { |
| 179 | println!( |
| 180 | "{} changesets; {} derived records computed", |
| 181 | report.changesets, report.computed |
| 182 | ); |
| 183 | } |
| 184 | Ok(ExitCode::SUCCESS) |
| 185 | } |
| 186 | |
| 187 | #[cfg(test)] |
| 188 | mod tests { |
| 189 | use super::*; |
| 190 | |
| 191 | #[test] |
| 192 | fn paths_are_taken_from_the_root() { |
| 193 | for (text, path) in [ |
| 194 | ("src/lib.rs", "src/lib.rs"), |
| 195 | ("src/", "src"), |
| 196 | ("./src//", "src"), |
| 197 | ("././a", "a"), |
| 198 | (".", ""), |
| 199 | ("", ""), |
| 200 | ("./", ""), |
| 201 | ] { |
| 202 | assert_eq!(repo_path(text).unwrap(), path.as_bytes(), "{text:?}"); |
| 203 | } |
| 204 | for bad in ["/abs", "a//b", "a/../b", ".."] { |
| 205 | assert!(repo_path(bad).is_err(), "{bad:?}"); |
| 206 | } |
| 207 | } |
| 208 | } |