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 at cursor.
 35        ToggleStaged,
 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        /// Stages the current file.
 48        StageFile,
 49        /// Unstages the current file.
 50        UnstageFile,
 51        // repo-wide
 52        /// Stages all changes in the repository.
 53        StageAll,
 54        /// Unstages all changes in the repository.
 55        UnstageAll,
 56        /// Restores all tracked files to their last committed state.
 57        RestoreTrackedFiles,
 58        /// Moves all untracked files to trash.
 59        TrashUntrackedFiles,
 60        /// Undoes the last commit, keeping changes in the working directory.
 61        Uncommit,
 62        /// Pushes commits to the remote repository.
 63        Push,
 64        /// Pushes commits to a specific remote branch.
 65        PushTo,
 66        /// Force pushes commits to the remote repository.
 67        ForcePush,
 68        /// Pulls changes from the remote repository.
 69        Pull,
 70        /// Fetches changes from the remote repository.
 71        Fetch,
 72        /// Fetches changes from a specific remote.
 73        FetchFrom,
 74        /// Creates a new commit with staged changes.
 75        Commit,
 76        /// Amends the last commit with staged changes.
 77        Amend,
 78        /// Cancels the current git operation.
 79        Cancel,
 80        /// Expands the commit message editor.
 81        ExpandCommitEditor,
 82        /// Generates a commit message using AI.
 83        GenerateCommitMessage,
 84        /// Initializes a new git repository.
 85        Init,
 86        /// Opens all modified files in the editor.
 87        OpenModifiedFiles,
 88    ]
 89);
 90
 91/// Restores a file to its last committed state, discarding local changes.
 92#[derive(Clone, Debug, Default, PartialEq, Deserialize, JsonSchema, Action)]
 93#[action(namespace = git, deprecated_aliases = ["editor::RevertFile"])]
 94#[serde(deny_unknown_fields)]
 95pub struct RestoreFile {
 96    #[serde(default)]
 97    pub skip_prompt: bool,
 98}
 99
100/// The length of a Git short SHA.
101pub const SHORT_SHA_LENGTH: usize = 7;
102
103#[derive(Clone, Copy, Eq, Hash, PartialEq)]
104pub struct Oid(libgit::Oid);
105
106impl Oid {
107    pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
108        let oid = libgit::Oid::from_bytes(bytes).context("failed to parse bytes into git oid")?;
109        Ok(Self(oid))
110    }
111
112    pub fn as_bytes(&self) -> &[u8] {
113        self.0.as_bytes()
114    }
115
116    pub(crate) fn is_zero(&self) -> bool {
117        self.0.is_zero()
118    }
119
120    /// Returns this [`Oid`] as a short SHA.
121    pub fn display_short(&self) -> String {
122        self.to_string().chars().take(SHORT_SHA_LENGTH).collect()
123    }
124}
125
126impl FromStr for Oid {
127    type Err = anyhow::Error;
128
129    fn from_str(s: &str) -> std::prelude::v1::Result<Self, Self::Err> {
130        libgit::Oid::from_str(s)
131            .context("parsing git oid")
132            .map(Self)
133    }
134}
135
136impl fmt::Debug for Oid {
137    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
138        fmt::Display::fmt(self, f)
139    }
140}
141
142impl fmt::Display for Oid {
143    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
144        self.0.fmt(f)
145    }
146}
147
148impl Serialize for Oid {
149    fn serialize<S>(&self, serializer: S) -> std::prelude::v1::Result<S::Ok, S::Error>
150    where
151        S: serde::Serializer,
152    {
153        serializer.serialize_str(&self.0.to_string())
154    }
155}
156
157impl<'de> Deserialize<'de> for Oid {
158    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
159    where
160        D: serde::Deserializer<'de>,
161    {
162        let s = String::deserialize(deserializer)?;
163        s.parse::<Oid>().map_err(serde::de::Error::custom)
164    }
165}
166
167impl Default for Oid {
168    fn default() -> Self {
169        Self(libgit::Oid::zero())
170    }
171}
172
173impl From<Oid> for u32 {
174    fn from(oid: Oid) -> Self {
175        let bytes = oid.0.as_bytes();
176        debug_assert!(bytes.len() > 4);
177
178        let mut u32_bytes: [u8; 4] = [0; 4];
179        u32_bytes.copy_from_slice(&bytes[..4]);
180
181        u32::from_ne_bytes(u32_bytes)
182    }
183}
184
185impl From<Oid> for usize {
186    fn from(oid: Oid) -> Self {
187        let bytes = oid.0.as_bytes();
188        debug_assert!(bytes.len() > 8);
189
190        let mut u64_bytes: [u8; 8] = [0; 8];
191        u64_bytes.copy_from_slice(&bytes[..8]);
192
193        u64::from_ne_bytes(u64_bytes) as usize
194    }
195}