use crate::{Error, Result};
pub const CORE_AUTOCRLF: &str = "core.autocrlf";
pub const CORE_EOL: &str = "core.eol";
pub const COMMIT_TEMPLATE: &str = "commit.template";
pub const CORE_COMMENT_CHAR: &str = "core.commentChar";
pub const COMMIT_GPGSIGN: &str = "commit.gpgSign";
pub const USER_NAME: &str = "user.name";
pub const USER_EMAIL: &str = "user.email";
pub const MERGE_FF: &str = "merge.ff";
pub const REPO_CONFIG_KEYS: &[(&str, &[&str])] = &[
(CORE_AUTOCRLF, &["true", "input", "false"]),
(CORE_EOL, &["lf", "crlf", "native"]),
(USER_NAME, &[]),
(USER_EMAIL, &[]),
(COMMIT_TEMPLATE, &[]),
(CORE_COMMENT_CHAR, &[]),
(COMMIT_GPGSIGN, &["true", "false"]),
(MERGE_FF, &["true", "false", "only"]),
];
pub fn comment_char(configured: Option<&str>) -> char {
match configured.map(str::trim) {
Some(v) if v != "auto" => v.chars().next().unwrap_or('#'),
_ => '#',
}
}
pub fn strip_comment_lines(message: &str, comment: char) -> String {
let kept: Vec<&str> = message
.lines()
.filter(|line| !line.starts_with(comment))
.collect();
kept.join("\n").trim().to_string()
}
pub fn check_repo_config_key(key: &str) -> Result<()> {
if REPO_CONFIG_KEYS.iter().any(|(k, _)| *k == key) {
Ok(())
} else {
Err(Error::Backend(format!(
"`{key}` is not a settable repository config key (allowed: {})",
REPO_CONFIG_KEYS
.iter()
.map(|(k, _)| *k)
.collect::<Vec<_>>()
.join(", ")
)))
}
}
pub fn check_repo_config_value(key: &str, value: &str) -> Result<()> {
check_repo_config_key(key)?;
let allowed = REPO_CONFIG_KEYS
.iter()
.find(|(k, _)| *k == key)
.map_or(&[][..], |(_, v)| *v);
if allowed.is_empty() {
return if value.trim().is_empty() || value.contains(['\n', '\r']) {
Err(Error::Backend(format!(
"{key} must be a non-blank single line"
)))
} else {
Ok(())
};
}
if allowed.contains(&value) {
Ok(())
} else {
Err(Error::Backend(format!(
"`{value}` is not a valid value of {key} (one of: {})",
allowed.join(", ")
)))
}
}
pub fn ssh_command_for_key(key_path: &str) -> String {
format!("ssh -i {} -o IdentitiesOnly=yes", sh_quote_path(key_path))
}
pub fn key_of_ssh_command(command: &str) -> Option<String> {
let words = sh_words(command)?;
let mut it = words.iter().map(String::as_str);
if it.next()? != "ssh" || it.next()? != "-i" {
return None;
}
let key = it.next()?.to_string();
match (it.next(), it.next(), it.next()) {
(None, ..) => {}
(Some("-o"), Some(opt), None) if opt.eq_ignore_ascii_case("IdentitiesOnly=yes") => {}
_ => return None,
}
(!key.is_empty()).then_some(key)
}
fn sh_words(text: &str) -> Option<Vec<String>> {
let mut out = Vec::new();
let mut cur = String::new();
let mut has = false;
let mut quote: Option<char> = None;
let mut chars = text.chars().peekable();
while let Some(c) = chars.next() {
match (quote, c) {
(Some(q), c) if c == q => quote = None,
(Some('"'), '\\') if matches!(chars.peek(), Some('"' | '$' | '`' | '\\')) => {
cur.push(chars.next()?);
}
(Some(_), c) => cur.push(c),
(None, '"' | '\'') => {
quote = Some(c);
has = true;
}
(None, c) if c.is_whitespace() => {
if has || !cur.is_empty() {
out.push(std::mem::take(&mut cur));
has = false;
}
}
(None, c) => cur.push(c),
}
}
if quote.is_some() {
return None;
}
if has || !cur.is_empty() {
out.push(cur);
}
Some(out)
}
pub fn sh_quote_path(path: &str) -> String {
let mut quoted = String::with_capacity(path.len() + 2);
quoted.push('"');
for c in path.chars() {
match c {
'\\' => quoted.push('/'),
'"' | '$' | '`' => {
quoted.push('\\');
quoted.push(c);
}
c => quoted.push(c),
}
}
quoted.push('"');
quoted
}
#[cfg(test)]
mod tests {
#[test]
fn the_key_path_is_quoted_for_sh() {
use super::ssh_command_for_key as c;
assert_eq!(c("/k/a b"), r#"ssh -i "/k/a b" -o IdentitiesOnly=yes"#);
assert_eq!(
c(r"C:\Users\me\.ssh\my key"),
r#"ssh -i "C:/Users/me/.ssh/my key" -o IdentitiesOnly=yes"#
);
assert_eq!(
c(r#"/k/$HOME/`x`/"q""#),
r#"ssh -i "/k/\$HOME/\`x\`/\"q\"" -o IdentitiesOnly=yes"#
);
}
#[test]
fn the_key_of_a_pin_is_read_back_and_other_commands_are_not_keys() {
use super::{key_of_ssh_command as k, ssh_command_for_key as c};
for key in ["/k/a b", "/k/$HOME/`x`/\"q\"", "C:/Users/me/.ssh/id"] {
assert_eq!(k(&c(key)).as_deref(), Some(key), "{key}");
}
assert_eq!(k("ssh -i /k/id").as_deref(), Some("/k/id"));
assert_eq!(k("ssh -i /k/id -F /x/config"), None);
assert_eq!(k("ssh -i /k/id -o StrictHostKeyChecking=no"), None);
assert_eq!(k("plink -i /k/id"), None);
assert_eq!(k("ssh"), None);
assert_eq!(k("ssh -i \"/open"), None);
}
#[test]
fn a_path_is_one_double_quoted_word() {
use super::sh_quote_path as q;
assert_eq!(q("/a b/c"), r#""/a b/c""#);
assert_eq!(q(r"C:\Program Files\x.exe"), r#""C:/Program Files/x.exe""#);
assert_eq!(q(r#"a"$`"#), r#""a\"\$\`""#);
}
use super::*;
#[test]
fn only_the_listed_keys_and_values_pass() {
assert!(check_repo_config_value(CORE_AUTOCRLF, "input").is_ok());
assert!(check_repo_config_value(CORE_EOL, "native").is_ok());
assert!(check_repo_config_value(CORE_EOL, "true").is_err());
assert!(check_repo_config_key("core.sshCommand").is_err());
assert!(check_repo_config_key("user.email").is_ok());
assert!(check_repo_config_value(USER_NAME, "Ada Lovelace").is_ok());
assert!(check_repo_config_value(USER_NAME, " ").is_err());
assert!(check_repo_config_value(USER_EMAIL, "a\nb").is_err());
assert!(check_repo_config_key("user.signingkey").is_err());
}
#[test]
fn comment_lines_are_stripped_with_the_configured_character() {
assert_eq!(comment_char(None), '#');
assert_eq!(comment_char(Some("auto")), '#');
assert_eq!(comment_char(Some(";")), ';');
assert_eq!(comment_char(Some(" ")), '#');
assert_eq!(
strip_comment_lines("# note\nfix: a\n\n# more\nbody\n", '#'),
"fix: a\n\nbody"
);
assert_eq!(strip_comment_lines("# a\n # b\nx", '#'), "# b\nx");
assert_eq!(strip_comment_lines("; a\n# b", ';'), "# b");
assert_eq!(strip_comment_lines("# only", '#'), "");
}
}