diff --git a/counsel.el b/counsel.el index 29ea4180..403eb3a9 100644 --- a/counsel.el +++ b/counsel.el @@ -1443,11 +1443,30 @@ TREE is the selected candidate." "Return worktree from candidate TREE." (substring tree 0 (string-match " " tree))) +(defun counsel-git-toplevel () + "Return the base directory of the current git repository." + (let ((out (string-trim-right (shell-command-to-string "git rev-parse --show-toplevel")))) + (and (string-match-p "Not a git repository" out) (error "Not a git repository!")) + out)) + +(defun counsel-git-close-worktree-files-action (root-dir) + "Close all buffers from the worktree located at ROOT-DIR." + (save-excursion + (dolist (buf (buffer-list)) + (set-buffer buf) + (and buffer-file-name + (string= "." (file-relative-name root-dir (counsel-git-toplevel))) + (kill-buffer buf))))) + +(ivy-set-actions + 'counsel-git-change-worktree + '(("k" counsel-git-close-worktree-files-action "kill all"))) + ;;;###autoload (defun counsel-git-change-worktree () "Find the file corresponding to the current buffer on a different worktree." (interactive) - (let ((git-root-dir (string-trim-right (shell-command-to-string "git rev-parse --show-toplevel")))) + (let ((git-root-dir (counsel-git-toplevel))) (ivy-read "Select worktree: " (or (cl-delete git-root-dir (counsel-git-worktree-list) :key #'counsel-git-worktree-parse-root :test #'string=)