gitpoulpi_core/domain/ops.rs
1use std::path::PathBuf;
2
3use serde::{Deserialize, Serialize};
4
5use super::{Oid, RefFilter};
6
7#[derive(Debug, Clone, Default, Serialize, Deserialize)]
8pub struct LogOptions {
9 pub limit: Option<u32>,
10 /// Drop the first `skip` commits of the walk before applying `limit`
11 /// (`git log --skip=<n>`); zero starts at the top. Makes the log
12 /// pageable: page `n` is `skip = n * page_size`.
13 ///
14 /// An offset rather than a "start after this commit" cursor: with
15 /// `all_refs` there is no single ref to resume from, and a cursor would
16 /// narrow the next page to one branch's ancestry.
17 ///
18 /// `#[serde(default)]` keeps an older client's JSON (no `skip` key)
19 /// deserializing against a newer daemon.
20 #[serde(default)]
21 pub skip: u32,
22 pub start_ref: Option<String>,
23 /// When true, walk history from *every* ref (branches, remotes, tags) -
24 /// `git log --all` rather than plain `git log`/`git log <ref>` --
25 /// so the graph shows every branch's commits, not just the checked-out
26 /// one's ancestry. Takes priority over `start_ref` when both are set.
27 pub all_refs: bool,
28 /// Limit history to commits touching at least one of these paths --
29 /// `git log -- <path>...`. Empty means no filter.
30 ///
31 /// Renames are **not** followed here (`git log --follow` takes one
32 /// pathspec only); `GitBackend::file_history` is the rename-following
33 /// per-file history.
34 pub paths: Vec<PathBuf>,
35 /// Show each author as the repository's `.mailmap` names them (git's
36 /// `%aN`/`%aE`, libgit2's `Mailmap`). The daemon sets it from
37 /// `log.use_mailmap`; a client's value is not trusted.
38 #[serde(default)]
39 pub use_mailmap: bool,
40 /// Refs the `all_refs` walk leaves out: commits only they reach vanish
41 /// from the result. Empty (the default, and then absent from the wire)
42 /// is exactly the plain all-refs walk. A non-empty filter always keeps
43 /// `HEAD` in the walk (the working-tree row and the next commit refer
44 /// to it), even when its branch is hidden. Ignored without `all_refs`.
45 #[serde(default, skip_serializing_if = "RefFilter::is_empty")]
46 pub hidden: RefFilter,
47}
48
49#[derive(Debug, Clone, Default, Serialize, Deserialize)]
50pub struct CommitOptions {
51 pub amend: bool,
52 pub sign: bool,
53 /// Skip the commit hooks (`--no-verify`: `pre-commit` and `commit-msg`).
54 /// Without it both backends run the repository's commit hooks, the way
55 /// the system `commit` does.
56 #[serde(default)]
57 pub no_verify: bool,
58 /// Overrides the author identity the commit is made with --
59 /// `general.active_profile` in `config.toml`, resolved by the TUI
60 /// before this crosses the wire. `None` (the default) leaves both
61 /// backends on whatever `git config user.*` says.
62 #[serde(default)]
63 pub author: Option<CommitAuthor>,
64}
65
66/// A commit's author identity, as `CommitOptions::author` overrides it.
67#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
68pub struct CommitAuthor {
69 pub name: String,
70 pub email: String,
71}
72
73#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
74pub enum CheckoutTarget {
75 Branch(String),
76 Commit(Oid),
77 File {
78 path: String,
79 source: Oid,
80 },
81 /// Several files from one commit, as one operation (one journal entry).
82 Files {
83 paths: Vec<String>,
84 source: Oid,
85 },
86}
87
88/// Whether a merge the user starts may fast-forward (`git.merge_fast_forward`
89/// and the repository's own override).
90#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
91#[serde(rename_all = "snake_case")]
92pub enum MergeFastForward {
93 /// Always make a merge commit (`--no-ff`), even when the branch could
94 /// simply be fast-forwarded.
95 #[default]
96 Never,
97 /// Fast-forward when possible, a merge commit otherwise (git's default,
98 /// and `merge.ff` when the repository sets it).
99 Allowed,
100 /// Fast-forward only (`--ff-only`): a diverged branch is refused with
101 /// the typed `NotFastForward`.
102 Only,
103}
104
105impl MergeFastForward {
106 pub const ALL: &'static [MergeFastForward] = &[Self::Never, Self::Allowed, Self::Only];
107
108 pub fn as_str(self) -> &'static str {
109 match self {
110 Self::Never => "never",
111 Self::Allowed => "allowed",
112 Self::Only => "only",
113 }
114 }
115
116 pub fn parse(text: &str) -> Option<Self> {
117 Self::ALL
118 .iter()
119 .copied()
120 .find(|m| m.as_str() == text.trim())
121 }
122
123 /// The repository's own choice wins over the global one; a value that is
124 /// not a policy (a hand-edited file) is ignored, never an error.
125 pub fn resolve(repo: Option<&str>, global: Self) -> Self {
126 repo.and_then(Self::parse).unwrap_or(global)
127 }
128}
129
130#[derive(Debug, Clone, Default, Serialize, Deserialize)]
131#[serde(default)]
132pub struct MergeOptions {
133 /// The fast-forward policy of a user-started merge. `None` lets the
134 /// daemon resolve it from the settings (repository override, then
135 /// `git.merge_fast_forward`) into `no_ff` / `fast_forward_only`; a request
136 /// that sets either flag itself is taken as it is.
137 pub ff: Option<MergeFastForward>,
138 pub fast_forward_only: bool,
139 pub no_commit: bool,
140 /// Always make a merge commit, even when a fast-forward is possible
141 /// (`git merge --no-ff`).
142 pub no_ff: bool,
143 /// Squash the other branch's commits into one new commit on the
144 /// checked-out branch (`git merge --squash`, then a commit). The
145 /// commit's message is `message`, or a default naming the branch.
146 pub squash: bool,
147 /// The message of the merge commit or of the squash commit.
148 pub message: Option<String>,
149}
150
151#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
152pub enum MergeOutcome {
153 FastForwarded(Oid),
154 Merged(Oid),
155 UpToDate,
156 Conflicted(Vec<String>),
157}
158
159/// What [`crate::GitBackend::fast_forward`] did.
160#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
161pub enum FastForwardOutcome {
162 /// The branch moved from `from` to `to`.
163 FastForwarded { from: Oid, to: Oid },
164 /// The branch already contained the target (it *is* the target, or
165 /// is ahead of it): nothing moved.
166 UpToDate,
167}
168
169/// Where a new linked worktree starts (see
170/// [`crate::GitBackend::worktree_add`]).
171#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
172pub enum WorktreeStart {
173 /// An existing *local* branch, by its short name. Without a new
174 /// branch name it is checked out in the new worktree (git refuses a
175 /// branch already checked out in another worktree); with one, the
176 /// new branch starts at its tip.
177 Branch(String),
178 /// A commit. Without a new branch name the new worktree gets a
179 /// detached HEAD there.
180 Commit(Oid),
181}
182
183/// The arguments of [`crate::GitBackend::worktree_add`] besides the path.
184#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
185pub struct WorktreeAddOptions {
186 pub start: WorktreeStart,
187 /// Create this local branch at `start` and check it out in the new
188 /// worktree (`git worktree add -b`). A name already taken is an
189 /// error, never a silent reuse.
190 pub new_branch: Option<String>,
191}
192
193/// One uncommitted change of a worktree, as `git status` lists it
194/// (see [`crate::GitBackend::worktree_changes`]).
195#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
196pub struct WorktreeChange {
197 /// Path relative to the worktree, `/`-separated.
198 pub path: String,
199 /// Not tracked by git (and not ignored).
200 pub untracked: bool,
201}
202
203/// Commit every change of the worktree on its branch before removing it.
204#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
205pub struct WorktreeCommit {
206 pub message: String,
207 /// A detached worktree has no branch to commit on: this names the
208 /// branch created at HEAD there first. Ignored on a branch.
209 pub branch: Option<String>,
210}
211
212/// The arguments of [`crate::GitBackend::worktree_remove`] besides the path.
213#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
214pub struct WorktreeRemoveOptions {
215 /// Remove even with uncommitted changes (they are lost).
216 pub force: bool,
217 /// Stage and commit every change first (tracked and untracked,
218 /// `.gitignore` respected), then remove.
219 pub commit: Option<WorktreeCommit>,
220 /// Stash every change first (`git stash push -u`, with this message), then
221 /// remove. The stash stack is shared by all worktrees of the repository.
222 pub stash: Option<String>,
223}
224
225/// What [`crate::GitBackend::worktree_remove`] did.
226#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
227pub struct WorktreeRemoved {
228 pub path: std::path::PathBuf,
229 /// The commit made first, if asked.
230 pub commit: Option<Oid>,
231 /// A stash was made first.
232 pub stashed: bool,
233}
234
235/// What [`crate::GitBackend::patch_create`] turns into a patch file.
236#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
237pub enum PatchSource {
238 /// One or more commits, given oldest-first. Each becomes its own
239 /// `git format-patch -1`, concatenated into a single mbox file - so
240 /// the result is exactly what applying them one at a time, in this
241 /// order, would produce. A merge commit or an unknown oid refuses
242 /// the whole request; nothing is written.
243 Commits(Vec<Oid>),
244 /// Every non-merge commit in `base..tip` (`git format-patch
245 /// base..tip`), oldest-first -- merges in the range are skipped
246 /// rather than refusing the whole range, since a merge itself never
247 /// applies as a patch.
248 Range { base: Oid, tip: Oid },
249 /// The working tree's current changes against `HEAD`
250 /// (`git diff HEAD --binary`), covering both staged and unstaged
251 /// modifications to tracked files. `paths` empty means every
252 /// changed file; otherwise only those paths.
253 ///
254 /// Untracked files are deliberately excluded: a working-tree patch
255 /// is a diff against `HEAD`, and an untracked file has no `HEAD`
256 /// side to diff against - `git diff` never lists it either. Stage
257 /// the file first (or use `PatchSource::Commits`) to include it.
258 WorkingTree { paths: Vec<String> },
259 /// One commit restricted to `paths` (`git format-patch -1 -- paths`):
260 /// the patch for just those files of a commit. A merge commit, an
261 /// unknown oid, no paths, or paths the commit did not touch refuse.
262 CommitPaths { commit: Oid, paths: Vec<String> },
263}
264
265/// What [`crate::GitBackend::patch_create`] wrote.
266#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
267pub struct PatchCreated {
268 pub path: PathBuf,
269 /// How many commits the patch carries. `0` for
270 /// [`PatchSource::WorkingTree`], which is not commit-shaped.
271 pub commits: usize,
272 pub bytes: u64,
273}
274
275/// Why [`crate::GitBackend::apply_commit_to_worktree`] refused before
276/// touching anything. A patch that merely does not apply is an ordinary
277/// error, not one of these.
278#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
279pub enum ApplyRefusal {
280 /// A merge commit has no single set of changes to replay.
281 MergeCommit,
282}
283
284/// What [`crate::GitBackend::patch_apply`] changed.
285#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
286pub struct PatchApplied {
287 /// The paths the patch touched, in the order `git apply` reported
288 /// them.
289 pub files: Vec<String>,
290}
291
292#[derive(Debug, Clone, Default, Serialize, Deserialize)]
293pub struct RebaseOptions {
294 pub autosquash: bool,
295}
296
297#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
298pub struct RebaseStep {
299 pub commit: Oid,
300 pub action: RebaseAction,
301 /// The new message for a [`RebaseAction::Reword`] step. Required
302 /// (validated by [`validate_plan`]) when `action` is `Reword`; ignored
303 /// for every other action.
304 #[serde(default)]
305 pub message: Option<String>,
306}
307
308/// Serializes as the variant name (`"Pick"`); deserializes from that, from
309/// the lowercase todo-list names and from their one-letter abbreviations,
310/// in any case (see [`RebaseAction::parse`]).
311#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
312#[serde(try_from = "String")]
313pub enum RebaseAction {
314 Pick,
315 Squash,
316 Fixup,
317 Edit,
318 Drop,
319 Reword,
320}
321
322impl RebaseAction {
323 /// `pick`/`p`, `reword`/`r`, `edit`/`e`, `squash`/`s`, `fixup`/`f`,
324 /// `drop`/`d`, case-insensitively: the spelling of a rebase todo list.
325 pub fn parse(text: &str) -> Option<Self> {
326 Some(match text.to_ascii_lowercase().as_str() {
327 "pick" | "p" => Self::Pick,
328 "reword" | "r" => Self::Reword,
329 "edit" | "e" => Self::Edit,
330 "squash" | "s" => Self::Squash,
331 "fixup" | "f" => Self::Fixup,
332 "drop" | "d" => Self::Drop,
333 _ => return None,
334 })
335 }
336}
337
338impl TryFrom<String> for RebaseAction {
339 type Error = String;
340
341 fn try_from(text: String) -> Result<Self, String> {
342 Self::parse(&text).ok_or_else(|| {
343 format!(
344 "unknown rebase action {text:?}, expected one of pick, reword, edit, squash, \
345 fixup, drop (or p, r, e, s, f, d)"
346 )
347 })
348 }
349}
350
351/// A request to run `git rebase -i` with an explicit, pre-decided todo
352/// list rather than an interactively edited one - see
353/// `crate::GitBackend::rebase_interactive`.
354#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
355pub struct InteractiveRebase {
356 /// The commit the range starts *after* - `None` means `--root`
357 /// (rebase the whole history onto `onto`, or in place with no
358 /// `onto`).
359 pub upstream: Option<Oid>,
360 /// Replay onto this commit instead of `upstream` (`git rebase
361 /// --onto`). `None` keeps replaying onto `upstream` itself, i.e. a
362 /// plain interactive rebase.
363 pub onto: Option<Oid>,
364 /// The plan, oldest first - must be exactly a permutation of the
365 /// range `upstream..HEAD` (or `HEAD` when `upstream` is `None`); see
366 /// [`validate_plan`].
367 pub steps: Vec<RebaseStep>,
368 /// Reorder `steps` with `git rebase --autosquash`'s algorithm before
369 /// building the todo list (see [`autosquash_order`]). The backend
370 /// itself always calls git with `--no-autosquash`, so this is the
371 /// only way autosquash reordering happens.
372 pub autosquash: bool,
373 /// Cherry-pick mode: `steps` are arbitrary commits (not the range
374 /// `upstream..HEAD`) to replay, in order, onto the current HEAD with
375 /// the same pick/reword/squash/fixup/edit/drop actions. `upstream`
376 /// and `onto` are ignored. Conflicts/stops are handled with the same
377 /// rebase continue/skip/abort operations.
378 #[serde(default)]
379 pub cherry_pick: bool,
380}
381
382/// What [`crate::GitBackend::rebase_plan`] reports: the range a rebase
383/// from `upstream` would replay, oldest first - the material a frontend
384/// builds an [`InteractiveRebase`] plan from.
385#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
386pub struct RebasePlanDraft {
387 pub upstream: Option<Oid>,
388 pub commits: Vec<PlanCommit>,
389}
390
391#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
392pub struct PlanCommit {
393 pub id: Oid,
394 pub summary: String,
395 pub message: String,
396}
397
398/// The state of a rebase (interactive or plain) currently in progress in
399/// the repository, as reported by [`crate::GitBackend::rebase_state`].
400#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
401pub struct RebaseState {
402 /// The branch being rebased, or `None` for a detached HEAD.
403 pub head_name: Option<String>,
404 pub onto: Oid,
405 /// The commit the rebase is currently stopped at (conflict or `edit`
406 /// stop), or `None` if it is not stopped (should not normally happen
407 /// while `RebaseState` exists, but guards a race reading git's own
408 /// state files).
409 pub stopped_at: Option<Oid>,
410 /// 1-based index of the step currently being applied.
411 pub step: usize,
412 pub total: usize,
413 pub conflicted: bool,
414 pub interactive: bool,
415}
416
417#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
418pub enum RebaseOutcome {
419 Completed,
420 Conflicted {
421 paused_at: Oid,
422 remaining: Vec<Oid>,
423 },
424 /// An `edit` step stopped the rebase deliberately - not a conflict.
425 /// `at` is the commit now checked out; `remaining` are the steps not
426 /// yet applied.
427 Stopped {
428 at: Oid,
429 remaining: Vec<Oid>,
430 },
431}
432
433/// Why [`crate::GitBackend::rebase_plan`], `rebase_interactive`,
434/// `rebase_continue`, `rebase_skip` or `rebase_abort` refused, before
435/// touching anything.
436#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
437#[serde(rename_all = "snake_case")]
438pub enum RebaseRefusal {
439 /// A merge, rebase, cherry-pick, revert or bisect is already in
440 /// progress.
441 OperationInProgress,
442 UncommittedChanges,
443 /// HEAD is detached, or the range crosses onto a commit not on the
444 /// current branch.
445 NotOnCurrentBranch,
446 /// The range `upstream..HEAD` contains a merge commit (more than one
447 /// parent) - `RebaseInteractive` never linearises history.
448 MergeInRange,
449 /// `steps` is not exactly a permutation of the range being rebased.
450 PlanMismatch,
451 /// A `Squash` or `Fixup` step is the oldest step in the plan, so it
452 /// has no predecessor to combine into.
453 SquashWithoutPredecessor,
454 /// A `Reword` step carries no (or an empty, after normalisation)
455 /// message.
456 EmptyRewordMessage,
457 /// `rebase_continue`/`rebase_skip`/`rebase_abort` was called with no
458 /// rebase in progress.
459 NoRebaseInProgress,
460}
461
462/// Validates that `steps` is exactly a permutation of `range` (same set
463/// of oids, no duplicates, no missing ones) and that every `Reword` step
464/// carries a non-empty message and no `Squash`/`Fixup` step is first.
465///
466/// Pure and backend-agnostic so every backend refuses identically and it
467/// can be unit tested without a repository.
468pub fn validate_plan(
469 range: &[Oid],
470 steps: &[RebaseStep],
471) -> std::result::Result<(), RebaseRefusal> {
472 if steps.len() != range.len() {
473 return Err(RebaseRefusal::PlanMismatch);
474 }
475 let mut wanted: Vec<Oid> = range.to_vec();
476 wanted.sort_by_key(|o| o.to_hex());
477 let mut got: Vec<Oid> = steps.iter().map(|s| s.commit).collect();
478 got.sort_by_key(|o| o.to_hex());
479 if wanted != got {
480 return Err(RebaseRefusal::PlanMismatch);
481 }
482 if let Some(first) = steps.first() {
483 if matches!(first.action, RebaseAction::Squash | RebaseAction::Fixup) {
484 return Err(RebaseRefusal::SquashWithoutPredecessor);
485 }
486 }
487 for step in steps {
488 if step.action == RebaseAction::Reword
489 && normalize_reword_message(step.message.as_deref().unwrap_or_default()).is_none()
490 {
491 return Err(RebaseRefusal::EmptyRewordMessage);
492 }
493 }
494 Ok(())
495}
496
497/// Reorders `rows` the way `git rebase --autosquash` would: a row whose
498/// summary starts with `squash! <target>` or `fixup! <target>` moves to
499/// sit directly after the row whose summary (after stripping its own
500/// `squash!`/`fixup!` prefixes) matches `<target>` - exactly, or as a
501/// prefix of it, the way git itself matches - and its action becomes
502/// `Squash`/`Fixup`. Rows with no match are left in place. Oldest first,
503/// like the plan it reorders.
504pub fn autosquash_order(rows: &mut Vec<(Oid, String, RebaseAction)>) {
505 fn autosquash_kind(summary: &str) -> Option<(RebaseAction, &str)> {
506 if let Some(rest) = summary.strip_prefix("squash! ") {
507 Some((RebaseAction::Squash, rest))
508 } else if let Some(rest) = summary.strip_prefix("fixup! ") {
509 Some((RebaseAction::Fixup, rest))
510 } else {
511 None
512 }
513 }
514
515 let original = rows.clone();
516 let mut out: Vec<(Oid, String, RebaseAction)> = Vec::with_capacity(original.len());
517 let mut consumed = vec![false; original.len()];
518
519 for (i, (_, summary, _)) in original.iter().enumerate() {
520 if consumed[i] {
521 continue;
522 }
523 if autosquash_kind(summary).is_some() {
524 continue;
525 }
526 out.push(original[i].clone());
527 consumed[i] = true;
528 // Any not-yet-placed row targeting this one, in original order.
529 for (j, (_, other_summary, _)) in original.iter().enumerate() {
530 if consumed[j] {
531 continue;
532 }
533 if let Some((action, target)) = autosquash_kind(other_summary) {
534 if summary.starts_with(target) {
535 out.push((original[j].0, original[j].1.clone(), action));
536 consumed[j] = true;
537 }
538 }
539 }
540 }
541 // Anything left (a squash!/fixup! with no matching target) keeps its
542 // original relative order at the end, unchanged (as `Pick`).
543 for (i, row) in original.into_iter().enumerate() {
544 if !consumed[i] {
545 out.push(row);
546 }
547 }
548 *rows = out;
549}
550
551#[derive(Debug, Clone, Default, Serialize, Deserialize)]
552pub struct CherryPickOptions {
553 pub no_commit: bool,
554}
555
556#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
557pub enum CherryPickOutcome {
558 Completed(Vec<Oid>),
559 Conflicted { paused_at: Oid, remaining: Vec<Oid> },
560}
561
562#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
563pub enum RevertOutcome {
564 Completed(Oid),
565 Conflicted,
566}
567
568/// What [`crate::GitBackend::reword`] did.
569///
570/// `previous_head` is the tip the branch (or a detached HEAD) had before
571/// the rewrite. Both backends also leave it in `ORIG_HEAD` and in the
572/// branch's reflog, so "put it back" is `reset --soft <previous_head>`
573/// whether or not the frontend kept this value around.
574#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
575pub struct RewordOutcome {
576 /// The new commit carrying the new message (the rewritten `commit`).
577 pub reworded: Oid,
578 /// HEAD before the rewrite.
579 pub previous_head: Oid,
580 /// HEAD after it. Equal to `reworded` when the reworded commit was
581 /// HEAD itself.
582 pub new_head: Oid,
583 /// How many descendants of the reworded commit were re-created on
584 /// top of it (0 when it was HEAD).
585 pub replayed: usize,
586}
587
588/// Why [`crate::GitBackend::reword`] refused, before touching anything.
589#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
590#[serde(rename_all = "snake_case")]
591pub enum RewordRefusal {
592 /// The commit is not HEAD nor an ancestor of HEAD, so there is no
593 /// current-branch history to rewrite it in.
594 NotOnCurrentBranch,
595 /// A merge, rebase, cherry-pick, revert or bisect is in progress.
596 OperationInProgress,
597 /// The new message is empty once trailing whitespace is removed.
598 EmptyMessage,
599 /// An amended name or email is empty, or holds `<`, `>`, a line break
600 /// (or, for an email, a space).
601 InvalidIdentity,
602 /// An amended date is neither git's raw format nor ISO 8601.
603 InvalidDate,
604}
605
606/// The message [`crate::GitBackend::reword`] stores for `message`, or
607/// `None` when nothing is left.
608///
609/// One rule shared by both backends so the new commit's oid is the same
610/// whichever wrote it: CRLF becomes LF, leading blank lines and trailing
611/// whitespace go, and the message ends in exactly one `\n`, as
612/// `git commit` leaves it.
613pub fn normalize_reword_message(message: &str) -> Option<String> {
614 let unix = message.replace("\r\n", "\n");
615 let mut rest = unix.as_str();
616 while let Some((line, after)) = rest.split_once('\n') {
617 if !line.trim().is_empty() {
618 break;
619 }
620 rest = after;
621 }
622 let trimmed = rest.trim_end();
623 if trimmed.is_empty() {
624 None
625 } else {
626 Some(format!("{trimmed}\n"))
627 }
628}
629
630#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
631pub enum ResetMode {
632 Soft,
633 Mixed,
634 Hard,
635}
636
637#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
638#[serde(default)]
639pub struct FetchOptions {
640 /// `--prune`: drop remote-tracking branches the remote no longer has.
641 pub prune: bool,
642 /// Also delete the **local** tags that were on a remote and that this
643 /// fetch learned the remote has deleted (git's `fetch.pruneTags`, but
644 /// narrower: a tag that was never on the remote - an unpushed one - is
645 /// never touched, and neither is one that moved locally). Needs git
646 /// 2.41+ to learn what was pruned; off by default, like git.
647 pub prune_tags: bool,
648}
649
650#[derive(Debug, Clone, Default, Serialize, Deserialize)]
651pub struct FetchOutcome {
652 pub updated_refs: Vec<String>,
653 /// Local tags deleted because `prune_tags` was on and the remote had
654 /// deleted them.
655 #[serde(default)]
656 pub pruned_tags: Vec<String>,
657}
658
659/// How a pull integrates what it fetched.
660///
661/// Always passed to git *explicitly* (`--no-rebase`, `--ff-only`,
662/// `--rebase`), so a `pull.rebase` or `pull.ff` in the user's own config
663/// cannot change what the button says.
664#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
665#[serde(rename_all = "snake_case")]
666pub enum PullMode {
667 /// Fast-forward when possible, otherwise a merge commit
668 /// (`git pull --no-rebase`).
669 #[default]
670 Merge,
671 /// Fast-forward or fail (`git pull --ff-only`). A diverged branch is
672 /// the typed [`crate::Error::NotFastForward`], never a merge.
673 FastForwardOnly,
674 /// Replay local commits on top of the upstream (`git pull --rebase`).
675 Rebase,
676}
677
678#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
679#[serde(default)]
680pub struct PullOptions {
681 pub mode: PullMode,
682 /// Pull the same-named branch from this remote instead of the
683 /// branch's configured upstream - what a branch with no upstream
684 /// needs. `None` is plain `git pull`: the upstream.
685 pub remote: Option<String>,
686 /// With `remote`: pull this branch of it instead of the same-named
687 /// one (a branch published under another name). `None` keeps the
688 /// local branch name.
689 pub remote_branch: Option<String>,
690}
691
692#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
693pub enum PullOutcome {
694 UpToDate,
695 FastForwarded(Oid),
696 Merged(Oid),
697 Conflicted,
698}
699
700#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
701#[serde(default)]
702pub struct PushOptions {
703 /// Overwrite the remote branch, but only if it is still where our
704 /// remote-tracking ref says it is: `--force-with-lease`. There is
705 /// deliberately no way to ask for a bare `--force` - a force push
706 /// that silently discards a colleague's commits pushed since our last
707 /// fetch is the one push mistake nobody sees coming.
708 ///
709 /// `force` is accepted as a spelling on the wire for older clients,
710 /// and means the same lease.
711 #[serde(alias = "force")]
712 pub force_with_lease: bool,
713 /// `--set-upstream`: record `<remote>/<branch>` as the branch's
714 /// upstream - what the first push of a new branch wants.
715 pub set_upstream: bool,
716 /// The local branch to push. `None` is the checked-out branch.
717 pub branch: Option<String>,
718 /// An explicit lease, overriding the bare one `force_with_lease`
719 /// asks for. `None` with `force_with_lease: true` means
720 /// [`PushLease::Tracking`].
721 pub lease: Option<PushLease>,
722 /// The destination branch name on the remote when it differs from
723 /// the local one (`refs/heads/<branch>:refs/heads/<remote_branch>`).
724 pub remote_branch: Option<String>,
725}
726
727/// What a leased force push expects the remote branch to hold.
728#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
729pub enum PushLease {
730 /// Whatever our remote-tracking ref holds now (a bare
731 /// `--force-with-lease`).
732 Tracking,
733 /// Exactly this commit (`--force-with-lease=<ref>:<oid>`): a fetch
734 /// between the decision and the push cannot widen the lease.
735 Expect(Oid),
736 /// The branch must not exist yet (`--force-with-lease=<ref>:`).
737 Absent,
738}
739
740/// Why a remote refused a push, when it is a refusal the user can act on
741/// rather than an arbitrary failure (see [`crate::Error::PushRejected`]).
742#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
743#[serde(rename_all = "snake_case")]
744pub enum PushRejectReason {
745 /// The remote branch has commits the local one does not - git's
746 /// `non-fast-forward` / `fetch first`. The remote has diverged.
747 NonFastForward,
748 /// A `--force-with-lease` push found the remote branch somewhere
749 /// other than where our remote-tracking ref said: someone pushed
750 /// since our last fetch, and the lease protected their work.
751 StaleLease,
752 /// The host's branch protection refused the push (protected branch,
753 /// force push not allowed). The remote's own words are in the
754 /// rejection's `detail`.
755 ProtectedByHost,
756 /// Any other `[remote rejected]`: a pre-receive hook, permissions.
757 /// The remote's own words are in the rejection's `detail`.
758 RemoteRefused,
759 /// A reason a newer peer knows and this one does not.
760 #[serde(other)]
761 Unknown,
762}
763
764/// A push the remote rejected, typed so a frontend can offer "pull
765/// first / force push / cancel" instead of printing git's stderr.
766#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
767pub struct PushRejection {
768 pub remote: String,
769 pub branch: String,
770 pub reason: PushRejectReason,
771 /// The command and its stderr, for the activity log. Absent on the wire
772 /// from a peer that predates it.
773 #[serde(default, skip_serializing_if = "Option::is_none")]
774 pub detail: Option<Box<crate::failure::ErrorDetail>>,
775}
776
777#[derive(Debug, Clone, Default, Serialize, Deserialize)]
778pub struct PushOutcome {
779 pub pushed_refs: Vec<String>,
780}
781
782/// Which tags [`crate::GitBackend::tag_push`] should send.
783///
784/// `AllUnpushed` is a *selection* resolved inside the backend, not a list
785/// the caller built by looping over `refs()`: it is one operation (one
786/// result, one `RepoChanged`), one `git push` (hooks and credential
787/// prompts run once), and the set is resolved **at push time** from the
788/// mirror namespace that drew the markers, so a tag created after the
789/// frontend last refreshed is included.
790#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
791pub enum TagSelection {
792 /// Exactly these tags, in this order. An unknown name is an error:
793 /// "push v9" quietly pushing nothing is the worst possible answer.
794 Named(Vec<String>),
795 /// Every local tag no remote is known to have (see
796 /// [`super::TagSync`]). An empty set is a *success* reporting no
797 /// pushed refs - "everything is already pushed" is not a failure.
798 AllUnpushed,
799}
800
801#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
802pub struct CloneOptions {
803 pub shallow_depth: Option<u32>,
804 pub recurse_submodules: bool,
805 /// Check out this branch instead of the remote's default HEAD --
806 /// `git clone --branch <name>`. `None` keeps git's own default.
807 #[serde(default)]
808 pub branch: Option<String>,
809 /// Name the new remote something other than `origin` --
810 /// `git clone --origin <name>`.
811 #[serde(default)]
812 pub remote_name: Option<String>,
813 /// Whether to download Git LFS objects after cloning (default: yes,
814 /// when `git-lfs` is installed). A clone never fails because of LFS.
815 #[serde(default)]
816 pub lfs: super::LfsCloneMode,
817 /// Sparse checkout in cone mode: only these top-level or nested
818 /// directories (plus the files at the repository root) are checked out;
819 /// the full history is still downloaded. `None` is a normal full clone.
820 /// Normalised with [`normalize_sparse_dirs`] before use.
821 #[serde(default)]
822 pub sparse: Option<Vec<String>>,
823}
824
825/// What a repository's sparse checkout looks like right now
826/// (`GitBackend::sparse_checkout_status`).
827#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
828pub struct SparseState {
829 /// `core.sparseCheckout` is on: part of the tree is not materialised.
830 pub enabled: bool,
831 /// Cone mode (directories, the git default). A repository set up in
832 /// non-cone mode with patterns elsewhere reports `false` and the raw
833 /// patterns in `dirs`.
834 pub cone: bool,
835 /// The checked-out directories, `/`-separated and relative to the root.
836 /// Empty when not enabled.
837 pub dirs: Vec<String>,
838}
839
840/// Cleans the directories of a sparse-checkout request: backslashes become
841/// `/`, surrounding and trailing slashes and a leading `./` go, duplicates
842/// collapse (order kept). Refuses an empty list, an empty or absolute
843/// path, `..`, and anything git would read as an option or a pattern.
844pub fn normalize_sparse_dirs(dirs: &[String]) -> crate::Result<Vec<String>> {
845 let mut out: Vec<String> = Vec::new();
846 for raw in dirs {
847 let mut d = raw.trim().replace('\\', "/");
848 while let Some(rest) = d.strip_prefix("./") {
849 d = rest.to_string();
850 }
851 let d = d.trim_matches('/').to_string();
852 if d.is_empty() || d == "." {
853 return Err(crate::Error::Backend(format!(
854 "`{raw}` is not a directory of the repository"
855 )));
856 }
857 if raw.trim().starts_with('/')
858 || d.starts_with('-')
859 || d.starts_with('!')
860 || d.starts_with('#')
861 || d.split('/').any(|c| c == ".." || c == "." || c.is_empty())
862 || d.contains(['*', '?', '[', ':'])
863 || d.chars().any(char::is_control)
864 {
865 return Err(crate::Error::Backend(format!(
866 "`{raw}` is not a valid sparse-checkout directory (use a path relative to the repository root, without patterns)"
867 )));
868 }
869 if !out.contains(&d) {
870 out.push(d);
871 }
872 }
873 if out.is_empty() {
874 return Err(crate::Error::Backend(
875 "a sparse checkout needs at least one directory".to_string(),
876 ));
877 }
878 Ok(out)
879}
880
881#[cfg(test)]
882mod sparse_tests {
883 use super::normalize_sparse_dirs;
884
885 fn n(v: &[&str]) -> crate::Result<Vec<String>> {
886 normalize_sparse_dirs(&v.iter().map(|s| s.to_string()).collect::<Vec<_>>())
887 }
888
889 #[test]
890 fn cleans_slashes_dots_and_duplicates() {
891 assert_eq!(
892 n(&["./src/", "docs\\guide", " src "]).unwrap(),
893 ["src", "docs/guide"]
894 );
895 }
896
897 #[test]
898 fn refuses_what_is_not_a_plain_relative_dir() {
899 for bad in ["", "/", "/etc", "..", "a/../b", "-x", "!x", "a/*", "a:b"] {
900 assert!(n(&[bad]).is_err(), "{bad:?} must be refused");
901 }
902 assert!(n(&[]).is_err());
903 }
904}
905
906/// What `GitBackend::init` should make.
907///
908/// Deliberately tiny: anything else belongs in the user's own git
909/// configuration, which `init` does not override.
910#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
911pub struct InitOptions {
912 /// A repository with no working tree (`git init --bare`).
913 #[serde(default)]
914 pub bare: bool,
915 /// The name of the branch HEAD points at before the first commit --
916 /// `git init --initial-branch <name>`. `None` leaves git's own default
917 /// (`init.defaultBranch`, or `master`).
918 #[serde(default)]
919 pub initial_branch: Option<String>,
920}
921
922/// How far along a `clone` is, pushed to the UI while the clone runs. The
923/// phases mirror git's own progress vocabulary.
924#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
925pub enum ClonePhase {
926 /// The connection is open, nothing has been counted yet.
927 Connecting,
928 /// The remote is enumerating what it will send.
929 Counting,
930 /// The remote is compressing objects.
931 Compressing,
932 /// Objects are arriving.
933 Receiving,
934 /// Deltas are being applied locally.
935 Resolving,
936 /// The working tree is being written.
937 CheckingOut,
938 /// Git LFS objects are being downloaded after the clone.
939 LfsObjects,
940 /// The clone finished; `percent` is 100.
941 Done,
942}
943
944impl ClonePhase {
945 /// The label a progress bar shows. Plain ASCII words, so the value is
946 /// safe in a terminal at any font (see the emoji-presentation rule in
947 /// `docs/developer/where-we-are.md`).
948 pub fn label(self) -> &'static str {
949 match self {
950 Self::Connecting => "Connecting",
951 Self::Counting => "Counting objects",
952 Self::Compressing => "Compressing objects",
953 Self::Receiving => "Receiving objects",
954 Self::Resolving => "Resolving deltas",
955 Self::CheckingOut => "Checking out files",
956 Self::LfsObjects => "Downloading LFS objects",
957 Self::Done => "Done",
958 }
959 }
960}
961
962/// One progress report from an in-flight clone.
963///
964/// `percent` is always present and always 0..=100, so a progress bar is
965/// drawable from this type alone. `current`/`total` carry the raw counts
966/// when git reported them, for a `(450/1000)` suffix.
967#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
968pub struct CloneProgress {
969 pub phase: ClonePhase,
970 pub percent: u8,
971 pub current: Option<u64>,
972 pub total: Option<u64>,
973}
974
975impl CloneProgress {
976 pub fn new(phase: ClonePhase, percent: u8) -> Self {
977 Self {
978 phase,
979 percent: percent.min(100),
980 current: None,
981 total: None,
982 }
983 }
984
985 pub fn with_counts(mut self, current: u64, total: u64) -> Self {
986 self.current = Some(current);
987 self.total = Some(total);
988 self
989 }
990
991 pub fn done() -> Self {
992 Self::new(ClonePhase::Done, 100)
993 }
994}
995
996/// The sink a backend reports clone progress to.
997///
998/// A plain callback rather than a channel, so `gitpoulpi-core` keeps no
999/// I/O-framework dependency: the daemon wraps a `broadcast::Sender`, the
1000/// CLI wraps stderr, a test wraps a `Vec`.
1001pub type CloneProgressSink<'a> = &'a (dyn Fn(CloneProgress) + Send + Sync);
1002
1003#[cfg(test)]
1004mod tests {
1005 use super::*;
1006
1007 #[test]
1008 fn the_merge_fast_forward_policy_defaults_to_never_and_the_repo_wins() {
1009 use MergeFastForward as P;
1010 assert_eq!(P::default(), P::Never, "the owner's expectation");
1011 // The repository's choice wins over the global one, either way.
1012 assert_eq!(P::resolve(Some("allowed"), P::Never), P::Allowed);
1013 assert_eq!(P::resolve(Some("never"), P::Allowed), P::Never);
1014 assert_eq!(P::resolve(Some("only"), P::Allowed), P::Only);
1015 // Nothing, or a value that is no policy: the global one.
1016 assert_eq!(P::resolve(None, P::Only), P::Only);
1017 assert_eq!(P::resolve(Some("sometimes"), P::Allowed), P::Allowed);
1018 assert_eq!(P::resolve(Some(""), P::Never), P::Never);
1019 for p in P::ALL {
1020 assert_eq!(P::parse(p.as_str()), Some(*p));
1021 assert_eq!(
1022 serde_json::to_string(p).unwrap(),
1023 format!("\"{}\"", p.as_str()),
1024 "the wire spelling is the config spelling"
1025 );
1026 }
1027 }
1028
1029 fn oid(byte: u8) -> Oid {
1030 Oid([byte; 20])
1031 }
1032
1033 #[test]
1034 fn validate_plan_accepts_any_permutation_of_the_range() {
1035 let range = [oid(1), oid(2), oid(3)];
1036 let steps = vec![
1037 RebaseStep {
1038 commit: oid(3),
1039 action: RebaseAction::Pick,
1040 message: None,
1041 },
1042 RebaseStep {
1043 commit: oid(1),
1044 action: RebaseAction::Pick,
1045 message: None,
1046 },
1047 RebaseStep {
1048 commit: oid(2),
1049 action: RebaseAction::Squash,
1050 message: None,
1051 },
1052 ];
1053 assert_eq!(validate_plan(&range, &steps), Ok(()));
1054 }
1055
1056 #[test]
1057 fn validate_plan_rejects_a_dropped_or_duplicated_commit() {
1058 let range = [oid(1), oid(2)];
1059 let missing = vec![
1060 RebaseStep {
1061 commit: oid(1),
1062 action: RebaseAction::Pick,
1063 message: None,
1064 },
1065 RebaseStep {
1066 commit: oid(1),
1067 action: RebaseAction::Pick,
1068 message: None,
1069 },
1070 ];
1071 assert_eq!(
1072 validate_plan(&range, &missing),
1073 Err(RebaseRefusal::PlanMismatch)
1074 );
1075 }
1076
1077 #[test]
1078 fn validate_plan_refuses_squash_or_fixup_as_the_oldest_step() {
1079 let range = [oid(1), oid(2)];
1080 let steps = vec![
1081 RebaseStep {
1082 commit: oid(1),
1083 action: RebaseAction::Fixup,
1084 message: None,
1085 },
1086 RebaseStep {
1087 commit: oid(2),
1088 action: RebaseAction::Pick,
1089 message: None,
1090 },
1091 ];
1092 assert_eq!(
1093 validate_plan(&range, &steps),
1094 Err(RebaseRefusal::SquashWithoutPredecessor)
1095 );
1096 }
1097
1098 #[test]
1099 fn validate_plan_refuses_an_empty_reword_message() {
1100 let range = [oid(1)];
1101 let steps = vec![RebaseStep {
1102 commit: oid(1),
1103 action: RebaseAction::Reword,
1104 message: Some(" \r\n ".into()),
1105 }];
1106 assert_eq!(
1107 validate_plan(&range, &steps),
1108 Err(RebaseRefusal::EmptyRewordMessage)
1109 );
1110 }
1111
1112 #[test]
1113 fn autosquash_order_moves_a_fixup_row_after_its_target_and_relabels_it() {
1114 let mut rows = vec![
1115 (oid(1), "base".to_string(), RebaseAction::Pick),
1116 (oid(2), "feature work".to_string(), RebaseAction::Pick),
1117 (
1118 oid(3),
1119 "fixup! feature work".to_string(),
1120 RebaseAction::Pick,
1121 ),
1122 ];
1123 autosquash_order(&mut rows);
1124 assert_eq!(
1125 rows,
1126 vec![
1127 (oid(1), "base".to_string(), RebaseAction::Pick),
1128 (oid(2), "feature work".to_string(), RebaseAction::Pick),
1129 (
1130 oid(3),
1131 "fixup! feature work".to_string(),
1132 RebaseAction::Fixup
1133 ),
1134 ]
1135 );
1136 }
1137
1138 #[test]
1139 fn autosquash_order_leaves_an_unmatched_squash_row_in_place() {
1140 let mut rows = vec![
1141 (
1142 oid(1),
1143 "squash! nothing matches".to_string(),
1144 RebaseAction::Pick,
1145 ),
1146 (oid(2), "unrelated".to_string(), RebaseAction::Pick),
1147 ];
1148 autosquash_order(&mut rows);
1149 assert_eq!(
1150 rows,
1151 vec![
1152 (oid(2), "unrelated".to_string(), RebaseAction::Pick),
1153 (
1154 oid(1),
1155 "squash! nothing matches".to_string(),
1156 RebaseAction::Pick
1157 ),
1158 ]
1159 );
1160 }
1161
1162 #[test]
1163 fn a_reword_message_is_normalized_the_way_git_commit_leaves_it() {
1164 assert_eq!(
1165 normalize_reword_message(" \r\n\nsubject\r\n\r\n body \r\n\n").as_deref(),
1166 Some("subject\n\n body\n")
1167 );
1168 assert_eq!(
1169 normalize_reword_message("one line").as_deref(),
1170 Some("one line\n")
1171 );
1172 assert_eq!(normalize_reword_message(" \r\n\t\n "), None);
1173 assert_eq!(normalize_reword_message(""), None);
1174 }
1175}
1176
1177/// The namespace `GitBackend::fetch_refspec` may write into: refs that
1178/// are neither branches, tags nor remote-tracking refs, so a fetch there
1179/// never shows up in the user's ref lists and cannot move anything they
1180/// work on.
1181pub const FETCH_REFSPEC_NAMESPACE: &str = "refs/gitpoulpi/";
1182
1183/// Validates a `fetch_refspec` spec (`[+]refs/<src>:refs/gitpoulpi/<dst>`)
1184/// and returns `(source, destination)`; `None` for anything else. Shared
1185/// by both backends so they refuse exactly the same specs: one ref per
1186/// spec, no wildcard, no option-looking or whitespace-carrying text, a
1187/// full source ref, and a destination strictly inside
1188/// [`FETCH_REFSPEC_NAMESPACE`].
1189pub fn parse_fetch_refspec(spec: &str) -> Option<(&str, &str)> {
1190 let spec = spec.strip_prefix('+').unwrap_or(spec);
1191 let (src, dst) = spec.split_once(':')?;
1192 let clean = |r: &str| {
1193 !r.is_empty()
1194 && !r.contains("..")
1195 && !r.contains("//")
1196 && !r.ends_with('/')
1197 && !r.ends_with(".lock")
1198 && !r.contains("@{")
1199 && !r
1200 .chars()
1201 .any(|c| c.is_control() || c.is_whitespace() || "~^:?*[\\".contains(c))
1202 };
1203 (src.starts_with("refs/")
1204 && clean(src)
1205 && dst.starts_with(FETCH_REFSPEC_NAMESPACE)
1206 && dst.len() > FETCH_REFSPEC_NAMESPACE.len()
1207 && clean(dst))
1208 .then_some((src, dst))
1209}
1210
1211#[cfg(test)]
1212mod fetch_refspec_tests {
1213 use super::parse_fetch_refspec;
1214
1215 #[test]
1216 fn only_namespaced_single_ref_specs_pass() {
1217 assert_eq!(
1218 parse_fetch_refspec("+refs/pull/7/head:refs/gitpoulpi/pr/7"),
1219 Some(("refs/pull/7/head", "refs/gitpoulpi/pr/7"))
1220 );
1221 for bad in [
1222 "refs/pull/7/head:refs/heads/x",
1223 "refs/pull/*/head:refs/gitpoulpi/pr/*",
1224 "refs/pull/7/head:refs/gitpoulpi/",
1225 "refs/pull/7/head",
1226 "--x:refs/gitpoulpi/a",
1227 "refs/a b:refs/gitpoulpi/a",
1228 ] {
1229 assert!(parse_fetch_refspec(bad).is_none(), "{bad}");
1230 }
1231 }
1232}