Last active
November 4, 2022 01:52
-
-
Save muendelezaji/55083238af9cdf3c1b8c26af4830ed75 to your computer and use it in GitHub Desktop.
Get PR number from a GitHub URL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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