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 TryFrom<&str> for Oid {
165 type Error = anyhow::Error;
166
167 fn try_from(value: &str) -> std::prelude::v1::Result<Self, Self::Error> {
168 Oid::from_str(value)
169 }
170}
171
172impl FromStr for Oid {
173 type Err = anyhow::Error;
174
175 fn from_str(s: &str) -> std::prelude::v1::Result<Self, Self::Err> {
176 libgit::Oid::from_str(s)
177 .context("parsing git oid")
178 .map(Self)
179 }
180}
181
182impl fmt::Debug for Oid {
183 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
184 fmt::Display::fmt(self, f)
185 }
186}
187
188impl fmt::Display for Oid {
189 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
190 self.0.fmt(f)
191 }
192}
193
194impl Serialize for Oid {
195 fn serialize<S>(&self, serializer: S) -> std::prelude::v1::Result<S::Ok, S::Error>
196 where
197 S: serde::Serializer,
198 {
199 serializer.serialize_str(&self.0.to_string())
200 }
201}
202
203impl<'de> Deserialize<'de> for Oid {
204 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
205 where
206 D: serde::Deserializer<'de>,
207 {
208 let s = String::deserialize(deserializer)?;
209 s.parse::<Oid>().map_err(serde::de::Error::custom)
210 }
211}
212
213impl Default for Oid {
214 fn default() -> Self {
215 Self(libgit::Oid::zero())
216 }
217}
218
219impl From<Oid> for u32 {
220 fn from(oid: Oid) -> Self {
221 let bytes = oid.0.as_bytes();
222 debug_assert!(bytes.len() > 4);
223
224 let mut u32_bytes: [u8; 4] = [0; 4];
225 u32_bytes.copy_from_slice(&bytes[..4]);
226
227 u32::from_ne_bytes(u32_bytes)
228 }
229}
230
231impl From<Oid> for usize {
232 fn from(oid: Oid) -> Self {
233 let bytes = oid.0.as_bytes();
234 debug_assert!(bytes.len() > 8);
235
236 let mut u64_bytes: [u8; 8] = [0; 8];
237 u64_bytes.copy_from_slice(&bytes[..8]);
238
239 u64::from_ne_bytes(u64_bytes) as usize
240 }
241}
242
243#[repr(i32)]
244#[derive(Copy, Clone, Debug)]
245pub enum RunHook {
246 PreCommit,
247}
248
249impl RunHook {
250 pub fn as_str(&self) -> &str {
251 match self {
252 Self::PreCommit => "pre-commit",
253 }
254 }
255
256 pub fn to_proto(&self) -> i32 {
257 *self as i32
258 }
259
260 pub fn from_proto(value: i32) -> Option<Self> {
261 match value {
262 0 => Some(Self::PreCommit),
263 _ => None,
264 }
265 }
266}