git.rs

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