Skip to content

Instantly share code, notes, and snippets.

@twlz0ne
Created November 14, 2022 06:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save twlz0ne/dab09e784512f9be60ea9a7e18f76f8b to your computer and use it in GitHub Desktop.
Save twlz0ne/dab09e784512f9be60ea9a7e18f76f8b to your computer and use it in GitHub Desktop.
Checkout Github pull-request locally. #git
#!/usr/bin/env sh
:; # -*- mode: emacs-lisp; lexical-binding: t -*-
:; # Checkout Github pull-request locally.
:; # Last-updated: 2022-11-14 13.42.02 +0800
:; # by: Gong Qijian
:; # Usage:
:; # git-checkout-pr.sh [pull-request-url]
:; # Example:
:; # git-checkout-pr.sh https://github.com/user1/project2/pull/3
:; #
:; exec emacs --script "$0" "$@"
(require 'seq)
(when-let*
((s (car argv))
((string-match "\\(?:git@\\|https://\\)github.com/\\(.*\\)/\\(.*\\)/pull/\\([0-9]+\\)" s))
(user (match-string 1 s))
(repo (match-string 2 s))
(pull (match-string 3 s))
(repo-reg (format "\\(?:git@\\|https://\\)github.com/%s/%s" user repo))
(branch
(gethash
"ref"
(gethash
"head"
(json-parse-string
(shell-command-to-string
(format "curl -sL https://api.github.com/repos/%s/%s/pulls/%s"
user repo pull))))))
(remote
(caar
(seq-filter
(pcase-lambda (`(,remote ,url ,act))
(and (string-match repo-reg url)
(string= act (concat "(fetch)"))))
(mapcar #'string-split
(string-split
(string-trim-right (shell-command-to-string "git remote -v"))
"\n")))))
(fetch-cmd (format "git fetch %s pull/%s/head:pr-%s-%s" remote pull pull branch)))
(message "==> %s" fetch-cmd)
(shell-command fetch-cmd))
;; git-checkout-pr.sh ends here