use crate::{git, model::Config, screen, ui};
use anyhow::{bail, Result};
use std::path::{Path, PathBuf};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Scope {
Local,
Global,
}
impl Scope {
fn flag(self) -> &'static str {
match self {
Scope::Local => "--local",
Scope::Global => "--global",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Origin {
Local,
Global,
Other,
}
pub fn parse_show_origin(text: &str) -> Option<(String, String)> {
let line = text
.lines()
.map(|l| l.trim_end_matches('\r'))
.find(|l| !l.trim().is_empty())?;
let (origin, value) = line.split_once('\t')?;
if origin.is_empty() {
return None;
}
Some((origin.to_string(), value.to_string()))
}
pub fn parse_aliases(text: &str) -> Vec<(String, String)> {
let mut out: Vec<(String, String)> = text
.lines()
.map(|l| l.trim_end_matches('\r'))
.filter_map(|line| {
let (key, command) = line.split_once(char::is_whitespace).unwrap_or((line, ""));
let name = key.strip_prefix("alias.")?;
if name.is_empty() {
return None;
}
Some((name.to_string(), command.trim().to_string()))
})
.collect();
out.sort();
out
}
pub fn active_hooks(names: &[String]) -> Vec<String> {
let mut out: Vec<String> = names
.iter()
.map(|n| n.trim().to_string())
.filter(|n| !n.is_empty() && !n.to_ascii_lowercase().ends_with(".sample"))
.collect();
out.sort();
out.dedup();
out
}
fn unquote(p: &str) -> String {
match p.strip_prefix('"').and_then(|r| r.strip_suffix('"')) {
Some(inner) => inner.replace("\\\\", "\\").replace("\\\"", "\""),
None => p.to_string(),
}
}
fn norm_path(p: &str) -> String {
unquote(p)
.replace('\\', "/")
.trim_end_matches('/')
.to_ascii_lowercase()
}
pub fn classify_scope(origin: &str, local: Option<&str>, global: Option<&str>) -> Origin {
let Some(path) = origin.strip_prefix("file:") else {
return Origin::Other;
};
let path = norm_path(path);
if local.is_some_and(|l| norm_path(l) == path) {
Origin::Local
} else if global.is_some_and(|g| norm_path(g) == path) {
Origin::Global
} else {
Origin::Other
}
}
pub fn validate_identity(value: &str) -> Result<String, String> {
let v = value.trim();
if v.is_empty() {
return Err("The value cannot be empty.".into());
}
if v.chars().any(char::is_control) {
return Err("The value cannot contain control characters.".into());
}
Ok(v.to_string())
}
pub fn validate_email(value: &str) -> Result<String, String> {
let v = validate_identity(value)?;
if !v.contains('@') || v.contains(char::is_whitespace) {
return Err("That does not look like an email address.".into());
}
Ok(v)
}
pub fn validate_alias_name(name: &str) -> Result<String, String> {
let n = name.trim();
if n.is_empty() {
return Err("The alias name cannot be empty.".into());
}
if !n
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
{
return Err("Use only letters, digits, - and _ in an alias name.".into());
}
if n.starts_with('-') {
return Err("An alias name cannot start with '-'.".into());
}
Ok(n.to_string())
}
pub fn validate_alias_command(command: &str) -> Result<String, String> {
let c = command.trim();
if c.is_empty() {
return Err("The alias command cannot be empty.".into());
}
if c.chars().any(char::is_control) {
return Err("The command cannot contain control characters.".into());
}
Ok(c.to_string())
}
fn cfg_text(args: &[&str]) -> Option<String> {
let out = git::git_raw(args, &git::Opts::default()).ok()?;
out.ok().then(|| out.text())
}
pub fn set_value(scope: Scope, key: &str, value: &str) -> Result<()> {
if key.starts_with('-') {
bail!("invalid key");
}
git::git_ok(&["config", scope.flag(), key, value], &git::Opts::default())?;
Ok(())
}
pub fn unset_value(scope: Scope, key: &str) -> Result<()> {
if key.starts_with('-') {
bail!("invalid key");
}
let out = git::git_raw(
&["config", scope.flag(), "--unset", key],
&git::Opts::default(),
)?;
if out.ok() || out.code == Some(5) {
Ok(())
} else {
bail!("{}", out.stderr.trim())
}
}
fn local_config_path() -> Option<String> {
let p = cfg_text(&[
"rev-parse",
"--path-format=absolute",
"--git-path",
"config",
])?;
(!p.is_empty()).then_some(p)
}
fn global_config_path() -> Option<String> {
let text = cfg_text(&["config", "--global", "--show-origin", "--list"])?;
let first = text.lines().next()?;
let (origin, _) = first.split_once('\t')?;
origin.strip_prefix("file:").map(unquote)
}
pub fn effective(key: &str) -> Option<(Origin, String, String)> {
let text = cfg_text(&["config", "--show-origin", "--get", key])?;
let (origin, value) = parse_show_origin(&text)?;
let resolved = match origin.strip_prefix("file:") {
Some(p) if !Path::new(&unquote(p)).is_absolute() => {
match cfg_text(&["rev-parse", "--show-toplevel"]) {
Some(top) => format!("file:{}", Path::new(&top).join(p).display()),
None => origin.clone(),
}
}
_ => origin.clone(),
};
let scope = classify_scope(
&resolved,
local_config_path().as_deref(),
global_config_path().as_deref(),
);
Some((scope, origin, value))
}
pub fn list_aliases() -> Vec<(String, String)> {
cfg_text(&["config", "--global", "--get-regexp", r"^alias\."])
.map(|t| parse_aliases(&t))
.unwrap_or_default()
}
pub fn add_alias(name: &str, command: &str) -> Result<()> {
let name = validate_alias_name(name).map_err(anyhow::Error::msg)?;
let command = validate_alias_command(command).map_err(anyhow::Error::msg)?;
set_value(Scope::Global, &format!("alias.{name}"), &command)
}
pub fn remove_alias(name: &str) -> Result<()> {
let name = validate_alias_name(name).map_err(anyhow::Error::msg)?;
unset_value(Scope::Global, &format!("alias.{name}"))
}
pub struct HooksInfo {
pub dir: Option<PathBuf>,
pub hooks_path: Option<String>,
pub files: Vec<String>,
}
pub fn hooks_info() -> HooksInfo {
let hooks_path = cfg_text(&["config", "--get", "core.hooksPath"]).filter(|s| !s.is_empty());
let dir = cfg_text(&["rev-parse", "--path-format=absolute", "--git-path", "hooks"])
.filter(|s| !s.is_empty())
.map(PathBuf::from);
let effective_dir = match &hooks_path {
Some(p) if Path::new(p).is_absolute() => Some(PathBuf::from(p)),
Some(p) => cfg_text(&["rev-parse", "--show-toplevel"]).map(|t| Path::new(&t).join(p)),
None => dir.clone(),
};
let names: Vec<String> = effective_dir
.as_ref()
.and_then(|d| std::fs::read_dir(d).ok())
.map(|rd| {
rd.flatten()
.filter(|e| e.path().is_file())
.map(|e| e.file_name().to_string_lossy().into_owned())
.collect()
})
.unwrap_or_default();
HooksInfo {
dir: effective_dir,
hooks_path,
files: active_hooks(&names),
}
}
fn origin_label(o: Origin, origin: &str) -> String {
match o {
Origin::Local => "this repository (local)".to_string(),
Origin::Global => "your global config".to_string(),
Origin::Other => format!("other ({origin})"),
}
}
fn ask_scope(local_ok: bool) -> Result<Option<Scope>> {
if !local_ok {
return Ok(Some(Scope::Global));
}
Ok(
match ui::choose(
"Where should this be saved?",
&[],
&["This repository only (local)", "All repositories (global)"],
)? {
Some(0) => Some(Scope::Local),
Some(1) => Some(Scope::Global),
_ => None,
},
)
}
fn apply(cfg: &Config, scope: Scope, key: &str, value: Option<&str>, what: &str) -> Result<()> {
let command = match value {
Some(v) => format!("git config {} {key} \"{v}\"", scope.flag()),
None => format!("git config {} --unset {key}", scope.flag()),
};
if scope == Scope::Global && !ui::confirm_action(cfg, what, &command)? {
return Ok(());
}
let result = match value {
Some(v) => set_value(scope, key, v),
None => unset_value(scope, key),
};
let mut lines = match result {
Ok(()) => vec![screen::success("Saved."), format!("$ {command}")],
Err(e) => vec![
screen::danger(format!("Failed: {e}")),
format!("$ {command}"),
],
};
lines.extend(ui::explain(
cfg,
&["Global settings apply to every repository on this computer."],
));
ui::notice("Git config", &lines)
}
type Check = fn(&str) -> Result<String, String>;
fn ask_valid(prompt: &str, initial: &str, check: Check) -> Result<Option<String>> {
loop {
let Some(answer) = ui::ask(prompt, initial)? else {
return Ok(None);
};
match check(&answer) {
Ok(v) => return Ok(Some(v)),
Err(msg) => ui::notice("Invalid value", &[msg])?,
}
}
}
pub fn edit_identity(cfg: &mut Config) -> Result<()> {
loop {
let local_ok = local_config_path().is_some();
let mut context = Vec::new();
for (label, key) in [("Name ", "user.name"), ("Email", "user.email")] {
context.push(match effective(key) {
Some((o, origin, v)) => {
format!("{label}: {v} [from {}]", origin_label(o, &origin))
}
None => format!("{label}: {}", screen::warning("not set")),
});
}
let account = cfg
.active_account
.as_ref()
.and_then(|a| cfg.accounts.iter().find(|x| &x.label == a))
.cloned();
let use_label;
let mut options = vec!["Set name", "Set email"];
if let Some(a) = &account {
use_label = format!("Use my active gct account ({})", a.label);
options.push(&use_label);
}
let Some(pick) = ui::choose("Identity (name and email)", &context, &options)? else {
return Ok(());
};
match pick {
0 | 1 => {
let (key, prompt, check): (&str, &str, Check) = if pick == 0 {
("user.name", "Your name", validate_identity)
} else {
("user.email", "Your email", validate_email)
};
let initial = effective(key).map(|(_, _, v)| v).unwrap_or_default();
let Some(value) = ask_valid(prompt, &initial, check)? else {
continue;
};
let Some(scope) = ask_scope(local_ok)? else {
continue;
};
apply(
cfg,
scope,
key,
Some(&value),
&format!("Set {key} to {value}"),
)?;
}
_ => {
let Some(a) = account else { continue };
let (Ok(name), Ok(email)) = (validate_identity(&a.name), validate_email(&a.email))
else {
ui::notice(
"Git config",
&["That account has an invalid name or email.".to_string()],
)?;
continue;
};
let Some(scope) = ask_scope(local_ok)? else {
continue;
};
apply(
cfg,
scope,
"user.name",
Some(&name),
&format!("Set user.name to {name}"),
)?;
apply(
cfg,
scope,
"user.email",
Some(&email),
&format!("Set user.email to {email}"),
)?;
}
}
}
}
fn current(key: &str) -> String {
cfg_text(&["config", "--global", "--get", key]).unwrap_or_else(|| "not set".into())
}
fn default_branch(cfg: &Config) -> Result<()> {
let ctx = vec![
format!(
"init.defaultBranch (global): {}",
current("init.defaultBranch")
),
"Name given to the first branch of every new repository.".to_string(),
];
let value = match ui::choose(
"Default branch name",
&ctx,
&["main", "master", "Custom name"],
)? {
Some(0) => "main".to_string(),
Some(1) => "master".to_string(),
Some(2) => {
let check: fn(&str) -> Result<String, String> = |s| {
let v = validate_identity(s)?;
if v.starts_with('-') || v.contains(char::is_whitespace) {
return Err("Invalid branch name.".into());
}
Ok(v)
};
match ask_valid("Default branch name", "", check)? {
Some(v) => v,
None => return Ok(()),
}
}
_ => return Ok(()),
};
apply(
cfg,
Scope::Global,
"init.defaultBranch",
Some(&value),
&format!("Set the default branch to {value}"),
)
}
fn pull_strategy(cfg: &Config) -> Result<()> {
let ctx = vec![
format!("pull.rebase: {}", current("pull.rebase")),
format!("pull.ff: {}", current("pull.ff")),
];
let Some(which) = ui::choose(
"Pull strategy",
&ctx,
&[
"pull.rebase (merge or rebase)",
"pull.ff (fast-forward only)",
],
)?
else {
return Ok(());
};
if which == 0 {
let mut help = vec![
"true = replay your commits on top of the remote ones (straight history).".to_string(),
"false = create a merge commit; unset = Git asks you to decide.".to_string(),
];
help.extend(ui::explain(
cfg,
&["Rebase keeps history linear; merge keeps every branch point."],
));
match ui::choose("pull.rebase", &help, &["true", "false", "unset"])? {
Some(0) => apply(
cfg,
Scope::Global,
"pull.rebase",
Some("true"),
"Pull will rebase",
)?,
Some(1) => apply(
cfg,
Scope::Global,
"pull.rebase",
Some("false"),
"Pull will merge",
)?,
Some(2) => apply(
cfg,
Scope::Global,
"pull.rebase",
None,
"Remove pull.rebase",
)?,
_ => {}
}
} else {
let mut help = vec![
"only = pull refuses unless it is a simple fast-forward (safest).".to_string(),
"default = let Git merge when branches diverged.".to_string(),
];
help.extend(ui::explain(
cfg,
&["'only' never creates surprise merge commits."],
));
match ui::choose("pull.ff", &help, &["only", "default"])? {
Some(0) => apply(
cfg,
Scope::Global,
"pull.ff",
Some("only"),
"Pull will only fast-forward",
)?,
Some(1) => apply(
cfg,
Scope::Global,
"pull.ff",
None,
"Return pull.ff to default",
)?,
_ => {}
}
}
Ok(())
}
fn line_endings(cfg: &Config) -> Result<()> {
let mut ctx = vec![format!(
"core.autocrlf (global): {}",
current("core.autocrlf")
)];
ctx.push("true = CRLF in your files, LF in the repository (Windows).".to_string());
ctx.push("input = keep LF, never convert on checkout (macOS/Linux).".to_string());
ctx.push("false = do not convert anything.".to_string());
ctx.extend(ui::explain(
cfg,
&["Windows and Linux end lines differently; this keeps commits clean."],
));
let value = match ui::choose(
"Line endings",
&ctx,
&["true (Windows)", "input (macOS / Linux)", "false"],
)? {
Some(0) => "true",
Some(1) => "input",
Some(2) => "false",
_ => return Ok(()),
};
apply(
cfg,
Scope::Global,
"core.autocrlf",
Some(value),
&format!("Set core.autocrlf to {value}"),
)
}
fn aliases(cfg: &Config) -> Result<()> {
loop {
let list = list_aliases();
let ctx: Vec<String> = if list.is_empty() {
vec!["No aliases yet. Add one, e.g. name 'st' command 'status -sb'.".to_string()]
} else {
list.iter().map(|(n, c)| format!("{n} = {c}")).collect()
};
match ui::choose(
"Aliases (global)",
&ctx,
&["Add an alias", "Remove an alias"],
)? {
Some(0) => {
let Some(name) = ask_valid("Alias name", "", validate_alias_name)? else {
continue;
};
let Some(command) =
ask_valid("Git command (without 'git')", "", validate_alias_command)?
else {
continue;
};
let cmd = format!("git config --global alias.{name} \"{command}\"");
if !ui::confirm_action(cfg, &format!("Add alias '{name}'"), &cmd)? {
continue;
}
let msg = match add_alias(&name, &command) {
Ok(()) => screen::success(format!("Alias '{name}' added. Use: git {name}")),
Err(e) => screen::danger(format!("Failed: {e}")),
};
ui::notice("Aliases", &[msg, format!("$ {cmd}")])?;
}
Some(1) if !list.is_empty() => {
let names: Vec<&str> = list.iter().map(|(n, _)| n.as_str()).collect();
let Some(i) = ui::choose("Remove which alias?", &[], &names)? else {
continue;
};
let name = &list[i].0;
let cmd = format!("git config --global --unset alias.{name}");
if !ui::confirm_action(cfg, &format!("Remove alias '{name}'"), &cmd)? {
continue;
}
let msg = match remove_alias(name) {
Ok(()) => screen::success(format!("Alias '{name}' removed.")),
Err(e) => screen::danger(format!("Failed: {e}")),
};
ui::notice("Aliases", &[msg, format!("$ {cmd}")])?;
}
Some(1) => ui::notice("Aliases", &["Nothing to remove.".to_string()])?,
_ => return Ok(()),
}
}
}
fn hooks() -> Result<()> {
loop {
let info = hooks_info();
let mut ctx = Vec::new();
if let Some(p) = &info.hooks_path {
ctx.push(format!("core.hooksPath = {p}"));
ctx.push("managed by your team (husky/lefthook) \u{2014} read only".to_string());
}
match &info.dir {
Some(d) => ctx.push(format!("Hooks folder: {}", d.display())),
None => ctx.push("Not inside a repository: no hooks folder.".to_string()),
}
if info.files.is_empty() {
ctx.push("No active hooks (files ending in .sample are ignored).".to_string());
return ui::notice("Hooks (read-only)", &ctx);
}
ctx.push("Pick a hook to read its first lines. gct never edits hooks.".to_string());
let names: Vec<&str> = info.files.iter().map(String::as_str).collect();
let Some(i) = ui::choose("Hooks (read-only)", &ctx, &names)? else {
return Ok(());
};
let Some(dir) = &info.dir else { return Ok(()) };
let text = std::fs::read(dir.join(&info.files[i]))
.map(|b| String::from_utf8_lossy(&b).into_owned())
.unwrap_or_else(|e| format!("Cannot read: {e}"));
let lines: Vec<String> = text.lines().take(40).map(str::to_string).collect();
ui::pager(&info.files[i], &lines, "")?;
}
}
pub fn run(config: &mut Config) -> Result<()> {
loop {
let options = [
"Identity (name and email)",
"Default branch name",
"Pull strategy",
"Line endings",
"Aliases",
"Hooks (read-only)",
"Ignore file (opens Ignore mode)",
];
match ui::choose("Git config", &[], &options)? {
Some(0) => edit_identity(config)?,
Some(1) => default_branch(config)?,
Some(2) => pull_strategy(config)?,
Some(3) => line_endings(config)?,
Some(4) => aliases(config)?,
Some(5) => hooks()?,
Some(6) => crate::modes::open("ignore", config)?,
_ => return Ok(()),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::testutil::TempRepo;
#[test]
fn show_origin_parsing() {
assert_eq!(
parse_show_origin("file:C:/Users/x/.gitconfig\tAda Lovelace\r\n"),
Some(("file:C:/Users/x/.gitconfig".into(), "Ada Lovelace".into()))
);
assert_eq!(parse_show_origin(""), None);
assert_eq!(parse_show_origin("no tab here"), None);
assert_eq!(
parse_show_origin("file:/a\tj\u{e9}r\u{f4}me").unwrap().1,
"j\u{e9}r\u{f4}me"
);
}
#[test]
fn alias_parsing() {
let t =
"alias.st status -sb\r\nalias.co checkout\nalias.lg log --oneline --graph\nother.x y\n";
assert_eq!(
parse_aliases(t),
vec![
("co".into(), "checkout".into()),
("lg".into(), "log --oneline --graph".into()),
("st".into(), "status -sb".into())
]
);
assert!(parse_aliases("").is_empty());
}
#[test]
fn hooks_filtering() {
let names: Vec<String> = [
"pre-commit",
"pre-push.sample",
"commit-msg.exe",
"PREPARE.SAMPLE",
"",
]
.iter()
.map(|s| s.to_string())
.collect();
assert_eq!(active_hooks(&names), vec!["commit-msg.exe", "pre-commit"]);
}
#[test]
fn validation() {
assert_eq!(validate_identity(" Ada ").unwrap(), "Ada");
assert!(validate_identity(" ").is_err());
assert!(validate_identity("a\u{7}b").is_err());
assert!(validate_email("a@b.c").is_ok());
assert!(validate_email("nope").is_err());
assert!(validate_alias_name("my-al_1").is_ok());
assert!(validate_alias_name("bad name").is_err());
assert!(validate_alias_name("-x").is_err());
assert!(validate_alias_command(" ").is_err());
}
#[test]
fn scope_classification() {
let l = Some("C:/r/.git/config");
let g = Some("C:/Users/x/.gitconfig");
assert_eq!(
classify_scope("file:C:\\R\\.git\\config", l, g),
Origin::Local
);
assert_eq!(
classify_scope("file:C:/Users/x/.gitconfig", l, g),
Origin::Global
);
assert_eq!(classify_scope("file:/etc/gitconfig", l, g), Origin::Other);
assert_eq!(classify_scope("command line:", l, g), Origin::Other);
assert_eq!(classify_scope("file:/x", None, None), Origin::Other);
let quoted = "file:\"C:\\Users\\x\\.gitconfig\"";
assert_eq!(classify_scope(quoted, l, g), Origin::Global);
}
#[test]
fn local_identity_round_trip() {
let repo = TempRepo::new(1);
repo.run(|| {
set_value(Scope::Local, "user.name", "Zed Local").unwrap();
let (o, origin, v) = effective("user.name").unwrap();
assert_eq!(v, "Zed Local");
assert_eq!(o, Origin::Local, "origin was {origin}");
});
}
#[test]
fn global_identity_uses_temp_global_only() {
let repo = TempRepo::new(1);
repo.git(&["config", "--unset", "user.name"]);
repo.run(|| {
set_value(Scope::Global, "user.name", "Glob Al").unwrap();
let (o, origin, v) = effective("user.name").unwrap();
assert_eq!((o, v.as_str()), (Origin::Global, "Glob Al"));
let real = global_config_path().unwrap();
assert!(
real.contains("gct-ut-"),
"global path escaped isolation: {real} ({origin})"
);
});
}
#[test]
fn alias_round_trip_and_default_branch() {
let repo = TempRepo::new(1);
repo.run(|| {
assert!(list_aliases().is_empty());
add_alias("st", "status -sb").unwrap();
assert_eq!(
list_aliases(),
vec![("st".to_string(), "status -sb".to_string())]
);
assert!(add_alias("bad name", "x").is_err());
remove_alias("st").unwrap();
assert!(list_aliases().is_empty());
remove_alias("st").unwrap();
set_value(Scope::Global, "init.defaultBranch", "trunk").unwrap();
assert_eq!(current("init.defaultBranch"), "trunk");
});
}
#[test]
fn hooks_listing() {
let repo = TempRepo::new(1);
repo.write(".git/hooks/pre-commit", "#!/bin/sh\nexit 0\n");
repo.write(".git/hooks/pre-push.sample", "#!/bin/sh\n");
let info = repo.run(hooks_info);
assert_eq!(info.files, vec!["pre-commit"]);
assert!(info.hooks_path.is_none());
assert!(info.dir.is_some());
}
}