use serde::{Deserialize, Serialize};
use std::fmt;
use crate::script::{shell_quote, wrap_step};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BlockReason {
UpToDate,
DirtyTree(Vec<String>),
OperationInProgress(String),
WrongBranch {
expected: String,
actual: String,
},
FetchFailed(String),
FetchMismatch,
RerunTargetMismatch {
head: String,
target: String,
},
NotFastForward,
InvalidStep {
step: usize,
message: String,
},
CommandFailed {
code: i32,
output: String,
},
}
impl fmt::Display for BlockReason {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::UpToDate => write!(f, "already up to date"),
Self::DirtyTree(files) => write!(f, "uncommitted changes: {}", files.join(", ")),
Self::OperationInProgress(op) => write!(f, "git operation in progress ({op})"),
Self::WrongBranch { expected, actual } if actual.is_empty() => {
write!(f, "HEAD is detached, expected branch `{expected}`")
}
Self::WrongBranch { expected, actual } => {
write!(f, "on branch `{actual}`, expected `{expected}`")
}
Self::FetchFailed(output) => {
write!(f, "the server couldn't fetch from origin: {output}")
}
Self::FetchMismatch => write!(f, "fetched commit does not match origin"),
Self::RerunTargetMismatch { head, target } => write!(
f,
"cannot rerun: checkout is {head}, but origin points to {target}"
),
Self::NotFastForward => write!(f, "origin is not a fast-forward of the server's HEAD"),
Self::InvalidStep { step, message } => write!(f, "step {step} is invalid: {message}"),
Self::CommandFailed { code, output } => {
write!(f, "preflight exited with {code}: {output}")
}
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum AbortReason {
LockLost,
HeadMoved {
expected: String,
actual: String,
},
DirtyTree(Vec<String>),
OperationInProgress(String),
WrongBranch {
expected: String,
actual: String,
},
MaintenanceDownFailed(i32),
ConnectFailed(String),
CheckFailed(String),
JournalFailed(String),
Cancelled,
}
impl fmt::Display for AbortReason {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::LockLost => write!(f, "the deploy lock was taken over"),
Self::HeadMoved { expected, actual } => {
write!(f, "HEAD moved from {expected} to {actual}")
}
Self::DirtyTree(files) => write!(f, "uncommitted changes: {}", files.join(", ")),
Self::OperationInProgress(op) => write!(f, "git operation in progress ({op})"),
Self::WrongBranch { expected, actual } if actual.is_empty() => {
write!(f, "HEAD is detached, expected branch `{expected}`")
}
Self::WrongBranch { expected, actual } => {
write!(f, "on branch `{actual}`, expected `{expected}`")
}
Self::MaintenanceDownFailed(code) => {
write!(f, "`php artisan down` exited with {code}")
}
Self::ConnectFailed(reason) => write!(f, "could not reach the server: {reason}"),
Self::CheckFailed(reason) => write!(f, "could not check the server: {reason}"),
Self::JournalFailed(reason) => write!(f, "could not save the receipt: {reason}"),
Self::Cancelled => write!(f, "the run was cancelled"),
}
}
}
#[derive(Debug, Default, PartialEq, Eq)]
pub(crate) struct State {
pub head: String,
pub branch: String,
pub operation: Option<String>,
pub dirty: Vec<String>,
}
#[derive(Debug, Default, PartialEq, Eq)]
pub(crate) struct Preflight {
pub state: State,
pub fetch_failed: Option<String>,
pub target: String,
pub fetch_head: String,
pub ancestor: bool,
pub commits: Vec<String>,
pub invalid_step: Option<(usize, String)>,
}
pub(crate) fn state_script(path: &str) -> String {
format!(
r#"cd {path} || exit $?
g=$(git rev-parse --absolute-git-dir) || exit $?
echo "@head $(git rev-parse HEAD)"
echo "@branch $(git symbolic-ref --quiet --short HEAD)"
for op in MERGE_HEAD rebase-merge rebase-apply CHERRY_PICK_HEAD REVERT_HEAD; do
[ -e "$g/$op" ] && echo "@operation $op"
done
s=$(git status --porcelain) || exit $?
[ -z "$s" ] || printf '%s\n' "$s" | sed 's/^/@dirty /'
"#,
path = shell_quote(path),
)
}
pub(crate) fn preflight_script(path: &str, branch: &str, steps: &[String]) -> String {
preflight_script_with_token(path, branch, steps, None)
}
pub(crate) fn preflight_script_with_token(
path: &str,
branch: &str,
steps: &[String],
auth: Option<(
&crate::github_auth::GitHubRepository,
&crate::github_auth::GitHubToken,
)>,
) -> String {
let mut s = state_script(path);
let refspec = format!("+refs/heads/{branch}:refs/remotes/origin/{branch}");
s.push_str("export GIT_TERMINAL_PROMPT=0 SSH_ASKPASS_REQUIRE=never\n");
if let Some((repository, token)) = auth {
s.insert_str(0, "set +x +v\n");
s.push_str(&token.fetch_script(repository, &refspec));
} else {
s.push_str(&format!(
r#"if ! out=$(git fetch origin {refspec} 2>&1 </dev/null); then
echo "@fetch_failed"
printf '%s\n' "$out" | sed 's/^/@message /'
exit 0
fi
"#,
refspec = shell_quote(&refspec),
));
}
s.push_str(&format!(
r#"
h=$(git rev-parse HEAD)
t=$(git rev-parse {remote})
echo "@target $t"
echo "@fetch_head $(git rev-parse FETCH_HEAD)"
git merge-base --is-ancestor "$h" "$t" && echo "@ancestor"
git log --oneline "$h..$t" | sed 's/^/@commit /'
"#,
remote = shell_quote(&format!("origin/{branch}")),
));
for (n, step) in (1..).zip(steps) {
s.push_str(&format!(
"if ! out=$(printf '%s' {} | bash -n 2>&1); then\n \
echo \"@invalid {n}\"\n \
printf '%s\\n' \"$out\" | sed 's/^/@message /'\n\
fi\n",
shell_quote(&wrap_step(path, step)),
));
}
s
}
fn facts(lines: &[String]) -> impl Iterator<Item = (&str, &str)> {
lines.iter().filter_map(|l| {
let l = l.strip_prefix('@')?;
Some(l.split_once(' ').unwrap_or((l, "")))
})
}
pub(crate) fn parse_state(lines: &[String]) -> State {
let mut state = State::default();
for (key, value) in facts(lines) {
match key {
"head" => state.head = value.to_string(),
"branch" => state.branch = value.to_string(),
"operation" if state.operation.is_none() => state.operation = Some(value.into()),
"dirty" => state.dirty.push(value.to_string()),
_ => {}
}
}
state
}
pub(crate) fn parse_preflight(lines: &[String]) -> Preflight {
let mut p = Preflight {
state: parse_state(lines),
..Preflight::default()
};
let mut messages = Vec::new();
let mut collecting = false;
for (key, value) in facts(lines) {
match key {
"fetch_failed" => {
p.fetch_failed = Some(String::new());
collecting = true;
}
"target" => p.target = value.to_string(),
"fetch_head" => p.fetch_head = value.to_string(),
"ancestor" => p.ancestor = true,
"commit" => p.commits.push(value.to_string()),
"invalid" => {
collecting = p.invalid_step.is_none();
if collecting {
p.invalid_step = value.parse().ok().map(|n| (n, String::new()));
}
}
"message" if collecting => messages.push(value),
_ => {}
}
}
let message = messages.join("\n");
if let Some(output) = &mut p.fetch_failed {
*output = message;
} else if let Some((_, text)) = &mut p.invalid_step {
*text = message;
}
p
}
pub(crate) fn block_reason(
p: &Preflight,
branch: &str,
allow_up_to_date: bool,
) -> Option<BlockReason> {
let s = &p.state;
if let Some(op) = &s.operation {
return Some(BlockReason::OperationInProgress(op.clone()));
}
if !s.dirty.is_empty() {
return Some(BlockReason::DirtyTree(s.dirty.clone()));
}
if s.branch != branch {
return Some(BlockReason::WrongBranch {
expected: branch.into(),
actual: s.branch.clone(),
});
}
if let Some(output) = &p.fetch_failed {
return Some(BlockReason::FetchFailed(output.clone()));
}
if p.target != p.fetch_head {
return Some(BlockReason::FetchMismatch);
}
if p.target == s.head && !allow_up_to_date {
return Some(BlockReason::UpToDate);
}
if !p.ancestor {
return Some(BlockReason::NotFastForward);
}
if allow_up_to_date && p.target != s.head {
return Some(BlockReason::RerunTargetMismatch {
head: s.head.clone(),
target: p.target.clone(),
});
}
p.invalid_step
.as_ref()
.map(|(step, message)| BlockReason::InvalidStep {
step: *step,
message: message.clone(),
})
}
pub(crate) fn recheck(state: &State, from_sha: &str, branch: &str) -> Option<AbortReason> {
if let Some(op) = &state.operation {
return Some(AbortReason::OperationInProgress(op.clone()));
}
if state.head != from_sha {
return Some(AbortReason::HeadMoved {
expected: from_sha.into(),
actual: state.head.clone(),
});
}
if state.branch != branch {
return Some(AbortReason::WrongBranch {
expected: branch.into(),
actual: state.branch.clone(),
});
}
if !state.dirty.is_empty() {
return Some(AbortReason::DirtyTree(state.dirty.clone()));
}
None
}
#[cfg(test)]
mod tests {
use super::*;
fn lines(v: &[&str]) -> Vec<String> {
v.iter().map(|s| s.to_string()).collect()
}
fn clean() -> Preflight {
Preflight {
state: State {
head: "a".into(),
branch: "main".into(),
..State::default()
},
target: "b".into(),
fetch_head: "b".into(),
ancestor: true,
..Preflight::default()
}
}
#[test]
fn preflight_output_is_parsed() {
let p = parse_preflight(&lines(&[
"motd from .profile",
"@head a",
"@branch main",
"@dirty M file",
"@dirty ?? new",
"@target b",
"@fetch_head b",
"@ancestor",
"@commit b2 Second",
"@invalid 1",
"@message bash: line 7: unexpected EOF",
"@message bash: syntax error",
]));
assert_eq!(p.state.head, "a");
assert_eq!(p.state.dirty, [" M file", "?? new"]);
assert!(p.ancestor);
assert_eq!(p.commits, ["b2 Second"]);
assert_eq!(
p.invalid_step,
Some((1, "bash: line 7: unexpected EOF\nbash: syntax error".into()))
);
}
#[test]
fn fetch_failure_keeps_git_output() {
let p = parse_preflight(&lines(&[
"@head a",
"@branch main",
"@fetch_failed",
"@message Permission denied (publickey).",
]));
assert_eq!(
p.fetch_failed.as_deref(),
Some("Permission denied (publickey).")
);
}
#[test]
fn block_reasons_in_order() {
assert_eq!(block_reason(&clean(), "main", false), None);
let mut p = clean();
p.state.operation = Some("MERGE_HEAD".into());
p.state.dirty = vec![" M f".into()];
assert_eq!(
block_reason(&p, "main", false),
Some(BlockReason::OperationInProgress("MERGE_HEAD".into()))
);
p.state.operation = None;
assert!(matches!(
block_reason(&p, "main", false),
Some(BlockReason::DirtyTree(_))
));
let mut p = clean();
assert_eq!(
block_reason(&p, "release", false),
Some(BlockReason::WrongBranch {
expected: "release".into(),
actual: "main".into()
})
);
p.fetch_head = "c".into();
assert_eq!(
block_reason(&p, "main", false),
Some(BlockReason::FetchMismatch)
);
let mut p = clean();
p.target = "a".into();
p.fetch_head = "a".into();
assert_eq!(block_reason(&p, "main", false), Some(BlockReason::UpToDate));
assert_eq!(block_reason(&p, "main", true), None);
let mut p = clean();
p.ancestor = false;
assert_eq!(
block_reason(&p, "main", false),
Some(BlockReason::NotFastForward)
);
let mut p = clean();
p.invalid_step = Some((2, "oops".into()));
assert_eq!(
block_reason(&p, "main", false),
Some(BlockReason::InvalidStep {
step: 2,
message: "oops".into()
})
);
}
#[test]
fn rerun_requires_the_fetched_target_to_be_checked_out() {
let mut p = clean();
p.state.head = "a".into();
p.target = "b".into();
p.fetch_head = "b".into();
assert_eq!(
block_reason(&p, "main", true),
Some(BlockReason::RerunTargetMismatch {
head: "a".into(),
target: "b".into(),
})
);
}
#[test]
fn recheck_catches_changes_since_preview() {
let state = |head: &str, dirty: &[&str]| State {
head: head.into(),
branch: "main".into(),
operation: None,
dirty: dirty.iter().map(|s| s.to_string()).collect(),
};
assert_eq!(recheck(&state("a", &[]), "a", "main"), None);
assert!(matches!(
recheck(&state("b", &[]), "a", "main"),
Some(AbortReason::HeadMoved { .. })
));
assert_eq!(
recheck(&state("a", &[]), "a", "release"),
Some(AbortReason::WrongBranch {
expected: "release".into(),
actual: "main".into(),
})
);
assert!(matches!(
recheck(&state("a", &[" M f"]), "a", "main"),
Some(AbortReason::DirtyTree(_))
));
}
#[test]
fn only_the_first_invalid_step_and_its_messages_are_kept() {
let p = parse_preflight(&lines(&[
"@head a",
"@invalid 1",
"@message e1",
"@invalid 2",
"@message e2",
]));
assert_eq!(p.invalid_step, Some((1, "e1".into())));
}
fn local_state(setup: &str) -> (Option<i32>, Vec<String>) {
let dir = std::env::temp_dir().join(format!(
"shipslip-state-{}-{}",
std::process::id(),
setup.len()
));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let status = std::process::Command::new("bash")
.arg("-c")
.arg(format!(
"git init -q && git -c user.email=t@t -c user.name=t commit -q --allow-empty -m init && {setup}"
))
.current_dir(&dir)
.status()
.unwrap();
assert!(status.success());
let output = std::process::Command::new("bash")
.arg("-c")
.arg(state_script(dir.to_str().unwrap()))
.output()
.unwrap();
let _ = std::fs::remove_dir_all(&dir);
let lines = String::from_utf8_lossy(&output.stdout)
.lines()
.map(String::from)
.collect();
(output.status.code(), lines)
}
#[test]
fn state_script_reports_dirty_files_and_fails_when_git_status_fails() {
let (code, lines) = local_state("echo x > new");
assert_eq!(code, Some(0));
assert_eq!(parse_state(&lines).dirty, ["?? new"]);
let (code, lines) = local_state("true");
assert_eq!(code, Some(0));
assert!(parse_state(&lines).dirty.is_empty());
let (code, _) = local_state("echo garbage > .git/index");
assert_ne!(code, Some(0));
}
#[test]
fn every_step_is_syntax_checked_as_generated() {
let steps = vec!["true".to_string(), "echo 'hi'".to_string()];
let s = preflight_script("/app", "main", &steps);
assert!(s.contains("echo \"@invalid 1\""));
assert!(s.contains("echo \"@invalid 2\""));
assert!(s.contains(&shell_quote(&wrap_step("/app", "echo 'hi'"))));
}
}