crates/repo/src/lib.rs 12.6 KiB raw
1
//! Repository abstraction layer for Rustik tools.
2
//!
3
//! Provides object identifiers ([`Oid`]) and backend modules for Git and
4
//! Jujutsu repositories.
5
6
#![deny(unsafe_code)]
7
#![warn(missing_docs)]
8
#![warn(clippy::unwrap_used)]
9
10
// `serde` is the local alias for the `microserde` crate; the derive macro
11
// emits `microserde::*` paths so the original crate name must remain in scope.
12
extern crate serde as microserde;
13
14
pub mod git;
15
pub mod jj;
16
pub mod oid;
17
18
pub use oid::{Oid, OidError};
19
20
use std::convert::Infallible;
21
use std::fmt;
22
use std::io;
23
use std::path::Path;
24
use std::process::Output;
25
use std::str::FromStr;
26
27
use git::refs::Qualified;
28
use serde::{Deserialize, Serialize};
29
30
/// Stable patch identifier returned by `git patch-id`.
31
#[derive(Clone, Debug, Default, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
32
#[serde(transparent)]
33
pub struct PatchId(String);
34
35
impl PatchId {
36
    /// Returns the patch identifier text.
37
    pub fn as_str(&self) -> &str {
38
        &self.0
39
    }
40
}
41
42
impl From<String> for PatchId {
43
    fn from(value: String) -> Self {
44
        Self(value)
45
    }
46
}
47
48
impl FromStr for PatchId {
49
    type Err = Infallible;
50
51
    fn from_str(input: &str) -> Result<Self, Self::Err> {
52
        Ok(Self(input.to_owned()))
53
    }
54
}
55
56
impl fmt::Display for PatchId {
57
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
58
        f.write_str(&self.0)
59
    }
