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