From de5a00e807fe9228745ffc15bb15dc51f64d1336 Mon Sep 17 00:00:00 2001 From: Norwin Date: Wed, 30 Sep 2020 19:44:22 +0000 Subject: [PATCH] Refactor addLoginMain() (#201) simplify NormalizeURL drop noisy log line must have been introduced recently? dont use PascalCase for default login names ...for readability. :fire: opinionated commit create GenerateLoginName() fixes fixup! Merge branch 'master' into refactor-loginMain move GetOwnerAndRepo() to modules/utils/parse.go Merge branch 'master' into refactor-loginMain make linter happy refactor addLoginMain() Co-authored-by: Norwin Roosen Reviewed-on: https://gitea.com/gitea/tea/pulls/201 Reviewed-by: 6543 <6543@noreply.gitea.io> Reviewed-by: Andrew Thornton --- cmd/pulls/create.go | 3 +- cmd/repos.go | 3 +- modules/config/config.go | 14 ---- modules/config/login.go | 156 ++++++++++++++++++++------------------ modules/interact/login.go | 4 +- modules/utils/parse.go | 23 ++++++ 6 files changed, 111 insertions(+), 92 deletions(-) diff --git a/cmd/pulls/create.go b/cmd/pulls/create.go index ee6564c..dbeb267 100644 --- a/cmd/pulls/create.go +++ b/cmd/pulls/create.go @@ -13,6 +13,7 @@ import ( "code.gitea.io/tea/modules/config" local_git "code.gitea.io/tea/modules/git" "code.gitea.io/tea/modules/print" + "code.gitea.io/tea/modules/utils" "code.gitea.io/sdk/gitea" "github.com/go-git/go-git/v5" @@ -106,7 +107,7 @@ func runPullsCreate(ctx *cli.Context) error { if err != nil { log.Fatal(err) } - owner, _ := config.GetOwnerAndRepo(strings.TrimLeft(url.Path, "/"), "") + owner, _ := utils.GetOwnerAndRepo(strings.TrimLeft(url.Path, "/"), "") head = fmt.Sprintf("%s:%s", owner, branchName) } diff --git a/cmd/repos.go b/cmd/repos.go index 208a3b6..d355dc9 100644 --- a/cmd/repos.go +++ b/cmd/repos.go @@ -9,6 +9,7 @@ import ( "code.gitea.io/tea/cmd/repos" "code.gitea.io/tea/modules/config" "code.gitea.io/tea/modules/print" + "code.gitea.io/tea/modules/utils" "code.gitea.io/sdk/gitea" "github.com/urfave/cli/v2" @@ -38,7 +39,7 @@ func runRepos(ctx *cli.Context) error { func runRepoDetail(path string) error { login := config.InitCommandLoginOnly(flags.GlobalLoginValue) client := login.Client() - repoOwner, repoName := config.GetOwnerAndRepo(path, login.User) + repoOwner, repoName := utils.GetOwnerAndRepo(path, login.User) repo, _, err := client.GetRepo(repoOwner, repoName) if err != nil { return err diff --git a/modules/config/config.go b/modules/config/config.go index fbefe38..e5a5cf6 100644 --- a/modules/config/config.go +++ b/modules/config/config.go @@ -56,7 +56,6 @@ func LoadConfig() error { ymlPath := GetConfigPath() exist, _ := utils.FileExist(ymlPath) if exist { - fmt.Println("Found config file", ymlPath) bs, err := ioutil.ReadFile(ymlPath) if err != nil { return err @@ -145,16 +144,3 @@ func curGitRepoPath(repoValue, remoteValue string) (*Login, string, error) { return nil, "", errors.New("No Gitea login found. You might want to specify --repo (and --login) to work outside of a repository") } - -// GetOwnerAndRepo return repoOwner and repoName -// based on relative path and default owner (if not in path) -func GetOwnerAndRepo(repoPath, user string) (string, string) { - if len(repoPath) == 0 { - return "", "" - } - p := strings.Split(repoPath, "/") - if len(p) >= 2 { - return p[0], p[1] - } - return user, repoPath -} diff --git a/modules/config/login.go b/modules/config/login.go index 14eb553..374b074 100644 --- a/modules/config/login.go +++ b/modules/config/login.go @@ -13,7 +13,6 @@ import ( "net/http/cookiejar" "net/url" "os" - "strings" "time" "code.gitea.io/tea/modules/utils" @@ -72,6 +71,29 @@ func (l *Login) GetSSHHost() string { return u.Hostname() } +// GenerateToken creates a new token when given BasicAuth credentials +func (l *Login) GenerateToken(user, pass string) (string, error) { + client := l.Client() + gitea.SetBasicAuth(user, pass)(client) + + host, _ := os.Hostname() + tl, _, err := client.ListAccessTokens(gitea.ListAccessTokensOptions{}) + if err != nil { + return "", err + } + tokenName := host + "-tea" + + for i := range tl { + if tl[i].Name == tokenName { + tokenName += time.Now().Format("2006-01-02_15-04-05") + break + } + } + + t, _, err := client.CreateAccessToken(gitea.CreateAccessTokenOption{Name: tokenName}) + return t.Token, err +} + // GetDefaultLogin return the default login func GetDefaultLogin() (*Login, error) { if len(Config.Logins) == 0 { @@ -98,7 +120,6 @@ func GetLoginByName(name string) *Login { // AddLogin add login to config ( global var & file) func AddLogin(name, token, user, passwd, sshKey, giteaURL string, insecure bool) error { - if len(giteaURL) == 0 { log.Fatal("You have to input Gitea server URL") } @@ -110,79 +131,45 @@ func AddLogin(name, token, user, passwd, sshKey, giteaURL string, insecure bool) log.Fatal("No user set") } - err := LoadConfig() + serverURL, err := utils.NormalizeURL(giteaURL) if err != nil { - log.Fatal(err) + log.Fatal("Unable to parse URL", err) } - httpClient := &http.Client{} - if insecure { - cookieJar, _ := cookiejar.New(nil) - httpClient = &http.Client{ - Jar: cookieJar, - Transport: &http.Transport{ - TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, - }} - } - client, err := gitea.NewClient(giteaURL, - gitea.SetToken(token), - gitea.SetBasicAuth(user, passwd), - gitea.SetHTTPClient(httpClient), - ) + err = LoadConfig() if err != nil { - log.Fatal(err) + log.Fatal("Unable to load config file " + yamlConfigPath) } - u, _, err := client.GetMyUserInfo() - if err != nil { - log.Fatal(err) - } - - if len(token) == 0 { - // create token - host, _ := os.Hostname() - tl, _, err := client.ListAccessTokens(gitea.ListAccessTokensOptions{}) - if err != nil { - return err - } - tokenName := host + "-tea" - for i := range tl { - if tl[i].Name == tokenName { - tokenName += time.Now().Format("2006-01-02_15-04-05") - break - } - } - t, _, err := client.CreateAccessToken(gitea.CreateAccessTokenOption{Name: tokenName}) - if err != nil { - return err - } - token = t.Token - } - - fmt.Println("Login successful! Login name " + u.UserName) - - if len(name) == 0 { - parsedURL, err := url.Parse(giteaURL) - if err != nil { - return err - } - name = strings.ReplaceAll(strings.Title(parsedURL.Host), ".", "") - for _, l := range Config.Logins { - if l.Name == name { - name += "_" + u.UserName - break - } - } - } - - err = addLoginToConfig(Login{ + login := Login{ Name: name, - URL: giteaURL, + URL: serverURL.String(), Token: token, Insecure: insecure, SSHKey: sshKey, - User: u.UserName, - }) + } + + if len(token) == 0 { + login.Token, err = login.GenerateToken(user, passwd) + if err != nil { + log.Fatal(err) + } + } + + u, _, err := login.Client().GetMyUserInfo() + if err != nil { + log.Fatal(err) + } + login.User = u.UserName + + if len(login.Name) == 0 { + login.Name, err = GenerateLoginName(giteaURL, login.User) + if err != nil { + log.Fatal(err) + } + } + + err = addLoginToConfig(login) if err != nil { log.Fatal(err) } @@ -192,9 +179,32 @@ func AddLogin(name, token, user, passwd, sshKey, giteaURL string, insecure bool) log.Fatal(err) } + fmt.Printf("Login as %s on %s successful. Added this login as %s\n", login.User, login.URL, login.Name) + return nil } +// GenerateLoginName generates a name string based on instance URL & adds username if the result is not unique +func GenerateLoginName(url, user string) (string, error) { + parsedURL, err := utils.NormalizeURL(url) + if err != nil { + return "", err + } + name := parsedURL.Host + + // append user name if login name already exists + if len(user) != 0 { + for _, l := range Config.Logins { + if l.Name == name { + name += "_" + user + break + } + } + } + + return name, nil +} + // addLoginToConfig add a login to global Config var func addLoginToConfig(login Login) error { for _, l := range Config.Logins { @@ -205,18 +215,18 @@ func addLoginToConfig(login Login) error { return errors.New("Login name has already been used") } if l.URL == login.URL && l.Token == login.Token { - return errors.New("URL has been added") + return errors.New("Login for this URL and token already exists") } } - u, err := url.Parse(login.URL) - if err != nil { - return err - } - - if login.SSHHost == "" { + if len(login.SSHHost) == 0 { + u, err := url.Parse(login.URL) + if err != nil { + return err + } login.SSHHost = u.Hostname() } + Config.Logins = append(Config.Logins, login) return nil @@ -254,7 +264,7 @@ func InitCommand(repoValue, loginValue, remoteValue string) (*Login, string, str } } - owner, repo := GetOwnerAndRepo(repoValue, login.User) + owner, repo := utils.GetOwnerAndRepo(repoValue, login.User) return login, owner, repo } diff --git a/modules/interact/login.go b/modules/interact/login.go index 4248cfb..dc34efc 100644 --- a/modules/interact/login.go +++ b/modules/interact/login.go @@ -6,7 +6,6 @@ package interact import ( "fmt" - "net/url" "strings" "code.gitea.io/tea/modules/config" @@ -27,11 +26,10 @@ func CreateLogin() error { return nil } - parsedURL, err := url.Parse(giteaURL) + name, err := config.GenerateLoginName(giteaURL, "") if err != nil { return err } - name = strings.ReplaceAll(strings.Title(parsedURL.Host), ".", "") fmt.Print("Name of new Login [" + name + "]: ") if _, err := fmt.Scanln(&stdin); err != nil { diff --git a/modules/utils/parse.go b/modules/utils/parse.go index 452b7e5..e3e9395 100644 --- a/modules/utils/parse.go +++ b/modules/utils/parse.go @@ -5,6 +5,7 @@ package utils import ( + "net/url" "strconv" "strings" ) @@ -16,3 +17,25 @@ func ArgToIndex(arg string) (int64, error) { } return strconv.ParseInt(arg, 10, 64) } + +// NormalizeURL normalizes the input with a protocol +func NormalizeURL(raw string) (*url.URL, error) { + var prefix string + if !strings.HasPrefix(raw, "http") { + prefix = "https://" + } + return url.Parse(prefix + raw) +} + +// GetOwnerAndRepo return repoOwner and repoName +// based on relative path and default owner (if not in path) +func GetOwnerAndRepo(repoPath, user string) (string, string) { + if len(repoPath) == 0 { + return "", "" + } + p := strings.Split(repoPath, "/") + if len(p) >= 2 { + return p[0], p[1] + } + return user, repoPath +}