git.rs

  1pub mod blame;
  2pub mod commit;
  3mod hosting_provider;
  4mod remote;
  5pub mod repository;
  6pub mod status;
  7
  8pub use crate::hosting_provider::*;
  9pub use crate::remote::*;
 10use anyhow::{Context as _, Result};
 11pub use git2 as libgit;
 12use gpui::{Action, actions};
 13pub use repository::WORK_DIRECTORY_REPO_PATH;
 14pub use repository::{GitCommandOutput, RemoteCommandOutput};
 15use schemars::JsonSchema;
 16use serde::{Deserialize, Serialize};
 17use std::ffi::OsStr;
 18use std::fmt;
 19use std::str::FromStr;
 20use std::sync::LazyLock;
 21
 22pub static DOT_GIT: LazyLock<&'static OsStr> = LazyLock::new(|| OsStr::new(".git"));
 23pub static GITIGNORE: LazyLock<&'static OsStr> = LazyLock::new(|| OsStr::new(".gitignore"));
 24pub static FSMONITOR_DAEMON: LazyLock<&'static OsStr> =
 25    LazyLock::new(|| OsStr::new("fsmonitor--daemon"));
 26pub static LFS_DIR: LazyLock<&'static OsStr> = LazyLock::new(|| OsStr::new("lfs"));
 27pub static COMMIT_MESSAGE: LazyLock<&'static OsStr> =
 28    LazyLock::new(|| OsStr::new("COMMIT_EDITMSG"));
 29pub static INDEX_LOCK: LazyLock<&'static OsStr> = LazyLock::new(|| OsStr::new("index.lock"));
 30
 31actions!(
 32    git,
 33    [
 34        // per-hunk
 35        /// Toggles the staged state of the hunk or status entry at cursor.
 36        ToggleStaged,
 37        /// Stage status entries between an anchor entry and the cursor.
 38        StageRange,
 39        /// Stages the current hunk and moves to the next one.
 40        StageAndNext,
 41        /// Unstages the current hunk and moves to the next one.
 42        UnstageAndNext,
 43        /// Restores the selected hunks to their original state.
 44        #[action(deprecated_aliases = ["editor::RevertSelectedHunks"])]
 45        Restore,
 46        // per-file
 47        /// Shows git blame information for the current file.
 48        #[action(deprecated_aliases = ["editor::ToggleGitBlame"])]
 49        Blame,
 50        /// Stages the current file.
 51        StageFile,
 52        /// Unstages the current file.
 53        UnstageFile,
 54        // repo-wide
 55        /// Stages all changes in the repository.
 56        StageAll,
 57        /// Unstages all changes in the repository.
 58        UnstageAll,
 59        /// Stashes all changes in the repository, including untracked files.
 60        StashAll,
 61        /// Pops the most recent stash.
 62        StashPop,
 63        /// Restores all tracked files to their last committed state.
 64        RestoreTrackedFiles,
 65        /// Moves all untracked files to trash.
 66        TrashUntrackedFiles,
 67        /// Undoes the last commit, keeping changes in the working directory.
 68        Uncommit,
 69        /// Pushes commits to the remote repository.
 70        Push,
 71        /// Pushes commits to a specific remote branch.
 72        PushTo,
 73        /// Force pushes commits to the remote repository.
 74        ForcePush,
 75        /// Pulls changes from the remote repository.
 76        Pull,
 77        /// Fetches changes from the remote repository.
 78        Fetch,
 79        /// Fetches changes from a specific remote.
 80        FetchFrom,
 81        /// Creates a new commit with staged changes.
 82        Commit,
 83        /// Amends the last commit with staged changes.
 84        Amend,
 85        /// Enable the --signoff option.
 86        Signoff,
 87        /// Cancels the current git operation.
 88        Cancel,
 89        /// Expands the commit message editor.
 90        ExpandCommitEditor,
 91        /// Generates a commit message using AI.
 92        GenerateCommitMessage,
 93        /// Initializes a new git repository.
 94        Init,
 95        /// Opens all modified files in the editor.
 96        OpenModifiedFiles,
 97        /// Clones a repository.
 98        Clone,
 99    ]
100);
101
102/// Renames a git branch.
103#[derive(Clone, Debug, Default, PartialEq, Deserialize, JsonSchema, Action)]
104#[action(namespace = git)]
105#[serde(deny_unknown_fields)]
106pub struct RenameBranch {
107    /// The branch to rename.
108    ///
109    /// Default: the current branch.
110    #[serde(default)]
111    pub branch: Option<String>,
112}
113
114/// Restores a file to its last committed state, discarding local changes.
115#[derive(Clone, Debug, Default, PartialEq, Deserialize, JsonSchema, Action)]
116#[action(namespace = git, deprecated_aliases = ["editor::RevertFile"])]
117#[serde(deny_unknown_fields)]
118pub struct RestoreFile {
119    #[serde(default)]
120    pub skip_prompt: bool,
121}
122
123/// The length of a Git short SHA.
124pub const SHORT_SHA_LENGTH: usize = 7;
125
126#[derive(Clone, Copy, Eq, Hash, PartialEq)]
127pub struct Oid(libgit::Oid);
128
129impl Oid {
130    pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
131        let oid = libgit::Oid::from_bytes(bytes).context("failed to parse bytes into git oid")?;
132        Ok(Self(oid))
133    }
134
135    #[cfg(any(test, feature = "test-support"))]
136    pub fn random(rng: &mut impl rand::Rng) -> Self {
137        let mut bytes = [0; 20];
138        rng.fill(&mut bytes);
139        Self::from_bytes(&bytes).unwrap()
140    }
141
142    pub fn as_bytes(&self) -> &[u8] {
143        self.0.as_bytes()
144    }
145
146    pub(crate) fn is_zero(&self) -> bool {
147        self.0.is_zero()
148    }
149
150    /// Returns this [`Oid`] as a short SHA.
151    pub fn display_short(&self) -> String {
152        self.to_string().chars().take(SHORT_SHA_LENGTH).collect()
153    }
154}
155
156impl FromStr for Oid {
157    type Err = anyhow::Error;
158
159    fn from_str(s: &str) -> std::prelude::v1::Result<Self, Self::Err> {
160        libgit::Oid::from_str(s)
161            .context("parsing git oid")
162            .map(Self)
163    }
164}
165
166impl fmt::Debug for Oid {
167    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
168        fmt::Display::fmt(self, f)
169    }
170}
171
172impl fmt::Display for Oid {
173    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
174        self.0.fmt(f)
175    }
176}
177
178impl Serialize for Oid {
179    fn serialize<S>(&self, serializer: S) -> std::prelude::v1::Result<S::Ok, S::Error>
180    where
181        S: serde::Serializer,
182    {
183        serializer.serialize_str(&self.0.to_string())
184    }
185}
186
187impl<'de> Deserialize<'de> for Oid {
188    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
189    where
190        D: serde::Deserializer<'de>,
191    {
192        let s = String::deserialize(deserializer)?;
193        s.parse::<Oid>().map_err(serde::de::Error::custom)
194    }
195}
196
197impl Default for Oid {
198    fn default() -> Self {
199        Self(libgit::Oid::zero())
200    }
201}
202
203impl From<Oid> for u32 {
204    fn from(oid: Oid) -> Self {
205        let bytes = oid.0.as_bytes();
206        debug_assert!(bytes.len() > 4);
207
208        let mut u32_bytes: [u8; 4] = [0; 4];
209        u32_bytes.copy_from_slice(&bytes[..4]);
210
211        u32::from_ne_bytes(u32_bytes)
212    }
213}
214
215impl From<Oid> for usize {
216    fn from(oid: Oid) -> Self {
217        let bytes = oid.0.as_bytes();
218        debug_assert!(bytes.len() > 8);
219
220        let mut u64_bytes: [u8; 8] = [0; 8];
221        u64_bytes.copy_from_slice(&bytes[..8]);
222
223        u64::from_ne_bytes(u64_bytes) as usize
224    }
225}