//! Repository abstraction layer for Rustik tools. //! //! Provides object identifiers ([`Oid`]) and backend modules for Git and //! Jujutsu repositories. #![deny(unsafe_code)] #![warn(missing_docs)] #![warn(clippy::unwrap_used)] // `serde` is the local alias for the `microserde` crate; the derive macro // emits `microserde::*` paths so the original crate name must remain in scope. extern crate serde as microserde; pub mod git; pub mod jj; pub mod oid; pub use oid::{Oid, OidError}; use std::convert::Infallible; use std::fmt; use std::io; use std::path::Path; use std::process::Output; use std::str::FromStr; use git::refs::Qualified; use serde::{Deserialize, Serialize}; /// Stable patch identifier returned by `git patch-id`. #[derive(Clone, Debug, Default, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)] #[serde(transparent)] pub struct PatchId(String); impl PatchId { /// Returns the patch identifier text. pub fn as_str(&self) -> &str { &self.0 } } impl From for PatchId { fn from(value: String) -> Self { Self(value) } } impl FromStr for PatchId { type Err = Infallible; fn from_str(input: &str) -> Result { Ok(Self(input.to_owned())) } } impl fmt::Display for PatchId { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(&self.0) } } /// Aggregated diff size of one commit, as reported by `git log --shortstat`. #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] pub struct DiffStat { /// Number of files the commit touches. pub files_changed: usize, /// Number of inserted lines. pub insertions: usize, /// Number of deleted lines. pub deletions: usize, } impl DiffStat { /// Parses one `--shortstat` summary line. /// /// Segments that Git omits (for example deletions in an insert-only /// commit) stay zero, so an unrecognized line parses as an empty stat. pub fn from_shortstat(line: &str) -> Self { let mut stat = Self::default(); for segment in line.split(',') { let segment = segment.trim(); let Some((count, label)) = segment.split_once(' ') else { continue; }; let Ok(count) = count.parse() else { continue; }; if label.starts_with("file") { stat.files_changed = count; } else if label.starts_with("insertion") { stat.insertions = count; } else if label.starts_with("deletion") { stat.deletions = count; } } stat } } /// User-supplied Git revision or Jujutsu revset selector. #[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)] pub struct Rev(String); impl Rev { /// Returns the selector text. pub fn as_str(&self) -> &str { &self.0 } } impl TryFrom<&str> for Rev { type Error = &'static str; fn try_from(value: &str) -> Result { if value.is_empty() { return Err("must not be empty"); } if value.starts_with('-') { return Err("must not start with '-'"); } Ok(Self(value.to_owned())) } } impl From for Rev { fn from(oid: Oid) -> Self { Self(oid.to_string()) } } /// Local branch head. #[derive(Clone, Debug, Eq, PartialEq)] pub struct Branch { /// Short branch name. pub name: String, /// Commit at the branch tip. pub head: Oid, /// Committer timestamp of the commit at the branch tip. pub time: CommitTime, } /// Commit timestamp in seconds since the Unix epoch. #[derive(Clone, Copy, Debug, Default, Eq, Ord, PartialEq, PartialOrd)] pub struct CommitTime { /// Seconds since the Unix epoch in the committer timestamp. pub seconds: i64, } /// Commit counts between a base and target revision. #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] pub struct AheadBehind { /// Commits reachable from the target but not the base. pub ahead: usize, /// Commits reachable from the base but not the target. pub behind: usize, } /// Whether a target can be merged into a base without content conflicts. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum MergeStatus { /// The merge does not report content conflicts. Clean, /// The merge reports content conflicts. Conflicts, } /// Repository operations that read commits, objects, refs, and derived data. pub trait ReadRepository { /// Resolves a revision reference to a commit id. fn commit_id(&self, rev: &Rev) -> Result; /// Returns the tree id for any commit or tree object. fn tree_id(&self, object: Oid) -> Result; /// Returns the current commit stored in `reference`, if the ref exists. fn optional_ref(&self, reference: &Qualified<'_>) -> Result, RepoError>; /// Returns refs below `prefix`, sorted by refname. fn refs(&self, prefix: &Qualified<'_>) -> Result, Oid)>, RepoError>; /// Returns local branches, sorted by branch name. fn branches(&self) -> Result, RepoError>; /// Returns a Git configuration value, if set. fn config(&self, key: &str) -> Result, RepoError>; /// Returns the repository trunk branch among `branches`. /// /// The trunk is the remote default branch when configured, the /// `init.defaultBranch` branch when configured, or `master` otherwise. fn trunk(&self, branches: &[Branch]) -> Result, RepoError>; /// Returns the best common ancestor of two revisions. fn merge_base(&self, left: &Rev, right: &Rev) -> Result; /// Returns the branch point between `target` and its configured upstream. /// /// The repository trunk is used when `target` has no upstream. fn branch_base(&self, target: &Rev) -> Result, RepoError>; /// Returns ahead and behind counts for `target` relative to `base`. fn ahead_behind(&self, base: &Rev, target: &Rev) -> Result; /// Returns whether `target` would merge into `base` with conflicts. fn merge_status(&self, base: &Rev, target: &Rev) -> Result; /// Returns the single parent of `commit`, or an error if it has more or fewer. fn parent(&self, commit: Oid) -> Result; /// Returns the full commit message for `commit`. fn commit_message(&self, commit: Oid) -> Result; /// Returns the committer timestamp for `commit`. fn commit_time(&self, commit: Oid) -> Result; /// Returns each commit's aggregated diff size, in the given order. fn commit_stats(&self, commits: &[Oid]) -> Result, RepoError>; /// Reads a blob object's bytes. fn cat_blob(&self, blob: Oid) -> Result, RepoError>; /// Produces a unified diff between two objects as text. fn diff(&self, from: Oid, to: Oid) -> Result; /// Computes a stable Git patch id for `patch` text. fn patch_id(&self, patch: &str) -> Result; /// Computes stable Git patch ids for patches that each produce an id. fn patch_ids(&self, patches: &[String]) -> Result, RepoError>; /// Computes a three-way merge tree and returns the resulting tree id. fn merge_tree(&self, merge_base: Oid, ours: Oid, theirs: Oid) -> Result; /// Returns commits in `base..target`, oldest first, as `(id, summary)` pairs. fn commits(&self, base: &Rev, target: &Rev) -> Result, RepoError>; /// Returns the unified diff for `commit` against its parent. fn commit_diff(&self, commit: Oid) -> Result, RepoError>; } /// Repository operations that write objects and refs. pub trait WriteRepository { /// Writes `bytes` as a blob object and returns its id. fn write_blob(&self, bytes: &[u8]) -> Result; /// Applies a Git-format patch to a temporary index and returns its tree id. /// /// Returns [`RepoError::PatchApply`] when the patch does not apply to /// `base`; other variants signal that the operation itself failed. fn apply_patch_to_tree(&self, base: Oid, patch: &str) -> Result; /// Creates a commit with `tree` and `parent`. fn commit( &self, tree: Oid, parent: Oid, author: &str, email: &str, message: &str, ) -> Result; /// Moves `updated` to `commit` and deletes `deleted` in one transaction. fn update_ref_and_delete( &self, updated: &Qualified<'_>, commit: Oid, deleted: &Qualified<'_>, ) -> Result<(), RepoError>; /// Moves `reference` to point at `commit`. fn update_ref(&self, reference: &Qualified<'_>, commit: Oid) -> Result<(), RepoError>; /// Moves `reference` to `commit` only when it still points to `expected`. /// /// Returns `false` when another writer changed the reference first. fn compare_and_update_ref( &self, reference: &Qualified<'_>, commit: Oid, expected: Option, ) -> Result; } /// A diff backend a viewer can re-query for wider hunk context. pub trait DiffRepository { /// Refetches `paths` with `context_lines` of unified context per hunk. /// /// Returns the raw unified-diff bytes; decoding them is the caller's job. fn diff(&self, context_lines: usize, paths: &[&Path]) -> Result, RepoError>; } /// A failure from a Git-backed repository operation. #[derive(Debug)] pub enum RepoError { /// Spawning or waiting on a process failed. Io(io::Error), /// A Git plumbing command failed, carrying its diagnostic. Git(String), /// A Jujutsu command failed, carrying its diagnostic. Jj(String), /// A three-way merge produced conflicts. MergeConflict(String), /// A patch did not apply to the requested tree, carrying its diagnostic. PatchApply(String), } impl RepoError { /// Builds a Git error from a failed command's output. pub(crate) fn git(output: &Output) -> Self { Self::Git(Self::diagnostic(output)) } /// Builds a Jujutsu error from a failed command's output. pub(crate) fn jj(output: &Output) -> Self { Self::Jj(Self::diagnostic(output)) } /// Builds a patch-apply error from a failed command's output. pub(crate) fn patch_apply(output: &Output) -> Self { Self::PatchApply(Self::diagnostic(output)) } /// Returns a failed command's combined output as a diagnostic. fn diagnostic(output: &Output) -> String { let stdout = String::from_utf8_lossy(&output.stdout); let stderr = String::from_utf8_lossy(&output.stderr); format!("{stdout}{stderr}").trim().to_owned() } } impl From for RepoError { fn from(error: io::Error) -> Self { Self::Io(error) } } impl std::fmt::Display for RepoError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Io(error) => write!(f, "{error}"), Self::Git(message) => write!(f, "git: {message}"), Self::Jj(message) => write!(f, "jj: {message}"), Self::MergeConflict(message) => write!(f, "merge conflict: {message}"), Self::PatchApply(message) => write!(f, "patch does not apply: {message}"), } } } impl std::error::Error for RepoError {} #[cfg(test)] #[allow(clippy::unwrap_used)] mod tests { use super::*; #[test] fn shortstat_lines_parse_with_partial_segments() { assert_eq!( DiffStat::from_shortstat(" 3 files changed, 10 insertions(+), 2 deletions(-)"), DiffStat { files_changed: 3, insertions: 10, deletions: 2 } ); assert_eq!( DiffStat::from_shortstat(" 1 file changed, 5 insertions(+)"), DiffStat { files_changed: 1, insertions: 5, deletions: 0 } ); assert_eq!(DiffStat::from_shortstat("nonsense"), DiffStat::default()); } #[test] fn rev_accepts_revision_syntax() { assert_eq!(Rev::try_from("HEAD~3").unwrap().as_str(), "HEAD~3"); assert_eq!(Rev::try_from("main^").unwrap().as_str(), "main^"); assert_eq!(Rev::try_from("@").unwrap().as_str(), "@"); assert_eq!(Rev::try_from("trunk()").unwrap().as_str(), "trunk()"); } #[test] fn rev_rejects_option_like_selectors() { assert!(Rev::try_from("").is_err()); assert!(Rev::try_from("--help").is_err()); } }