forge
Clone
https://git.tahinli.com/Tahinli/forge.git
0 watching·0 forks·Rust·AGPL-3.0·10.9 MiB·2e29cbc·Tahinli·6 hours ago·333 commits
| 1 | use std::ffi::{OsStr, OsString}; |
| 2 | use std::path::{Path, PathBuf}; |
| 3 | use std::process::{Output, Stdio}; |
| 4 | |
| 5 | use crate::error::{Error, Result}; |
| 6 | |
| 7 | #[derive(Debug, Clone)] |
| 8 | pub struct GitEnv { |
| 9 | pub git_bin: PathBuf, |
| 10 | pub data_dir: PathBuf, |
| 11 | } |
| 12 | |
| 13 | #[derive(Debug, Clone, Copy, Default)] |
| 14 | pub struct ObjectSource<'a> { |
| 15 | pub extra: Option<&'a Path>, |
| 16 | } |
| 17 | |
| 18 | #[derive(Debug)] |
| 19 | pub struct GitCommand { |
| 20 | program: PathBuf, |
| 21 | git_dir: Option<OsString>, |
| 22 | subcommand: &'static str, |
| 23 | args: Vec<OsString>, |
| 24 | envs: Vec<(&'static str, OsString)>, |
| 25 | end_of_options: bool, |
| 26 | local_transport: bool, |
| 27 | configs: Vec<String>, |
| 28 | } |
| 29 | |
| 30 | fn check_user_value(v: &str) -> Result<()> { |
| 31 | if v.is_empty() { |
| 32 | return Err(Error::InvalidInput("empty value".into())); |
| 33 | } |
| 34 | if v.starts_with('-') { |
| 35 | return Err(Error::InvalidInput(format!("value starts with '-': {v}"))); |
| 36 | } |
| 37 | if v.contains('\0') { |
| 38 | return Err(Error::InvalidInput("value contains NUL".into())); |
| 39 | } |
| 40 | Ok(()) |
| 41 | } |
| 42 | |
| 43 | impl GitCommand { |
| 44 | pub fn new(env: &GitEnv, subcommand: &'static str) -> Self { |
| 45 | let envs = vec![ |
| 46 | ("PATH", OsString::from("/usr/local/bin:/usr/bin:/bin")), |
| 47 | ("HOME", env.data_dir.as_os_str().to_os_string()), |
| 48 | ("GIT_CONFIG_NOSYSTEM", OsString::from("1")), |
| 49 | ( |
| 50 | "GIT_CONFIG_GLOBAL", |
| 51 | env.data_dir.join("gitconfig").into_os_string(), |
| 52 | ), |
| 53 | ("GIT_TERMINAL_PROMPT", OsString::from("0")), |
| 54 | ("LANG", OsString::from("C")), |
| 55 | ]; |
| 56 | Self { |
| 57 | program: env.git_bin.clone(), |
| 58 | git_dir: None, |
| 59 | subcommand, |
| 60 | args: Vec::new(), |
| 61 | envs, |
| 62 | end_of_options: false, |
| 63 | local_transport: false, |
| 64 | configs: Vec::new(), |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | pub fn config(mut self, kv: &'static str) -> Self { |
| 69 | self.configs.push(kv.to_string()); |
| 70 | self |
| 71 | } |
| 72 | |
| 73 | pub fn config_checked(mut self, kv: String) -> Result<Self> { |
| 74 | if !kv.contains('=') || kv.chars().any(|c| c.is_whitespace() || c.is_control()) { |
| 75 | return Err(Error::InvalidInput("invalid git config pair".into())); |
| 76 | } |
| 77 | self.configs.push(kv); |
| 78 | Ok(self) |
| 79 | } |
| 80 | |
| 81 | pub fn arg(mut self, a: &'static str) -> Self { |
| 82 | self.args.push(OsString::from(a)); |
| 83 | self |
| 84 | } |
| 85 | |
| 86 | pub fn git_dir(mut self, p: &Path) -> Self { |
| 87 | let mut s = OsString::from("--git-dir="); |
| 88 | s.push(p.as_os_str()); |
| 89 | self.git_dir = Some(s); |
| 90 | self |
| 91 | } |
| 92 | |
| 93 | pub fn allow_local_transport(mut self) -> Self { |
| 94 | self.local_transport = true; |
| 95 | self |
| 96 | } |
| 97 | |
| 98 | pub fn user_revs(mut self, revs: &[&str]) -> Result<Self> { |
| 99 | for r in revs { |
| 100 | check_user_value(r)?; |
| 101 | } |
| 102 | if !self.end_of_options { |
| 103 | self.args.push(OsString::from("--end-of-options")); |
| 104 | self.end_of_options = true; |
| 105 | } |
| 106 | self.args.extend(revs.iter().map(OsString::from)); |
| 107 | Ok(self) |
| 108 | } |
| 109 | |
| 110 | pub fn user_arg(mut self, v: &str) -> Result<Self> { |
| 111 | check_user_value(v)?; |
| 112 | self.args.push(OsString::from(v)); |
| 113 | Ok(self) |
| 114 | } |
| 115 | |
| 116 | pub fn user_pattern(mut self, pattern: &str) -> Result<Self> { |
| 117 | if pattern.is_empty() { |
| 118 | return Err(Error::InvalidInput("empty pattern".into())); |
| 119 | } |
| 120 | if pattern.contains('\0') { |
| 121 | return Err(Error::InvalidInput("pattern contains NUL".into())); |
| 122 | } |
| 123 | self.args.push(OsString::from("-e")); |
| 124 | self.args.push(OsString::from(pattern)); |
| 125 | Ok(self) |
| 126 | } |
| 127 | |
| 128 | pub fn user_opt(mut self, flag: &'static str, v: &str) -> Result<Self> { |
| 129 | check_user_value(v)?; |
| 130 | self.args.push(OsString::from(format!("{flag}={v}"))); |
| 131 | Ok(self) |
| 132 | } |
| 133 | |
| 134 | pub fn paths(mut self, paths: &[&str]) -> Self { |
| 135 | self.args.push(OsString::from("--")); |
| 136 | self.args.extend(paths.iter().map(OsString::from)); |
| 137 | self |
| 138 | } |
| 139 | |
| 140 | pub fn env(mut self, k: &'static str, v: impl AsRef<OsStr>) -> Self { |
| 141 | self.envs.push((k, v.as_ref().to_os_string())); |
| 142 | self |
| 143 | } |
| 144 | |
| 145 | pub fn alternate_objects(mut self, dir: &Path) -> Result<Self> { |
| 146 | let text = dir |
| 147 | .to_str() |
| 148 | .ok_or_else(|| Error::InvalidInput("object dir is not valid UTF-8".into()))?; |
| 149 | if !dir.is_absolute() || text.contains([':', '\n']) { |
| 150 | return Err(Error::InvalidInput(format!("bad object dir: {text:?}"))); |
| 151 | } |
| 152 | if !dir.is_dir() { |
| 153 | return Err(Error::InvalidInput(format!( |
| 154 | "object dir does not exist: {text:?}" |
| 155 | ))); |
| 156 | } |
| 157 | self.envs |
| 158 | .push(("GIT_ALTERNATE_OBJECT_DIRECTORIES", OsString::from(text))); |
| 159 | Ok(self) |
| 160 | } |
| 161 | |
| 162 | pub fn objects(self, src: ObjectSource<'_>) -> Result<Self> { |
| 163 | match src.extra { |
| 164 | Some(dir) => self.alternate_objects(dir), |
| 165 | None => Ok(self), |
| 166 | } |
| 167 | } |
| 168 | |
| 169 | pub fn into_tokio(self) -> tokio::process::Command { |
| 170 | let mut cmd = tokio::process::Command::new(&self.program); |
| 171 | cmd.env_clear(); |
| 172 | for (k, v) in &self.envs { |
| 173 | cmd.env(k, v); |
| 174 | } |
| 175 | if let Some(g) = &self.git_dir { |
| 176 | cmd.arg(g); |
| 177 | } |
| 178 | if self.local_transport { |
| 179 | cmd.args(["-c", "protocol.file.allow=always"]); |
| 180 | } |
| 181 | for kv in &self.configs { |
| 182 | cmd.args(["-c", kv.as_str()]); |
| 183 | } |
| 184 | cmd.arg(self.subcommand); |
| 185 | cmd.args(&self.args); |
| 186 | cmd.stdin(Stdio::null()); |
| 187 | cmd.kill_on_drop(true); |
| 188 | cmd |
| 189 | } |
| 190 | |
| 191 | pub async fn output(self) -> Result<Vec<u8>> { |
| 192 | let subcommand = self.subcommand; |
| 193 | let out = self.into_tokio().output().await?; |
| 194 | check_status(subcommand, &out)?; |
| 195 | Ok(out.stdout) |
| 196 | } |
| 197 | |
| 198 | pub async fn output_stdin(self, input: &[u8]) -> Result<Vec<u8>> { |
| 199 | use tokio::io::AsyncWriteExt; |
| 200 | |
| 201 | let subcommand = self.subcommand; |
| 202 | let mut cmd = self.into_tokio(); |
| 203 | cmd.stdin(Stdio::piped()) |
| 204 | .stdout(Stdio::piped()) |
| 205 | .stderr(Stdio::piped()); |
| 206 | let mut child = cmd.spawn()?; |
| 207 | if let Some(mut stdin) = child.stdin.take() { |
| 208 | stdin.write_all(input).await?; |
| 209 | stdin.shutdown().await?; |
| 210 | } |
| 211 | let out = child.wait_with_output().await?; |
| 212 | check_status(subcommand, &out)?; |
| 213 | Ok(out.stdout) |
| 214 | } |
| 215 | |
| 216 | pub async fn status(self) -> Result<()> { |
| 217 | self.output().await.map(|_| ()) |
| 218 | } |
| 219 | } |
| 220 | |
| 221 | pub(crate) fn failed(subcommand: &str, out: &Output) -> Error { |
| 222 | Error::Failed(format!( |
| 223 | "git {subcommand} exited with {}: {}", |
| 224 | out.status, |
| 225 | String::from_utf8_lossy(&out.stderr).trim() |
| 226 | )) |
| 227 | } |
| 228 | |
| 229 | fn check_status(subcommand: &str, out: &Output) -> Result<()> { |
| 230 | if out.status.success() { |
| 231 | return Ok(()); |
| 232 | } |
| 233 | Err(failed(subcommand, out)) |
| 234 | } |
| 235 | |
| 236 | #[cfg(test)] |
| 237 | mod tests { |
| 238 | use super::*; |
| 239 | |
| 240 | fn env() -> GitEnv { |
| 241 | GitEnv { |
| 242 | git_bin: PathBuf::from("/usr/bin/git"), |
| 243 | data_dir: PathBuf::from("/"), |
| 244 | } |
| 245 | } |
| 246 | |
| 247 | fn alternates_of(cmd: GitCommand) -> Option<OsString> { |
| 248 | cmd.into_tokio() |
| 249 | .as_std() |
| 250 | .get_envs() |
| 251 | .find(|(k, _)| *k == OsStr::new("GIT_ALTERNATE_OBJECT_DIRECTORIES")) |
| 252 | .and_then(|(_, v)| v.map(OsStr::to_os_string)) |
| 253 | } |
| 254 | |
| 255 | #[test] |
| 256 | fn alternate_objects_is_validated_and_set_on_the_child_only() { |
| 257 | let dir = tempfile::tempdir().expect("tempdir"); |
| 258 | let objects = dir.path().join("objects"); |
| 259 | std::fs::create_dir(&objects).expect("objects dir"); |
| 260 | |
| 261 | assert!( |
| 262 | GitCommand::new(&env(), "log") |
| 263 | .alternate_objects(Path::new("objects")) |
| 264 | .is_err() |
| 265 | ); |
| 266 | assert!( |
| 267 | GitCommand::new(&env(), "log") |
| 268 | .alternate_objects(&dir.path().join("nope")) |
| 269 | .is_err() |
| 270 | ); |
| 271 | assert!( |
| 272 | GitCommand::new(&env(), "log") |
| 273 | .alternate_objects(Path::new("/a:b")) |
| 274 | .is_err() |
| 275 | ); |
| 276 | |
| 277 | let set = GitCommand::new(&env(), "log") |
| 278 | .alternate_objects(&objects) |
| 279 | .expect("valid dir"); |
| 280 | assert_eq!(alternates_of(set), Some(objects.clone().into_os_string())); |
| 281 | assert_eq!(alternates_of(GitCommand::new(&env(), "log")), None); |
| 282 | let none = GitCommand::new(&env(), "log") |
| 283 | .objects(ObjectSource::default()) |
| 284 | .expect("no source"); |
| 285 | assert_eq!(alternates_of(none), None); |
| 286 | } |
| 287 | } |