From b02263adb0f0bffeefe08616ce7b65bb0843d331 Mon Sep 17 00:00:00 2001 From: appleboy Date: Sun, 30 Apr 2023 11:43:26 +0800 Subject: [PATCH] refactor: improve code quality and efficiency in various files (#548) - Replace loadConfig() with _ = loadConfig() - Update file permissions from 0660 to 0o660 - Simplify variable declarations - Replace golang.org/x/crypto/ssh/terminal with golang.org/x/term - Remove unused getCertPrincipals function - Replace time.Now().Sub() with time.Since() - Add test for ArgToIndex function Signed-off-by: appleboy Co-authored-by: Lunny Xiao Reviewed-on: https://gitea.com/gitea/tea/pulls/548 Reviewed-by: Lunny Xiao Reviewed-by: techknowlogick Co-authored-by: appleboy Co-committed-by: appleboy --- go.mod | 2 +- modules/config/config.go | 4 +-- modules/git/url.go | 11 +++----- modules/interact/comments.go | 4 +-- modules/print/comment.go | 6 ++--- modules/print/formatters.go | 4 +-- modules/print/issue.go | 8 +++--- modules/print/login.go | 2 +- modules/print/markdown.go | 6 ++--- modules/print/organization.go | 2 +- modules/print/repo.go | 4 +-- modules/print/table.go | 1 - modules/task/login_httpsign.go | 12 --------- modules/task/repo_clone.go | 7 +++-- modules/utils/parse.go | 5 +--- modules/utils/parse_test.go | 48 ++++++++++++++++++++++++++++++++++ 16 files changed, 78 insertions(+), 48 deletions(-) create mode 100644 modules/utils/parse_test.go diff --git a/go.mod b/go.mod index d519255..2e853e6 100644 --- a/go.mod +++ b/go.mod @@ -18,6 +18,7 @@ require ( github.com/stretchr/testify v1.7.0 github.com/urfave/cli/v2 v2.16.3 golang.org/x/crypto v0.0.0-20220926161630-eccd6366d1be + golang.org/x/term v0.0.0-20220722155259-a9ba230a4035 gopkg.in/yaml.v2 v2.4.0 ) @@ -60,7 +61,6 @@ require ( github.com/yuin/goldmark-emoji v1.0.1 // indirect golang.org/x/net v0.0.0-20220909164309-bea034e7d591 // indirect golang.org/x/sys v0.0.0-20220926163933-8cfa568d3c25 // indirect - golang.org/x/term v0.0.0-20220722155259-a9ba230a4035 // indirect golang.org/x/text v0.3.7 // indirect golang.org/x/tools v0.1.12 // indirect gopkg.in/warnings.v0 v0.1.2 // indirect diff --git a/modules/config/config.go b/modules/config/config.go index 203e3d1..062417b 100644 --- a/modules/config/config.go +++ b/modules/config/config.go @@ -74,7 +74,7 @@ func GetConfigPath() string { // GetPreferences returns preferences based on the config file func GetPreferences() Preferences { - loadConfig() + _ = loadConfig() return config.Prefs } @@ -105,5 +105,5 @@ func saveConfig() error { if err != nil { return err } - return ioutil.WriteFile(ymlPath, bs, 0660) + return ioutil.WriteFile(ymlPath, bs, 0o660) } diff --git a/modules/git/url.go b/modules/git/url.go index f76a666..f076f94 100644 --- a/modules/git/url.go +++ b/modules/git/url.go @@ -10,13 +10,10 @@ import ( "strings" ) -var ( - protocolRe = regexp.MustCompile("^[a-zA-Z_+-]+://") -) +var protocolRe = regexp.MustCompile("^[a-zA-Z_+-]+://") // URLParser represents a git URL parser -type URLParser struct { -} +type URLParser struct{} // Parse parses the git URL func (p *URLParser) Parse(rawURL string) (u *url.URL, err error) { @@ -50,9 +47,7 @@ func (p *URLParser) Parse(rawURL string) (u *url.URL, err error) { } // .git suffix is optional and breaks normalization - if strings.HasSuffix(u.Path, ".git") { - u.Path = strings.TrimSuffix(u.Path, ".git") - } + u.Path = strings.TrimSuffix(u.Path, ".git") return } diff --git a/modules/interact/comments.go b/modules/interact/comments.go index 194335d..99b59e0 100644 --- a/modules/interact/comments.go +++ b/modules/interact/comments.go @@ -13,7 +13,7 @@ import ( "code.gitea.io/tea/modules/print" "github.com/AlecAivazis/survey/v2" - "golang.org/x/crypto/ssh/terminal" + "golang.org/x/term" ) // ShowCommentsMaybeInteractive fetches & prints comments, depending on the --comments flag. @@ -72,5 +72,5 @@ func ShowCommentsPaginated(ctx *context.TeaContext, idx int64, totalComments int // IsStdinPiped checks if stdin is piped func IsStdinPiped() bool { - return !terminal.IsTerminal(int(os.Stdin.Fd())) + return !term.IsTerminal(int(os.Stdin.Fd())) } diff --git a/modules/print/comment.go b/modules/print/comment.go index 64947d1..db8b342 100644 --- a/modules/print/comment.go +++ b/modules/print/comment.go @@ -18,12 +18,12 @@ func Comments(comments []*gitea.Comment) { baseURL = getRepoURL(comments[0].HTMLURL) } - var out = make([]string, len(comments)) + out := make([]string, len(comments)) for i, c := range comments { out[i] = formatComment(c) } - outputMarkdown(fmt.Sprintf( + _ = outputMarkdown(fmt.Sprintf( // this will become a heading by means of the first --- from a comment "Comments\n%s", strings.Join(out, "\n"), @@ -32,7 +32,7 @@ func Comments(comments []*gitea.Comment) { // Comment renders a comment to stdout func Comment(c *gitea.Comment) { - outputMarkdown(formatComment(c), getRepoURL(c.HTMLURL)) + _ = outputMarkdown(formatComment(c), getRepoURL(c.HTMLURL)) } func formatComment(c *gitea.Comment) string { diff --git a/modules/print/formatters.go b/modules/print/formatters.go index ec53fa0..4b3da6e 100644 --- a/modules/print/formatters.go +++ b/modules/print/formatters.go @@ -12,12 +12,12 @@ import ( "code.gitea.io/sdk/gitea" "github.com/muesli/termenv" - "golang.org/x/crypto/ssh/terminal" + "golang.org/x/term" ) // IsInteractive checks if the output is piped, but NOT if the session is run interactively.. func IsInteractive() bool { - return terminal.IsTerminal(int(os.Stdout.Fd())) + return term.IsTerminal(int(os.Stdout.Fd())) } // captures the repo URL part // of an url diff --git a/modules/print/issue.go b/modules/print/issue.go index ec1c892..6478f1f 100644 --- a/modules/print/issue.go +++ b/modules/print/issue.go @@ -28,7 +28,7 @@ func IssueDetails(issue *gitea.Issue, reactions []*gitea.Reaction) { out += fmt.Sprintf("\n---\n\n%s\n", formatReactions(reactions)) } - outputMarkdown(out, getRepoURL(issue.HTMLURL)) + _ = outputMarkdown(out, getRepoURL(issue.HTMLURL)) } func formatReactions(reactions []*gitea.Reaction) string { @@ -74,7 +74,7 @@ var IssueFields = []string{ func printIssues(issues []*gitea.Issue, output string, fields []string) { labelMap := map[int64]string{} - var printables = make([]printable, len(issues)) + printables := make([]printable, len(issues)) machineReadable := isMachineReadable(output) for i, x := range issues { @@ -133,13 +133,13 @@ func (x printableIssue) FormatField(field string, machineReadable bool) string { } return "" case "labels": - var labels = make([]string, len(x.Labels)) + labels := make([]string, len(x.Labels)) for i, l := range x.Labels { labels[i] = (*x.formattedLabels)[l.ID] } return strings.Join(labels, " ") case "assignees": - var assignees = make([]string, len(x.Assignees)) + assignees := make([]string, len(x.Assignees)) for i, a := range x.Assignees { assignees[i] = formatUserName(a) } diff --git a/modules/print/login.go b/modules/print/login.go index e8bd5d5..0a13cc8 100644 --- a/modules/print/login.go +++ b/modules/print/login.go @@ -28,7 +28,7 @@ func LoginDetails(login *config.Login) { } in += fmt.Sprintf("\nCreated: %s", time.Unix(login.Created, 0).Format(time.RFC822)) - outputMarkdown(in, "") + _ = outputMarkdown(in, "") } // LoginsList prints a listing of logins diff --git a/modules/print/markdown.go b/modules/print/markdown.go index 99318ab..5daac47 100644 --- a/modules/print/markdown.go +++ b/modules/print/markdown.go @@ -9,7 +9,7 @@ import ( "os" "github.com/charmbracelet/glamour" - "golang.org/x/crypto/ssh/terminal" + "golang.org/x/term" ) // outputMarkdown prints markdown to stdout, formatted for terminals. @@ -47,8 +47,8 @@ func outputMarkdown(markdown string, baseURL string) error { func getWordWrap() int { fd := int(os.Stdout.Fd()) width := 80 - if terminal.IsTerminal(fd) { - if w, _, err := terminal.GetSize(fd); err == nil { + if term.IsTerminal(fd) { + if w, _, err := term.GetSize(fd); err == nil { width = w } } diff --git a/modules/print/organization.go b/modules/print/organization.go index a9e10c6..ae6c9bd 100644 --- a/modules/print/organization.go +++ b/modules/print/organization.go @@ -12,7 +12,7 @@ import ( // OrganizationDetails prints details of an org with formatting func OrganizationDetails(org *gitea.Organization) { - outputMarkdown(fmt.Sprintf( + _ = outputMarkdown(fmt.Sprintf( "# %s\n%s\n\n- Visibility: %s\n- Location: %s\n- Website: %s\n", org.UserName, org.Description, diff --git a/modules/print/repo.go b/modules/print/repo.go index e7c3962..bb2984f 100644 --- a/modules/print/repo.go +++ b/modules/print/repo.go @@ -14,7 +14,7 @@ import ( // ReposList prints a listing of the repos func ReposList(repos []*gitea.Repository, output string, fields []string) { - var printables = make([]printable, len(repos)) + printables := make([]printable, len(repos)) for i, r := range repos { printables[i] = &printableRepo{r} } @@ -56,7 +56,7 @@ func RepoDetails(repo *gitea.Repository, topics []string) { updated := fmt.Sprintf( "Updated: %s (%s ago)\n", repo.Updated.Format("2006-01-02 15:04"), - time.Now().Sub(repo.Updated).Truncate(time.Minute), + time.Since(repo.Updated).Truncate(time.Minute), ) urls := fmt.Sprintf( diff --git a/modules/print/table.go b/modules/print/table.go index 1ce6b34..b36b739 100644 --- a/modules/print/table.go +++ b/modules/print/table.go @@ -66,7 +66,6 @@ func (t *table) sort(column uint, desc bool) { func (t table) Len() int { return len(t.values) } func (t table) Swap(i, j int) { t.values[i], t.values[j] = t.values[j], t.values[i] } func (t table) Less(i, j int) bool { - const column = 0 if t.sortDesc { i, j = j, i } diff --git a/modules/task/login_httpsign.go b/modules/task/login_httpsign.go index 4b77c64..e2dc233 100644 --- a/modules/task/login_httpsign.go +++ b/modules/task/login_httpsign.go @@ -91,15 +91,3 @@ func parseKeys(pkinput []byte, sshPath string) string { return ssh.FingerprintSHA256(pkey) + " " + pkey.Type() + " " + comment + " (" + sshPath + ")" } - -func getCertPrincipals(pkey ssh.PublicKey) []string { - var principals []string - - if cert, ok := pkey.(*ssh.Certificate); ok { - for _, principal := range cert.ValidPrincipals { - principals = append(principals, principal) - } - } - - return principals -} diff --git a/modules/task/repo_clone.go b/modules/task/repo_clone.go index bc164fc..e9e3497 100644 --- a/modules/task/repo_clone.go +++ b/modules/task/repo_clone.go @@ -26,7 +26,6 @@ func RepoClone( callback func(string) (string, error), depth int, ) (*local_git.TeaRepo, error) { - repoMeta, _, err := login.Client().GetRepo(repoOwner, repoName) if err != nil { return nil, err @@ -64,10 +63,14 @@ func RepoClone( return nil, err } upstreamBranch := repoMeta.Parent.DefaultBranch - repo.CreateRemote(&git_config.RemoteConfig{ + _, err = repo.CreateRemote(&git_config.RemoteConfig{ Name: "upstream", URLs: []string{upstreamURL.String()}, }) + if err != nil { + return nil, err + } + repoConf, err := repo.Config() if err != nil { return nil, err diff --git a/modules/utils/parse.go b/modules/utils/parse.go index 94aa8e9..1c4c220 100644 --- a/modules/utils/parse.go +++ b/modules/utils/parse.go @@ -24,10 +24,7 @@ func ArgsToIndices(args []string) ([]int64, error) { // ArgToIndex take issue/pull index as string and return int64 func ArgToIndex(arg string) (int64, error) { - if strings.HasPrefix(arg, "#") { - arg = arg[1:] - } - return strconv.ParseInt(arg, 10, 64) + return strconv.ParseInt(strings.TrimPrefix(arg, "#"), 10, 64) } // NormalizeURL normalizes the input with a protocol diff --git a/modules/utils/parse_test.go b/modules/utils/parse_test.go new file mode 100644 index 0000000..e213b2c --- /dev/null +++ b/modules/utils/parse_test.go @@ -0,0 +1,48 @@ +// Copyright 2023 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package utils + +import "testing" + +func TestArgToIndex(t *testing.T) { + tests := []struct { + name string + arg string + want int64 + wantErr bool + }{ + { + name: "Valid argument", + arg: "#123", + want: 123, + wantErr: false, + }, + { + name: "Invalid argument", + arg: "abc", + want: 0, + wantErr: true, + }, + { + name: "Empty argument", + arg: "", + want: 0, + wantErr: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := ArgToIndex(tt.arg) + if (err != nil) != tt.wantErr { + t.Errorf("ArgToIndex() error = %v, wantErr %v", err, tt.wantErr) + return + } + if got != tt.want { + t.Errorf("ArgToIndex() = %v, want %v", got, tt.want) + } + }) + } +}