Skip to content

armgit / zed

Public Imported from GitHub
0

Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.

git_ui: Add option to commit with --no-verify (#61529)

Smit Barmaseb2a4fb47b1d4
diff --git a/crates/git/src/git.rs b/crates/git/src/git.rs
index 4bb16a39515..bb74142139e 100644
--- a/crates/git/src/git.rs
+++ b/crates/git/src/git.rs
@@ -100,6 +100,8 @@ actions!(
FetchFrom,
/// Creates a new commit with staged changes.
Commit,
+ /// Runs the next commit with `git commit --no-verify`.
+ SkipHooks,
/// Amends the last commit with staged changes.
Amend,
/// Enable the --signoff option.
diff --git a/crates/git/src/repository.rs b/crates/git/src/repository.rs
index c4daf3ff87a..528d1fdfebf 100644
--- a/crates/git/src/repository.rs
+++ b/crates/git/src/repository.rs
@@ -458,6 +458,7 @@ pub struct CommitOptions {
pub amend: bool,
pub signoff: bool,
pub allow_empty: bool,
+ pub no_verify: bool,
}
#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
@@ -2561,6 +2562,10 @@ impl GitRepository for RealGitRepository {
cmd.arg("--allow-empty");
}
+ if options.no_verify {
+ cmd.arg("--no-verify");
+ }
+
if let Some((name, email)) = name_and_email {
cmd.arg("--author").arg(&format!("{name} <{email}>"));
}
@@ -5031,6 +5036,28 @@ mod tests {
let message = git_command_output(repo_dir.path(), ["log", "-1", "--pretty=%B"]);
assert_eq!(message, "rewritten by commit-msg hook");
+
+ write_hook("pre-commit", "#!/bin/sh\nexit 1\n");
+ fs::write(repo_dir.path().join("file"), "three").unwrap();
+ repo.stage_paths(vec![repo_path("file")], Arc::new(HashMap::default()))
+ .await
+ .unwrap();
+
+ repo.commit(
+ "Commit without verification".into(),
+ None,
+ CommitOptions {
+ no_verify: true,
+ ..Default::default()
+ },
+ AskPassDelegate::new(&mut cx.to_async(), |_, _, _| {}),
+ Arc::new(test_commit_envs()),
+ )
+ .await
+ .expect("--no-verify should skip pre-commit and commit-msg hooks");
+
+ let message = git_command_output(repo_dir.path(), ["log", "-1", "--pretty=%B"]);
+ assert_eq!(message, "Commit without verification");
}
#[gpui::test]
diff --git a/crates/git_ui/src/commit_modal.rs b/crates/git_ui/src/commit_modal.rs
index 7ba5558dd95..d36bc840004 100644
--- a/crates/git_ui/src/commit_modal.rs
+++ b/crates/git_ui/src/commit_modal.rs
@@ -3,13 +3,12 @@ use crate::git_panel::{
GitPanel, commit_message_editor, commit_title_exceeds_limit, git_commit_editor_style,
};
use crate::git_panel_settings::GitPanelSettings;
-use git::repository::CommitOptions;
-use git::{Amend, Commit, GenerateCommitMessage, Signoff};
+use git::{Amend, Commit, GenerateCommitMessage, Signoff, SkipHooks};
use project::DisableAiSettings;
use settings::Settings;
use ui::{
- ButtonLike, ContextMenu, ElevationIndex, KeybindingHint, PopoverMenu, PopoverMenuHandle,
- SplitButton, Tooltip, prelude::*,
+ ButtonLike, ContextMenu, ContextMenuEntry, DocumentationSide, ElevationIndex, KeybindingHint,
+ PopoverMenu, PopoverMenuHandle, SplitButton, Tooltip, prelude::*,
};
use zed_actions::{DecreaseBufferFontSize, IncreaseBufferFontSize, ResetBufferFontSize};
@@ -287,6 +286,7 @@ impl CommitModal {
let git_panel = git_panel_entity.read(cx);
let amend_enabled = git_panel.amend_pending();
let signoff_enabled = git_panel.signoff_enabled();
+ let skip_hooks_enabled = git_panel.skip_hooks_enabled();
let has_previous_commit = git_panel.head_commit(cx).is_some();
Some(ContextMenu::build(window, cx, |context_menu, _, _| {
@@ -326,6 +326,17 @@ impl CommitModal {
}
},
)
+ .item(
+ ContextMenuEntry::new("Skip Hooks")
+ .toggleable(IconPosition::Start, skip_hooks_enabled)
+ .action(Box::new(SkipHooks))
+ .handler(move |window, cx| {
+ window.dispatch_action(Box::new(SkipHooks), cx)
+ })
+ .documentation_aside(DocumentationSide::Left, |_| {
+ Label::new("git commit --no-verify").into_any_element()
+ }),
+ )
}))
}
})
@@ -344,8 +355,7 @@ impl CommitModal {
co_authors,
generate_commit_message,
active_repo,
- is_amend_pending,
- is_signoff_enabled,
+ commit_options,
workspace,
is_generating,
) = self.git_panel.update(cx, |git_panel, cx| {
@@ -354,8 +364,7 @@ impl CommitModal {
let co_authors = git_panel.render_co_authors(cx);
let generate_commit_message = git_panel.render_generate_commit_message_button(cx);
let active_repo = git_panel.active_repository.clone();
- let is_amend_pending = git_panel.amend_pending();
- let is_signoff_enabled = git_panel.signoff_enabled();
+ let commit_options = git_panel.commit_options();
let is_generating = git_panel.is_generating_commit_message();
(
can_commit,
@@ -364,8 +373,7 @@ impl CommitModal {
co_authors,
generate_commit_message,
active_repo,
- is_amend_pending,
- is_signoff_enabled,
+ commit_options,
git_panel.workspace.clone(),
is_generating,
)
@@ -450,15 +458,8 @@ impl CommitModal {
.on_click(cx.listener(move |this, _: &ClickEvent, window, cx| {
telemetry::event!("Git Committed", source = "Git Modal");
this.git_panel.update(cx, |git_panel, cx| {
- git_panel.commit_changes(
- CommitOptions {
- amend: is_amend_pending,
- signoff: is_signoff_enabled,
- allow_empty: false,
- },
- window,
- cx,
- )
+ let options = git_panel.commit_options();
+ git_panel.commit_changes(options, window, cx)
});
cx.emit(DismissEvent);
}))
@@ -470,9 +471,18 @@ impl CommitModal {
tooltip,
Some(&git::Commit),
format!(
- "git commit{}{}",
- if is_amend_pending { " --amend" } else { "" },
- if is_signoff_enabled { " --signoff" } else { "" }
+ "git commit{}{}{}",
+ if commit_options.amend { " --amend" } else { "" },
+ if commit_options.signoff {
+ " --signoff"
+ } else {
+ ""
+ },
+ if commit_options.no_verify {
+ " --no-verify"
+ } else {
+ ""
+ }
),
&focus_handle.clone(),
cx,
@@ -516,6 +526,17 @@ impl CommitModal {
}
}
+ fn on_toggle_skip_hooks(
+ &mut self,
+ action: &git::SkipHooks,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ self.git_panel.update(cx, |git_panel, cx| {
+ git_panel.toggle_skip_hooks(action, window, cx)
+ });
+ }
+
fn on_amend(&mut self, _: &git::Amend, window: &mut Window, cx: &mut Context<Self>) {
if self.git_panel.update(cx, |git_panel, cx| {
git_panel.amend(&self.commit_editor.focus_handle(cx), window, cx)
@@ -592,6 +613,7 @@ impl Render for CommitModal {
.key_context("GitCommit")
.on_action(cx.listener(Self::dismiss))
.on_action(cx.listener(Self::on_commit))
+ .on_action(cx.listener(Self::on_toggle_skip_hooks))
.on_action(cx.listener(Self::on_amend))
.on_action(cx.listener(Self::increase_font_size))
.on_action(cx.listener(Self::decrease_font_size))
diff --git a/crates/git_ui/src/git_panel.rs b/crates/git_ui/src/git_panel.rs
index af402961899..83ebe566f3c 100644
--- a/crates/git_ui/src/git_panel.rs
+++ b/crates/git_ui/src/git_panel.rs
@@ -36,7 +36,9 @@ use git::repository::{
};
use git::stash::GitStash;
use git::status::{DiffStat, StageStatus};
-use git::{Amend, Commit, Signoff, ToggleStaged, repository::RepoPath, status::FileStatus};
+use git::{
+ Amend, Commit, Signoff, SkipHooks, ToggleStaged, repository::RepoPath, status::FileStatus,
+};
use git::{
ExpandCommitEditor, GitHostingProviderRegistry, GitRemote, RestoreTrackedFiles, StageAll,
StashAll, StashApply, StashPop, ToggleFillCommitEditor, TrashUntrackedFiles, UnstageAll,
@@ -84,9 +86,10 @@ use strum::{IntoEnumIterator, VariantNames};
use theme_settings::ThemeSettings;
use time::OffsetDateTime;
use ui::{
- ButtonLike, Checkbox, Chip, ContextMenu, ContextMenuEntry, Divider, ElevationIndex,
- IndentGuideColors, KeyBinding, PopoverMenu, PopoverMenuHandle, ProjectEmptyState, ScrollAxes,
- Scrollbars, SplitButton, Tab, TintColor, Tooltip, WithScrollbar, prelude::*,
+ ButtonLike, Checkbox, Chip, ContextMenu, ContextMenuEntry, Divider, DocumentationSide,
+ ElevationIndex, IndentGuideColors, KeyBinding, PopoverMenu, PopoverMenuHandle,
+ ProjectEmptyState, ScrollAxes, Scrollbars, SplitButton, Tab, TintColor, Tooltip, WithScrollbar,
+ prelude::*,
};
use util::paths::PathStyle;
use util::{ResultExt, TryFutureExt, markdown::MarkdownInlineCode, maybe, rel_path::RelPath};
@@ -930,6 +933,7 @@ pub struct GitPanel {
original_commit_message: Option<String>,
pending_commit_message_restores: BTreeMap<String, SerializedCommitMessage>,
signoff_enabled: bool,
+ skip_hooks_enabled: bool,
pending_serialization: Task<()>,
pub(crate) project: Entity<Project>,
scroll_handle: UniformListScrollHandle,
@@ -1231,6 +1235,7 @@ impl GitPanel {
original_commit_message,
pending_commit_message_restores,
signoff_enabled,
+ skip_hooks_enabled: false,
pending_serialization: Task::ready(()),
single_staged_entry: None,
single_tracked_entry: None,
@@ -2781,15 +2786,8 @@ impl GitPanel {
cx: &mut Context<Self>,
) -> bool {
if commit_editor_focus_handle.contains_focused(window, cx) {
- self.commit_changes(
- CommitOptions {
- amend: self.amend_pending,
- signoff: self.signoff_enabled,
- allow_empty: false,
- },
- window,
- cx,
- );
+ let options = self.commit_options();
+ self.commit_changes(options, window, cx);
true
} else {
cx.propagate();
@@ -2909,6 +2907,15 @@ impl GitPanel {
}
}
+ pub(crate) fn commit_options(&self) -> CommitOptions {
+ CommitOptions {
+ amend: self.amend_pending,
+ signoff: self.signoff_enabled,
+ allow_empty: false,
+ no_verify: self.skip_hooks_enabled,
+ }
+ }
+
pub(crate) fn commit_changes(
&mut self,
options: CommitOptions,
@@ -2985,6 +2992,7 @@ impl GitPanel {
match result {
Ok(()) => {
+ this.set_skip_hooks_enabled(false, cx);
if options.amend {
this.set_amend_pending(false, cx);
} else {
@@ -4346,6 +4354,7 @@ impl GitPanel {
let active_repository_changed = self.active_repository.as_ref().map(Entity::entity_id)
!= new_active_repository.as_ref().map(Entity::entity_id);
if active_repository_changed {
+ self.set_skip_hooks_enabled(false, cx);
if self.amend_pending {
// Leaving a repository with a pending amend: undo it so the amend
// state doesn't carry over to the newly active repository. The
@@ -5381,6 +5390,7 @@ impl GitPanel {
let has_previous_commit = self.head_commit(cx).is_some();
let amend = self.amend_pending();
let signoff = self.signoff_enabled;
+ let skip_hooks = self.skip_hooks_enabled;
move |window, cx| {
Some(ContextMenu::build(window, cx, |context_menu, _, _| {
@@ -5413,6 +5423,17 @@ impl GitPanel {
Some(Box::new(Signoff)),
move |window, cx| window.dispatch_action(Box::new(Signoff), cx),
)
+ .item(
+ ContextMenuEntry::new("Skip Hooks")
+ .toggleable(IconPosition::Start, skip_hooks)
+ .action(Box::new(SkipHooks))
+ .handler(move |window, cx| {
+ window.dispatch_action(Box::new(SkipHooks), cx)
+ })
+ .documentation_aside(DocumentationSide::Left, |_| {
+ Label::new("git commit --no-verify").into_any_element()
+ }),
+ )
}))
}
})
@@ -5855,8 +5876,10 @@ impl GitPanel {
let (can_commit, tooltip) = self.configure_commit_button(cx);
let title = self.commit_button_title();
let commit_tooltip_focus_handle = self.commit_editor.focus_handle(cx);
- let amend = self.amend_pending();
- let signoff = self.signoff_enabled;
+ let options = self.commit_options();
+ let amend = options.amend;
+ let signoff = options.signoff;
+ let no_verify = options.no_verify;
let label_color = if self.pending_commit.is_some() {
Color::Disabled
@@ -5888,15 +5911,8 @@ impl GitPanel {
telemetry::event!("Git Committed", source = "Git Panel");
git_panel
.update(cx, |git_panel, cx| {
- git_panel.commit_changes(
- CommitOptions {
- amend,
- signoff,
- allow_empty: false,
- },
- window,
- cx,
- );
+ let options = git_panel.commit_options();
+ git_panel.commit_changes(options, window, cx);
})
.ok();
}
@@ -5909,9 +5925,10 @@ impl GitPanel {
tooltip,
Some(&git::Commit),
format!(
- "git commit{}{}",
+ "git commit{}{}{}",
if amend { " --amend" } else { "" },
- if signoff { " --signoff" } else { "" }
+ if signoff { " --signoff" } else { "" },
+ if no_verify { " --no-verify" } else { "" }
),
&handle.clone(),
cx,
@@ -7814,6 +7831,26 @@ impl GitPanel {
self.signoff_enabled
}
+ pub fn skip_hooks_enabled(&self) -> bool {
+ self.skip_hooks_enabled
+ }
+
+ fn set_skip_hooks_enabled(&mut self, value: bool, cx: &mut Context<Self>) {
+ if self.skip_hooks_enabled != value {
+ self.skip_hooks_enabled = value;
+ cx.notify();
+ }
+ }
+
+ pub fn toggle_skip_hooks(
+ &mut self,
+ _: &SkipHooks,
+ _window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ self.set_skip_hooks_enabled(!self.skip_hooks_enabled, cx);
+ }
+
pub fn set_signoff_enabled(&mut self, value: bool, cx: &mut Context<Self>) {
self.signoff_enabled = value;
self.serialize(cx);
@@ -8015,6 +8052,7 @@ impl Render for GitPanel {
this.on_action(cx.listener(Self::toggle_staged_for_selected))
.on_action(cx.listener(Self::stage_range))
.on_action(cx.listener(GitPanel::on_commit))
+ .on_action(cx.listener(GitPanel::toggle_skip_hooks))
.on_action(cx.listener(GitPanel::on_amend))
.on_action(cx.listener(GitPanel::toggle_signoff_enabled))
.on_action(cx.listener(Self::stage_all))
@@ -8961,6 +8999,7 @@ mod tests {
tree: serde_json::Value,
status_entries: &[(&str, git::status::StatusCode)],
) -> (
+ Arc<FakeFs>,
Entity<Project>,
Entity<Workspace>,
Entity<GitPanel>,
@@ -8979,7 +9018,7 @@ mod tests {
);
}
- let project = Project::test(fs, [Path::new(path!("/project"))], cx).await;
+ let project = Project::test(fs.clone(), [Path::new(path!("/project"))], cx).await;
let window_handle =
cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
let workspace = window_handle
@@ -9005,7 +9044,117 @@ mod tests {
let panel = workspace.update_in(&mut cx, GitPanel::new);
await_git_panel_entries(&panel, &mut cx).await;
- (project, workspace, panel, cx)
+ (fs, project, workspace, panel, cx)
+ }
+
+ #[gpui::test]
+ async fn test_skip_hooks_toggle(cx: &mut TestAppContext) {
+ init_test(cx);
+ let (_, _, _, panel, mut cx) = setup_git_panel_with_changes(
+ cx,
+ json!({
+ ".git": {},
+ "file": "modified\n",
+ }),
+ &[("file", StatusCode::Modified)],
+ )
+ .await;
+
+ panel.update_in(&mut cx, |panel, window, cx| {
+ assert!(!panel.skip_hooks_enabled());
+ panel.toggle_skip_hooks(&SkipHooks, window, cx);
+ assert!(panel.skip_hooks_enabled());
+ assert!(panel.commit_options().no_verify);
+
+ panel.toggle_skip_hooks(&SkipHooks, window, cx);
+ assert!(!panel.skip_hooks_enabled());
+ assert!(!panel.commit_options().no_verify);
+ });
+ }
+
+ #[gpui::test]
+ async fn test_skip_hooks_clears_after_successful_commit(cx: &mut TestAppContext) {
+ init_test(cx);
+ let (fs, _, _, panel, mut cx) = setup_git_panel_with_changes(
+ cx,
+ json!({
+ ".git": {},
+ "file": "modified\n",
+ }),
+ &[("file", StatusCode::Modified)],
+ )
+ .await;
+
+ panel.update_in(&mut cx, |panel, window, cx| {
+ panel
+ .commit_message_buffer(cx)
+ .update(cx, |buffer, cx| buffer.set_text("Test commit", cx));
+ panel.toggle_skip_hooks(&SkipHooks, window, cx);
+ assert!(panel.commit_options().no_verify);
+
+ let focus_handle = panel.commit_editor.focus_handle(cx);
+ focus_handle.focus(window, cx);
+ assert!(panel.commit(&focus_handle, window, cx));
+ });
+ cx.run_until_parked();
+
+ panel.read_with(&cx, |panel, _| {
+ assert!(!panel.skip_hooks_enabled());
+ });
+ let commit_count = fs
+ .with_git_state(path!("/project/.git").as_ref(), false, |state| {
+ state.commit_history.len()
+ })
+ .expect("fake repository should exist");
+ assert_eq!(commit_count, 1);
+ }
+
+ #[gpui::test]
+ async fn test_skip_hooks_remains_enabled_after_failed_commit(cx: &mut TestAppContext) {
+ init_test(cx);
+ let (fs, _, _, panel, mut cx) = setup_git_panel_with_changes(
+ cx,
+ json!({
+ ".git": {},
+ "file": "modified\n",
+ }),
+ &[("file", StatusCode::Modified)],
+ )
+ .await;
+
+ fs.set_status_for_repo(
+ path!("/project/.git").as_ref(),
+ &[("file", StatusCode::Modified.index())],
+ );
+ cx.run_until_parked();
+ await_git_panel_entries(&panel, &mut cx).await;
+ fs.with_git_state(path!("/project/.git").as_ref(), false, |state| {
+ state.index_contents = state.head_contents.clone();
+ })
+ .expect("fake repository should exist");
+
+ panel.update_in(&mut cx, |panel, window, cx| {
+ panel
+ .commit_message_buffer(cx)
+ .update(cx, |buffer, cx| buffer.set_text("Test commit", cx));
+ panel.toggle_skip_hooks(&SkipHooks, window, cx);
+ assert!(panel.commit_options().no_verify);
+
+ let focus_handle = panel.commit_editor.focus_handle(cx);
+ focus_handle.focus(window, cx);
+ assert!(panel.commit(&focus_handle, window, cx));
+ });
+ cx.run_until_parked();
+
+ panel.read_with(&cx, |panel, _| {
+ assert!(panel.skip_hooks_enabled());
+ });
+ let commit_count = fs
+ .with_git_state(path!("/project/.git").as_ref(), false, |state| {
+ state.commit_history.len()
+ })
+ .expect("fake repository should exist");
+ assert_eq!(commit_count, 0);
}
#[gpui::test]
@@ -9137,7 +9286,7 @@ mod tests {
async fn test_view_file_tree_view(cx: &mut TestAppContext) {
init_test(cx);
- let (_project, workspace, panel, mut cx) = setup_git_panel_with_changes(
+ let (_, _project, workspace, panel, mut cx) = setup_git_panel_with_changes(
cx,
json!({
".git": {},
@@ -11132,7 +11281,7 @@ mod tests {
}
#[gpui::test]
- async fn test_amend_state_is_per_repository(cx: &mut TestAppContext) {
+ async fn test_pending_commit_state_is_per_repository(cx: &mut TestAppContext) {
init_test(cx);
let fs = FakeFs::new(cx.background_executor.clone());
fs.insert_tree(
@@ -11217,6 +11366,8 @@ mod tests {
buffer.edit([(start..end, "Amended message")], None, cx);
});
assert!(panel.amend_pending());
+ panel.set_skip_hooks_enabled(true, cx);
+ assert!(panel.skip_hooks_enabled());
});
// Switching the active repository away exits the amend state instead of
@@ -11226,6 +11377,7 @@ mod tests {
panel.update(cx, |panel, cx| {
assert!(!panel.amend_pending());
+ assert!(!panel.skip_hooks_enabled());
// Only the active repository may serialize a pending amend, and we
// just left repository A's amend, so nothing is left pending.
let serialized = panel.serialized_commit_messages(cx);
@@ -12367,7 +12519,7 @@ mod tests {
async fn test_focus_handle(cx: &mut TestAppContext) {
init_test(cx);
- let (_project, workspace, panel, mut cx) = setup_git_panel_with_changes(
+ let (_, _project, workspace, panel, mut cx) = setup_git_panel_with_changes(
cx,
json!({
".git": {},
diff --git a/crates/project/src/git_store.rs b/crates/project/src/git_store.rs
index 148ed9603b7..eb998cb7d96 100644
--- a/crates/project/src/git_store.rs
+++ b/crates/project/src/git_store.rs
@@ -3126,6 +3126,7 @@ impl GitStore {
amend: options.amend,
signoff: options.signoff,
allow_empty: options.allow_empty,
+ no_verify: options.no_verify,
},
askpass,
cx,
@@ -7564,6 +7565,7 @@ impl Repository {
amend: options.amend,
signoff: options.signoff,
allow_empty: options.allow_empty,
+ no_verify: options.no_verify,
}),
askpass_id,
})
diff --git a/crates/proto/proto/git.proto b/crates/proto/proto/git.proto
index 64687374c61..2fb5f79ecff 100644
--- a/crates/proto/proto/git.proto
+++ b/crates/proto/proto/git.proto
@@ -413,6 +413,7 @@ message Commit {
bool amend = 1;
bool signoff = 2;
bool allow_empty = 3;
+ bool no_verify = 4;
}
}