use std::path::PathBuf;
use serde::{Deserialize, Serialize};
use super::{Oid, RefFilter};
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct LogOptions {
pub limit: Option<u32>,
#[serde(default)]
pub skip: u32,
pub start_ref: Option<String>,
pub all_refs: bool,
pub paths: Vec<PathBuf>,
#[serde(default)]
pub use_mailmap: bool,
#[serde(default, skip_serializing_if = "RefFilter::is_empty")]
pub hidden: RefFilter,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct CommitOptions {
pub amend: bool,
pub sign: bool,
#[serde(default)]
pub no_verify: bool,
#[serde(default)]
pub author: Option<CommitAuthor>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CommitAuthor {
pub name: String,
pub email: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum CheckoutTarget {
Branch(String),
Commit(Oid),
File {
path: String,
source: Oid,
},
Files {
paths: Vec<String>,
source: Oid,
},
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MergeFastForward {
#[default]
Never,
Allowed,
Only,
}
impl MergeFastForward {
pub const ALL: &'static [MergeFastForward] = &[Self::Never, Self::Allowed, Self::Only];
pub fn as_str(self) -> &'static str {
match self {
Self::Never => "never",
Self::Allowed => "allowed",
Self::Only => "only",
}
}
pub fn parse(text: &str) -> Option<Self> {
Self::ALL
.iter()
.copied()
.find(|m| m.as_str() == text.trim())
}
pub fn resolve(repo: Option<&str>, global: Self) -> Self {
repo.and_then(Self::parse).unwrap_or(global)
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct MergeOptions {
pub ff: Option<MergeFastForward>,
pub fast_forward_only: bool,
pub no_commit: bool,
pub no_ff: bool,
pub squash: bool,
pub message: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum MergeOutcome {
FastForwarded(Oid),
Merged(Oid),
UpToDate,
Conflicted(Vec<String>),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum FastForwardOutcome {
FastForwarded { from: Oid, to: Oid },
UpToDate,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum WorktreeStart {
Branch(String),
Commit(Oid),
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct WorktreeAddOptions {
pub start: WorktreeStart,
pub new_branch: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct WorktreeChange {
pub path: String,
pub untracked: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct WorktreeCommit {
pub message: String,
pub branch: Option<String>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct WorktreeRemoveOptions {
pub force: bool,
pub commit: Option<WorktreeCommit>,
pub stash: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct WorktreeRemoved {
pub path: std::path::PathBuf,
pub commit: Option<Oid>,
pub stashed: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum PatchSource {
Commits(Vec<Oid>),
Range { base: Oid, tip: Oid },
WorkingTree { paths: Vec<String> },
CommitPaths { commit: Oid, paths: Vec<String> },
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PatchCreated {
pub path: PathBuf,
pub commits: usize,
pub bytes: u64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ApplyRefusal {
MergeCommit,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PatchApplied {
pub files: Vec<String>,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct RebaseOptions {
pub autosquash: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RebaseStep {
pub commit: Oid,
pub action: RebaseAction,
#[serde(default)]
pub message: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(try_from = "String")]
pub enum RebaseAction {
Pick,
Squash,
Fixup,
Edit,
Drop,
Reword,
}
impl RebaseAction {
pub fn parse(text: &str) -> Option<Self> {
Some(match text.to_ascii_lowercase().as_str() {
"pick" | "p" => Self::Pick,
"reword" | "r" => Self::Reword,
"edit" | "e" => Self::Edit,
"squash" | "s" => Self::Squash,
"fixup" | "f" => Self::Fixup,
"drop" | "d" => Self::Drop,
_ => return None,
})
}
}
impl TryFrom<String> for RebaseAction {
type Error = String;
fn try_from(text: String) -> Result<Self, String> {
Self::parse(&text).ok_or_else(|| {
format!(
"unknown rebase action {text:?}, expected one of pick, reword, edit, squash, \
fixup, drop (or p, r, e, s, f, d)"
)
})
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct InteractiveRebase {
pub upstream: Option<Oid>,
pub onto: Option<Oid>,
pub steps: Vec<RebaseStep>,
pub autosquash: bool,
#[serde(default)]
pub cherry_pick: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RebasePlanDraft {
pub upstream: Option<Oid>,
pub commits: Vec<PlanCommit>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PlanCommit {
pub id: Oid,
pub summary: String,
pub message: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RebaseState {
pub head_name: Option<String>,
pub onto: Oid,
pub stopped_at: Option<Oid>,
pub step: usize,
pub total: usize,
pub conflicted: bool,
pub interactive: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum RebaseOutcome {
Completed,
Conflicted {
paused_at: Oid,
remaining: Vec<Oid>,
},
Stopped {
at: Oid,
remaining: Vec<Oid>,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RebaseRefusal {
OperationInProgress,
UncommittedChanges,
NotOnCurrentBranch,
MergeInRange,
PlanMismatch,
SquashWithoutPredecessor,
EmptyRewordMessage,
NoRebaseInProgress,
}
pub fn validate_plan(
range: &[Oid],
steps: &[RebaseStep],
) -> std::result::Result<(), RebaseRefusal> {
if steps.len() != range.len() {
return Err(RebaseRefusal::PlanMismatch);
}
let mut wanted: Vec<Oid> = range.to_vec();
wanted.sort_by_key(|o| o.to_hex());
let mut got: Vec<Oid> = steps.iter().map(|s| s.commit).collect();
got.sort_by_key(|o| o.to_hex());
if wanted != got {
return Err(RebaseRefusal::PlanMismatch);
}
if let Some(first) = steps.first() {
if matches!(first.action, RebaseAction::Squash | RebaseAction::Fixup) {
return Err(RebaseRefusal::SquashWithoutPredecessor);
}
}
for step in steps {
if step.action == RebaseAction::Reword
&& normalize_reword_message(step.message.as_deref().unwrap_or_default()).is_none()
{
return Err(RebaseRefusal::EmptyRewordMessage);
}
}
Ok(())
}
pub fn autosquash_order(rows: &mut Vec<(Oid, String, RebaseAction)>) {
fn autosquash_kind(summary: &str) -> Option<(RebaseAction, &str)> {
if let Some(rest) = summary.strip_prefix("squash! ") {
Some((RebaseAction::Squash, rest))
} else if let Some(rest) = summary.strip_prefix("fixup! ") {
Some((RebaseAction::Fixup, rest))
} else {
None
}
}
let original = rows.clone();
let mut out: Vec<(Oid, String, RebaseAction)> = Vec::with_capacity(original.len());
let mut consumed = vec![false; original.len()];
for (i, (_, summary, _)) in original.iter().enumerate() {
if consumed[i] {
continue;
}
if autosquash_kind(summary).is_some() {
continue;
}
out.push(original[i].clone());
consumed[i] = true;
for (j, (_, other_summary, _)) in original.iter().enumerate() {
if consumed[j] {
continue;
}
if let Some((action, target)) = autosquash_kind(other_summary) {
if summary.starts_with(target) {
out.push((original[j].0, original[j].1.clone(), action));
consumed[j] = true;
}
}
}
}
for (i, row) in original.into_iter().enumerate() {
if !consumed[i] {
out.push(row);
}
}
*rows = out;
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct CherryPickOptions {
pub no_commit: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum CherryPickOutcome {
Completed(Vec<Oid>),
Conflicted { paused_at: Oid, remaining: Vec<Oid> },
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum RevertOutcome {
Completed(Oid),
Conflicted,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RewordOutcome {
pub reworded: Oid,
pub previous_head: Oid,
pub new_head: Oid,
pub replayed: usize,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RewordRefusal {
NotOnCurrentBranch,
OperationInProgress,
EmptyMessage,
InvalidIdentity,
InvalidDate,
}
pub fn normalize_reword_message(message: &str) -> Option<String> {
let unix = message.replace("\r\n", "\n");
let mut rest = unix.as_str();
while let Some((line, after)) = rest.split_once('\n') {
if !line.trim().is_empty() {
break;
}
rest = after;
}
let trimmed = rest.trim_end();
if trimmed.is_empty() {
None
} else {
Some(format!("{trimmed}\n"))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ResetMode {
Soft,
Mixed,
Hard,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct FetchOptions {
pub prune: bool,
pub prune_tags: bool,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct FetchOutcome {
pub updated_refs: Vec<String>,
#[serde(default)]
pub pruned_tags: Vec<String>,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PullMode {
#[default]
Merge,
FastForwardOnly,
Rebase,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct PullOptions {
pub mode: PullMode,
pub remote: Option<String>,
pub remote_branch: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum PullOutcome {
UpToDate,
FastForwarded(Oid),
Merged(Oid),
Conflicted,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct PushOptions {
#[serde(alias = "force")]
pub force_with_lease: bool,
pub set_upstream: bool,
pub branch: Option<String>,
pub lease: Option<PushLease>,
pub remote_branch: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum PushLease {
Tracking,
Expect(Oid),
Absent,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PushRejectReason {
NonFastForward,
StaleLease,
ProtectedByHost,
RemoteRefused,
#[serde(other)]
Unknown,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PushRejection {
pub remote: String,
pub branch: String,
pub reason: PushRejectReason,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub detail: Option<Box<crate::failure::ErrorDetail>>,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct PushOutcome {
pub pushed_refs: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum TagSelection {
Named(Vec<String>),
AllUnpushed,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct CloneOptions {
pub shallow_depth: Option<u32>,
pub recurse_submodules: bool,
#[serde(default)]
pub branch: Option<String>,
#[serde(default)]
pub remote_name: Option<String>,
#[serde(default)]
pub lfs: super::LfsCloneMode,
#[serde(default)]
pub sparse: Option<Vec<String>>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct SparseState {
pub enabled: bool,
pub cone: bool,
pub dirs: Vec<String>,
}
pub fn normalize_sparse_dirs(dirs: &[String]) -> crate::Result<Vec<String>> {
let mut out: Vec<String> = Vec::new();
for raw in dirs {
let mut d = raw.trim().replace('\\', "/");
while let Some(rest) = d.strip_prefix("./") {
d = rest.to_string();
}
let d = d.trim_matches('/').to_string();
if d.is_empty() || d == "." {
return Err(crate::Error::Backend(format!(
"`{raw}` is not a directory of the repository"
)));
}
if raw.trim().starts_with('/')
|| d.starts_with('-')
|| d.starts_with('!')
|| d.starts_with('#')
|| d.split('/').any(|c| c == ".." || c == "." || c.is_empty())
|| d.contains(['*', '?', '[', ':'])
|| d.chars().any(char::is_control)
{
return Err(crate::Error::Backend(format!(
"`{raw}` is not a valid sparse-checkout directory (use a path relative to the repository root, without patterns)"
)));
}
if !out.contains(&d) {
out.push(d);
}
}
if out.is_empty() {
return Err(crate::Error::Backend(
"a sparse checkout needs at least one directory".to_string(),
));
}
Ok(out)
}
#[cfg(test)]
mod sparse_tests {
use super::normalize_sparse_dirs;
fn n(v: &[&str]) -> crate::Result<Vec<String>> {
normalize_sparse_dirs(&v.iter().map(|s| s.to_string()).collect::<Vec<_>>())
}
#[test]
fn cleans_slashes_dots_and_duplicates() {
assert_eq!(
n(&["./src/", "docs\\guide", " src "]).unwrap(),
["src", "docs/guide"]
);
}
#[test]
fn refuses_what_is_not_a_plain_relative_dir() {
for bad in ["", "/", "/etc", "..", "a/../b", "-x", "!x", "a/*", "a:b"] {
assert!(n(&[bad]).is_err(), "{bad:?} must be refused");
}
assert!(n(&[]).is_err());
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct InitOptions {
#[serde(default)]
pub bare: bool,
#[serde(default)]
pub initial_branch: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ClonePhase {
Connecting,
Counting,
Compressing,
Receiving,
Resolving,
CheckingOut,
LfsObjects,
Done,
}
impl ClonePhase {
pub fn label(self) -> &'static str {
match self {
Self::Connecting => "Connecting",
Self::Counting => "Counting objects",
Self::Compressing => "Compressing objects",
Self::Receiving => "Receiving objects",
Self::Resolving => "Resolving deltas",
Self::CheckingOut => "Checking out files",
Self::LfsObjects => "Downloading LFS objects",
Self::Done => "Done",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct CloneProgress {
pub phase: ClonePhase,
pub percent: u8,
pub current: Option<u64>,
pub total: Option<u64>,
}
impl CloneProgress {
pub fn new(phase: ClonePhase, percent: u8) -> Self {
Self {
phase,
percent: percent.min(100),
current: None,
total: None,
}
}
pub fn with_counts(mut self, current: u64, total: u64) -> Self {
self.current = Some(current);
self.total = Some(total);
self
}
pub fn done() -> Self {
Self::new(ClonePhase::Done, 100)
}
}
pub type CloneProgressSink<'a> = &'a (dyn Fn(CloneProgress) + Send + Sync);
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_merge_fast_forward_policy_defaults_to_never_and_the_repo_wins() {
use MergeFastForward as P;
assert_eq!(P::default(), P::Never, "the owner's expectation");
assert_eq!(P::resolve(Some("allowed"), P::Never), P::Allowed);
assert_eq!(P::resolve(Some("never"), P::Allowed), P::Never);
assert_eq!(P::resolve(Some("only"), P::Allowed), P::Only);
assert_eq!(P::resolve(None, P::Only), P::Only);
assert_eq!(P::resolve(Some("sometimes"), P::Allowed), P::Allowed);
assert_eq!(P::resolve(Some(""), P::Never), P::Never);
for p in P::ALL {
assert_eq!(P::parse(p.as_str()), Some(*p));
assert_eq!(
serde_json::to_string(p).unwrap(),
format!("\"{}\"", p.as_str()),
"the wire spelling is the config spelling"
);
}
}
fn oid(byte: u8) -> Oid {
Oid([byte; 20])
}
#[test]
fn validate_plan_accepts_any_permutation_of_the_range() {
let range = [oid(1), oid(2), oid(3)];
let steps = vec![
RebaseStep {
commit: oid(3),
action: RebaseAction::Pick,
message: None,
},
RebaseStep {
commit: oid(1),
action: RebaseAction::Pick,
message: None,
},
RebaseStep {
commit: oid(2),
action: RebaseAction::Squash,
message: None,
},
];
assert_eq!(validate_plan(&range, &steps), Ok(()));
}
#[test]
fn validate_plan_rejects_a_dropped_or_duplicated_commit() {
let range = [oid(1), oid(2)];
let missing = vec![
RebaseStep {
commit: oid(1),
action: RebaseAction::Pick,
message: None,
},
RebaseStep {
commit: oid(1),
action: RebaseAction::Pick,
message: None,
},
];
assert_eq!(
validate_plan(&range, &missing),
Err(RebaseRefusal::PlanMismatch)
);
}
#[test]
fn validate_plan_refuses_squash_or_fixup_as_the_oldest_step() {
let range = [oid(1), oid(2)];
let steps = vec![
RebaseStep {
commit: oid(1),
action: RebaseAction::Fixup,
message: None,
},
RebaseStep {
commit: oid(2),
action: RebaseAction::Pick,
message: None,
},
];
assert_eq!(
validate_plan(&range, &steps),
Err(RebaseRefusal::SquashWithoutPredecessor)
);
}
#[test]
fn validate_plan_refuses_an_empty_reword_message() {
let range = [oid(1)];
let steps = vec![RebaseStep {
commit: oid(1),
action: RebaseAction::Reword,
message: Some(" \r\n ".into()),
}];
assert_eq!(
validate_plan(&range, &steps),
Err(RebaseRefusal::EmptyRewordMessage)
);
}
#[test]
fn autosquash_order_moves_a_fixup_row_after_its_target_and_relabels_it() {
let mut rows = vec![
(oid(1), "base".to_string(), RebaseAction::Pick),
(oid(2), "feature work".to_string(), RebaseAction::Pick),
(
oid(3),
"fixup! feature work".to_string(),
RebaseAction::Pick,
),
];
autosquash_order(&mut rows);
assert_eq!(
rows,
vec![
(oid(1), "base".to_string(), RebaseAction::Pick),
(oid(2), "feature work".to_string(), RebaseAction::Pick),
(
oid(3),
"fixup! feature work".to_string(),
RebaseAction::Fixup
),
]
);
}
#[test]
fn autosquash_order_leaves_an_unmatched_squash_row_in_place() {
let mut rows = vec![
(
oid(1),
"squash! nothing matches".to_string(),
RebaseAction::Pick,
),
(oid(2), "unrelated".to_string(), RebaseAction::Pick),
];
autosquash_order(&mut rows);
assert_eq!(
rows,
vec![
(oid(2), "unrelated".to_string(), RebaseAction::Pick),
(
oid(1),
"squash! nothing matches".to_string(),
RebaseAction::Pick
),
]
);
}
#[test]
fn a_reword_message_is_normalized_the_way_git_commit_leaves_it() {
assert_eq!(
normalize_reword_message(" \r\n\nsubject\r\n\r\n body \r\n\n").as_deref(),
Some("subject\n\n body\n")
);
assert_eq!(
normalize_reword_message("one line").as_deref(),
Some("one line\n")
);
assert_eq!(normalize_reword_message(" \r\n\t\n "), None);
assert_eq!(normalize_reword_message(""), None);
}
}
pub const FETCH_REFSPEC_NAMESPACE: &str = "refs/gitpoulpi/";
pub fn parse_fetch_refspec(spec: &str) -> Option<(&str, &str)> {
let spec = spec.strip_prefix('+').unwrap_or(spec);
let (src, dst) = spec.split_once(':')?;
let clean = |r: &str| {
!r.is_empty()
&& !r.contains("..")
&& !r.contains("//")
&& !r.ends_with('/')
&& !r.ends_with(".lock")
&& !r.contains("@{")
&& !r
.chars()
.any(|c| c.is_control() || c.is_whitespace() || "~^:?*[\\".contains(c))
};
(src.starts_with("refs/")
&& clean(src)
&& dst.starts_with(FETCH_REFSPEC_NAMESPACE)
&& dst.len() > FETCH_REFSPEC_NAMESPACE.len()
&& clean(dst))
.then_some((src, dst))
}
#[cfg(test)]
mod fetch_refspec_tests {
use super::parse_fetch_refspec;
#[test]
fn only_namespaced_single_ref_specs_pass() {
assert_eq!(
parse_fetch_refspec("+refs/pull/7/head:refs/gitpoulpi/pr/7"),
Some(("refs/pull/7/head", "refs/gitpoulpi/pr/7"))
);
for bad in [
"refs/pull/7/head:refs/heads/x",
"refs/pull/*/head:refs/gitpoulpi/pr/*",
"refs/pull/7/head:refs/gitpoulpi/",
"refs/pull/7/head",
"--x:refs/gitpoulpi/a",
"refs/a b:refs/gitpoulpi/a",
] {
assert!(parse_fetch_refspec(bad).is_none(), "{bad}");
}
}
}