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";
 26
 27actions!(
 28    git,
 29    [
 30        // per-hunk
 31        /// Toggles the staged state of the hunk or status entry at cursor.
 32        ToggleStaged,
 33        /// Stage status entries between an anchor entry and the cursor.
 34        StageRange,
 35        /// Stages the current hunk and moves to the next one.
 36        StageAndNext,
 37        /// Unstages the current hunk and moves to the next one.
 38        UnstageAndNext,
 39        /// Restores the selected hunks to their original state.
 40        #[action(deprecated_aliases = ["editor::RevertSelectedHunks"])]
 41        Restore,
 42        // per-file
 43        /// Shows git blame information for the current file.
 44        #[action(deprecated_aliases = ["editor::ToggleGitBlame"])]
 45        Blame,
 46        /// Stages the current file.
 47        StageFile,
 48        /// Unstages the current file.
 49        UnstageFile,
 50        // repo-wide
 51        /// Stages all changes in the repository.
 52        StageAll,
 53        /// Unstages all changes in the repository.
 54        UnstageAll,
 55        /// Stashes all changes in the repository, including untracked files.
 56        StashAll,
 57        /// Pops the most recent stash.
 58        StashPop,
 59        /// Apply the most recent stash.
 60        StashApply,
 61        /// Restores all tracked files to their last committed state.
 62        RestoreTrackedFiles,
 63        /// Moves all untracked files to trash.
 64        TrashUntrackedFiles,
 65        /// Undoes the last commit, keeping changes in the working directory.
 66        Uncommit,
 67        /// Pushes commits to the remote repository.
 68        Push,
 69        /// Pushes commits to a specific remote branch.
 70        PushTo,
 71        /// Force pushes commits to the remote repository.
 72        ForcePush,
 73        /// Pulls changes from the remote repository.
 74        Pull,
 75        /// Pulls changes from the remote repository with rebase.
 76        PullRebase,
 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        /// Adds a file to .gitignore.
100        AddToGitignore,
101    ]
102);
103
104/// Renames a git branch.
105#[derive(Clone, Debug, Default, PartialEq, Deserialize, JsonSchema, Action)]
106#[action(namespace = git)]
107#[serde(deny_unknown_fields)]
108pub struct RenameBranch {
109    /// The branch to rename.
110    ///
111    /// Default: the current branch.
112    #[serde(default)]
113    pub branch: Option<String>,
114}
115
116/// Restores a file to its last committed state, discarding local changes.
117#[derive(Clone, Debug, Default, PartialEq, Deserialize, JsonSchema, Action)]
118#[action(namespace = git, deprecated_aliases = ["editor::RevertFile"])]
119#[serde(deny_unknown_fields)]
120pub struct RestoreFile {
121    #[serde(default)]
122    pub skip_prompt: bool,
123}
124
125/// The length of a Git short SHA.
126pub const SHORT_SHA_LENGTH: usize = 7;
127
128#[derive(Clone, Copy, Eq, Hash, PartialEq)]
129pub struct Oid(libgit::Oid);
130
131impl Oid {
132    pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
133        let oid = libgit::Oid::from_bytes(bytes).context("failed to parse bytes into git oid")?;
134        Ok(Self(oid))
135    }
136
137    #[cfg(any(test, feature = "test-support"))]
138    pub fn random(rng: &mut impl rand::Rng) -> Self {
139        let mut bytes = [0; 20];
140        rng.fill(&mut bytes);
141        Self::from_bytes(&bytes).unwrap()
142    }
143
144    pub fn as_bytes(&self) -> &[u8] {
145        self.0.as_bytes()
146    }
147
148    pub(crate) fn is_zero(&self) -> bool {
149        self.0.is_zero()
150    }
151
152    /// Returns this [`Oid`] as a short SHA.
153    pub fn display_short(&self) -> String {
154        self.to_string().chars().take(SHORT_SHA_LENGTH).collect()
155    }
156}
157
158impl FromStr for Oid {
159    type Err = anyhow::Error;
160
161    fn from_str(s: &str) -> std::prelude::v1::Result<Self, Self::Err> {
162        libgit::Oid::from_str(s)
163            .context("parsing git oid")
164            .map(Self)
165    }
166}
167
168impl fmt::Debug for Oid {
169    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
170        fmt::Display::fmt(self, f)
171    }
172}
173
174impl fmt::Display for Oid {
175    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
176        self.0.fmt(f)
177    }
178}
179
180impl Serialize for Oid {
181    fn serialize<S>(&self, serializer: S) -> std::prelude::v1::Result<S::Ok, S::Error>
182    where
183        S: serde::Serializer,
184    {
185        serializer.serialize_str(&self.0.to_string())
186    }
187}
188
189impl<'de> Deserialize<'de> for Oid {
190    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
191    where
192        D: serde::Deserializer<'de>,
193    {
194        let s = String::deserialize(deserializer)?;
195        s.parse::<Oid>().map_err(serde::de::Error::custom)
196    }
197}
198
199impl Default for Oid {
200    fn default() -> Self {
201        Self(libgit::Oid::zero())
202    }
203}
204
205impl From<Oid> for u32 {
206    fn from(oid: Oid) -> Self {
207        let bytes = oid.0.as_bytes();
208        debug_assert!(bytes.len() > 4);
209
210        let mut u32_bytes: [u8; 4] = [0; 4];
211        u32_bytes.copy_from_slice(&bytes[..4]);
212
213        u32::from_ne_bytes(u32_bytes)
214    }
215}
216
217impl From<Oid> for usize {
218    fn from(oid: Oid) -> Self {
219        let bytes = oid.0.as_bytes();
220        debug_assert!(bytes.len() > 8);
221
222        let mut u64_bytes: [u8; 8] = [0; 8];
223        u64_bytes.copy_from_slice(&bytes[..8]);
224
225        u64::from_ne_bytes(u64_bytes) as usize
226    }
227}