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