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 command to create tags at HEAD (#61973)
Xiaobo Liu5eed2397a863
diff --git a/crates/fs/src/fake_git_repo.rs b/crates/fs/src/fake_git_repo.rsindex fae26d0a28d..8801d7f4d62 100644--- a/crates/fs/src/fake_git_repo.rs+++ b/crates/fs/src/fake_git_repo.rs@@ -224,6 +224,13 @@ impl FakeGitRepository {fn edit_ref(&self, edit: RefEdit) -> BoxFuture<'_, Result<()>> {self.with_state_async(true, move |state| {match edit {+ RefEdit::Create { ref_name, commit } => {+ anyhow::ensure!(+ !state.refs.contains_key(&ref_name),+ "reference {ref_name} already exists"+ );+ state.refs.insert(ref_name, commit);+ }RefEdit::Update { ref_name, commit } => {state.refs.insert(ref_name, commit);}@@ -1747,6 +1754,10 @@ impl GitRepository for FakeGitRepository {}))}+ fn create_ref(&self, ref_name: String, commit: String) -> BoxFuture<'_, Result<()>> {+ self.edit_ref(RefEdit::Create { ref_name, commit })+ }+fn update_ref(&self, ref_name: String, commit: String) -> BoxFuture<'_, Result<()>> {self.edit_ref(RefEdit::Update { ref_name, commit })}diff --git a/crates/git/src/git.rs b/crates/git/src/git.rsindex 3896903516d..6749bbf0101 100644--- a/crates/git/src/git.rs+++ b/crates/git/src/git.rs@@ -145,6 +145,8 @@ actions!(AddToGitInfoExclude,/// Copies the current branch name to the clipboard.CopyBranchName,+ /// Creates a tag at HEAD.+ CreateTagAtHead,]);diff --git a/crates/git/src/repository.rs b/crates/git/src/repository.rsindex b467990e20d..de42e3ec1e9 100644--- a/crates/git/src/repository.rs+++ b/crates/git/src/repository.rs@@ -1132,6 +1132,7 @@ pub trait GitRepository: Send + Sync {fn commit_data_reader(&self) -> Result<CommitDataReader>;+ fn create_ref(&self, ref_name: String, commit: String) -> BoxFuture<'_, Result<()>>;fn update_ref(&self, ref_name: String, commit: String) -> BoxFuture<'_, Result<()>>;fn delete_ref(&self, ref_name: String) -> BoxFuture<'_, Result<()>>;@@ -1181,6 +1182,7 @@ pub struct RealGitRepository {#[derive(Debug)]pub enum RefEdit {+ Create { ref_name: String, commit: String },Update { ref_name: String, commit: String },Delete { ref_name: String },}@@ -1188,6 +1190,14 @@ pub enum RefEdit {impl RefEdit {fn into_args(self) -> Vec<OsString> {match self {+ Self::Create { ref_name, commit } => {+ vec![+ "update-ref".into(),+ ref_name.into(),+ commit.into(),+ "".into(),+ ]+ }Self::Update { ref_name, commit } => {vec!["update-ref".into(), ref_name.into(), commit.into()]}@@ -2794,6 +2804,10 @@ impl GitRepository for RealGitRepository {.boxed()}+ fn create_ref(&self, ref_name: String, commit: String) -> BoxFuture<'_, Result<()>> {+ self.edit_ref(RefEdit::Create { ref_name, commit })+ }+fn update_ref(&self, ref_name: String, commit: String) -> BoxFuture<'_, Result<()>> {self.edit_ref(RefEdit::Update { ref_name, commit })}@@ -4294,6 +4308,18 @@ mod tests {use super::*;use gpui::TestAppContext;+ #[test]+ fn test_create_ref_requires_ref_to_not_exist() {+ assert_eq!(+ RefEdit::Create {+ ref_name: "refs/tags/v1.0.0".to_string(),+ commit: "abcdef".to_string(),+ }+ .into_args(),+ ["update-ref", "refs/tags/v1.0.0", "abcdef", ""].map(OsString::from)+ );+ }+#[test]fn test_commit_hash_search_query_accepts_sha1_and_sha256_hashes() {assert_eq!(diff --git a/crates/git_ui/src/git_graph.rs b/crates/git_ui/src/git_graph.rsindex 454b88b3ed1..f70188fa6a8 100644--- a/crates/git_ui/src/git_graph.rs+++ b/crates/git_ui/src/git_graph.rs@@ -1825,6 +1825,10 @@ impl GitGraph {}}}+ RepositoryEvent::TagsChanged => {+ self.pending_select_sha = None;+ self.invalidate_state(cx);+ }RepositoryEvent::HeadChanged | RepositoryEvent::BranchListChanged => {// Only invalidate if we scanned atleast once,// meaning we are not inside the initial repo loading state@@ -7073,6 +7077,104 @@ mod tests {assert_eq!(reloaded_shas, vec![updated_head, updated_stash]);}+ #[gpui::test]+ async fn test_graph_data_reloaded_after_tag_created(cx: &mut TestAppContext) {+ init_test(cx);++ let fs = FakeFs::new(cx.executor());+ fs.insert_tree(+ Path::new("/project"),+ json!({+ ".git": {},+ "file.txt": "content",+ }),+ )+ .await;++ let head = Oid::from_bytes(&[1; 20]).unwrap();+ fs.set_graph_commits(+ Path::new("/project/.git"),+ vec![Arc::new(InitialGraphCommitData {+ sha: head,+ parents: smallvec![],+ ref_names: vec!["HEAD -> main".into()],+ })],+ );++ let project = Project::test(fs.clone(), [Path::new("/project")], cx).await;+ cx.run_until_parked();++ let repository = project.read_with(cx, |project, cx| {+ project+ .active_repository(cx)+ .expect("should have a repository")+ });++ let (multi_workspace, cx) = cx.add_window_view(|window, cx| {+ workspace::MultiWorkspace::test_new(project.clone(), window, cx)+ });+ let workspace_weak =+ multi_workspace.read_with(&*cx, |multi, _| multi.workspace().downgrade());+ let git_graph = cx.new_window_entity(|window, cx| {+ GitGraph::new(+ repository.read(cx).id,+ project.read(cx).git_store().clone(),+ workspace_weak,+ None,+ window,+ cx,+ )+ });+ cx.run_until_parked();++ let ref_names_of_head = |cx: &mut gpui::VisualTestContext| {+ git_graph.read_with(&*cx, |graph, _| {+ graph+ .graph_data+ .commits+ .iter()+ .map(|commit| commit.data.ref_names.clone())+ .collect::<Vec<_>>()+ })+ };+ assert_eq!(+ ref_names_of_head(cx),+ vec![vec![SharedString::from("HEAD -> main")]]+ );++ fs.set_graph_commits(+ Path::new("/project/.git"),+ vec![Arc::new(InitialGraphCommitData {+ sha: head,+ parents: smallvec![],+ ref_names: vec!["HEAD -> main".into(), "tag: v1.0.0".into()],+ })],+ );+ repository+ .update(cx, |repository, _| {+ repository.create_tag("v1.0.0".to_string(), head.to_string())+ })+ .await+ .unwrap()+ .unwrap();+ cx.run_until_parked();++ cx.draw(+ point(px(0.), px(0.)),+ gpui::size(px(1200.), px(800.)),+ |_, _| git_graph.clone().into_any_element(),+ );+ cx.run_until_parked();++ assert_eq!(+ ref_names_of_head(cx),+ vec![vec![+ SharedString::from("HEAD -> main"),+ SharedString::from("tag: v1.0.0"),+ ]]+ );+ }+#[gpui::test]async fn test_git_graph_row_at_position_rounding(cx: &mut TestAppContext) {init_test(cx);diff --git a/crates/git_ui/src/git_panel.rs b/crates/git_ui/src/git_panel.rsindex dee2d808e51..6f43798ee2a 100644--- a/crates/git_ui/src/git_panel.rs+++ b/crates/git_ui/src/git_panel.rs@@ -7430,7 +7430,10 @@ impl GitPanel {self._repo_subscriptions.push(cx.subscribe(&active_repository,|this, _repo, event, cx| {- if let RepositoryEvent::GraphEvent(_, _) = event {+ if matches!(+ event,+ RepositoryEvent::GraphEvent(_, _) | RepositoryEvent::TagsChanged+ ) {if this.active_tab == GitPanelTab::History {this.fetch_commit_history_entries(cx);}diff --git a/crates/git_ui/src/git_ui.rs b/crates/git_ui/src/git_ui.rsindex 7038a7a8e9f..95ce53826dd 100644--- a/crates/git_ui/src/git_ui.rs+++ b/crates/git_ui/src/git_ui.rs@@ -8,6 +8,7 @@ mod blame_ui;pub mod clone;use git::{+ Oid,repository::{Branch, CommitDetails, Upstream, UpstreamTracking, UpstreamTrackingStatus},status::{FileStatus, StatusCode, UnmergedStatus, UnmergedStatusCode},};@@ -16,10 +17,12 @@ use gpui::{SharedString, Subscription, Task, TaskExt, WeakEntity, Window,};use menu::{Cancel, Confirm};+use notifications::status_toast::StatusToast;use project::git_store::Repository;use project_diff::ProjectDiff;use time::OffsetDateTime;use ui::{ButtonLike, ContextMenu, ElevationIndex, PopoverMenuHandle, TintColor, prelude::*};+use util::ResultExt as _;use workspace::{ModalView, OpenMode, Workspace,notifications::{DetachAndPromptErr, NotifyTaskExt},@@ -351,6 +354,9 @@ pub fn init(cx: &mut App) {workspace.register_action(|workspace, _: &git::RenameBranch, window, cx| {rename_current_branch(workspace, window, cx);});+ workspace.register_action(|workspace, _: &git::CreateTagAtHead, window, cx| {+ create_tag_at_head(workspace, window, cx);+ });workspace.register_action(|workspace, _: &git::CopyBranchName, _, cx| {copy_branch_name(workspace, cx);});@@ -527,6 +533,103 @@ impl Render for RenameBranchModal {}}+struct CreateTagModal {+ commit: Oid,+ editor: Entity<Editor>,+ repo: Entity<Repository>,+ workspace: WeakEntity<Workspace>,+}++impl CreateTagModal {+ fn new(+ commit: Oid,+ repo: Entity<Repository>,+ workspace: WeakEntity<Workspace>,+ window: &mut Window,+ cx: &mut Context<Self>,+ ) -> Self {+ let editor = cx.new(|cx| {+ let mut editor = Editor::single_line(window, cx);+ editor.set_placeholder_text("Tag name", window, cx);+ editor+ });+ Self {+ commit,+ editor,+ repo,+ workspace,+ }+ }++ fn cancel(&mut self, _: &Cancel, _window: &mut Window, cx: &mut Context<Self>) {+ cx.emit(DismissEvent);+ }++ fn confirm(&mut self, _: &Confirm, window: &mut Window, cx: &mut Context<Self>) {+ let tag_name = self.editor.read(cx).text(cx).trim().to_string();+ if tag_name.is_empty() {+ return;+ }++ let repo = self.repo.clone();+ let commit = self.commit.to_string();+ let workspace = self.workspace.clone();+ let success_message = format!("Created tag {tag_name} at HEAD");+ cx.spawn(async move |_, cx| {+ repo.update(cx, |repo, _| repo.create_tag(tag_name, commit))+ .await??;++ workspace+ .update(cx, |workspace, cx| {+ let toast = StatusToast::new(success_message, cx, |this, _| this);+ workspace.toggle_status_toast(toast, cx);+ })+ .log_err();+ Ok(())+ })+ .detach_and_prompt_err("Failed to create tag", window, cx, |error, _, _| {+ Some(error.to_string())+ });+ cx.emit(DismissEvent);+ }+}++impl EventEmitter<DismissEvent> for CreateTagModal {}+impl ModalView for CreateTagModal {}+impl Focusable for CreateTagModal {+ fn focus_handle(&self, cx: &App) -> FocusHandle {+ self.editor.focus_handle(cx)+ }+}++impl Render for CreateTagModal {+ fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {+ v_flex()+ .key_context("CreateTagModal")+ .on_action(cx.listener(Self::cancel))+ .on_action(cx.listener(Self::confirm))+ .elevation_2(cx)+ .w(rems(34.))+ .child(+ h_flex()+ .px_3()+ .pt_2()+ .pb_1()+ .w_full()+ .gap_1p5()+ .child(Icon::new(IconName::GitCommit).size(IconSize::XSmall))+ .child(+ Headline::new(format!(+ "Create Tag at HEAD ({})",+ self.commit.display_short()+ ))+ .size(HeadlineSize::XSmall),+ ),+ )+ .child(div().px_3().pb_3().w_full().child(self.editor.clone()))+ }+}+fn rename_current_branch(workspace: &mut Workspace,window: &mut Window,@@ -555,6 +658,25 @@ fn rename_current_branch(});}+fn create_tag_at_head(workspace: &mut Workspace, window: &mut Window, cx: &mut Context<Workspace>) {+ let Some(repo) = workspace.project().read(cx).active_repository(cx) else {+ return;+ };+ let Some(commit) = repo+ .read(cx)+ .head_commit+ .as_ref()+ .and_then(|commit| Oid::try_from(commit.sha.as_ref()).ok())+ else {+ return;+ };+ let workspace_handle = cx.weak_entity();++ workspace.toggle_modal(window, cx, |window, cx| {+ CreateTagModal::new(commit, repo, workspace_handle, window, cx)+ });+}+fn copy_branch_name(workspace: &mut Workspace, cx: &mut Context<Workspace>) {let Some(panel) = workspace.panel::<GitPanel>(cx) else {return;@@ -1451,4 +1573,45 @@ mod view_commit_tests {assert!(!initial_modal_state);assert!(final_modal_state);}++ #[gpui::test]+ async fn test_create_tag_at_head(cx: &mut TestAppContext) {+ init_test(cx);+ let fs = setup_git_repo(cx).await;+ let commit = Oid::try_from("abcdef1234567890abcdef1234567890abcdef12")+ .expect("commit SHA should be valid");+ fs.set_head_for_repo(Path::new("/root/project/.git"), &[], commit.to_string());+ let (_project, workspace) = create_test_workspace(fs.clone(), cx).await;+ let cx = &mut VisualTestContext::from_window(*workspace, cx);+ cx.executor().run_until_parked();++ workspace+ .update(cx, |workspace, window, cx| {+ create_tag_at_head(workspace, window, cx);+ })+ .expect("workspace should exist");++ let modal = workspace+ .update(cx, |workspace, _, cx| {+ workspace.active_modal::<CreateTagModal>(cx)+ })+ .expect("workspace should exist")+ .expect("create tag modal should be open");+ assert_eq!(modal.read_with(cx, |modal, _| modal.commit), commit);++ modal.update_in(cx, |modal, window, cx| {+ modal.editor.update(cx, |editor, cx| {+ editor.set_text("v1.0.0", window, cx);+ });+ modal.confirm(&Confirm, window, cx);+ });+ cx.run_until_parked();++ let tagged_commit = fs+ .with_git_state(Path::new("/root/project/.git"), false, |state| {+ state.refs.get("refs/tags/v1.0.0").cloned()+ })+ .expect("fake git state should exist");+ assert_eq!(tagged_commit, Some(commit.to_string()));+ }}diff --git a/crates/project/src/git_store.rs b/crates/project/src/git_store.rsindex 5468e825009..a9730c4f071 100644--- a/crates/project/src/git_store.rs+++ b/crates/project/src/git_store.rs@@ -846,6 +846,7 @@ pub enum RepositoryEvent {StatusesChanged,HeadChanged,BranchListChanged,+ TagsChanged,StashEntriesChanged,GitWorktreeListChanged,PendingOpsChanged { pending_ops: SumTree<PendingOps> },@@ -4219,17 +4220,30 @@ impl GitStore {let repository_id = RepositoryId::from_proto(envelope.payload.repository_id);let repository_handle = Self::repository_for_request(&this, repository_id, &mut cx)?;let ref_name = envelope.payload.ref_name;- let commit = match envelope.payload.action {- Some(proto::git_edit_ref::Action::UpdateToCommit(sha)) => Some(sha),- Some(proto::git_edit_ref::Action::Delete(_)) => None,+ match envelope.payload.action {+ Some(proto::git_edit_ref::Action::CreateToCommit(sha)) => {+ repository_handle+ .update(&mut cx, |repository_handle, _| {+ repository_handle.create_ref(ref_name, sha)+ })+ .await??;+ }+ Some(proto::git_edit_ref::Action::UpdateToCommit(sha)) => {+ repository_handle+ .update(&mut cx, |repository_handle, _| {+ repository_handle.edit_ref(ref_name, Some(sha))+ })+ .await??;+ }+ Some(proto::git_edit_ref::Action::Delete(_)) => {+ repository_handle+ .update(&mut cx, |repository_handle, _| {+ repository_handle.edit_ref(ref_name, None)+ })+ .await??;+ }None => anyhow::bail!("GitEditRef missing action"),- };-- repository_handle- .update(&mut cx, |repository_handle, _| {- repository_handle.edit_ref(ref_name, commit)- })- .await??;+ }Ok(proto::Ack {})}@@ -6649,6 +6663,10 @@ impl Repository {self.initial_graph_data.clear();}}+ // Tags are only changed by explicit user actions, never during the initial scan.+ RepositoryEvent::TagsChanged => {+ self.initial_graph_data.clear();+ }RepositoryEvent::StashEntriesChanged => {if self.scan_id > 2 {self.initial_graph_data@@ -9379,6 +9397,45 @@ impl Repository {})}+ fn create_ref(&mut self, ref_name: String, commit: String) -> oneshot::Receiver<Result<()>> {+ let id = self.id;+ let this = self.this.clone();+ self.send_job(+ "create_ref",+ Some(format!("git update-ref {ref_name} {commit}").into()),+ move |repo, mut cx| async move {+ match repo {+ RepositoryState::Local(LocalRepositoryState { backend, .. }) => {+ backend.create_ref(ref_name, commit).await?;+ }+ RepositoryState::Remote(RemoteRepositoryState { project_id, client }) => {+ client+ .request(proto::GitEditRef {+ project_id: project_id.0,+ repository_id: id.to_proto(),+ ref_name,+ action: Some(proto::git_edit_ref::Action::CreateToCommit(commit)),+ })+ .await?;+ }+ }++ this.update(&mut cx, |_, cx| {+ cx.emit(RepositoryEvent::TagsChanged);+ })?;+ Ok(())+ },+ )+ }++ pub fn create_tag(+ &mut self,+ tag_name: String,+ commit: String,+ ) -> oneshot::Receiver<Result<()>> {+ self.create_ref(format!("refs/tags/{tag_name}"), commit)+ }+fn edit_ref(&mut self,ref_name: String,diff --git a/crates/proto/proto/git.proto b/crates/proto/proto/git.protoindex aece2bd61b6..c217707c433 100644--- a/crates/proto/proto/git.proto+++ b/crates/proto/proto/git.proto@@ -642,6 +642,7 @@ message GitEditRef {oneof action {string update_to_commit = 4;DeleteRef delete = 5;+ string create_to_commit = 6;}message DeleteRef {}}diff --git a/docs/src/git.md b/docs/src/git.mdindex 2168b3d61a5..9fbba860c50 100644--- a/docs/src/git.md+++ b/docs/src/git.md@@ -119,6 +119,10 @@ To view File History:- Right-click on an editor tab and select "View File History"- Use the Command Palette and search for "file history"+## Tags++To create a lightweight tag at `HEAD`, use {#action git::CreateTagAtHead} from the Command Palette. Tags are created locally and are not pushed automatically.+## Fetch, Push, and PullFetch, push, or pull from your Git repository in Zed via the buttons available on the Git Panel or via the Command Palette by looking at the respective actions: {#action git::Fetch}, {#action git::Push}, and {#action git::Pull}.