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