分享几个封装的实用git命令的函数

首先,当前buffer是git仓库中的一个文件。

  • 找出一块区域的代码是谁写的。
(defun eye/git-blame-file-or-region ()
  "显示当前文件git blame 记录,如果有选中区域,则显示选中区域历史记录: git blame -Lstart,end file"
  (interactive)
  (let* ((file-path (xah-copy-file-path))
         (file-name (buffer-name))
         (output-buffer (format "*blame-%s*" file-name))
         (args "")
         (command "git blame ")
         p1 p2
         )
    (if (region-active-p)
        (let ((region-lines (eye--get-region-line-number)))
          (setq p1 (car region-lines))
          (setq p2 (cdr region-lines))
          (setq command (concat command (format "-L%s,%s " p1 p2)))
          (deactivate-mark)
          )
      )
    (setq command (concat command file-path))

    ;; (message "cmd:%s" command)
    (shell-command command output-buffer nil)

    (switch-to-buffer output-buffer)
    (delete-other-windows)
    (if (string-equal "c" (f-ext file-name))
        (c-mode))
    (if (string-equal "h" (f-ext file-name))
        (c-mode))
    (if (string-equal "cpp" (f-ext file-name))
        (c++-mode))
    (if (string-equal "cc" (f-ext file-name))
        (c++-mode))
    )
  )
  • 光标停在commit id上,显示一个commit id的记录,主要用于查看上一个函数列出来的commit的详情情况。
(defun eye/git-show-commit (&optional commit-id)
  "光标停在commit id上,显示一个commit id的记录"
  (interactive)
  (save-excursion
    (let* ((cid (or (thing-at-point 'word) (read-string "commit id:") ))
           (command (format "git show %s" cid))
           (output-buffer (format "*commit-%s*" cid))
           )
      (shell-command command output-buffer nil)
      (switch-to-buffer output-buffer)
      (diff-mode)
      (delete-other-windows)
      )
    ))
  • 显示当前文件的所有git记录。
(defun eye/git-log-current-file ()
  "显示当前文件的git记录"
  (interactive)
  (let* ((file-path (xah-copy-file-path))
         (file-name (buffer-name))
         (output-buffer (format "*gitlog-%s*" file-name))
         (args "")
         (command "git log --date=iso -- ")
         )
    (setq command (concat command file-path))

    (message "cmd:%s" command)
    (shell-command command output-buffer nil)
    )
  )

代码写得非常简单,但是功能很实用,感叹emacs的可定制性实在是太强了!

完整代码见 gist.

4 个赞

进入diff-mode,意外发现居然可以用counsel-imenu导航到不同的文件。

看起来这个包功能就是你需要的

preview

这个包也不错,实时显示了。