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