Skip to content

Instantly share code, notes, and snippets.

@muendelezaji
Last active November 4, 2022 01:52
Show Gist options
  • Save muendelezaji/55083238af9cdf3c1b8c26af4830ed75 to your computer and use it in GitHub Desktop.
Save muendelezaji/55083238af9cdf3c1b8c26af4830ed75 to your computer and use it in GitHub Desktop.
Get PR number from a GitHub URL
// Derived from paste at https://pastebin.com/iwqG6zvH
// Lightly edited to make it run
// Original discussion: https://t.me/GolangTZ/475
// You can edit this code!
// Click here and start typing.
package main
import (
"bufio"
"fmt"
"io"
"log"
"os"
"regexp"
"strconv"
"strings"
)
// Example 1: https://github.com/microsoft/vscode/pull/12345
// Example 2: https://github.com/refined-github/refined-github/pull/123
var prRe = regexp.MustCompile(`https://github.com/[[:word:]-\.]+/[[:word:]-\.]+/pull/([\d]+)`)
func main() {
prLink, err := ReadInput(os.Stdin, "PR: ")
if err != nil {
log.Fatal(err)
os.Exit(1)
}
pr, err := GetPR(prLink)
if err != nil {
log.Fatal(err)
}
fmt.Println(pr)
}
func GetPR(prLink string) (PR, error) {
var (
pr PR = PR{}
err error
)
if err != nil {
return pr, err
}
res := prRe.FindStringSubmatch(prLink)
if len(res) == 0 {
return pr, fmt.Errorf("invalid PR link")
}
num, err := strconv.Atoi(res[1])
if err != nil {
return pr, err
}
pr.link = prLink
pr.num = num
return pr, err
}
func ReadInput(reader io.Reader, msg string) (string, error) {
if msg != "" {
fmt.Print(msg)
}
r := bufio.NewReader(reader)
text, err := r.ReadString('\n')
if err != nil {
return "", err
}
return strings.TrimSpace(text), nil
}
type PR struct {
link string
num int
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment