use crate::git::{self, Opts};
use crate::input;
use crate::model::{Config, Level};
use crate::policy::{self, Op};
use crate::repo_state::{self, Head, RepoState};
use crate::screen;
use crate::ui::{self, Choice, Key};
use anyhow::{anyhow, Result};
use std::sync::atomic::AtomicBool;
use std::time::Duration;
const FETCH_SECS: u64 = 180;
const PULL_SECS: u64 = 180;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PullChoice {
FastForward,
Rebase,
Merge,
}
impl PullChoice {
const ALL: [PullChoice; 3] = [
PullChoice::FastForward,
PullChoice::Rebase,
PullChoice::Merge,
];
fn label(self) -> &'static str {
match self {
PullChoice::FastForward => "Fast-forward only (safe)",
PullChoice::Rebase => "Rebase my commits on top",
PullChoice::Merge => "Merge (creates a merge commit)",
}
}
}
fn integrate_args(choice: PullChoice, fork_point: Option<&str>) -> Vec<String> {
let args: Vec<&str> = match (choice, fork_point) {
(PullChoice::FastForward, _) => vec!["merge", "--ff-only", "FETCH_HEAD"],
(PullChoice::Rebase, Some(fork)) => vec!["rebase", "--onto", "FETCH_HEAD", fork],
(PullChoice::Rebase, None) => vec!["rebase", "FETCH_HEAD"],
(PullChoice::Merge, _) => vec!["merge", "--no-edit", "FETCH_HEAD"],
};
args.into_iter().map(String::from).collect()
}
fn fetch_args(remote: &str, branch: &str) -> Vec<String> {
vec![
"fetch".into(),
remote.into(),
format!("refs/heads/{branch}"),
]
}
fn pull_command(
choice: PullChoice,
remote: &str,
branch: &str,
fork_point: Option<&str>,
) -> String {
format!(
"{} && git {}",
fetch_args(remote, branch).join(" "),
integrate_args(choice, fork_point).join(" ")
)
}
fn branch_problem(name: &str) -> Option<String> {
if name.is_empty() || name.starts_with('-') {
return Some(format!("'{name}' is not a usable branch name."));
}
let ok = git::git_raw(&["check-ref-format", "--branch", name], &Opts::default())
.is_ok_and(|out| out.ok());
(!ok).then(|| format!("'{name}' is not a valid branch name."))
}
fn names_problem(remote: &str, branch: &str) -> Option<String> {
remote_name_problem(remote)
.map(String::from)
.or_else(|| branch_problem(branch))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PullError {
Diverged,
NoUpstream,
Auth,
Conflict,
Other,
}
fn looks_like_auth(text: &str) -> bool {
[
"authentication failed",
"could not read username",
"could not read password",
"permission denied",
"terminal prompts disabled",
"invalid credentials",
"the requested url returned error: 403",
"the requested url returned error: 401",
]
.iter()
.any(|needle| text.contains(needle))
}
fn classify_pull_error(stderr: &str) -> PullError {
let text = stderr.to_ascii_lowercase();
if looks_like_auth(&text) {
PullError::Auth
} else if text.contains("conflict")
|| text.contains("automatic merge failed")
|| text.contains("could not apply")
{
PullError::Conflict
} else if text.contains("not possible to fast-forward")
|| text.contains("divergent branches")
|| text.contains("need to specify how to reconcile")
{
PullError::Diverged
} else if text.contains("no tracking information") || text.contains("no upstream") {
PullError::NoUpstream
} else {
PullError::Other
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PushError {
Rejected,
NoUpstream,
Auth,
Other,
}
fn classify_push_error(stderr: &str) -> PushError {
let text = stderr.to_ascii_lowercase();
if looks_like_auth(&text) {
PushError::Auth
} else if text.contains("no upstream branch") {
PushError::NoUpstream
} else if text.contains("[remote rejected]") {
PushError::Other
} else if text.contains("[rejected]")
|| text.contains("non-fast-forward")
|| text.contains("fetch first")
|| text.contains("stale info")
{
PushError::Rejected
} else {
PushError::Other
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum RemoteChoice {
Use(String),
Pick(Vec<String>),
None,
}
fn upstream_remote<'a>(upstream: &str, remotes: &'a [String]) -> Option<&'a str> {
remotes
.iter()
.filter(|remote| {
upstream
.strip_prefix(remote.as_str())
.is_some_and(|rest| rest.starts_with('/'))
})
.max_by_key(|remote| remote.len())
.map(String::as_str)
}
fn choose_remote(default: &str, remotes: &[String], upstream: Option<&str>) -> RemoteChoice {
if remotes.is_empty() {
return RemoteChoice::None;
}
if remotes.iter().any(|remote| remote == default) {
return RemoteChoice::Use(default.to_string());
}
if let Some(remote) = upstream.and_then(|up| upstream_remote(up, remotes)) {
return RemoteChoice::Use(remote.to_string());
}
if let [only] = remotes {
return RemoteChoice::Use(only.clone());
}
RemoteChoice::Pick(remotes.to_vec())
}
fn pull_branch(upstream: Option<&str>, remote: &str, local: &str) -> String {
upstream
.and_then(|up| up.strip_prefix(remote))
.and_then(|rest| rest.strip_prefix('/'))
.filter(|name| !name.is_empty())
.unwrap_or(local)
.to_string()
}
fn parse_remotes(text: &str) -> Vec<(String, String)> {
let mut found: Vec<(String, String)> = Vec::new();
for line in text.lines() {
let Some((name, rest)) = line.trim_end().split_once('\t') else {
continue;
};
let url = rest
.strip_suffix(" (fetch)")
.or_else(|| rest.strip_suffix(" (push)"));
let Some(url) = url else { continue };
if !found.iter().any(|(known, _)| known == name) {
found.push((name.to_string(), url.to_string()));
}
}
found
}
fn remote_name_problem(name: &str) -> Option<&'static str> {
if name.is_empty() {
Some("The name cannot be empty.")
} else if name.starts_with('-') {
Some("The name cannot start with '-'.")
} else if name.contains("..")
|| name
.chars()
.any(|c| c.is_whitespace() || c.is_control() || "~^:?*[\\".contains(c))
{
Some("The name has characters git does not allow (spaces, ~ ^ : ? * [ \\ or ..).")
} else {
None
}
}
fn remote_url_problem(url: &str) -> Option<&'static str> {
if url.trim().is_empty() {
Some("The URL cannot be empty.")
} else if url.starts_with('-') {
Some("The URL cannot start with '-'.")
} else {
None
}
}
fn login_of(cfg: &Config) -> Option<String> {
let label = cfg.active_account.as_deref()?;
let account = cfg.accounts.iter().find(|account| account.label == label)?;
Some(account.github_username.clone()).filter(|login| !login.is_empty())
}
fn branch_name(head: &Head) -> Result<&str, &'static str> {
match head {
Head::Branch { name, .. } => Ok(name),
Head::Unborn { .. } => Err("This branch has no commits yet. Make a commit first."),
Head::Detached { .. } => {
Err("HEAD is detached (not on a branch). Check out a branch first, for example in Branch mode.")
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Item {
Fetch,
Pull,
Push,
PushSetUpstream,
ForcePush,
Remotes,
}
impl Item {
fn row(self) -> &'static str {
match self {
Item::Fetch => "Fetch download news, change nothing",
Item::Pull => "Pull bring remote commits into this branch",
Item::Push => "Push send this branch to the remote",
Item::PushSetUpstream => "Push and set upstream first push of a new branch",
Item::ForcePush => "Force push with lease overwrite the remote branch (careful)",
Item::Remotes => "Remotes list, add, rename, remove",
}
}
fn key(self) -> Key {
let (key, label) = match self {
Item::Fetch => ('f', "fetch"),
Item::Pull => ('l', "pull"),
Item::Push => ('p', "push"),
Item::PushSetUpstream => ('u', "push+upstream"),
Item::ForcePush => ('x', "force push"),
Item::Remotes => ('m', "remotes"),
};
Key { key, label }
}
}
fn menu_items(level: Level, has_upstream: bool) -> Vec<Item> {
let mut items = vec![Item::Fetch, Item::Pull, Item::Push];
if !has_upstream {
items.push(Item::PushSetUpstream);
}
if level != Level::Beginner {
items.push(Item::ForcePush);
}
items.push(Item::Remotes);
items
}
#[derive(Debug)]
enum Net {
Done(String),
Failed(String),
Cancelled,
}
fn run_net(args: &[&str], secs: u64, cancel: &AtomicBool) -> Result<Net> {
let opts = Opts {
timeout: Some(Duration::from_secs(secs)),
cancel: Some(cancel),
..Opts::default()
};
let out = git::git_raw(args, &opts)?;
if out.cancelled {
return Ok(Net::Cancelled);
}
let mut text = out.stderr.trim().to_string();
let stdout = out.text();
if !stdout.is_empty() {
if !text.is_empty() {
text.push('\n');
}
text.push_str(&stdout);
}
if out.ok() {
Ok(Net::Done(text))
} else if text.is_empty() {
Ok(Net::Failed(format!(
"git did not finish (timed out after {secs}s or was stopped)"
)))
} else {
Ok(Net::Failed(text))
}
}
fn run_fetch(remote: Option<&str>, cancel: &AtomicBool) -> Result<Net> {
match remote {
Some(remote) => run_net(&["fetch", "--prune", remote], FETCH_SECS, cancel),
None => run_net(&["fetch", "--prune", "--all"], FETCH_SECS, cancel),
}
}
fn run_local(args: &[&str]) -> Result<Net> {
let out = git::git_raw(args, &Opts::default())?;
let mut text = out.stderr.trim().to_string();
let stdout = out.text();
if !stdout.is_empty() {
if !text.is_empty() {
text.push('\n');
}
text.push_str(&stdout);
}
Ok(if out.ok() {
Net::Done(text)
} else {
Net::Failed(text)
})
}
fn fork_point(remote: &str, branch: &str) -> Option<String> {
let tracking = format!("refs/remotes/{remote}/{branch}");
git::git_ok(
&["rev-parse", "--verify", "--quiet", &tracking],
&Opts::default(),
)
.ok()?;
git::git_ok(
&["merge-base", "--fork-point", &tracking, "HEAD"],
&Opts::default(),
)
.ok()
.map(|oid| oid.trim().to_string())
.filter(|oid| !oid.is_empty())
}
type Pulled = (Net, Option<String>, String);
fn run_pull(choice: PullChoice, remote: &str, branch: &str, cancel: &AtomicBool) -> Result<Pulled> {
let fork = if choice == PullChoice::Rebase {
fork_point(remote, branch)
} else {
None
};
let command = pull_command(choice, remote, branch, fork.as_deref());
let fetch = fetch_args(remote, branch);
let fetch: Vec<&str> = fetch.iter().map(String::as_str).collect();
match run_net(&fetch, PULL_SECS, cancel)? {
Net::Done(_) => {}
other => return Ok((other, None, command)),
}
let has_head = git::git_ok(
&["rev-parse", "--verify", "--quiet", "HEAD"],
&Opts::default(),
)
.is_ok();
let backup = if choice != PullChoice::FastForward && has_head {
Some(crate::safety::backup("pull", "HEAD")?)
} else {
None
};
let owned = integrate_args(choice, fork.as_deref());
let args: Vec<&str> = owned.iter().map(String::as_str).collect();
Ok((run_local(&args)?, backup, command))
}
fn lease_for(remote: &str, branch: &str) -> Result<String> {
let tracking = format!("refs/remotes/{remote}/{branch}");
let oid = git::git_ok(
&["rev-parse", "--verify", "--quiet", &tracking],
&Opts::default(),
)
.map_err(|_| anyhow!("{remote}/{branch} is not known locally yet; fetch first"))?;
Ok(format!("refs/heads/{branch}:{oid}"))
}
fn list_remotes() -> Result<Vec<(String, String)>> {
Ok(parse_remotes(&git::git_ok(
&["remote", "-v"],
&Opts::default(),
)?))
}
fn remote_names() -> Result<Vec<String>> {
Ok(list_remotes()?.into_iter().map(|(name, _)| name).collect())
}
fn error_lines(plain: &str, stderr: &str) -> Vec<String> {
let mut lines = vec![screen::danger(plain), String::new()];
lines.extend(crate::cmdlog::mask(stderr).lines().map(String::from));
lines
}
fn result_lines(command: &str, report: &str, cfg: &Config, why: &[&str]) -> Vec<String> {
let mut lines = vec![
screen::success("Done."),
screen::muted(format!("$ git {command}")),
String::new(),
];
lines.extend(crate::cmdlog::mask(report).lines().map(String::from));
lines.extend(ui::explain(cfg, why));
lines
}
fn header_lines(state: &RepoState, remotes: &[String]) -> Vec<String> {
let info = &state.branch;
let branch = match &info.head {
Head::Branch { name, .. } | Head::Unborn { name } => name.clone(),
Head::Detached { oid } => format!("(detached at {})", oid.get(..7).unwrap_or(oid)),
};
let upstream = match (&info.upstream, info.upstream_gone) {
(Some(up), true) => format!("{up} (gone from the remote)"),
(Some(up), false) => format!("{up} ahead {} / behind {}", info.ahead, info.behind),
(None, _) => "none (not published yet)".to_string(),
};
let names = if remotes.is_empty() {
"none".to_string()
} else {
remotes.join(", ")
};
vec![
format!("{} {}", screen::muted("Branch "), screen::accent(branch)),
format!("{} {}", screen::muted("Upstream"), upstream),
format!("{} {}", screen::muted("Remotes "), names),
String::new(),
]
}
fn resolve_remote(cfg: &mut Config, upstream: Option<&str>) -> Result<Option<String>> {
let mut remotes = remote_names()?;
if remotes.is_empty() {
let mut lines =
vec!["This repository has no remote, so there is nowhere to sync with.".to_string()];
lines.extend(ui::explain(
cfg,
&["A remote is a copy of the project on a server, like GitHub."],
));
lines.push("Next you can add one.".into());
ui::notice("No remote", &lines)?;
add_remote(cfg)?;
remotes = remote_names()?;
}
match choose_remote(&cfg.default_remote, &remotes, upstream) {
RemoteChoice::Use(name) => Ok(Some(name)),
RemoteChoice::None => Ok(None),
RemoteChoice::Pick(names) => {
let options: Vec<&str> = names.iter().map(String::as_str).collect();
let context = vec!["Which remote?".to_string()];
Ok(ui::choose("Choose a remote", &context, &options)?.map(|i| names[i].clone()))
}
}
}
fn conflicts_pending() -> bool {
repo_state::load()
.is_ok_and(|state| state.op.is_some() || state.entries.iter().any(|e| e.conflicted()))
}
fn fetch_flow(cfg: &mut Config) -> Result<()> {
let state = repo_state::load()?;
let Some(remote) = resolve_remote(cfg, state.branch.upstream.as_deref())? else {
return Ok(());
};
let mut all = false;
if remote_names()?.len() > 1 {
let options = [format!("Only {remote}"), "All remotes".to_string()];
let options: Vec<&str> = options.iter().map(String::as_str).collect();
match ui::choose("Fetch from", &[], &options)? {
Some(1) => all = true,
Some(_) => {}
None => return Ok(()),
}
}
let target = if all { None } else { Some(remote.as_str()) };
let command = if all {
"fetch --prune --all".to_string()
} else {
format!("fetch --prune {remote}")
};
let net = ui::git_job_cancellable(
&format!("Fetching {}...", target.unwrap_or("all remotes")),
|cancel| run_fetch(target, cancel),
)?;
match net {
Net::Done(report) => {
let report = if report.is_empty() {
"Already up to date.".to_string()
} else {
report
};
let why = ["Fetch only downloads. Your files and branches stay untouched."];
ui::notice("Fetch", &result_lines(&command, &report, cfg, &why))
}
Net::Failed(text) => {
let plain = if looks_like_auth(&text.to_ascii_lowercase()) {
"Git could not sign in. Run `gct --account` to pick or add a GitHub account."
} else {
"The fetch failed."
};
ui::notice("Fetch failed", &error_lines(plain, &text))
}
Net::Cancelled => ui::notice("Fetch", &["Cancelled.".to_string()]),
}
}
fn pull_flow(cfg: &mut Config) -> Result<()> {
let state = repo_state::load()?;
if state.op.is_some() || state.entries.iter().any(|e| e.conflicted()) {
ui::notice(
"Pull",
&["Finish the operation in progress first. Opening the conflicts screen.".to_string()],
)?;
return crate::modes::open("conflicts", cfg);
}
let local = match branch_name(&state.branch.head) {
Ok(name) => name.to_string(),
Err(why) => return ui::notice("Pull", &[why.to_string()]),
};
let Some(remote) = resolve_remote(cfg, state.branch.upstream.as_deref())? else {
return Ok(());
};
let branch = pull_branch(state.branch.upstream.as_deref(), &remote, &local);
let labels: Vec<&str> = PullChoice::ALL.iter().map(|c| c.label()).collect();
let mut context = vec![format!("Pull {remote}/{branch} into {local}")];
context.extend(ui::explain(
cfg,
&["Fast-forward only refuses to pull when both sides have new commits."],
));
if let Some(problem) = names_problem(&remote, &branch) {
return ui::notice("Pull", &[problem]);
}
let Some(first) = ui::choose("Pull how?", &context, &labels)? else {
return Ok(());
};
let mut choice = PullChoice::ALL[first];
loop {
let (net, backup, command) =
ui::git_job_cancellable(&format!("Pulling {remote}/{branch}..."), |cancel| {
run_pull(choice, &remote, &branch, cancel)
})?;
let backup_line = backup
.as_ref()
.map(|name| format!("Backup of your branch before the pull: {name}"));
let text = match net {
Net::Done(report) => {
let why = ["Pull = fetch + bring the new commits into your branch."];
let mut lines = result_lines(&command, &report, cfg, &why);
lines.extend(backup_line);
return ui::notice("Pull", &lines);
}
Net::Cancelled => return ui::notice("Pull", &["Cancelled.".to_string()]),
Net::Failed(text) => text,
};
let kind = classify_pull_error(&text);
if kind == PullError::Conflict || conflicts_pending() {
let mut lines = error_lines(
"Some files changed on both sides. Resolve them next.",
&text,
);
lines.extend(backup_line);
ui::notice("Pull stopped on conflicts", &lines)?;
return crate::modes::open("conflicts", cfg);
}
match kind {
PullError::Diverged => {
let context = vec![
"Your branch and the remote both have new commits, so they have diverged."
.to_string(),
"A fast-forward is not possible. Pick another way to combine them:".to_string(),
];
let others: Vec<PullChoice> = PullChoice::ALL
.into_iter()
.filter(|c| *c != choice)
.collect();
let mut labels: Vec<&str> = others.iter().map(|c| c.label()).collect();
labels.push("Cancel");
match ui::choose("Branches diverged", &context, &labels)? {
Some(i) if i < others.len() => choice = others[i],
_ => return Ok(()),
}
}
PullError::NoUpstream => {
return ui::notice(
"Pull",
&error_lines("This branch is not tracking a remote branch yet. Push it with 'Push and set upstream' first.", &text),
);
}
PullError::Auth => return ui::notice("Pull", &error_lines(AUTH_HELP, &text)),
PullError::Conflict | PullError::Other => {
return ui::notice("Pull failed", &error_lines("The pull failed.", &text));
}
}
}
}
const AUTH_HELP: &str =
"Git could not sign in. Run `gct --account` to pick or add a GitHub account.";
fn push_flow(cfg: &mut Config, force: bool, set_upstream: bool) -> Result<()> {
let state = repo_state::load()?;
let branch = match branch_name(&state.branch.head) {
Ok(name) => name.to_string(),
Err(why) => return ui::notice("Push", &[why.to_string()]),
};
let Some(remote) = resolve_remote(cfg, state.branch.upstream.as_deref())? else {
return Ok(());
};
if let Some(problem) = names_problem(&remote, &branch) {
return ui::notice("Push", &[problem]);
}
let refspec = format!("refs/heads/{branch}:refs/heads/{branch}");
let mut lease = None;
let mut command = format!(
"push {}{remote} {refspec}",
if set_upstream { "-u " } else { "" }
);
if force {
let verdict = policy::check(
cfg,
&Op::ForcePush {
remote: &remote,
branch: &branch,
},
);
let what = format!("Overwrite {remote}/{branch} with your local {branch}. Commits only on the remote are lost.");
let value = match lease_for(&remote, &branch) {
Ok(value) => value,
Err(error) => {
if matches!(verdict, policy::Verdict::Deny(_)) {
ui::gate(cfg, &verdict, &what, "")?;
return Ok(());
}
return ui::notice("Force push", &[error.to_string()]);
}
};
command = format!("push --force-with-lease={value} --force-if-includes {remote} {refspec}");
if !ui::gate(cfg, &verdict, &what, &format!("git {command}"))? {
return Ok(());
}
lease = Some(value);
}
let login = login_of(cfg);
let net = ui::git_job_cancellable(&format!("Pushing {branch} to {remote}..."), |cancel| {
git::push_to_cancellable(
&remote,
&branch,
lease.as_deref(),
set_upstream,
login.as_deref(),
Some(cancel),
)
});
match net {
Ok(report) => {
let why = ["Push uploads your commits so others (and GitHub) can see them."];
let report = if report.is_empty() {
"Everything is already up to date.".to_string()
} else {
report
};
ui::notice("Push", &result_lines(&command, &report, cfg, &why))
}
Err(error) if input::is_cancel(&error) || error.is::<ui::JobPanic>() => Err(error),
Err(error) => push_failed(cfg, set_upstream, force, &format!("{error:#}")),
}
}
fn push_failed(cfg: &mut Config, set_upstream: bool, force: bool, text: &str) -> Result<()> {
match classify_push_error(text) {
PushError::Rejected => {
let mut lines = error_lines(
if force {
"The remote branch changed since you last fetched, so the lease refused the overwrite. Fetch and look first."
} else {
"The remote has commits you do not have yet, so git refused the push."
},
text,
);
lines.extend(ui::explain(
cfg,
&["Pull first to combine both histories, then push again."],
));
ui::notice("Push rejected", &lines)?;
if !force && ui::choose("Next step", &[], &["Pull now", "Back"])? == Some(0) {
return pull_flow(cfg);
}
Ok(())
}
PushError::NoUpstream if !set_upstream => {
let context = error_lines(
"This branch has no upstream yet (it was never pushed).",
text,
);
if ui::choose(
"Set the upstream?",
&context,
&["Push and set upstream", "Back"],
)? == Some(0)
{
return push_flow(cfg, false, true);
}
Ok(())
}
PushError::Auth => ui::notice("Push failed", &error_lines(AUTH_HELP, text)),
PushError::NoUpstream | PushError::Other => {
ui::notice("Push failed", &error_lines("The push failed.", text))
}
}
}
pub fn push_current(cfg: &mut Config, set_upstream: bool) -> Result<()> {
push_flow(cfg, false, set_upstream)
}
pub fn add_remote(cfg: &mut Config) -> Result<()> {
let existing = remote_names()?;
let initial = if existing.contains(&cfg.default_remote) {
""
} else {
cfg.default_remote.as_str()
};
let Some(name) = ui::ask("Remote name (usually origin)", initial)? else {
return Ok(());
};
let name = name.trim().to_string();
if let Some(problem) = remote_name_problem(&name) {
return ui::notice("Add remote", &[problem.to_string()]);
}
if existing.contains(&name) {
return ui::notice(
"Add remote",
&[format!("A remote named '{name}' already exists.")],
);
}
let Some(url) = ui::ask("Remote URL (https://github.com/you/repo.git)", "")? else {
return Ok(());
};
let url = url.trim().to_string();
if let Some(problem) = remote_url_problem(&url) {
return ui::notice("Add remote", &[problem.to_string()]);
}
ui::run_git(cfg, "Adding the remote...", &["remote", "add", &name, &url])?;
let mut lines = result_lines(
&format!("remote add {name} {}", crate::cmdlog::mask(&url)),
"",
cfg,
&[],
);
lines.extend(ui::explain(
cfg,
&["Next: Fetch to download it, then Push and set upstream."],
));
ui::notice("Remote added", &lines)
}
fn remotes_screen(cfg: &mut Config) -> Result<()> {
let mut index = 0usize;
loop {
let remotes = list_remotes()?;
let rows: Vec<String> = remotes
.iter()
.map(|(name, url)| format!("{name:<12} {}", crate::cmdlog::mask(url)))
.collect();
let header = if rows.is_empty() {
vec![
"No remotes yet. Press A to add one.".to_string(),
String::new(),
]
} else {
vec![String::new()]
};
let keys = [
Key {
key: 'a',
label: "add",
},
Key {
key: 'n',
label: "rename",
},
Key {
key: 'u',
label: "set URL",
},
Key {
key: 'd',
label: "remove",
},
];
let (action, at) = match ui::action_list("Remotes", &header, &rows, &keys, &mut index)? {
Choice::Back => return Ok(()),
Choice::Action(key, at) => (key, at),
Choice::Open(at) => {
let picked = ui::choose(
"Remote",
&[rows.get(at).cloned().unwrap_or_default()],
&["Rename", "Change URL", "Remove", "Back"],
)?;
match picked {
Some(0) => ('n', at),
Some(1) => ('u', at),
Some(2) => ('d', at),
_ => continue,
}
}
};
if action == 'a' {
add_remote(cfg)?;
continue;
}
let Some((name, url)) = remotes.get(at) else {
continue;
};
match action {
'n' => {
let Some(new) = ui::ask(&format!("New name for {name}"), name)? else {
continue;
};
let new = new.trim().to_string();
if let Some(problem) = remote_name_problem(&new) {
ui::notice("Rename remote", &[problem.to_string()])?;
} else if &new != name {
ui::run_git(cfg, "Renaming...", &["remote", "rename", name, &new])?;
}
}
'u' => {
let Some(new) = ui::ask(&format!("New URL for {name}"), url)? else {
continue;
};
let new = new.trim().to_string();
if let Some(problem) = remote_url_problem(&new) {
ui::notice("Change URL", &[problem.to_string()])?;
} else {
ui::run_git(
cfg,
"Changing the URL...",
&["remote", "set-url", name, &new],
)?;
}
}
'd' => {
let what = format!("Remove the remote '{name}'. Its remote-tracking branches are forgotten locally; the server is not touched.");
if ui::confirm_danger(cfg, &what, &format!("git remote remove {name}"))? {
ui::run_git(cfg, "Removing...", &["remote", "remove", name])?;
}
}
_ => {}
}
}
}
pub fn run(config: &mut Config) -> Result<()> {
let mut index = 0usize;
loop {
let state = repo_state::load()?;
let remotes = remote_names()?;
let items = menu_items(config.level(), state.branch.upstream.is_some());
let rows: Vec<String> = items.iter().map(|item| item.row().to_string()).collect();
let keys: Vec<Key> = items.iter().map(|item| item.key()).collect();
let header = header_lines(&state, &remotes);
let item = match ui::action_list("Sync", &header, &rows, &keys, &mut index)? {
Choice::Back => return Ok(()),
Choice::Open(at) => items.get(at).copied(),
Choice::Action(key, _) => items.iter().find(|item| item.key().key == key).copied(),
};
match item {
Some(Item::Fetch) => fetch_flow(config)?,
Some(Item::Pull) => pull_flow(config)?,
Some(Item::Push) => push_flow(config, false, false)?,
Some(Item::PushSetUpstream) => push_flow(config, false, true)?,
Some(Item::ForcePush) => push_flow(config, true, false)?,
Some(Item::Remotes) => remotes_screen(config)?,
None => {}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::policy::Verdict;
use crate::testutil::TempRepo;
fn names(list: &[&str]) -> Vec<String> {
list.iter().map(|s| s.to_string()).collect()
}
#[test]
fn classify_push_table() {
let cases = [
("! [rejected] main -> main (non-fast-forward)\nerror: failed to push some refs", PushError::Rejected),
(" ! [rejected] main -> main (fetch first)", PushError::Rejected),
(" ! [rejected] main -> main (stale info)", PushError::Rejected),
("fatal: The current branch feat has no upstream branch.\nTo push the current branch and set the remote as upstream, use", PushError::NoUpstream),
("remote: Invalid username or password.\nfatal: Authentication failed for 'https://github.com/a/b.git/'", PushError::Auth),
("fatal: could not read Username for 'https://github.com': terminal prompts disabled", PushError::Auth),
(" ! [remote rejected] main -> main (protected branch hook declined)", PushError::Other),
("fatal: unable to access: Could not resolve host", PushError::Other),
("", PushError::Other),
];
for (text, want) in cases {
assert_eq!(classify_push_error(text), want, "{text}");
}
}
#[test]
fn classify_pull_table() {
let cases = [
("fatal: Not possible to fast-forward, aborting.", PullError::Diverged),
("hint: You have divergent branches\nfatal: Need to specify how to reconcile divergent branches.", PullError::Diverged),
("CONFLICT (content): Merge conflict in a.txt\nAutomatic merge failed; fix conflicts", PullError::Conflict),
("error: could not apply 1234567... msg", PullError::Conflict),
("There is no tracking information for the current branch.", PullError::NoUpstream),
("fatal: Authentication failed for 'https://x/y.git/'", PullError::Auth),
("fatal: couldn't find remote ref nope", PullError::Other),
];
for (text, want) in cases {
assert_eq!(classify_pull_error(text), want, "{text}");
}
}
#[test]
fn integrate_args_table() {
assert_eq!(
integrate_args(PullChoice::FastForward, Some("x")),
["merge", "--ff-only", "FETCH_HEAD"]
);
assert_eq!(
integrate_args(PullChoice::Rebase, None),
["rebase", "FETCH_HEAD"]
);
assert_eq!(
integrate_args(PullChoice::Rebase, Some("abc")),
["rebase", "--onto", "FETCH_HEAD", "abc"]
);
assert_eq!(
integrate_args(PullChoice::Merge, None),
["merge", "--no-edit", "FETCH_HEAD"]
);
assert_eq!(
pull_command(PullChoice::Rebase, "o", "b", None),
"fetch o refs/heads/b && git rebase FETCH_HEAD"
);
}
#[test]
fn branch_names_are_validated() {
let repo = TempRepo::new(1);
repo.run(|| {
assert!(names_problem("origin", "feat/x").is_none());
assert!(names_problem("origin", "-x").is_some());
assert!(names_problem("origin", "a..b").is_some());
assert!(names_problem("", "main").is_some());
assert!(names_problem("--upload-pack=x", "main").is_some());
});
}
#[test]
fn rebase_and_merge_pull_take_a_backup() {
for choice in [PullChoice::Rebase, PullChoice::Merge] {
let repo = TempRepo::new(2).with_remote();
let dir = other_clone(&repo);
commit_in(&repo, &dir, "theirs.txt", None);
repo.write("mine.txt", "m\n");
repo.git(&["add", "."]);
repo.git(&["commit", "-q", "-m", "mine"]);
let before = repo.git(&["rev-parse", "HEAD"]);
let cancel = AtomicBool::new(false);
repo.run(|| {
let (net, backup, _) = run_pull(choice, "origin", "main", &cancel).unwrap();
assert!(matches!(net, Net::Done(_)), "{net:?}");
let name = backup.expect("backup taken");
assert_eq!(
git::git_ok(&["rev-parse", &name], &Opts::default()).unwrap(),
before
);
});
assert!(repo.path().join("theirs.txt").exists());
}
}
#[test]
fn ff_pull_takes_no_backup() {
let repo = TempRepo::new(2).with_remote();
let cancel = AtomicBool::new(false);
repo.run(|| {
let (net, backup, _) =
run_pull(PullChoice::FastForward, "origin", "main", &cancel).unwrap();
assert!(matches!(net, Net::Done(_)));
assert!(backup.is_none());
});
}
#[test]
fn choose_remote_table() {
let two = names(&["origin", "second"]);
assert_eq!(choose_remote("origin", &[], None), RemoteChoice::None);
assert_eq!(
choose_remote("second", &two, Some("origin/main")),
RemoteChoice::Use("second".into())
);
assert_eq!(
choose_remote("zzz", &two, Some("second/main")),
RemoteChoice::Use("second".into())
);
assert_eq!(
choose_remote("zzz", &two, None),
RemoteChoice::Pick(two.clone())
);
assert_eq!(
choose_remote("zzz", &names(&["only"]), None),
RemoteChoice::Use("only".into())
);
let nested = names(&["a", "a/b"]);
assert_eq!(
choose_remote("zzz", &nested, Some("a/b/main")),
RemoteChoice::Use("a/b".into())
);
assert_eq!(pull_branch(Some("origin/feat/x"), "origin", "x"), "feat/x");
assert_eq!(pull_branch(Some("other/main"), "origin", "dev"), "dev");
assert_eq!(pull_branch(None, "origin", "dev"), "dev");
}
#[test]
fn remotes_and_validation() {
let text = "origin\thttps://h/a.git (fetch)\r\norigin\thttps://h/a.git (push)\nüp\tC:\\Users\\x y\\r (fetch)\nüp\tC:\\Users\\x y\\r (push)\n";
assert_eq!(
parse_remotes(text),
[
("origin".to_string(), "https://h/a.git".to_string()),
("üp".to_string(), "C:\\Users\\x y\\r".to_string())
]
);
assert!(parse_remotes("").is_empty());
assert!(remote_name_problem("").is_some());
assert!(remote_name_problem("-x").is_some());
assert!(remote_name_problem("a b").is_some());
assert!(remote_name_problem("up-stream").is_none());
assert!(remote_url_problem(" ").is_some());
assert!(remote_url_problem("--upload-pack=x").is_some());
assert!(remote_url_problem("https://h/r.git").is_none());
}
#[test]
fn menu_depends_on_level_and_upstream() {
let beginner = menu_items(Level::Beginner, true);
assert!(!beginner.contains(&Item::ForcePush));
assert!(!beginner.contains(&Item::PushSetUpstream));
let pro = menu_items(Level::Pro, false);
assert!(pro.contains(&Item::ForcePush) && pro.contains(&Item::PushSetUpstream));
assert!(branch_name(&Head::Detached { oid: "a".into() }).is_err());
}
#[test]
fn login_uses_active_account() {
let mut cfg = Config::default();
assert_eq!(login_of(&cfg), None);
cfg.accounts.push(crate::accounts::Account {
label: "w".into(),
name: String::new(),
email: String::new(),
github_username: "octo".into(),
});
cfg.active_account = Some("w".into());
assert_eq!(login_of(&cfg).as_deref(), Some("octo"));
}
#[test]
fn push_to_second_default_remote() {
let repo = TempRepo::new(2).with_remote();
let second = repo.path().parent().unwrap().join("second.git");
repo.git(&[
"init",
"-q",
"--bare",
"-b",
"main",
&second.to_string_lossy(),
]);
repo.git(&["remote", "add", "second", &second.to_string_lossy()]);
let cfg = Config {
default_remote: "second".into(),
..Config::default()
};
let want = repo.git(&["rev-parse", "HEAD"]);
repo.run(|| {
let remotes = remote_names().unwrap();
let RemoteChoice::Use(remote) =
choose_remote(&cfg.default_remote, &remotes, Some("origin/main"))
else {
panic!("expected a remote");
};
assert_eq!(remote, "second");
git::push_to(&remote, "main", None, true, None).unwrap();
});
assert_eq!(
repo.git(&["--git-dir", &second.to_string_lossy(), "rev-parse", "main"]),
want
);
assert_eq!(
repo.git(&["rev-parse", "--abbrev-ref", "@{u}"]),
"second/main"
);
}
#[test]
fn force_push_to_main_is_denied() {
let cfg = Config::default();
let verdict = policy::check(
&cfg,
&Op::ForcePush {
remote: "origin",
branch: "main",
},
);
assert!(matches!(verdict, Verdict::Deny(_)));
let other = policy::check(
&cfg,
&Op::ForcePush {
remote: "origin",
branch: "feat",
},
);
assert_eq!(other, Verdict::Danger);
}
fn other_clone(repo: &TempRepo) -> String {
let dir = repo.path().parent().unwrap().join("other");
let dir = dir.to_string_lossy().into_owned();
repo.git(&["clone", "-q", &repo.remote_path().to_string_lossy(), &dir]);
dir
}
fn commit_in(repo: &TempRepo, dir: &str, file: &str, branch: Option<&str>) {
if let Some(branch) = branch {
repo.git(&["-C", dir, "checkout", "-q", branch]);
}
std::fs::write(std::path::Path::new(dir).join(file), "x\n").unwrap();
repo.git(&["-C", dir, "add", "."]);
repo.git(&[
"-C",
dir,
"-c",
"user.name=O",
"-c",
"user.email=o@e.com",
"commit",
"-q",
"-m",
file,
]);
repo.git(&["-C", dir, "push", "-q"]);
}
#[test]
fn fetch_then_ff_pull_round_trip() {
let repo = TempRepo::new(2).with_remote();
let dir = other_clone(&repo);
commit_in(&repo, &dir, "new.txt", None);
let cancel = AtomicBool::new(false);
repo.run(|| {
assert!(matches!(
run_fetch(Some("origin"), &cancel).unwrap(),
Net::Done(_)
));
assert!(matches!(run_fetch(None, &cancel).unwrap(), Net::Done(_)));
let state = repo_state::load().unwrap();
assert_eq!(state.branch.behind, 1);
let (net, _, _) = run_pull(PullChoice::FastForward, "origin", "main", &cancel).unwrap();
assert!(matches!(net, Net::Done(_)), "{net:?}");
assert_eq!(repo_state::load().unwrap().branch.behind, 0);
});
assert!(repo.path().join("new.txt").exists());
}
#[test]
fn diverged_ff_pull_is_classified() {
let repo = TempRepo::new(2).with_remote();
let dir = other_clone(&repo);
commit_in(&repo, &dir, "theirs.txt", None);
repo.write("mine.txt", "m\n");
repo.git(&["add", "."]);
repo.git(&["commit", "-q", "-m", "mine"]);
let cancel = AtomicBool::new(false);
repo.run(|| {
let (Net::Failed(text), _, _) =
run_pull(PullChoice::FastForward, "origin", "main", &cancel).unwrap()
else {
panic!("ff pull should fail");
};
assert_eq!(classify_pull_error(&text), PullError::Diverged, "{text}");
let Net::Failed(text) = git::push_to("origin", "main", None, false, None)
.map(Net::Done)
.unwrap_or_else(|e| Net::Failed(format!("{e:#}")))
else {
panic!("push should be rejected");
};
assert_eq!(classify_push_error(&text), PushError::Rejected, "{text}");
assert!(matches!(
run_pull(PullChoice::Merge, "origin", "main", &cancel)
.unwrap()
.0,
Net::Done(_)
));
});
}
fn commit_text(repo: &TempRepo, dir: &str, file: &str, text: &str, extra: &[&str]) {
std::fs::write(std::path::Path::new(dir).join(file), text).unwrap();
repo.git(&["-C", dir, "add", "."]);
let mut args = vec![
"-C",
dir,
"-c",
"user.name=O",
"-c",
"user.email=o@e.com",
"commit",
"-q",
"-m",
file,
];
args.extend_from_slice(extra);
repo.git(&args);
}
#[test]
fn pull_works_without_a_tracking_ref() {
for choice in [
PullChoice::FastForward,
PullChoice::Rebase,
PullChoice::Merge,
] {
let repo = TempRepo::new(2).with_remote();
let dir = other_clone(&repo);
repo.git(&["-C", &dir, "checkout", "-q", "-b", "feat"]);
commit_text(&repo, &dir, "theirs.txt", "t\n", &[]);
repo.git(&["-C", &dir, "push", "-q", "origin", "feat"]);
repo.git(&[
"config",
"remote.origin.fetch",
"+refs/heads/main:refs/remotes/origin/main",
]);
repo.git(&["checkout", "-q", "-b", "feat"]);
if choice != PullChoice::FastForward {
repo.write("mine.txt", "m\n");
repo.git(&["add", "."]);
repo.git(&["commit", "-q", "-m", "mine"]);
}
let cancel = AtomicBool::new(false);
repo.run(|| {
let (net, _, command) = run_pull(choice, "origin", "feat", &cancel).unwrap();
assert!(matches!(net, Net::Done(_)), "{choice:?}: {net:?}");
assert!(
command.starts_with("fetch origin refs/heads/feat && git "),
"{command}"
);
});
assert!(repo.path().join("theirs.txt").exists(), "{choice:?}");
assert_eq!(
repo.git(&["for-each-ref", "refs/remotes/origin/feat"]),
"",
"no tracking ref was made"
);
assert_eq!(repo.git(&["status", "--porcelain"]), "");
}
}
#[test]
fn rebase_after_upstream_force_push_replays_only_my_commits() {
let repo = TempRepo::new(2).with_remote();
let dir = other_clone(&repo);
commit_text(&repo, &dir, "shared.txt", "b1\n", &[]);
repo.git(&["-C", &dir, "push", "-q"]);
repo.git(&["pull", "-q", "--ff-only"]);
repo.write("mine.txt", "m\n");
repo.git(&["add", "."]);
repo.git(&["commit", "-q", "-m", "mine"]);
commit_text(&repo, &dir, "shared.txt", "b2\n", &["--amend"]);
repo.git(&["-C", &dir, "push", "-q", "--force"]);
let cancel = AtomicBool::new(false);
repo.run(|| {
let (net, backup, command) =
run_pull(PullChoice::Rebase, "origin", "main", &cancel).unwrap();
assert!(matches!(net, Net::Done(_)), "{net:?}");
assert!(backup.is_some());
assert!(command.contains("rebase --onto FETCH_HEAD "), "{command}");
assert_eq!(repo_state::load().unwrap().op, None);
});
let upstream = repo.git(&[
"--git-dir",
&repo.remote_path().to_string_lossy(),
"rev-parse",
"main",
]);
assert_eq!(repo.git(&["rev-parse", "HEAD~1"]), upstream);
assert_eq!(repo.git(&["log", "-1", "--format=%s"]), "mine");
let shared = std::fs::read_to_string(repo.path().join("shared.txt")).unwrap();
assert_eq!(shared.replace('\r', ""), "b2\n");
}
#[test]
fn failed_fetch_leaves_the_repo_untouched() {
let repo = TempRepo::new(2).with_remote();
let before = repo.git(&["rev-parse", "HEAD"]);
let cancel = AtomicBool::new(false);
for choice in PullChoice::ALL {
repo.run(|| {
let (net, backup, _) =
run_pull(choice, "origin", "no-such-branch", &cancel).unwrap();
assert!(matches!(net, Net::Failed(_)), "{net:?}");
assert!(backup.is_none());
});
}
assert_eq!(repo.git(&["rev-parse", "HEAD"]), before);
assert_eq!(repo.git(&["for-each-ref", "refs/gct/"]), "");
assert_eq!(repo.git(&["status", "--porcelain"]), "");
}
#[test]
fn force_with_lease_overwrites_and_detects_stale() {
let repo = TempRepo::new(2).with_remote();
repo.git(&["checkout", "-q", "-b", "feat"]);
repo.git(&["push", "-q", "-u", "origin", "feat"]);
repo.git(&["commit", "-q", "--amend", "-m", "rewritten"]);
let local = repo.git(&["rev-parse", "HEAD"]);
repo.run(|| {
let lease = lease_for("origin", "feat").unwrap();
assert!(lease.starts_with("refs/heads/feat:"));
git::push_to("origin", "feat", Some(&lease), false, None).unwrap();
});
assert_eq!(
repo.git(&[
"--git-dir",
&repo.remote_path().to_string_lossy(),
"rev-parse",
"feat"
]),
local
);
let dir = other_clone(&repo);
commit_in(&repo, &dir, "o.txt", Some("feat"));
repo.git(&["commit", "-q", "--amend", "-m", "again"]);
repo.run(|| {
let lease = lease_for("origin", "feat").unwrap();
let error = git::push_to("origin", "feat", Some(&lease), false, None).unwrap_err();
assert_eq!(
classify_push_error(&format!("{error:#}")),
PushError::Rejected,
"{error:#}"
);
assert!(lease_for("origin", "nope").is_err());
});
}
}