Merge pull request #3773 from bchadwic/first-browse-pull

Feature/Create browse command
This commit is contained in:
Nate Smith 2021-06-29 09:17:30 -07:00 committed by GitHub
commit 0474ba686d
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 488 additions and 0 deletions

177
pkg/cmd/browse/browse.go Normal file
View file

@ -0,0 +1,177 @@
package browse
import (
"fmt"
"net/http"
"strconv"
"strings"
"github.com/MakeNowJust/heredoc"
"github.com/cli/cli/api"
"github.com/cli/cli/internal/ghrepo"
"github.com/cli/cli/pkg/cmdutil"
"github.com/cli/cli/pkg/iostreams"
"github.com/spf13/cobra"
)
type browser interface {
Browse(string) error
}
type BrowseOptions struct {
BaseRepo func() (ghrepo.Interface, error)
Browser browser
HttpClient func() (*http.Client, error)
IO *iostreams.IOStreams
SelectorArg string
Branch string
ProjectsFlag bool
SettingsFlag bool
WikiFlag bool
}
func NewCmdBrowse(f *cmdutil.Factory, runF func(*BrowseOptions) error) *cobra.Command {
opts := &BrowseOptions{
Browser: f.Browser,
HttpClient: f.HttpClient,
IO: f.IOStreams,
}
cmd := &cobra.Command{
Long: "Open the GitHub repository in the web browser.",
Short: "Open the repository in the browser",
Use: "browse [<number> | <path>]",
Args: cobra.MaximumNArgs(1),
Example: heredoc.Doc(`
$ gh browse
#=> Open the home page of the current repository
$ gh browse 217
#=> Open issue or pull request 217
$ gh browse --settings
#=> Open repository settings
$ gh browse main.go:312
#=> Open main.go at line 312
$ gh browse main.go --branch main
#=> Open main.go in the main branch
`),
Annotations: map[string]string{
"IsCore": "true",
"help:arguments": heredoc.Doc(`
A browser location can be specified using arguments in the following format:
- by number for issue or pull request, e.g. "123"; or
- by path for opening folders and files, e.g. "cmd/gh/main.go"
`),
"help:environment": heredoc.Doc(`
To configure a web browser other than the default, use the BROWSER environment variable.
`),
},
RunE: func(cmd *cobra.Command, args []string) error {
opts.BaseRepo = f.BaseRepo
if len(args) > 0 {
opts.SelectorArg = args[0]
}
if err := cmdutil.MutuallyExclusive(
"specify only one of `--branch`, `--projects`, `--wiki`, or `--settings`",
opts.Branch != "",
opts.WikiFlag,
opts.SettingsFlag,
opts.ProjectsFlag,
); err != nil {
return err
}
if runF != nil {
return runF(opts)
}
return runBrowse(opts)
},
}
cmdutil.EnableRepoOverride(cmd, f)
cmd.Flags().BoolVarP(&opts.ProjectsFlag, "projects", "p", false, "Open repository projects")
cmd.Flags().BoolVarP(&opts.WikiFlag, "wiki", "w", false, "Open repository wiki")
cmd.Flags().BoolVarP(&opts.SettingsFlag, "settings", "s", false, "Open repository settings")
cmd.Flags().StringVarP(&opts.Branch, "branch", "b", "", "Select another branch by passing in the branch name")
return cmd
}
func runBrowse(opts *BrowseOptions) error {
baseRepo, err := opts.BaseRepo()
if err != nil {
return fmt.Errorf("unable to determine base repository: %w", err)
}
httpClient, err := opts.HttpClient()
if err != nil {
return fmt.Errorf("unable to create an http client: %w", err)
}
url := ghrepo.GenerateRepoURL(baseRepo, "")
if opts.SelectorArg == "" {
if opts.ProjectsFlag {
url += "/projects"
}
if opts.SettingsFlag {
url += "/settings"
}
if opts.WikiFlag {
url += "/wiki"
}
if opts.Branch != "" {
url += "/tree/" + opts.Branch + "/"
}
} else {
if isNumber(opts.SelectorArg) {
url += "/issues/" + opts.SelectorArg
} else {
fileArg, err := parseFileArg(opts.SelectorArg)
if err != nil {
return err
}
if opts.Branch != "" {
url += "/tree/" + opts.Branch + "/"
} else {
apiClient := api.NewClientFromHTTP(httpClient)
branchName, err := api.RepoDefaultBranch(apiClient, baseRepo)
if err != nil {
return err
}
url += "/tree/" + branchName + "/"
}
url += fileArg
}
}
if opts.IO.IsStdoutTTY() {
fmt.Fprintf(opts.IO.Out, "now opening %s in browser\n", url)
}
return opts.Browser.Browse(url)
}
func parseFileArg(fileArg string) (string, error) {
arr := strings.Split(fileArg, ":")
if len(arr) > 2 {
return "", fmt.Errorf("invalid use of colon\nUse 'gh browse --help' for more information about browse\n")
}
if len(arr) > 1 {
if !isNumber(arr[1]) {
return "", fmt.Errorf("invalid line number after colon\nUse 'gh browse --help' for more information about browse\n")
}
return arr[0] + "#L" + arr[1], nil
}
return arr[0], nil
}
func isNumber(arg string) bool {
_, err := strconv.Atoi(arg)
return err == nil
}