60
}
61
62
/// Aggregated diff size of one commit, as reported by `git log --shortstat`.
63
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
64
pub struct DiffStat {
65
    /// Number of files the commit touches.
66
    pub files_changed: usize,
67
    /// Number of inserted lines.
68
    pub insertions: usize,
69
    /// Number of deleted lines.
70
    pub deletions: usize,
71
}
72
73
impl DiffStat {
74
    /// Parses one `--shortstat` summary line.
75
    ///
76
    /// Segments that Git omits (for example deletions in an insert-only
77
    /// commit) stay zero, so an unrecognized line parses as an empty stat.
78
    pub fn from_shortstat(line: &str) -> Self {
79
        let mut stat = Self::default();
80
        for segment in line.split(',') {
81
            let segment = segment.trim();
82
            let Some((count, label)) = segment.split_once(' ') else {
83
                continue;
84
            };
85
            let Ok(count) = count.parse() else {
86
                continue;
87
            };
88
            if label.starts_with("file") {
89
                stat.files_changed = count;
90
            } else if label.starts_with("insertion") {
91
                stat.insertions = count;
92
            } else if label.starts_with("deletion") {
93
                stat.deletions = count;
94
            }
95
        }
96
        stat
97
    }
98
}
99
100
/// User-supplied Git revision or Jujutsu revset selector.
101
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
102
pub struct Rev(String);
103
104
impl Rev {
105
    /// Returns the selector text.
106
    pub fn as_str(&self) -> &str {
107
        &self.0
108
    }
109
}
110
111
impl TryFrom<&str> for Rev {
112
    type Error = &'static str;
113
114
    fn try_from(value: &str) -> Result<Self, Self::Error> {
115
        if value.is_empty() {
116
            return Err("must not be empty");
117
        }
118
        if value.starts_with('-') {
119
            return Err("must not start with '-'");
120
        }
121
        Ok(Self(value.to_owned()))
122
    }
123
}
124
125
impl From<Oid> for Rev {
126
    fn from(oid: Oid) -> Self {
127
        Self(oid.to_string())
128
    }
129
}
130
131
/// Local branch head.
132
#[derive(Clone, Debug, Eq, PartialEq)]
133
pub struct Branch {
134
    /// Short branch name.
135
    pub name: String,
136
    /// Commit at the branch tip.
137
    pub head: Oid,
138
    /// Committer timestamp of the commit at the branch tip.
139
    pub time: CommitTime,
140
}
141
142
/// Commit timestamp in seconds since the Unix epoch.
143
#[derive(Clone, Copy, Debug, Default, Eq, Ord, PartialEq, PartialOrd)]
144
pub struct CommitTime {
145
    /// Seconds since the Unix epoch in the committer timestamp.
146
    pub seconds: i64,
147
}
148
149
/// Commit counts between a base and target revision.
150
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
151
pub struct AheadBehind {
152
    /// Commits reachable from the target but not the base.
153
    pub ahead: usize,
154
    /// Commits reachable from the base but not the target.
155
    pub behind: usize,
156
}
157
158
/// Whether a target can be merged into a base without content conflicts.
159
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
160
pub enum MergeStatus {
161
    /// The merge does not report content conflicts.
162
    Clean,
163
    /// The merge reports content conflicts.
164
    Conflicts,
165
}
166
167
/// Repository operations that read commits, objects, refs, and derived data.
168
pub trait ReadRepository {
169
    /// Resolves a revision reference to a commit id.
170
    fn commit_id(&self, rev: &Rev) -> Result<Oid, RepoError>;
171
172
    /// Returns the tree id for any commit or tree object.
173
    fn tree_id(&self, object: Oid) -> Result<Oid, RepoError>;
174
175
    /// Returns the current commit stored in `reference`, if the ref exists.
176
    fn optional_ref(&self, reference: &Qualified<'_>) -> Result<Option<Oid>, RepoError>;
177
178
    /// Returns refs below `prefix`, sorted by refname.
179
    fn refs(&self, prefix: &Qualified<'_>) -> Result<Vec<(Qualified<'static>, Oid)>, RepoError>;
180
181
    /// Returns local branches, sorted by branch name.
182
    fn branches(&self) -> Result<Vec<Branch>, RepoError>;
183
184
    /// Returns a Git configuration value, if set.
185
    fn config(&self, key: &str) -> Result<Option<String>, RepoError>;
186
187
    /// Returns the repository trunk branch among `branches`.
188
    ///
189
    /// The trunk is the remote default branch when configured, the
190
    /// `init.defaultBranch` branch when configured, or `master` otherwise.
191
    fn trunk(&self, branches: &[Branch]) -> Result<Option<Branch>, RepoError>;
192
193
    /// Returns the best common ancestor of two revisions.
194
    fn merge_base(&self, left: &Rev, right: &Rev) -> Result<Oid, RepoError>;
195
196
    /// Returns the branch point between `target` and its configured upstream.
197
    ///
198
    /// The repository trunk is used when `target` has no upstream.
199
    fn branch_base(&self, target: &Rev) -> Result<Option<Oid>, RepoError>;
200
201
    /// Returns ahead and behind counts for `target` relative to `base`.
202
    fn ahead_behind(&self, base: &Rev, target: &Rev) -> Result<AheadBehind, RepoError>;
203
204
    /// Returns whether `target` would merge into `base` with conflicts.
205
    fn merge_status(&self, base: &Rev, target: &Rev) -> Result<MergeStatus, RepoError>;
206
207
    /// Returns the single parent of `commit`, or an error if it has more or fewer.
208
    fn parent(&self, commit: Oid) -> Result<Oid, RepoError>;
209
210
    /// Returns the full commit message for `commit`.
211
    fn commit_message(&self, commit: Oid) -> Result<String, RepoError>;
212
213
    /// Returns the committer timestamp for `commit`.
214
    fn commit_time(&self, commit: Oid) -> Result<CommitTime, RepoError>;
215
216
    /// Returns each commit's aggregated diff size, in the given order.
217
    fn commit_stats(&self, commits: &[Oid]) -> Result<Vec<DiffStat>, RepoError>;
218
219
    /// Reads a blob object's bytes.
220
    fn cat_blob(&self, blob: Oid) -> Result<Vec<u8>, RepoError>;
221
222
    /// Produces a unified diff between two objects as text.
223
    fn diff(&self, from: Oid, to: Oid) -> Result<String, RepoError>;
224
225
    /// Computes a stable Git patch id for `patch` text.
226
    fn patch_id(&self, patch: &str) -> Result<PatchId, RepoError>;
227
228
    /// Computes stable Git patch ids for patches that each produce an id.
229
    fn patch_ids(&self, patches: &[String]) -> Result<Vec<PatchId>, RepoError>;
230
231
    /// Computes a three-way merge tree and returns the resulting tree id.
232
    fn merge_tree(&self, merge_base: Oid, ours: Oid, theirs: Oid) -> Result<Oid, RepoError>;
233
234
    /// Returns commits in `base..target`, oldest first, as `(id, summary)` pairs.
235
    fn commits(&self, base: &Rev, target: &Rev) -> Result<Vec<(Oid, String)>, RepoError>;
236
237
    /// Returns the unified diff for `commit` against its parent.
238
    fn commit_diff(&self, commit: Oid) -> Result<Vec<u8>, RepoError>;
239
}
240
241
/// Repository operations that write objects and refs.
242
pub trait WriteRepository {
243
    /// Writes `bytes` as a blob object and returns its id.
244
    fn write_blob(&self, bytes: &[u8]) -> Result<Oid, RepoError>;
245
246
    /// Applies a Git-format patch to a temporary index and returns its tree id.
247
    ///
248
    /// Returns [`RepoError::PatchApply`] when the patch does not apply to
249
    /// `base`; other variants signal that the operation itself failed.
250
    fn apply_patch_to_tree(&self, base: Oid, patch: &str) -> Result<Oid, RepoError>;
251
252
    /// Creates a commit with `tree` and `parent`.
253
    fn commit(
254
        &self,
255
        tree: Oid,
256
        parent: Oid,
257
        author: &str,
258
        email: &str,
259
        message: &str,
260
    ) -> Result<Oid, RepoError>;
261
262
    /// Moves `updated` to `commit` and deletes `deleted` in one transaction.
263
    fn update_ref_and_delete(
264
        &self,
265
        updated: &Qualified<'_>,
266
        commit: Oid,
267
        deleted: &Qualified<'_>,
268
    ) -> Result<(), RepoError>;
269
270
    /// Moves `reference` to point at `commit`.
271
    fn update_ref(&self, reference: &Qualified<'_>, commit: Oid) -> Result<(), RepoError>;
272
273
    /// Moves `reference` to `commit` only when it still points to `expected`.
274
    ///
275
    /// Returns `false` when another writer changed the reference first.
276
    fn compare_and_update_ref(
277
        &self,
278
        reference: &Qualified<'_>,
279
        commit: Oid,
280
        expected: Option<Oid>,
281
    ) -> Result<bool, RepoError>;
282
}
283
284
/// A diff backend a viewer can re-query for wider hunk context.
285
pub trait DiffRepository {
286
    /// Refetches `paths` with `context_lines` of unified context per hunk.
287
    ///
288
    /// Returns the raw unified-diff bytes; decoding them is the caller's job.
289
    fn diff(&self, context_lines: usize, paths: &[&Path]) -> Result<Vec<u8>, RepoError>;
290
}
291
292
/// A failure from a Git-backed repository operation.
293
#[derive(Debug)]
294
pub enum RepoError {
295
    /// Spawning or waiting on a process failed.
296
    Io(io::Error),
297
    /// A Git plumbing command failed, carrying its diagnostic.
298
    Git(String),
299
    /// A Jujutsu command failed, carrying its diagnostic.
300
    Jj(String),
301
    /// A three-way merge produced conflicts.
302
    MergeConflict(String),
303
    /// A patch did not apply to the requested tree, carrying its diagnostic.
304
    PatchApply(String),
305
}
306
307
impl RepoError {
308
    /// Builds a Git error from a failed command's output.
309
    pub(crate) fn git(output: &Output) -> Self {
310
        Self::Git(Self::diagnostic(output))
311
    }
312
    /// Builds a Jujutsu error from a failed command's output.
313
    pub(crate) fn jj(output: &Output) -> Self {
314
        Self::Jj(Self::diagnostic(output))
315
    }
316
317
    /// Builds a patch-apply error from a failed command's output.
318
    pub(crate) fn patch_apply(output: &Output) -> Self {
319
        Self::PatchApply(Self::diagnostic(output))
320
    }
321
322
    /// Returns a failed command's combined output as a diagnostic.
323
    fn diagnostic(output: &Output) -> String {
324
        let stdout = String::from_utf8_lossy(&output.stdout);
325
        let stderr = String::from_utf8_lossy(&output.stderr);
326
327
        format!("{stdout}{stderr}").trim().to_owned()
328
    }
329
}
330
331
impl From<io::Error> for RepoError {
332
    fn from(error: io::Error) -> Self {
333
        Self::Io(error)
334
    }
335
}
336
337
impl std::fmt::Display for RepoError {
338
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
339
        match self {
340
            Self::Io(error) => write!(f, "{error}"),
341
            Self::Git(message) => write!(f, "git: {message}"),
342
            Self::Jj(message) => write!(f, "jj: {message}"),
343
            Self::MergeConflict(message) => write!(f, "merge conflict: {message}"),
344
            Self::PatchApply(message) => write!(f, "patch does not apply: {message}"),
345
        }
346
    }
347
}
348
349
impl std::error::Error for RepoError {}
350
351
#[cfg(test)]
352
#[allow(clippy::unwrap_used)]
353
mod tests {
354
    use super::*;
355
356
    #[test]
357
    fn shortstat_lines_parse_with_partial_segments() {
358
        assert_eq!(
359
            DiffStat::from_shortstat(" 3 files changed, 10 insertions(+), 2 deletions(-)"),
360
            DiffStat {
361
                files_changed: 3,
362
                insertions: 10,
363
                deletions: 2
364
            }
365
        );
366
        assert_eq!(
367
            DiffStat::from_shortstat(" 1 file changed, 5 insertions(+)"),
368
            DiffStat {
369
                files_changed: 1,
370
                insertions: 5,
371
                deletions: 0
372
            }
373
        );
374
        assert_eq!(DiffStat::from_shortstat("nonsense"), DiffStat::default());
375
    }
376
377
    #[test]
378
    fn rev_accepts_revision_syntax() {
379
        assert_eq!(Rev::try_from("HEAD~3").unwrap().as_str(), "HEAD~3");
380
        assert_eq!(Rev::try_from("main^").unwrap().as_str(), "main^");
381
        assert_eq!(Rev::try_from("@").unwrap().as_str(), "@");
382
        assert_eq!(Rev::try_from("trunk()").unwrap().as_str(), "trunk()");
383
    }
384
385
    #[test]
386
    fn rev_rejects_option_like_selectors() {
387
        assert!(Rev::try_from("").is_err());
388
        assert!(Rev::try_from("--help").is_err());
389
    }
390
}