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        /// Fetches changes from the remote repository.
 76        Fetch,
 77        /// Fetches changes from a specific remote.
 78        FetchFrom,
 79        /// Creates a new commit with staged changes.
 80        Commit,
 81        /// Amends the last commit with staged changes.
 82        Amend,
 83        /// Enable the --signoff option.
 84        Signoff,
 85        /// Cancels the current git operation.
 86        Cancel,
 87        /// Expands the commit message editor.
 88        ExpandCommitEditor,
 89        /// Generates a commit message using AI.
 90        GenerateCommitMessage,
 91        /// Initializes a new git repository.
 92        Init,
 93        /// Opens all modified files in the editor.
 94        OpenModifiedFiles,
 95        /// Clones a repository.
 96        Clone,
 97        /// Adds a file to .gitignore.
 98        AddToGitignore,
 99    ]
100);
101
102/// Renames a git branch.
103#[derive(Clone, Debug, Default, PartialEq, Deserialize, JsonSchema, Action)]
104#[action(namespace = git)]
105#[serde(deny_unknown_fields)]
106pub struct RenameBranch {
107    /// The branch to rename.
108    ///
109    /// Default: the current branch.
110    #[serde(default)]
111    pub branch: Option<String>,
112}
113
114/// Restores a file to its last committed state, discarding local changes.
115#[derive(Clone, Debug, Default, PartialEq, Deserialize, JsonSchema, Action)]
116#[action(namespace = git, deprecated_aliases = ["editor::RevertFile"])]
117#[serde(deny_unknown_fields)]
118pub struct RestoreFile {
119    #[serde(default)]
120    pub skip_prompt: bool,
121}
122
123/// The length of a Git short SHA.
124pub const SHORT_SHA_LENGTH: usize = 7;
125
126#[derive(Clone, Copy, Eq, Hash, PartialEq)]
127pub struct Oid(libgit::Oid);
128
129impl Oid {
130    pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
131        let oid = libgit::Oid::from_bytes(bytes).context("failed to parse bytes into git oid")?;
132        Ok(Self(oid))
133    }
134
135    #[cfg(any(test, feature = "test-support"))]
136    pub fn random(rng: &mut impl rand::Rng) -> Self {
137        let mut bytes = [0; 20];
138        rng.fill(&mut bytes);
139        Self::from_bytes(&bytes).unwrap()
140    }
141
142    pub fn as_bytes(&self) -> &[u8] {
143        self.0.as_bytes()
144    }
145
146    pub(crate) fn is_zero(&self) -> bool {
147        self.0.is_zero()
148    }
149
150    /// Returns this [`Oid`] as a short SHA.
151    pub fn display_short(&self) -> String {
152        self.to_string().chars().take(SHORT_SHA_LENGTH).collect()
153    }
154}
155
156impl FromStr for Oid {
157    type Err = anyhow::Error;
158
159    fn from_str(s: &str) -> std::prelude::v1::Result<Self, Self::Err> {
160        libgit::Oid::from_str(s)
161            .context("parsing git oid")
162            .map(Self)
163    }
164}
165
166impl fmt::Debug for Oid {
167    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
168        fmt::Display::fmt(self, f)
169    }
170}
171
172impl fmt::Display for Oid {
173    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
174        self.0.fmt(f)
175    }
176}
177
178impl Serialize for Oid {
179    fn serialize<S>(&self, serializer: S) -> std::prelude::v1::Result<S::Ok, S::Error>
180    where
181        S: serde::Serializer,
182    {
183        serializer.serialize_str(&self.0.to_string())
184    }
185}
186
187impl<'de> Deserialize<'de> for Oid {
188    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
189    where
190        D: serde::Deserializer<'de>,
191    {
192        let s = String::deserialize(deserializer)?;
193        s.parse::<Oid>().map_err(serde::de::Error::custom)
194    }
195}
196
197impl Default for Oid {
198    fn default() -> Self {
199        Self(libgit::Oid::zero())
200    }
201}
202
203impl From<Oid> for u32 {
204    fn from(oid: Oid) -> Self {
205        let bytes = oid.0.as_bytes();
206        debug_assert!(bytes.len() > 4);
207
208        let mut u32_bytes: [u8; 4] = [0; 4];
209        u32_bytes.copy_from_slice(&bytes[..4]);
210
211        u32::from_ne_bytes(u32_bytes)
212    }
213}
214
215impl From<Oid> for usize {
216    fn from(oid: Oid) -> Self {
217        let bytes = oid.0.as_bytes();
218        debug_assert!(bytes.len() > 8);
219
220        let mut u64_bytes: [u8; 8] = [0; 8];
221        u64_bytes.copy_from_slice(&bytes[..8]);
222
223        u64::from_ne_bytes(u64_bytes) as usize
224    }
225}