Elffuss BraidHub

utopia-ia/elffuss-braid public

Short ids: six hex digits or more name an object

Repo::resolve takes, after a ref name and a full id, a short id: at
least six hex digits, in either case, that start the id of exactly one
stored object, found with Store::ids_with_prefix. A ref spelled like a
short id still wins. A short id that several objects start with is an
error that lists the first few, each with enough digits to tell it from
the others and its kind.

Repo::resolve_kind is the same for commands that need one kind of
object: a short id only has to be unique among the objects of that
kind, and an object of another kind is an error that says what it is.
show, log, workspace add --at and change create --base take changesets
that way; cat-object and ref set take any object. Text output keeps
twelve-digit ids, so the id commit prints works in show.
Changesetab37fe03cdadf72ad352de4b2d03ac8bea8999c476ba7e2497543193425ff474
AuthorKikoCis <KikoCis@users.noreply.github.com> · 2026-10-15 23:35 +02:00
CommitterKikoCis <KikoCis@users.noreply.github.com> · 2026-10-15 23:35 +02:00
Parentse3b3feb238a5

Browse the files at this changeset

5 files changed

modified crates/cli/src/main.rs +13 −6
@@ -65,7 +65,7 @@
6565 },
6666 /// Write an object's raw payload to standard output.
6767 CatObject {
68- /// Ref name or full object id.
68+ /// A ref, an object id, or a short id (6 hex digits or more).
6969 revision: String,
7070 },
7171 /// List refs and the objects they point at.
@@ -84,7 +84,8 @@
8484 Undo,
8585 /// Show history, following first parents.
8686 Log {
87- /// Where to start: a ref name or a full changeset id.
87+ /// Where to start: a ref, a changeset id, or a short id (6 hex
88+ /// digits or more).
8889 #[arg(default_value = "main")]
8990 revision: String,
9091 /// How many changesets to show.
@@ -93,7 +94,7 @@
9394 },
9495 /// Show one changeset: parents, root, signatures, message, changed paths.
9596 Show {
96- /// A ref name or a full changeset id.
97+ /// A ref, a changeset id, or a short id (6 hex digits or more).
9798 #[arg(default_value = "main")]
9899 revision: String,
99100 },
@@ -144,7 +145,8 @@
144145 Set {
145146 /// Ref name.
146147 name: String,
147- /// Ref name or full object id to point at.
148+ /// What to point at: a ref, an object id, or a short id (6 hex
149+ /// digits or more).
148150 target: String,
149151 /// Only move the ref if it currently points at this id ("none" if it
150152 /// must not exist yet).
@@ -573,6 +575,11 @@
573575 })
574576 }
575577
578+/// A changeset named by a ref, its id or a short id.
579+pub(crate) fn resolve_changeset(repo: &Repo, revision: &str) -> Result<ObjectId> {
580+ Ok(repo.resolve_kind(revision, Kind::Changeset)?)
581+}
582+
576583 fn read_changeset(repo: &Repo, id: &ObjectId) -> Result<Changeset> {
577584 match repo.store().get(id)? {
578585 Some((Kind::Changeset, bytes)) => {
@@ -633,7 +640,7 @@
633640
634641 fn log(cli: &Cli, revision: &str, limit: usize) -> Result<ExitCode> {
635642 let repo = open_repo(cli)?;
636- let mut next = Some(repo.resolve(revision)?);
643+ let mut next = Some(resolve_changeset(&repo, revision)?);
637644 let mut entries = Vec::new();
638645 while let Some(id) = next {
639646 if entries.len() == limit {
@@ -689,7 +696,7 @@
689696
690697 fn show(cli: &Cli, revision: &str) -> Result<ExitCode> {
691698 let repo = open_repo(cli)?;
692- let id = repo.resolve(revision)?;
699+ let id = resolve_changeset(&repo, revision)?;
693700 let changeset = read_changeset(&repo, &id)?;
694701 let changes = read_changes(&repo, &changeset)?;
695702 if cli.json {
modified crates/cli/src/work.rs +7 −15
@@ -14,7 +14,7 @@
1414
1515 use anyhow::{Context, Result, bail};
1616 use braid_engine::{Conflict, ConflictKind, HunkSide};
17-use braid_format::{ChangeOp, EntryKind, Kind, ObjectId, Objects};
17+use braid_format::{ChangeOp, EntryKind, ObjectId};
1818 use braid_repo::{Location, Repo};
1919 use braid_wc::{
2020 ChangeRequest, CommitRequest, Expect, Identity, LandReport, Landed, RebaseProgress, Updated,
@@ -23,7 +23,7 @@
2323 use clap::{Args, Subcommand};
2424 use serde_json::{Value, json};
2525
26-use crate::{Cli, change_json, open_repo, print_json};
26+use crate::{Cli, change_json, open_repo, print_json, resolve_changeset};
2727
2828 /// Exit status of a command that stopped on conflicts.
2929 const CONFLICTS: u8 = 2;
@@ -37,8 +37,9 @@
3737 /// Its directory, which must not exist or be empty (default:
3838 /// ./<name>).
3939 path: Option<PathBuf>,
40- /// The changeset to start at: a ref or a full id (default: the head
41- /// of the tracked branch, or nothing if it does not exist yet).
40+ /// The changeset to start at: a ref, an id or a short id (default:
41+ /// the head of the tracked branch, or nothing if it does not exist
42+ /// yet).
4243 #[arg(long, value_name = "REV")]
4344 at: Option<String>,
4445 /// The branch the workspace lands on and updates from.
@@ -100,8 +101,8 @@
100101
101102 #[derive(Debug, Args)]
102103 pub(crate) struct CreateArgs {
103- /// The changeset to build on: a ref, a full id, or "none" for a first
104- /// changeset.
104+ /// The changeset to build on: a ref, an id, a short id (6 hex digits or
105+ /// more), or "none" for a first changeset.
105106 #[arg(long, value_name = "REV")]
106107 base: String,
107108 /// Set a file: PATH=@FILE takes the content of FILE, PATH=@- reads
@@ -205,15 +206,6 @@
205206 id.map_or_else(|| "(none)".to_owned(), |id| id.short())
206207 }
207208
208-/// A changeset named by a ref or a full id.
209-fn resolve_changeset(repo: &Repo, revision: &str) -> Result<ObjectId> {
210- let id = repo.resolve(revision)?;
211- match repo.store().stat(&id)? {
212- Some((Kind::Changeset, _)) => Ok(id),
213- _ => bail!("{revision} is not a changeset"),
214- }
215-}
216-
217209 pub(crate) fn workspace(cli: &Cli, action: &WorkspaceAction) -> Result<ExitCode> {
218210 match action {
219211 WorkspaceAction::Add {
modified crates/cli/tests/cli.rs +85 −0
@@ -162,6 +162,91 @@
162162 assert_eq!(fsck["objects"], 1);
163163 }
164164
165+/// Two blob contents whose ids start with the same six hex digits or more.
166+fn blob_twins() -> (Vec<u8>, Vec<u8>) {
167+ let mut seen = std::collections::HashMap::new();
168+ for n in 0u64.. {
169+ let content = format!("twin {n}\n").into_bytes();
170+ let id = ObjectId::hash(Kind::Blob, &content);
171+ let start = id.to_hex()[..6].to_owned();
172+ if let Some(other) = seen.insert(start, content.clone()) {
173+ return (other, content);
174+ }
175+ }
176+ unreachable!("the search ends")
177+}
178+
179+#[test]
180+fn short_ids_and_an_ambiguous_one() {
181+ let dir = tempfile::tempdir().unwrap();
182+ assert!(
183+ braid()
184+ .arg("init")
185+ .arg(dir.path())
186+ .output()
187+ .unwrap()
188+ .status
189+ .success()
190+ );
191+ let (one, two) = blob_twins();
192+ let files = [dir.path().join("one"), dir.path().join("two")];
193+ std::fs::write(&files[0], &one).unwrap();
194+ std::fs::write(&files[1], &two).unwrap();
195+ let written = run_json(
196+ braid_in(dir.path())
197+ .args(["hash-object", "-w"])
198+ .args(&files),
199+ );
200+ let ids: Vec<String> = (0..2)
201+ .map(|i| written[i]["id"].as_str().unwrap().to_owned())
202+ .collect();
203+ let shared = ids[0]
204+ .bytes()
205+ .zip(ids[1].bytes())
206+ .take_while(|(a, b)| a == b)
207+ .count();
208+ assert!(shared >= 6);
209+
210+ // Six digits name both: an error that lists them, and nothing printed.
211+ let out = braid_in(dir.path())
212+ .args(["cat-object", &ids[0][..6]])
213+ .output()
214+ .unwrap();
215+ assert_eq!(out.status.code(), Some(1));
216+ assert!(out.stdout.is_empty());
217+ let err = String::from_utf8(out.stderr).unwrap();
218+ assert!(err.contains("ambiguous"), "{err}");
219+ for id in &ids {
220+ assert!(err.contains(&id[..12]), "{err}");
221+ }
222+
223+ // One digit more names one of them, wherever a revision is taken.
224+ let unique: Vec<&str> = ids.iter().map(|id| &id[..shared + 1]).collect();
225+ let cat = braid_in(dir.path())
226+ .args(["cat-object", unique[1]])
227+ .output()
228+ .unwrap();
229+ assert_eq!(cat.stdout, two);
230+ let cat = run_json(braid_in(dir.path()).args(["cat-object", unique[0]]));
231+ assert_eq!(cat["id"], ids[0].as_str());
232+ let set = run_json(braid_in(dir.path()).args(["ref", "set", "pinned", unique[0]]));
233+ assert_eq!(set["updates"][0]["new"], ids[0].as_str());
234+ // A ref spelled like a short id wins over it.
235+ run_json(braid_in(dir.path()).args(["ref", "set", &ids[1][..6], unique[1]]));
236+ let cat = braid_in(dir.path())
237+ .args(["cat-object", &ids[1][..6]])
238+ .output()
239+ .unwrap();
240+ assert_eq!(cat.stdout, two);
241+ // A short id is no changeset: show says what it is.
242+ let out = braid_in(dir.path())
243+ .args(["show", unique[0]])
244+ .output()
245+ .unwrap();
246+ let err = String::from_utf8(out.stderr).unwrap();
247+ assert!(err.contains("is a blob, not a changeset"), "{err}");
248+}
249+
165250 #[test]
166251 fn commands_outside_a_repository_fail_clearly() {
167252 let dir = tempfile::tempdir().unwrap();
modified crates/cli/tests/workspaces.rs +57 −0
@@ -484,6 +484,63 @@
484484 assert!(repo.fsck_is_clean());
485485 }
486486
487+#[test]
488+fn the_short_id_commit_prints_works_everywhere() {
489+ let repo = Repo::new();
490+ seed(&repo, &[("README.md", "hello\n")]);
491+ let ws = repo.workspace("ws");
492+ write(&ws, "notes.txt", "notes\n");
493+ let out = braid(&ws, &["commit", "-m", "notes"]);
494+ assert!(out.status.success(), "{}", stderr(&out));
495+ let text = String::from_utf8(out.stdout).unwrap();
496+ assert!(text.starts_with("Committed "), "{text}");
497+ let short = text.split_whitespace().nth(1).unwrap().to_owned();
498+ assert_eq!(short.len(), 12, "{text}");
499+
500+ // show and log take it, and give the full id in JSON.
501+ let shown = json(&repo.root, &["show", &short]);
502+ let full = shown["id"].as_str().unwrap().to_owned();
503+ assert_eq!(full.len(), 64);
504+ assert!(full.starts_with(&short));
505+ assert_eq!(
506+ json(&repo.root, &["log", &short[..6], "-n", "1"])[0]["id"],
507+ full.as_str()
508+ );
509+ // So do --at and --base.
510+ let other = repo.root.parent().unwrap().join("other");
511+ let added = json(
512+ &repo.root,
513+ &[
514+ "workspace",
515+ "add",
516+ "other",
517+ other.to_str().unwrap(),
518+ "--at",
519+ &short[..8],
520+ ],
521+ );
522+ assert_eq!(added["base"], full.as_str());
523+ assert_eq!(read(&other, "notes.txt"), "notes\n");
524+ let made = json(
525+ &repo.root,
526+ &[
527+ "change",
528+ "create",
529+ "--base",
530+ &short[..7],
531+ "--delete",
532+ "notes.txt",
533+ "-m",
534+ "no notes",
535+ ],
536+ );
537+ assert_eq!(made["base"], full.as_str());
538+ // commit --json gives the full id.
539+ write(&ws, "more.txt", "more\n");
540+ let committed = json(&ws, &["commit", "-m", "more"]);
541+ assert_eq!(committed["changeset"].as_str().unwrap().len(), 64);
542+}
543+
487544 #[test]
488545 fn removing_a_workspace() {
489546 let repo = Repo::new();
modified crates/repo/src/lib.rs +247 −6
@@ -13,6 +13,10 @@
1313 //! A workspace is any directory holding a `.braid` *file* instead: a
1414 //! [`WorkspaceLink`] naming the repository and the workspace. [`locate`] and
1515 //! [`Repo::discover`] find the repository from inside either.
16+//!
17+//! A revision is a ref name, a full object id, or a short id: at least
18+//! [`MIN_SHORT_ID`] hex digits that start the id of exactly one stored
19+//! object (see [`Repo::resolve`]).
1620
1721 #![forbid(unsafe_code)]
1822
@@ -27,7 +31,7 @@
2731 use std::io;
2832 use std::path::{Path, PathBuf};
2933
30-use braid_format::{ObjectId, Objects};
34+use braid_format::{Kind, ObjectId, Objects};
3135 use braid_store::{Options, Store};
3236
3337 pub use braid_engine::{Conflict, ConflictHunk, ConflictKind, HunkSide};
@@ -68,6 +72,26 @@
6872 /// A name that is neither a ref nor the id of a stored object.
6973 #[error("no ref or object named {0:?}")]
7074 UnknownRevision(String),
75+ /// A short id that several stored objects start with.
76+ #[error("{}", ambiguous(.prefix, .candidates, *.more))]
77+ AmbiguousRevision {
78+ /// The short id, as given.
79+ prefix: String,
80+ /// The first few objects it could name, sorted, with their kinds.
81+ candidates: Vec<(ObjectId, Kind)>,
82+ /// Whether more objects start with it than `candidates` lists.
83+ more: bool,
84+ },
85+ /// A revision that names an object of another kind than the one needed.
86+ #[error("{revision:?} is a {found}, not a {expected}")]
87+ WrongKind {
88+ /// The revision, as given.
89+ revision: String,
90+ /// The kind needed.
91+ expected: Kind,
92+ /// The kind of the object it names.
93+ found: Kind,
94+ },
7195 /// The store failed.
7296 #[error(transparent)]
7397 Store(#[from] braid_store::Error),
@@ -212,18 +236,110 @@
212236 &self.store
213237 }
214238
215- /// Resolves a ref name or a full object id to an object id.
239+ /// Resolves a revision to an object id: a ref name, a full id, or a
240+ /// short id, the first [`MIN_SHORT_ID`] or more hex digits of an id
241+ /// that no other stored object starts with. A ref wins over a short id
242+ /// that is spelled the same. Hex digits may be given in either case.
216243 pub fn resolve(&self, revision: &str) -> Result<ObjectId, Error> {
244+ self.lookup(revision, None)
245+ }
246+
247+ /// Resolves a revision that must name an object of `kind`, as
248+ /// [`resolve`](Self::resolve) does, except that a short id only has to
249+ /// be unique among the objects of that kind.
250+ pub fn resolve_kind(&self, revision: &str, kind: Kind) -> Result<ObjectId, Error> {
251+ let id = self.lookup(revision, Some(kind))?;
252+ match self.store.stat(&id)? {
253+ Some((found, _)) if found == kind => Ok(id),
254+ Some((found, _)) => Err(Error::WrongKind {
255+ revision: revision.to_owned(),
256+ expected: kind,
257+ found,
258+ }),
259+ None => Err(Error::UnknownRevision(revision.to_owned())),
260+ }
261+ }
262+
263+ fn lookup(&self, revision: &str, kind: Option<Kind>) -> Result<ObjectId, Error> {
217264 if let Some(id) = self.store.refs()?.get(revision) {
218265 return Ok(id);
219266 }
220- if let Ok(id) = revision.parse::<ObjectId>()
221- && self.store.contains(&id)?
267+ let unknown = || Error::UnknownRevision(revision.to_owned());
268+ let digits = revision.len();
269+ if !(MIN_SHORT_ID..=2 * ObjectId::LEN).contains(&digits)
270+ || !revision.bytes().all(|byte| byte.is_ascii_hexdigit())
222271 {
223- return Ok(id);
272+ return Err(unknown());
273+ }
274+ let hex = revision.to_ascii_lowercase();
275+ if digits == 2 * ObjectId::LEN {
276+ let id: ObjectId = hex.parse().map_err(|_| unknown())?;
277+ return if self.store.contains(&id)? {
278+ Ok(id)
279+ } else {
280+ Err(unknown())
281+ };
224282 }
225- Err(Error::UnknownRevision(revision.to_owned()))
283+ let mut candidates = Vec::new();
284+ for id in self.store.ids_with_prefix(&hex, CANDIDATE_LIMIT)? {
285+ if let Some((found, _)) = self.store.stat(&id)? {
286+ candidates.push((id, found));
287+ }
288+ }
289+ // Objects of the kind wanted settle it, if there are any.
290+ if let Some(kind) = kind
291+ && candidates.iter().any(|(_, found)| *found == kind)
292+ {
293+ candidates.retain(|(_, found)| *found == kind);
294+ }
295+ match candidates.as_slice() {
296+ [] => Err(unknown()),
297+ [(id, _)] => Ok(*id),
298+ _ => {
299+ let more = candidates.len() > CANDIDATES_SHOWN;
300+ candidates.truncate(CANDIDATES_SHOWN);
301+ Err(Error::AmbiguousRevision {
302+ prefix: revision.to_owned(),
303+ candidates,
304+ more,
305+ })
306+ }
307+ }
308+ }
309+}
310+
311+/// The fewest hex digits a short id may have.
312+pub const MIN_SHORT_ID: usize = 6;
313+
314+/// How many objects starting with a short id are looked at, at most.
315+const CANDIDATE_LIMIT: usize = 64;
316+
317+/// How many of them an ambiguous short id lists.
318+const CANDIDATES_SHOWN: usize = 5;
319+
320+/// The message for an ambiguous short id: each candidate with enough digits
321+/// to tell it from the others, and its kind.
322+fn ambiguous(prefix: &str, candidates: &[(ObjectId, Kind)], more: bool) -> String {
323+ let hexes: Vec<String> = candidates.iter().map(|(id, _)| id.to_hex()).collect();
324+ let mut shown = ObjectId::SHORT_HEX;
325+ for (i, a) in hexes.iter().enumerate() {
326+ for b in &hexes[i + 1..] {
327+ let shared = a.bytes().zip(b.bytes()).take_while(|(x, y)| x == y).count();
328+ shown = shown.max(shared + 1);
329+ }
330+ }
331+ let mut listed: Vec<String> = hexes
332+ .iter()
333+ .zip(candidates)
334+ .map(|(hex, (_, kind))| format!("{} ({kind})", &hex[..shown.min(hex.len())]))
335+ .collect();
336+ if more {
337+ listed.push("and more".to_owned());
226338 }
339+ format!(
340+ "the short id {prefix:?} is ambiguous: {}; give more digits",
341+ listed.join(", ")
342+ )
227343 }
228344
229345 #[cfg(test)]
@@ -268,6 +384,131 @@
268384 ));
269385 }
270386
387+ /// Two payloads whose ids, as objects of `first` and of `second`, start
388+ /// with the same three bytes: six hex digits or more.
389+ fn twins(first: Kind, second: Kind) -> (Vec<u8>, Vec<u8>) {
390+ let start = |kind, payload: &[u8]| -> [u8; 3] {
391+ let bytes = ObjectId::hash(kind, payload);
392+ [
393+ bytes.as_bytes()[0],
394+ bytes.as_bytes()[1],
395+ bytes.as_bytes()[2],
396+ ]
397+ };
398+ let mut firsts = std::collections::HashMap::new();
399+ let mut seconds = std::collections::HashMap::new();
400+ for n in 0u64.. {
401+ let payload = format!("twin {n}").into_bytes();
402+ let (a, b) = (start(first, &payload), start(second, &payload));
403+ if let Some(other) = seconds.get(&a) {
404+ return (payload, Vec::clone(other));
405+ }
406+ if let Some(other) = firsts.get(&b) {
407+ return (Vec::clone(other), payload);
408+ }
409+ firsts.insert(a, payload.clone());
410+ seconds.insert(b, payload);
411+ }
412+ unreachable!("the search ends")
413+ }
414+
415+ fn put(repo: &Repo, kind: Kind, payload: &[u8]) -> ObjectId {
416+ repo.store().put(kind, payload).unwrap()
417+ }
418+
419+ #[test]
420+ fn short_ids() {
421+ let dir = tempfile::tempdir().unwrap();
422+ let repo = Repo::init(dir.path()).unwrap();
423+ let (a, b) = twins(Kind::Blob, Kind::Blob);
424+ let (a, b) = (put(&repo, Kind::Blob, &a), put(&repo, Kind::Blob, &b));
425+ let (hex_a, hex_b) = (a.to_hex(), b.to_hex());
426+ let shared = hex_a
427+ .bytes()
428+ .zip(hex_b.bytes())
429+ .take_while(|(x, y)| x == y)
430+ .count();
431+ assert!(shared >= MIN_SHORT_ID);
432+
433+ // Both start with six digits: an error that lists them.
434+ let err = repo.resolve(&hex_a[..MIN_SHORT_ID]).unwrap_err();
435+ let Error::AmbiguousRevision {
436+ candidates, more, ..
437+ } = &err
438+ else {
439+ panic!("expected an ambiguous short id, got {err:?}");
440+ };
441+ let mut both = vec![(a, Kind::Blob), (b, Kind::Blob)];
442+ both.sort();
443+ assert_eq!(*candidates, both);
444+ assert!(!more);
445+ let message = err.to_string();
446+ let digits = (shared + 1).max(ObjectId::SHORT_HEX);
447+ for hex in [&hex_a, &hex_b] {
448+ assert!(
449+ message.contains(&format!("{} (blob)", &hex[..digits])),
450+ "{message}"
451+ );
452+ }
453+ // One digit more tells them apart, in either case.
454+ assert_eq!(repo.resolve(&hex_a[..shared + 1]).unwrap(), a);
455+ let upper = hex_b[..shared + 1].to_ascii_uppercase();
456+ assert_eq!(repo.resolve(&upper).unwrap(), b);
457+ assert_eq!(repo.resolve(&hex_a.to_ascii_uppercase()).unwrap(), a);
458+ // Too short, not hex, or starting no id.
459+ let free = ["0", "f"]
460+ .into_iter()
461+ .find(|digit| !hex_a.starts_with(digit))
462+ .unwrap();
463+ for bad in [&hex_a[..MIN_SHORT_ID - 1], "zzzzzz", &free.repeat(8)] {
464+ assert!(
465+ matches!(repo.resolve(bad), Err(Error::UnknownRevision(_))),
466+ "{bad}"
467+ );
468+ }
469+ // A ref spelled like a short id wins.
470+ repo.store()
471+ .transact("test", "a ref that looks like an id", |_| {
472+ Ok::<_, std::convert::Infallible>(vec![RefUpdate::new(
473+ &hex_a[..MIN_SHORT_ID],
474+ None,
475+ Some(b),
476+ )])
477+ })
478+ .unwrap();
479+ assert_eq!(repo.resolve(&hex_a[..MIN_SHORT_ID]).unwrap(), b);
480+
481+ // A short id shared by objects of two kinds names the one of the
482+ // kind wanted.
483+ let (blob, changeset) = twins(Kind::Blob, Kind::Changeset);
484+ let blob = put(&repo, Kind::Blob, &blob);
485+ let changeset = put(&repo, Kind::Changeset, &changeset);
486+ let short = &blob.to_hex()[..MIN_SHORT_ID];
487+ assert!(matches!(
488+ repo.resolve(short),
489+ Err(Error::AmbiguousRevision { .. })
490+ ));
491+ assert_eq!(
492+ repo.resolve_kind(short, Kind::Changeset).unwrap(),
493+ changeset
494+ );
495+ assert_eq!(repo.resolve_kind(short, Kind::Blob).unwrap(), blob);
496+ let err = repo
497+ .resolve_kind(&blob.to_hex(), Kind::Changeset)
498+ .unwrap_err();
499+ assert!(
500+ matches!(
501+ err,
502+ Error::WrongKind {
503+ expected: Kind::Changeset,
504+ found: Kind::Blob,
505+ ..
506+ }
507+ ),
508+ "{err:?}"
509+ );
510+ }
511+
271512 #[test]
272513 fn discover_through_a_workspace_file() {
273514 let repo_dir = tempfile::tempdir().unwrap();