From b49d4ae25d1d1b48556419baf29d34e1d80315f3 Mon Sep 17 00:00:00 2001 From: Wassim Metallaoui Date: Sun, 19 May 2024 17:30:16 -0500 Subject: [PATCH] feat: support comparing against main on forked repo When doing some open source work I realized I couldn't easily compare my forked branch against the upstream repos main branch. --- main.go | 30 ++++++++++++++++++++++++++---- 1 file changed, 26 insertions(+), 4 deletions(-) diff --git a/main.go b/main.go index 1ed8808..b2f920e 100644 --- a/main.go +++ b/main.go @@ -21,15 +21,33 @@ func main() { if err != nil { log.Fatal(err) } - currentBranch := ref.Name().Short() var compareArgument string + var forkedRepo bool + var originRepo string + + remotes, err := gitRepo.Remotes() + if err != nil { + log.Fatal(err) + } + + for _, remote := range remotes { + if remote.Config().Name == "upstream" { + forkedRepo = true + } - if len(os.Args) == 2 { + if remote.Config().Name == "origin" { + originRepo = parseRepoOriginOwnerFromURL(remote.Config().URLs[0]) + } + } + + if forkedRepo { + compareArgument = fmt.Sprintf("main...%s:%s", originRepo, currentBranch) + } else if len(os.Args) == 2 { compareArgument = os.Args[1] - if !(strings.Contains(compareArgument, "..") || strings.Contains(compareArgument, "...")) { + if !strings.Contains(compareArgument, "..") && !strings.Contains(compareArgument, "...") { compareArgument = compareArgument + "..." + currentBranch } } else { @@ -40,7 +58,6 @@ func main() { if err != nil { log.Fatal(err) } - url := fmt.Sprintf("https://%s/%s/%s/compare/%s", ghRepo.Host, ghRepo.Owner, ghRepo.Name, compareArgument) browser := browser.New("", os.Stdout, os.Stderr) @@ -49,3 +66,8 @@ func main() { log.Fatal(err) } } + +func parseRepoOriginOwnerFromURL(url string) string { + parts := strings.Split(url, ":") + return strings.Split(parts[1], "/")[0] +}