|
| 1 | +// ==UserScript== |
| 2 | +// @name GitHub Add Branch to "gh pr checkout" |
| 3 | +// @description Add "-b author/<branch name>" to "gh pr checkout ..." command |
| 4 | +// @namespace http://tampermonkey.net/ |
| 5 | +// @version 2026-01-04 |
| 6 | +// @author Hugo Alliaume |
| 7 | +// @match https://github.com/*/*/pull/* |
| 8 | +// @icon https://www.google.com/s2/favicons?sz=64&domain=github.com |
| 9 | +// @grant none |
| 10 | +// ==/UserScript== |
| 11 | + |
| 12 | +/** |
| 13 | + * When developing an open-source project, relying on `gh pr checkout ...` command could |
| 14 | + * become a mess if the PR's branch name is pretty basic like "patch-1", which can conflicts |
| 15 | + * with already existing branches. |
| 16 | + */ |
| 17 | + |
| 18 | +const me = 'kocal'; |
| 19 | + |
| 20 | +(function() { |
| 21 | + 'use strict'; |
| 22 | + |
| 23 | + const $headRef = document.querySelector('.commit-ref.head-ref'); |
| 24 | + const headRef = $headRef.textContent; |
| 25 | + |
| 26 | + if (!headRef || headRef.startsWith(`${me}:`)) { |
| 27 | + console.log(`Missing head ref, or starting with "${me}:", ignoring`); |
| 28 | + return; |
| 29 | + } |
| 30 | + |
| 31 | + const headRefSanitized = headRef.replace(':', '/'); |
| 32 | + const $getRepoDetails = document.querySelector('get-repo details-menu'); |
| 33 | + const observer = new MutationObserver((mutations) => { |
| 34 | + mutations.forEach((mutation) => { |
| 35 | + if (mutation.type !== 'childList') { |
| 36 | + return; |
| 37 | + } |
| 38 | + |
| 39 | + const $getRepo = $getRepoDetails.querySelector('[data-target="get-repo.modal"]'); |
| 40 | + if (!$getRepo) { |
| 41 | + return; |
| 42 | + } |
| 43 | + |
| 44 | + const $inputCheckoutGhCli = $getRepo.querySelector('input[value^="gh pr checkout "]'); |
| 45 | + const $buttonCopyCheckoutGhCli = $getRepo.querySelector('clipboard-copy[value^="gh pr checkout "]'); |
| 46 | + const commandGhPrCheckout = $inputCheckoutGhCli.value + ' -b ' + headRefSanitized; |
| 47 | + |
| 48 | + $inputCheckoutGhCli.setAttribute('value', commandGhPrCheckout); |
| 49 | + $inputCheckoutGhCli.setAttribute('aria-label', commandGhPrCheckout); |
| 50 | + $buttonCopyCheckoutGhCli.setAttribute('value', commandGhPrCheckout); |
| 51 | + |
| 52 | + observer.disconnect(); |
| 53 | + }); |
| 54 | + }); |
| 55 | + observer.observe($getRepoDetails, { |
| 56 | + subtree: true, |
| 57 | + childList: true, |
| 58 | + }); |
| 59 | +})(); |
0 commit comments