|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "errors" |
| 5 | + "fmt" |
| 6 | + "io" |
| 7 | + "os" |
| 8 | + "regexp" |
| 9 | + |
| 10 | + "github.com/function61/gokit/os/osutil" |
| 11 | + "github.com/pkg/browser" |
| 12 | + "github.com/spf13/cobra" |
| 13 | +) |
| 14 | + |
| 15 | +func openProjectHomepageEntrypoint() *cobra.Command { |
| 16 | + return &cobra.Command{ |
| 17 | + Use: "www", |
| 18 | + Aliases: []string{"gh"}, |
| 19 | + Short: "Open project homepage / GitHub repo in browser", |
| 20 | + Hidden: true, |
| 21 | + Args: cobra.NoArgs, |
| 22 | + Run: func(_ *cobra.Command, _ []string) { |
| 23 | + osutil.ExitIfError(func() error { |
| 24 | + repo, err := gitHubRepoRefFromGit() |
| 25 | + if err != nil { |
| 26 | + return err |
| 27 | + } |
| 28 | + |
| 29 | + // not interested in browser output |
| 30 | + browser.Stdout = io.Discard |
| 31 | + browser.Stderr = io.Discard |
| 32 | + |
| 33 | + return browser.OpenURL(githubURL(*repo)) |
| 34 | + }()) |
| 35 | + }, |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +func gitHubRepoRefFromGit() (*githubRepoRef, error) { |
| 40 | + conf, err := os.ReadFile(".git/config") |
| 41 | + if err != nil { |
| 42 | + return nil, err |
| 43 | + } |
| 44 | + |
| 45 | + // dirty |
| 46 | + originParseRe := regexp. MustCompile( `url = [email protected]:(.+)/(.+).git`) |
| 47 | + |
| 48 | + matches := originParseRe.FindStringSubmatch(string(conf)) |
| 49 | + if matches == nil { |
| 50 | + return nil, errors.New("unable to resolve GitHub organization/repo name") |
| 51 | + } |
| 52 | + |
| 53 | + org, repo := matches[1], matches[2] |
| 54 | + |
| 55 | + return &githubRepoRef{org, repo}, nil |
| 56 | +} |
| 57 | + |
| 58 | +type githubRepoRef struct { |
| 59 | + org string |
| 60 | + repo string |
| 61 | +} |
| 62 | + |
| 63 | +func githubURL(repo githubRepoRef) string { |
| 64 | + return fmt.Sprintf("https://github.com/%s/%s", repo.org, repo.repo) |
| 65 | +} |
0 commit comments