LINE1 10 20 30 40 50 60 70 80 901#[cfg(not(feature = "testing"))]2use std::process::{Command, Output};34#[cfg(all(test, not(feature = "testing")))]5use std::path::PathBuf;67#[cfg(not(feature = "testing"))]8use anyhow::{Context, bail};910use crate::server_url::TwigUrl;1112pub trait GitConfigurator {13 fn check_git_available(&self) -> anyhow::Result<()>;14 fn ensure_tree_helper(&self, server: &TwigUrl) -> anyhow::Result<()>;15}1617#[cfg(not(feature = "testing"))]18pub struct GitConfig {19 #[cfg(all(test, not(feature = "testing")))]20 global_file: Option<PathBuf>,21}2223#[cfg(not(feature = "testing"))]24impl GitConfig {25 pub fn global() -> Self {26 Self {27 #[cfg(all(test, not(feature = "testing")))]28 global_file: None,29 }30 }3132 #[cfg(all(test, not(feature = "testing")))]33 pub fn with_global_file(path: PathBuf) -> Self {34 Self {35 global_file: Some(path),36 }37 }3839 pub fn check_git_available(&self) -> anyhow::Result<()> {40 let output = self.run(["--version"])?;41 if !output.status.success() {42 bail!("Git is required to configure Twig credentials");43 }44 Ok(())45 }4647 pub fn ensure_tree_helper(&self, server: &TwigUrl) -> anyhow::Result<()> {48 let url = server.as_url().as_str();49 let helper_key = format!("credential.{url}.helper");50 let helper_value = format!("!tree credential --url {}", shell_quote(url));5152 let existing = self.read_all(&helper_key)?;53 if !existing.iter().any(|value| value == &helper_value) {54 let output = self.run(["config", "--global", "--add", &helper_key, &helper_value])?;55 ensure_success(output, "Failed to add the Twig Git credential helper")?;56 }5758 let path_key = format!("credential.{url}.useHttpPath");59 if !self60 .read_all(&path_key)?61 .iter()62 .any(|value| value.eq_ignore_ascii_case("true"))63 {64 let output = self.run(["config", "--global", "--replace-all", &path_key, "true"])?;65 ensure_success(output, "Failed to enable path-aware Twig credentials")?;66 }6768 Ok(())69 }7071 fn read_all(&self, key: &str) -> anyhow::Result<Vec<String>> {72 let output = self.run(["config", "--global", "--get-all", key])?;73 if output.status.success() {74 return Ok(String::from_utf8(output.stdout)75 .context("Git config output was not valid UTF-8")?76 .lines()77 .map(str::to_owned)78 .collect());79 }80 if output.status.code() == Some(1) {81 return Ok(Vec::new());82 }83 ensure_success(output, "Failed to read global Git configuration")?;84 unreachable!("ensure_success returns an error for unsuccessful output")85 }8687 fn run<const N: usize>(&self, args: [&str; N]) -> anyhow::Result<Output> {88 let mut command = Command::new("git");89 command.args(args);90 #[cfg(all(test, not(feature = "testing")))]91 if let Some(global_file) = &self.global_file {92 command.env("GIT_CONFIG_GLOBAL", global_file);93 }94 command.output().context("Failed to run Git")95 }96}9798#[cfg(not(feature = "testing"))]99impl GitConfigurator for GitConfig {100 fn check_git_available(&self) -> anyhow::Result<()> {101 GitConfig::check_git_available(self)102 }103104 fn ensure_tree_helper(&self, server: &TwigUrl) -> anyhow::Result<()> {105 GitConfig::ensure_tree_helper(self, server)106 }107}108109#[cfg(not(feature = "testing"))]110fn ensure_success(output: Output, message: &str) -> anyhow::Result<()> {111 if output.status.success() {112 return Ok(());113 }114 let stderr = String::from_utf8_lossy(&output.stderr);115 bail!("{message}: {}", stderr.trim());116}117118#[cfg(not(feature = "testing"))]119fn shell_quote(value: &str) -> String {120 format!("'{}'", value.replace('\'', "'\\''"))121}122123#[cfg(all(test, not(feature = "testing")))]124mod tests {125 use std::{126 fs,127 time::{SystemTime, UNIX_EPOCH},128 };129130 use super::*;131132 fn temp_config_path() -> PathBuf {133 let unique = SystemTime::now()134 .duration_since(UNIX_EPOCH)135 .expect("clock after epoch")136 .as_nanos();137 std::env::temp_dir().join(format!("tree-git-config-{}-{unique}", std::process::id()))138 }139140 #[test]141 fn registration_is_idempotent_and_preserves_other_url_helpers() {142 let path = temp_config_path();143 let git = GitConfig::with_global_file(path.clone());144 let server = TwigUrl::parse("https://twig.example.dev/").unwrap();145146 git.ensure_tree_helper(&server).unwrap();147 git.ensure_tree_helper(&server).unwrap();148149 let url = server.as_url().as_str();150 let helper_key = format!("credential.{url}.helper");151 let helpers = git.read_all(&helper_key).unwrap();152 assert_eq!(helpers.len(), 1);153 assert_eq!(154 helpers[0],155 "!tree credential --url 'https://twig.example.dev/'"156 );157 assert_eq!(158 git.read_all(&format!("credential.{url}.useHttpPath"))159 .unwrap(),160 ["true"]161 );162163 let other_helpers = git.read_all("credential.https://other.example.dev.helper");164 assert!(other_helpers.unwrap().is_empty());165166 let matching_url = git167 .run([168 "config",169 "--global",170 "--get-urlmatch",171 "credential.helper",172 "https://twig.example.dev/ns/repo.git",173 ])174 .unwrap();175 assert!(matching_url.status.success());176 assert!(String::from_utf8_lossy(&matching_url.stdout).contains("!tree credential"));177178 let unrelated_url = git179 .run([180 "config",181 "--global",182 "--get-urlmatch",183 "credential.helper",184 "https://other.example.dev/ns/repo.git",185 ])186 .unwrap();187 assert!(!unrelated_url.status.success());188189 let path_scoped = GitConfig::with_global_file(path.clone());190 let scoped_url = TwigUrl::parse("https://git.example.dev/twig/").unwrap();191 path_scoped.ensure_tree_helper(&scoped_url).unwrap();192 let under_prefix = path_scoped193 .run([194 "config",195 "--global",196 "--get-urlmatch",197 "credential.helper",198 "https://git.example.dev/twig/ns/repo.git",199 ])200 .unwrap();201 assert!(under_prefix.status.success());202 let outside_prefix = path_scoped203 .run([204 "config",205 "--global",206 "--get-urlmatch",207 "credential.helper",208 "https://git.example.dev/other/repo.git",209 ])210 .unwrap();211 assert!(!outside_prefix.status.success());212 let _ = fs::remove_file(path);213 }214215 #[test]216 fn git_is_available_for_the_auth_flow() {217 GitConfig::global()218 .check_git_available()219 .expect("Git should be installed for repository tests");220 }221}