|
| 1 | +use std::io::Write; |
| 2 | +use std::path::{Path, PathBuf}; |
| 3 | +use std::process::{Command, Stdio}; |
| 4 | + |
| 5 | +use serde::Deserialize; |
| 6 | +use tracing::debug; |
| 7 | + |
| 8 | +#[derive(Debug, thiserror::Error)] |
| 9 | +pub enum VersionControlError { |
| 10 | + #[error("Attempted to initialize a Git repository, but `git` was not found in PATH")] |
| 11 | + GitNotInstalled, |
| 12 | + #[error("Failed to initialize Git repository at `{0}`\nstdout: {1}\nstderr: {2}")] |
| 13 | + GitInit(PathBuf, String, String), |
| 14 | + #[error("`git` command failed")] |
| 15 | + GitCommand(#[source] std::io::Error), |
| 16 | + #[error(transparent)] |
| 17 | + Io(#[from] std::io::Error), |
| 18 | +} |
| 19 | + |
| 20 | +/// The version control system to use. |
| 21 | +#[derive(Clone, Copy, Debug, PartialEq, Default, Deserialize)] |
| 22 | +#[serde(deny_unknown_fields, rename_all = "kebab-case")] |
| 23 | +#[cfg_attr(feature = "clap", derive(clap::ValueEnum))] |
| 24 | +#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))] |
| 25 | +pub enum VersionControlSystem { |
| 26 | + /// Use Git for version control. |
| 27 | + #[default] |
| 28 | + Git, |
| 29 | + /// Do not use any version control system. |
| 30 | + None, |
| 31 | +} |
| 32 | + |
| 33 | +impl VersionControlSystem { |
| 34 | + /// Initializes the VCS system based on the provided path. |
| 35 | + pub fn init(&self, path: &Path) -> Result<(), VersionControlError> { |
| 36 | + match self { |
| 37 | + Self::Git => { |
| 38 | + let Ok(git) = which::which("git") else { |
| 39 | + return Err(VersionControlError::GitNotInstalled); |
| 40 | + }; |
| 41 | + |
| 42 | + if path.join(".git").try_exists()? { |
| 43 | + debug!("Git repository already exists at: `{}`", path.display()); |
| 44 | + } else { |
| 45 | + let output = Command::new(git) |
| 46 | + .arg("init") |
| 47 | + .current_dir(path) |
| 48 | + .stdout(Stdio::piped()) |
| 49 | + .stderr(Stdio::piped()) |
| 50 | + .output() |
| 51 | + .map_err(VersionControlError::GitCommand)?; |
| 52 | + if !output.status.success() { |
| 53 | + let stdout = String::from_utf8_lossy(&output.stdout); |
| 54 | + let stderr = String::from_utf8_lossy(&output.stderr); |
| 55 | + return Err(VersionControlError::GitInit( |
| 56 | + path.to_path_buf(), |
| 57 | + stdout.to_string(), |
| 58 | + stderr.to_string(), |
| 59 | + )); |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + // Create the `.gitignore`, if it doesn't exist. |
| 64 | + match fs_err::OpenOptions::new() |
| 65 | + .write(true) |
| 66 | + .create_new(true) |
| 67 | + .open(path.join(".gitignore")) |
| 68 | + { |
| 69 | + Ok(mut file) => file.write_all(GITIGNORE.as_bytes())?, |
| 70 | + Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => (), |
| 71 | + Err(err) => return Err(err.into()), |
| 72 | + } |
| 73 | + |
| 74 | + Ok(()) |
| 75 | + } |
| 76 | + Self::None => Ok(()), |
| 77 | + } |
| 78 | + } |
| 79 | + |
| 80 | + /// Detects the VCS system based on the provided path. |
| 81 | + pub fn detect(path: &Path) -> Option<Self> { |
| 82 | + // Determine whether the path is inside a Git work tree. |
| 83 | + if which::which("git").is_ok_and(|git| { |
| 84 | + Command::new(git) |
| 85 | + .arg("rev-parse") |
| 86 | + .arg("--is-inside-work-tree") |
| 87 | + .current_dir(path) |
| 88 | + .stdout(Stdio::null()) |
| 89 | + .stderr(Stdio::null()) |
| 90 | + .status() |
| 91 | + .map(|status| status.success()) |
| 92 | + .unwrap_or(false) |
| 93 | + }) { |
| 94 | + return Some(Self::Git); |
| 95 | + } |
| 96 | + |
| 97 | + None |
| 98 | + } |
| 99 | +} |
| 100 | + |
| 101 | +impl std::fmt::Display for VersionControlSystem { |
| 102 | + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 103 | + match self { |
| 104 | + Self::Git => write!(f, "git"), |
| 105 | + Self::None => write!(f, "none"), |
| 106 | + } |
| 107 | + } |
| 108 | +} |
| 109 | + |
| 110 | +const GITIGNORE: &str = "# Python-generated files |
| 111 | +__pycache__/ |
| 112 | +*.py[oc] |
| 113 | +build/ |
| 114 | +dist/ |
| 115 | +wheels/ |
| 116 | +*.egg-info |
| 117 | +
|
| 118 | +# Virtual environments |
| 119 | +.venv |
| 120 | +"; |
0 commit comments