diff --git a/cmd/checkout.go b/cmd/checkout.go index 4f16cb4..8adbe80 100644 --- a/cmd/checkout.go +++ b/cmd/checkout.go @@ -31,9 +31,9 @@ func newCheckoutCommand() (c *cobra.Command) { flags.StringVarP(&opt.remote, "remote", "", "origin", "The remote name") flags.StringVarP(&opt.sshPrivateKey, "ssh-private-key", "", "$HOME/.ssh/id_rsa", "The SSH private key file path") - flags.StringVarP(&opt.branch, "branch", "", "master", "The branch want to checkout") + flags.StringVarP(&opt.branch, "branch", "b", "master", "The branch want to checkout. It could be a short name or fullname. Such as master or refs/heads/master") flags.StringVarP(&opt.tag, "tag", "", "", "The tag want to checkout") - flags.IntVarP(&opt.pr, "pr", "", -1, "The pr number want to checkout, -1 means do nothing") + flags.IntVarP(&opt.pr, "pr", "p", -1, "The pr number want to checkout, -1 means do nothing") flags.StringVarP(&opt.target, "target", "", ".", "Clone git repository to the target path") flags.StringVarP(&opt.versionOutput, "version-output", "", "", "Write the version to target file") return @@ -43,6 +43,7 @@ func (o *checkoutOption) preRunE(c *cobra.Command, args []string) (err error) { if o.url == "" && len(args) > 0 { o.url = args[0] } + o.branch = strings.TrimPrefix(o.branch, "refs/heads/") return } diff --git a/cmd/checkout_test.go b/cmd/checkout_test.go index 549a173..75a6610 100644 --- a/cmd/checkout_test.go +++ b/cmd/checkout_test.go @@ -84,3 +84,50 @@ func TestGetAuth(t *testing.T) { assert.Nil(t, auth) assert.Nil(t, err) } + +func TestPreRunE(t *testing.T) { + const sampleGit = "https://github.com/linuxsuren/gogit" + const anotherGit = "https://github.com/linuxsuren/gogit.git" + + tests := []struct { + name string + opt *checkoutOption + args []string + expectErr bool + verify func(t *testing.T, opt *checkoutOption) + }{{ + name: "url is empty", + opt: &checkoutOption{}, + args: []string{sampleGit}, + expectErr: false, + verify: func(t *testing.T, opt *checkoutOption) { + assert.Equal(t, sampleGit, opt.url) + }, + }, { + name: "url is not empty", + opt: &checkoutOption{url: anotherGit}, + args: []string{sampleGit}, + expectErr: false, + verify: func(t *testing.T, opt *checkoutOption) { + assert.Equal(t, anotherGit, opt.url) + }, + }, { + name: "branch is fullname", + opt: &checkoutOption{branch: "refs/heads/master"}, + expectErr: false, + verify: func(t *testing.T, opt *checkoutOption) { + assert.Equal(t, "master", opt.branch) + }, + }} + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := tt.opt.preRunE(nil, tt.args) + if tt.expectErr { + assert.NotNil(t, err) + } else { + assert.Nil(t, err) + } + tt.verify(t, tt.opt) + }) + } +}