Make Magit ask for confirmation when pushing to main and master
Over the years, I have accidentally pushed to the main/master branch while believing I was on another branch. When this happened in personal projects, it was not a big deal, as I could easily fix it with a revert commit or a reset. But it was not so simple in a project where I did not have force-push rights. As a result, I added the following Elisp code to my Emacs configuration, so that I am always asked for confirmation before pushing to main/master.
The Elisp code
(use-package magit :ensure t :commands magit-status :hook (git-commit-mode . company-mode) :custom (magit-diff-refine-hunk 'all) :config (defun my/magit-confirm-push-to-main (orig-fun &rest args) "Ask for confirmation before pushing to main or master." (let ((branch (magit-get-current-branch))) (if (and branch (member branch '("master" "main"))) (when (yes-or-no-p (format "Pushing to %s. Continue? " branch)) (apply orig-fun args)) (apply orig-fun args)))) (dolist (fn '(magit-push-current-to-pushremote magit-push-current magit-push)) (advice-add fn :around #'my/magit-confirm-push-to-main)))