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        /// Adds a file to .gitignore.
106        AddToGitignore,
107    ]
108);
109
110/// Renames a git branch.
111#[derive(Clone, Debug, Default, PartialEq, Deserialize, JsonSchema, Action)]
112#[action(namespace = git)]
113#[serde(deny_unknown_fields)]
114pub struct RenameBranch {
115    /// The branch to rename.
116    ///
117    /// Default: the current branch.
118    #[serde(default)]
119    pub branch: Option<String>,
120}
121
122/// Restores a file to its last committed state, discarding local changes.
123#[derive(Clone, Debug, Default, PartialEq, Deserialize, JsonSchema, Action)]
124#[action(namespace = git, deprecated_aliases = ["editor::RevertFile"])]
125#[serde(deny_unknown_fields)]
126pub struct RestoreFile {
127    #[serde(default)]
128    pub skip_prompt: bool,
129}
130
131/// The length of a Git short SHA.
132pub const SHORT_SHA_LENGTH: usize = 7;
133
134#[derive(Clone, Copy, Eq, Hash, PartialEq)]
135pub struct Oid(libgit::Oid);
136
137impl Oid {
138    pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
139        let oid = libgit::Oid::from_bytes(bytes).context("failed to parse bytes into git oid")?;
140        Ok(Self(oid))
141    }
142
143    #[cfg(any(test, feature = "test-support"))]
144    pub fn random(rng: &mut impl rand::Rng) -> Self {
145        let mut bytes = [0; 20];
146        rng.fill(&mut bytes);
147        Self::from_bytes(&bytes).unwrap()
148    }
149
150    pub fn as_bytes(&self) -> &[u8] {
151        self.0.as_bytes()
152    }
153
154    pub(crate) fn is_zero(&self) -> bool {
155        self.0.is_zero()
156    }
157
158    /// Returns this [`Oid`] as a short SHA.
159    pub fn display_short(&self) -> String {
160        self.to_string().chars().take(SHORT_SHA_LENGTH).collect()
161    }
162}
163
164impl FromStr for Oid {
165    type Err = anyhow::Error;
166
167    fn from_str(s: &str) -> std::prelude::v1::Result<Self, Self::Err> {
168        libgit::Oid::from_str(s)
169            .context("parsing git oid")
170            .map(Self)
171    }
172}
173
174impl fmt::Debug for Oid {
175    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
176        fmt::Display::fmt(self, f)
177    }
178}
179
180impl fmt::Display for Oid {
181    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
182        self.0.fmt(f)
183    }
184}
185
186impl Serialize for Oid {
187    fn serialize<S>(&self, serializer: S) -> std::prelude::v1::Result<S::Ok, S::Error>
188    where
189        S: serde::Serializer,
190    {
191        serializer.serialize_str(&self.0.to_string())
192    }
193}
194
195impl<'de> Deserialize<'de> for Oid {
196    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
197    where
198        D: serde::Deserializer<'de>,
199    {
200        let s = String::deserialize(deserializer)?;
201        s.parse::<Oid>().map_err(serde::de::Error::custom)
202    }
203}
204
205impl Default for Oid {
206    fn default() -> Self {
207        Self(libgit::Oid::zero())
208    }
209}
210
211impl From<Oid> for u32 {
212    fn from(oid: Oid) -> Self {
213        let bytes = oid.0.as_bytes();
214        debug_assert!(bytes.len() > 4);
215
216        let mut u32_bytes: [u8; 4] = [0; 4];
217        u32_bytes.copy_from_slice(&bytes[..4]);
218
219        u32::from_ne_bytes(u32_bytes)
220    }
221}
222
223impl From<Oid> for usize {
224    fn from(oid: Oid) -> Self {
225        let bytes = oid.0.as_bytes();
226        debug_assert!(bytes.len() > 8);
227
228        let mut u64_bytes: [u8; 8] = [0; 8];
229        u64_bytes.copy_from_slice(&bytes[..8]);
230
231        u64::from_ne_bytes(u64_bytes) as usize
232    }
233}
234
235#[repr(i32)]
236#[derive(Copy, Clone, Debug)]
237pub enum RunHook {
238    PreCommit,
239}
240
241impl RunHook {
242    pub fn as_str(&self) -> &str {
243        match self {
244            Self::PreCommit => "pre-commit",
245        }
246    }
247
248    pub fn to_proto(&self) -> i32 {
249        *self as i32
250    }
251
252    pub fn from_proto(value: i32) -> Option<Self> {
253        match value {
254            0 => Some(Self::PreCommit),
255            _ => None,
256        }
257    }
258}