From a447c078cfa3a293fe1225d18ef572dccf2f4a63 Mon Sep 17 00:00:00 2001 From: Yuta Iwama Date: Mon, 15 Aug 2022 20:43:11 +0900 Subject: [PATCH] Enable browsing to commit page (#5729) --- pkg/cmd/browse/browse.go | 15 +++++++++++++++ pkg/cmd/browse/browse_test.go | 29 +++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/pkg/cmd/browse/browse.go b/pkg/cmd/browse/browse.go index 7d29f9723..5129e45a9 100644 --- a/pkg/cmd/browse/browse.go +++ b/pkg/cmd/browse/browse.go @@ -6,6 +6,7 @@ import ( "net/url" "path" "path/filepath" + "regexp" "strconv" "strings" @@ -62,6 +63,9 @@ func NewCmdBrowse(f *cmdutil.Factory, runF func(*BrowseOptions) error) *cobra.Co $ gh browse 217 #=> Open issue or pull request 217 + $ gh browse 77507cd94ccafcf568f8560cfecde965fcfa63 + #=> Open commit page + $ gh browse --settings #=> Open repository settings @@ -169,6 +173,10 @@ func parseSection(baseRepo ghrepo.Interface, opts *BrowseOptions) (string, error return fmt.Sprintf("issues/%s", opts.SelectorArg), nil } + if isCommit(opts.SelectorArg) { + return fmt.Sprintf("commit/%s", opts.SelectorArg), nil + } + filePath, rangeStart, rangeEnd, err := parseFile(*opts, opts.SelectorArg) if err != nil { return "", err @@ -252,6 +260,13 @@ func isNumber(arg string) bool { return err == nil } +// sha1 and sha256 are supported +var commitHash = regexp.MustCompile(`\A[a-f0-9]{7,64}\z`) + +func isCommit(arg string) bool { + return commitHash.MatchString(arg) +} + // gitClient is used to implement functions that can be performed on both local and remote git repositories type gitClient interface { LastCommit() (*git.Commit, error) diff --git a/pkg/cmd/browse/browse_test.go b/pkg/cmd/browse/browse_test.go index 576818431..380a6fc1c 100644 --- a/pkg/cmd/browse/browse_test.go +++ b/pkg/cmd/browse/browse_test.go @@ -414,6 +414,35 @@ func Test_runBrowse(t *testing.T) { expectedURL: "https://github.com/bchadwic/test/blob/branch/with%20spaces%3F/%3F=hello%20world/%20%2A?plain=1#L23-L44", wantsErr: false, }, + { + name: "commit hash in selector arg", + opts: BrowseOptions{ + SelectorArg: "77507cd94ccafcf568f8560cfecde965fcfa63e7", + }, + baseRepo: ghrepo.New("bchadwic", "test"), + expectedURL: "https://github.com/bchadwic/test/commit/77507cd94ccafcf568f8560cfecde965fcfa63e7", + wantsErr: false, + }, + { + name: "short commit hash in selector arg", + opts: BrowseOptions{ + SelectorArg: "6e3689d5", + }, + baseRepo: ghrepo.New("bchadwic", "test"), + expectedURL: "https://github.com/bchadwic/test/commit/6e3689d5", + wantsErr: false, + }, + + { + name: "commit hash with extension", + opts: BrowseOptions{ + SelectorArg: "77507cd94ccafcf568f8560cfecde965fcfa63e7.txt", + Branch: "trunk", + }, + baseRepo: ghrepo.New("bchadwic", "test"), + expectedURL: "https://github.com/bchadwic/test/tree/trunk/77507cd94ccafcf568f8560cfecde965fcfa63e7.txt", + wantsErr: false, + }, } for _, tt := range tests {