| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright (c) 2026 UtopiaIA |
| 3 | |
| 4 | //! `braid hub log` and `diff`: the changesets of a branch on the hub, and |
| 5 | //! what one changed, read without cloning. |
| 6 | //! |
| 7 | //! Each takes the repository with `-R OWNER/NAME` (default: the one this |
| 8 | //! repository is linked to). A revision is a branch, `tags/<name>`, a |
| 9 | //! changeset's full id or its first 12 hex digits or more. |
| 10 | |
| 11 | use std::io::Write; |
| 12 | use std::process::ExitCode; |
| 13 | |
| 14 | use anyhow::Result; |
| 15 | use braid_hubproto::RepoPath; |
| 16 | use braid_hubproto::history::{ChangesetSummary, DiffPage, Log}; |
| 17 | use clap::Args; |
| 18 | |
| 19 | use super::http::HttpHub; |
| 20 | use super::remote::{HubError, shown}; |
| 21 | use super::social_common::{HubRepoArg, exit_for, hub_repo}; |
| 22 | use crate::{Cli, print_json}; |
| 23 | |
| 24 | /// The most changesets one request asks for: a page of the hub's lists. |
| 25 | const PAGE: usize = 100; |
| 26 | |
| 27 | /// The most pages of a diff `diff --json` reads. |
| 28 | const MAX_PAGES: u64 = 10_000; |
| 29 | |
| 30 | /// `hub log`. |
| 31 | #[derive(Debug, Args)] |
| 32 | pub(crate) struct LogArgs { |
| 33 | #[command(flatten)] |
| 34 | pub(crate) repo: HubRepoArg, |
| 35 | /// The revision to start from, following first parents: a branch, |
| 36 | /// tags/NAME, or a changeset's id or its start (default: the default |
| 37 | /// branch). |
| 38 | #[arg(long = "ref", value_name = "REV")] |
| 39 | pub(crate) reference: Option<String>, |
| 40 | /// How many changesets to show. |
| 41 | #[arg(long, value_name = "N", default_value_t = 30, value_parser = clap::value_parser!(u64).range(1..=100_000))] |
| 42 | pub(crate) limit: u64, |
| 43 | } |
| 44 | |
| 45 | /// `hub diff`. |
| 46 | #[derive(Debug, Args)] |
| 47 | pub(crate) struct DiffArgs { |
| 48 | /// The changeset: a branch or tags/NAME for its head, or a changeset's |
| 49 | /// id or its start. Its diff is against its first parent. |
| 50 | #[arg(value_name = "REV")] |
| 51 | pub(crate) rev: String, |
| 52 | #[command(flatten)] |
| 53 | pub(crate) repo: HubRepoArg, |
| 54 | /// Only the diff of this file, from the repository's root: for a diff |
| 55 | /// larger than the hub gives whole. |
| 56 | #[arg(long, value_name = "PATH")] |
| 57 | pub(crate) path: Option<String>, |
| 58 | } |
| 59 | |
| 60 | /// `text` percent-encoded, every byte but letters, digits and `-._~`: a |
| 61 | /// part of a path or a query that holds anything. |
| 62 | fn encoded(text: &str) -> String { |
| 63 | let mut out = String::with_capacity(text.len()); |
| 64 | for &byte in text.as_bytes() { |
| 65 | if byte.is_ascii_alphanumeric() || b"-._~".contains(&byte) { |
| 66 | out.push(char::from(byte)); |
| 67 | } else { |
| 68 | out.push_str(&format!("%{byte:02X}")); |
| 69 | } |
| 70 | } |
| 71 | out |
| 72 | } |
| 73 | |
| 74 | /// Says on standard error why asking the hub failed, and gives the exit |
| 75 | /// status of [`exit_for`]. |
| 76 | fn failed(err: &HubError) -> ExitCode { |
| 77 | eprintln!("braid: error: {err}"); |
| 78 | ExitCode::from(exit_for(err)) |
| 79 | } |
| 80 | |
| 81 | /// A time of the hub's (RFC 3339) as `braid log` writes one: |
| 82 | /// `2026-10-18 12:00 +0200`. |
| 83 | fn date(time: &str) -> String { |
| 84 | let (Some(day), Some(clock)) = (time.get(..10), time.get(11..16)) else { |
| 85 | return shown(time); |
| 86 | }; |
| 87 | let zone = match time.get(19..) { |
| 88 | Some("Z") | None => "+0000".to_owned(), |
| 89 | Some(zone) => zone.replace(':', ""), |
| 90 | }; |
| 91 | shown(&format!("{day} {clock} {zone}")) |
| 92 | } |
| 93 | |
| 94 | /// A changeset as `braid log` prints one: its short id, its author's date, |
| 95 | /// the author with the agent, and the summary. |
| 96 | fn line(entry: &ChangesetSummary) -> String { |
| 97 | let agent = entry |
| 98 | .agent |
| 99 | .as_deref() |
| 100 | .map_or_else(String::new, |agent| format!(" ({})", shown(agent))); |
| 101 | format!( |
| 102 | "{} {} {}{agent} {}", |
| 103 | entry.id.short(), |
| 104 | date(&entry.author.time), |
| 105 | shown(&entry.author.name), |
| 106 | shown(&entry.summary) |
| 107 | ) |
| 108 | } |
| 109 | |
| 110 | pub(crate) fn log(cli: &Cli, args: &LogArgs) -> Result<ExitCode> { |
| 111 | let (hub, repo) = hub_repo(cli, args.repo.hub_repo.as_deref())?; |
| 112 | let limit = usize::try_from(args.limit).unwrap_or(usize::MAX); |
| 113 | let log = match fetch_log(&hub, &repo, args.reference.as_deref(), limit) { |
| 114 | Ok(log) => log, |
| 115 | Err(err) => return Ok(failed(&err)), |
| 116 | }; |
| 117 | if cli.json { |
| 118 | print_json(&serde_json::to_value(&log)?)?; |
| 119 | return Ok(ExitCode::SUCCESS); |
| 120 | } |
| 121 | let mut out = std::io::stdout().lock(); |
| 122 | for entry in &log.changesets { |
| 123 | writeln!(out, "{}", line(entry))?; |
| 124 | } |
| 125 | out.flush()?; |
| 126 | Ok(ExitCode::SUCCESS) |
| 127 | } |
| 128 | |
| 129 | /// At most `limit` changesets of the log of `reference`, page after page, |
| 130 | /// as one log: its `next` is where it would go on. |
| 131 | fn fetch_log( |
| 132 | hub: &HttpHub, |
| 133 | repo: &RepoPath, |
| 134 | reference: Option<&str>, |
| 135 | limit: usize, |
| 136 | ) -> Result<Log, HubError> { |
| 137 | log_pages( |
| 138 | |route| hub.call_json("GET", route, &[], None), |
| 139 | repo, |
| 140 | reference, |
| 141 | limit, |
| 142 | ) |
| 143 | } |
| 144 | |
| 145 | /// [`fetch_log`], each page asked for with `get`. |
| 146 | fn log_pages( |
| 147 | mut get: impl FnMut(&str) -> Result<Log, HubError>, |
| 148 | repo: &RepoPath, |
| 149 | reference: Option<&str>, |
| 150 | limit: usize, |
| 151 | ) -> Result<Log, HubError> { |
| 152 | let mut log: Option<Log> = None; |
| 153 | loop { |
| 154 | let listed = log.as_ref().map_or(0, |log| log.changesets.len()); |
| 155 | let mut route = format!( |
| 156 | "{}/log?limit={}", |
| 157 | repo.api_path(), |
| 158 | (limit - listed).min(PAGE) |
| 159 | ); |
| 160 | if let Some(rev) = reference { |
| 161 | route.push_str(&format!("&ref={}", encoded(rev))); |
| 162 | } |
| 163 | if let Some(after) = log.as_ref().and_then(|log| log.next.as_deref()) { |
| 164 | route.push_str(&format!("&after={}", encoded(after))); |
| 165 | } |
| 166 | let page: Log = get(&route)?; |
| 167 | // A page that brings nothing ends the log, whatever cursor it |
| 168 | // gives: a hub that answers so would be asked for ever. |
| 169 | let brought = page.changesets.len(); |
| 170 | let log = match &mut log { |
| 171 | None => log.insert(page), |
| 172 | Some(log) => { |
| 173 | log.changesets.extend(page.changesets); |
| 174 | log.next = page.next; |
| 175 | log |
| 176 | } |
| 177 | }; |
| 178 | if log.changesets.len() > limit { |
| 179 | log.changesets.truncate(limit); |
| 180 | } |
| 181 | if brought == 0 || log.next.is_none() || log.changesets.len() >= limit { |
| 182 | break; |
| 183 | } |
| 184 | } |
| 185 | Ok(log.unwrap_or_else(|| Log { |
| 186 | reference: String::new(), |
| 187 | changesets: Vec::new(), |
| 188 | next: None, |
| 189 | })) |
| 190 | } |
| 191 | |
| 192 | pub(crate) fn diff(cli: &Cli, args: &DiffArgs) -> Result<ExitCode> { |
| 193 | let (hub, repo) = hub_repo(cli, args.repo.hub_repo.as_deref())?; |
| 194 | let route = format!("{}/changesets/{}/diff", repo.api_path(), encoded(&args.rev)); |
| 195 | let path = args |
| 196 | .path |
| 197 | .as_deref() |
| 198 | .map(|path| format!("path={}", encoded(path.trim_matches('/')))); |
| 199 | if !cli.json { |
| 200 | let query = path.map(|path| format!("?{path}")).unwrap_or_default(); |
| 201 | let asked = hub.call( |
| 202 | "GET", |
| 203 | &format!("{route}{query}"), |
| 204 | &[("Accept", "text/x-diff")], |
| 205 | None, |
| 206 | ); |
| 207 | let text = match asked { |
| 208 | Ok(text) => text, |
| 209 | Err(err) => return Ok(failed(&err)), |
| 210 | }; |
| 211 | let mut out = std::io::stdout().lock(); |
| 212 | out.write_all(&text)?; |
| 213 | out.flush()?; |
| 214 | return Ok(ExitCode::SUCCESS); |
| 215 | } |
| 216 | // Every page, as one. |
| 217 | let mut all = DiffPage::default(); |
| 218 | let mut number = 1; |
| 219 | while number <= MAX_PAGES { |
| 220 | let mut query = format!("?page={number}"); |
| 221 | if let Some(path) = &path { |
| 222 | query.push('&'); |
| 223 | query.push_str(path); |
| 224 | } |
| 225 | let page: DiffPage = match hub.call_json("GET", &format!("{route}{query}"), &[], None) { |
| 226 | Ok(page) => page, |
| 227 | Err(err) => return Ok(failed(&err)), |
| 228 | }; |
| 229 | all.files.extend(page.files); |
| 230 | match page.next_page { |
| 231 | Some(next) if next > number => number = next, |
| 232 | _ => break, |
| 233 | } |
| 234 | } |
| 235 | print_json(&serde_json::to_value(&all)?)?; |
| 236 | Ok(ExitCode::SUCCESS) |
| 237 | } |
| 238 | |
| 239 | #[cfg(test)] |
| 240 | mod tests { |
| 241 | use super::*; |
| 242 | |
| 243 | #[test] |
| 244 | fn dates_as_braid_log_writes_them() { |
| 245 | assert_eq!(date("2023-11-14T22:13:20Z"), "2023-11-14 22:13 +0000"); |
| 246 | assert_eq!(date("2023-11-14T23:43:20+01:30"), "2023-11-14 23:43 +0130"); |
| 247 | assert_eq!(date("2023-11-14T17:13:20-05:00"), "2023-11-14 17:13 -0500"); |
| 248 | assert_eq!(date("soon"), "soon"); |
| 249 | assert_eq!(encoded("release/1.0 x"), "release%2F1.0%20x"); |
| 250 | assert_eq!(encoded("ñ"), "%C3%B1"); |
| 251 | } |
| 252 | |
| 253 | /// A changeset of a log page, by its number. |
| 254 | fn entry(n: u8) -> ChangesetSummary { |
| 255 | ChangesetSummary { |
| 256 | id: braid_format::ObjectId::hash(braid_format::Kind::Changeset, &[n]), |
| 257 | parents: Vec::new(), |
| 258 | author: Default::default(), |
| 259 | committer: Default::default(), |
| 260 | summary: format!("change {n}"), |
| 261 | agent: None, |
| 262 | } |
| 263 | } |
| 264 | |
| 265 | #[test] |
| 266 | fn a_log_stops_whatever_the_hub_answers() { |
| 267 | let repo: RepoPath = "ada/demo".parse().unwrap(); |
| 268 | // A hub that gives a next page and nothing on it, again and again: |
| 269 | // the log ends instead of asking for ever. |
| 270 | let mut asked = 0; |
| 271 | let empty = log_pages( |
| 272 | |_| { |
| 273 | asked += 1; |
| 274 | assert!(asked < 100, "the log asks again and again"); |
| 275 | Ok(Log { |
| 276 | reference: "main".into(), |
| 277 | changesets: Vec::new(), |
| 278 | next: Some("cursor".into()), |
| 279 | }) |
| 280 | }, |
| 281 | &repo, |
| 282 | None, |
| 283 | 30, |
| 284 | ) |
| 285 | .unwrap(); |
| 286 | assert!(empty.changesets.is_empty()); |
| 287 | assert_eq!(asked, 1); |
| 288 | // A hub that gives more than asked for: no more than the limit. |
| 289 | let more = log_pages( |
| 290 | |_| { |
| 291 | Ok(Log { |
| 292 | reference: "main".into(), |
| 293 | changesets: (0..5).map(entry).collect(), |
| 294 | next: None, |
| 295 | }) |
| 296 | }, |
| 297 | &repo, |
| 298 | None, |
| 299 | 2, |
| 300 | ) |
| 301 | .unwrap(); |
| 302 | assert_eq!(more.changesets, vec![entry(0), entry(1)]); |
| 303 | // What the hub pages is read page after page, each from the cursor |
| 304 | // the one before gave. |
| 305 | let mut routes = Vec::new(); |
| 306 | let paged = log_pages( |
| 307 | |route| { |
| 308 | routes.push(route.to_owned()); |
| 309 | let page = routes.len() as u8; |
| 310 | Ok(Log { |
| 311 | reference: "main".into(), |
| 312 | changesets: vec![entry(page)], |
| 313 | next: (page < 3).then(|| format!("c{page}")), |
| 314 | }) |
| 315 | }, |
| 316 | &repo, |
| 317 | Some("tags/v1"), |
| 318 | 10, |
| 319 | ) |
| 320 | .unwrap(); |
| 321 | assert_eq!(paged.changesets, vec![entry(1), entry(2), entry(3)]); |
| 322 | assert_eq!(paged.next, None); |
| 323 | assert!( |
| 324 | routes[0].ends_with("/log?limit=10&ref=tags%2Fv1"), |
| 325 | "{routes:?}" |
| 326 | ); |
| 327 | assert!(routes[2].ends_with("&after=c2"), "{routes:?}"); |
| 328 | } |
| 329 | } |