View file

@ -0,0 +1,309 @@
package browse
import (
"net/http"
"testing"
"github.com/cli/cli/internal/ghrepo"
"github.com/cli/cli/pkg/cmdutil"
"github.com/cli/cli/pkg/httpmock"
"github.com/cli/cli/pkg/iostreams"
"github.com/google/shlex"
"github.com/stretchr/testify/assert"
)
func TestNewCmdBrowse(t *testing.T) {
tests := []struct {
name string
cli string
factory func(*cmdutil.Factory) *cmdutil.Factory
wants BrowseOptions
wantsErr bool
}{
{
name: "no arguments",
cli: "",
wantsErr: false,
},
{
name: "settings flag",
cli: "--settings",
wants: BrowseOptions{
SettingsFlag: true,
},
wantsErr: false,
},
{
name: "projects flag",
cli: "--projects",
wants: BrowseOptions{
ProjectsFlag: true,
},
wantsErr: false,
},
{
name: "wiki flag",
cli: "--wiki",
wants: BrowseOptions{
WikiFlag: true,
},
wantsErr: false,
},
{
name: "branch flag",
cli: "--branch main",
wants: BrowseOptions{
Branch: "main",
},
wantsErr: false,
},
{
name: "branch flag without a branch name",
cli: "--branch",
wantsErr: true,
},
{
name: "combination: settings projects",
cli: "--settings --projects",
wants: BrowseOptions{
SettingsFlag: true,
ProjectsFlag: true,
},
wantsErr: true,
},
{
name: "combination: projects wiki",
cli: "--projects --wiki",
wants: BrowseOptions{
ProjectsFlag: true,
WikiFlag: true,
},
wantsErr: true,
},
{
name: "passed argument",
cli: "main.go",
wants: BrowseOptions{
SelectorArg: "main.go",
},
wantsErr: false,
},
{
name: "passed two arguments",
cli: "main.go main.go",
wantsErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
f := cmdutil.Factory{}
var opts *BrowseOptions
cmd := NewCmdBrowse(&f, func(o *BrowseOptions) error {
opts = o
return nil
})
argv, err := shlex.Split(tt.cli)
assert.NoError(t, err)
cmd.SetArgs(argv)
_, err = cmd.ExecuteC()
if tt.wantsErr {
assert.Error(t, err)
return
} else {
assert.NoError(t, err)
}
assert.Equal(t, tt.wants.Branch, opts.Branch)
assert.Equal(t, tt.wants.SelectorArg, opts.SelectorArg)
assert.Equal(t, tt.wants.ProjectsFlag, opts.ProjectsFlag)
assert.Equal(t, tt.wants.WikiFlag, opts.WikiFlag)
assert.Equal(t, tt.wants.SettingsFlag, opts.SettingsFlag)
})
}
}
func Test_runBrowse(t *testing.T) {
tests := []struct {
name string
opts BrowseOptions
baseRepo ghrepo.Interface
defaultBranch string
expectedURL string
wantsErr bool
}{
{
name: "no arguments",
opts: BrowseOptions{
SelectorArg: "",
},
baseRepo: ghrepo.New("jlsestak", "cli"),
expectedURL: "https://github.com/jlsestak/cli",
},
{
name: "settings flag",
opts: BrowseOptions{
SettingsFlag: true,
},
baseRepo: ghrepo.New("bchadwic", "ObscuredByClouds"),
expectedURL: "https://github.com/bchadwic/ObscuredByClouds/settings",
},
{
name: "projects flag",
opts: BrowseOptions{
ProjectsFlag: true,
},
baseRepo: ghrepo.New("ttran112", "7ate9"),
expectedURL: "https://github.com/ttran112/7ate9/projects",
},
{
name: "wiki flag",
opts: BrowseOptions{
WikiFlag: true,
},
baseRepo: ghrepo.New("ravocean", "ThreatLevelMidnight"),
expectedURL: "https://github.com/ravocean/ThreatLevelMidnight/wiki",
},
{
name: "file argument",
opts: BrowseOptions{SelectorArg: "path/to/file.txt"},
baseRepo: ghrepo.New("ken", "mrprofessor"),
defaultBranch: "main",
expectedURL: "https://github.com/ken/mrprofessor/tree/main/path/to/file.txt",
},
{
name: "issue argument",
opts: BrowseOptions{
SelectorArg: "217",
},
baseRepo: ghrepo.New("kevin", "MinTy"),
expectedURL: "https://github.com/kevin/MinTy/issues/217",
},
{
name: "branch flag",
opts: BrowseOptions{
Branch: "trunk",
},
baseRepo: ghrepo.New("jlsestak", "CouldNotThinkOfARepoName"),
expectedURL: "https://github.com/jlsestak/CouldNotThinkOfARepoName/tree/trunk/",
},
{
name: "branch flag with file",
opts: BrowseOptions{
Branch: "trunk",
SelectorArg: "main.go",
},
baseRepo: ghrepo.New("bchadwic", "LedZeppelinIV"),
expectedURL: "https://github.com/bchadwic/LedZeppelinIV/tree/trunk/main.go",
},
{
name: "file with line number",
opts: BrowseOptions{
SelectorArg: "path/to/file.txt:32",
},
baseRepo: ghrepo.New("ravocean", "angur"),
defaultBranch: "trunk",
expectedURL: "https://github.com/ravocean/angur/tree/trunk/path/to/file.txt#L32",
},
{
name: "file with invalid line number",
opts: BrowseOptions{
SelectorArg: "path/to/file.txt:32:32",
},
baseRepo: ghrepo.New("ttran112", "ttrain211"),
wantsErr: true,
},
{
name: "branch with issue number",
opts: BrowseOptions{
SelectorArg: "217",
Branch: "trunk",
},
baseRepo: ghrepo.New("ken", "grc"),
wantsErr: false,
expectedURL: "https://github.com/ken/grc/issues/217",
},
{
name: "opening branch file with line number",
opts: BrowseOptions{
Branch: "first-browse-pull",
SelectorArg: "browse.go:32",
},
baseRepo: ghrepo.New("github", "ThankYouGitHub"),
wantsErr: false,
expectedURL: "https://github.com/github/ThankYouGitHub/tree/first-browse-pull/browse.go#L32",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
io, _, stdout, stderr := iostreams.Test()
browser := cmdutil.TestBrowser{}
reg := httpmock.Registry{}
defer reg.Verify(t)
if tt.defaultBranch != "" {
reg.StubRepoInfoResponse(tt.baseRepo.RepoOwner(), tt.baseRepo.RepoName(), tt.defaultBranch)
}
opts := tt.opts
opts.IO = io
opts.BaseRepo = func() (ghrepo.Interface, error) {
return tt.baseRepo, nil
}
opts.HttpClient = func() (*http.Client, error) {
return &http.Client{Transport: &reg}, nil
}
opts.Browser = &browser
err := runBrowse(&opts)
if tt.wantsErr {
assert.Error(t, err)
} else {
assert.NoError(t, err)
}
assert.Equal(t, "", stdout.String())
assert.Equal(t, "", stderr.String())
browser.Verify(t, tt.expectedURL)
})
}
}
func Test_parseFileArg(t *testing.T) {
tests := []struct {
name string
arg string
errorExpected bool
expectedFileArg string
stderrExpected string
}{
{
name: "non line number",
arg: "main.go",
errorExpected: false,
expectedFileArg: "main.go",
},
{
name: "line number",
arg: "main.go:32",
errorExpected: false,
expectedFileArg: "main.go#L32",
},
{
name: "non line number error",
arg: "ma:in.go",
errorExpected: true,
stderrExpected: "invalid line number after colon\nUse 'gh browse --help' for more information about browse\n",
},
}
for _, tt := range tests {
fileArg, err := parseFileArg(tt.arg)
if tt.errorExpected {
assert.Equal(t, err.Error(), tt.stderrExpected)
} else {
assert.Equal(t, err, nil)
assert.Equal(t, tt.expectedFileArg, fileArg)
}
}
}

View file

@ -8,6 +8,7 @@ import (
aliasCmd "github.com/cli/cli/pkg/cmd/alias"
apiCmd "github.com/cli/cli/pkg/cmd/api"
authCmd "github.com/cli/cli/pkg/cmd/auth"
browseCmd "github.com/cli/cli/pkg/cmd/browse"
completionCmd "github.com/cli/cli/pkg/cmd/completion"
configCmd "github.com/cli/cli/pkg/cmd/config"
extensionsCmd "github.com/cli/cli/pkg/cmd/extensions"
@ -88,6 +89,7 @@ func NewCmdRoot(f *cmdutil.Factory, version, buildDate string) *cobra.Command {
repoResolvingCmdFactory := *f
repoResolvingCmdFactory.BaseRepo = factory.SmartBaseRepoFunc(f)
cmd.AddCommand(browseCmd.NewCmdBrowse(&repoResolvingCmdFactory, nil))
cmd.AddCommand(prCmd.NewCmdPR(&repoResolvingCmdFactory))
cmd.AddCommand(issueCmd.NewCmdIssue(&repoResolvingCmdFactory))
cmd.AddCommand(releaseCmd.NewCmdRelease(&repoResolvingCmdFactory))