;;; version-control-lexical.el --- Functions for version control -*- lexical-binding: t; -*-

;; Copyright (C) 2020 Free Software Foundation, Inc.

;; Author: Oleg Pykhalov <go.wigust@gmail.com>
;; Version: 0.0.1
;; Package-Requires: ((ffap "1.0") ((magit "1.0")))
;; Keywords: browse-url, magit, vc
;; URL: https://github.com/kitnil/dotfiles/

;;; Commentary:

;; This package provides functions to work with version control systems.

;;; Code:

(require 'ffap)
;; (require 'magit-diff)

;;;###autoload
(defun wi-define-browse-url-git-commit (name directory url->commit)
  "Define browse-url-* function.

NAME part of function name browse-url-NAME-git-commit.
DIRECTORY Git project directory.
URL->COMMIT function to parse commit from url.

The following example defines `browse-url-guix-git-commit'
function, which opens
https://git.savannah.gnu.org/cgit/guix.git/commit/?id=df05842332be80e…
with `magit-show-commit' function in /home/oleg/src/git.savannah.gnu.org/git/guix directory.

\(wi-define-browse-url-git-commit
 \"guix\"
 (expand-file-name \"/home/oleg/src/git.savannah.gnu.org/git/guix\")
 (lambda (url) (car (last (split-string url \"=\")))))"
  (defalias (intern (concat "browse-url-" name "-git-commit"))
    (function
     (lambda (url &optional _new-window)
       (interactive (list (read-string "Commit: " nil nil (word-at-point))))
       (let ((default-directory directory)
             (commit (funcall url->commit url)))
         (when (eq (cdr (assoc 'major-mode
                               (buffer-local-variables (current-buffer))))
                   'elfeed-search-mode)
           (let* ((entry (elfeed-search-selected t))
                  (title (elfeed-entry-title entry)))
             (elfeed-untag entry 'unread)
             (elfeed-search-update-entry entry)
             (unless (or elfeed-search-remain-on-entry (use-region-p))
               (forward-line))))
         (condition-case user-error
             (magit-show-commit commit)
           (error (magit-status default-directory))))))
    (format "Show a Git `commit' from the %s checkout.

If no commit hash provides, show a commit from hash at current point."
            name)))

(defun wi-magit-show-commit ()
  (interactive)
  (call-interactively #'magit-show-commit)
  (call-interactively #'crux-transpose-windows)
  (call-interactively #'other-window))

(with-eval-after-load 'magit
  (let ((map magit-log-mode-map))
    (define-key map (kbd "RET") 'wi-magit-show-commit)))

;;; version-control-lexical.el ends here
