diff options
Diffstat (limited to 'bridge/github/config.go')
-rw-r--r-- | bridge/github/config.go | 228 |
1 files changed, 69 insertions, 159 deletions
diff --git a/bridge/github/config.go b/bridge/github/config.go index cc312230..b6f69d74 100644 --- a/bridge/github/config.go +++ b/bridge/github/config.go @@ -1,7 +1,6 @@ package github import ( - "bufio" "bytes" "context" "encoding/json" @@ -10,14 +9,11 @@ import ( "io/ioutil" "math/rand" "net/http" - "os" "regexp" "sort" - "strconv" "strings" "time" - text "github.com/MichaelMure/go-term-text" "github.com/pkg/errors" "github.com/MichaelMure/git-bug/bridge/core" @@ -25,19 +21,24 @@ import ( "github.com/MichaelMure/git-bug/cache" "github.com/MichaelMure/git-bug/input" "github.com/MichaelMure/git-bug/repository" - "github.com/MichaelMure/git-bug/util/colors" ) var ( ErrBadProjectURL = errors.New("bad project url") ) -func (g *Github) Configure(repo *cache.RepoCache, params core.BridgeParams) (core.Configuration, error) { - if params.BaseURL != "" { - fmt.Println("warning: --base-url is ineffective for a Github bridge") +func (g *Github) ValidParams() map[string]interface{} { + return map[string]interface{}{ + "URL": nil, + "Login": nil, + "CredPrefix": nil, + "TokenRaw": nil, + "Owner": nil, + "Project": nil, } +} - conf := make(core.Configuration) +func (g *Github) Configure(repo *cache.RepoCache, params core.BridgeParams) (core.Configuration, error) { var err error var owner string var project string @@ -86,7 +87,7 @@ func (g *Github) Configure(repo *cache.RepoCache, params core.BridgeParams) (cor } login = l case params.TokenRaw != "": - token := auth.NewToken(params.TokenRaw, target) + token := auth.NewToken(target, params.TokenRaw) login, err = getLoginFromToken(token) if err != nil { return nil, err @@ -121,9 +122,10 @@ func (g *Github) Configure(repo *cache.RepoCache, params core.BridgeParams) (cor return nil, fmt.Errorf("project doesn't exist or authentication token has an incorrect scope") } + conf := make(core.Configuration) conf[core.ConfigKeyTarget] = target - conf[keyOwner] = owner - conf[keyProject] = project + conf[confKeyOwner] = owner + conf[confKeyProject] = project err = g.ValidateConfig(conf) if err != nil { @@ -148,18 +150,18 @@ func (*Github) ValidateConfig(conf core.Configuration) error { return fmt.Errorf("unexpected target name: %v", v) } - if _, ok := conf[keyOwner]; !ok { - return fmt.Errorf("missing %s key", keyOwner) + if _, ok := conf[confKeyOwner]; !ok { + return fmt.Errorf("missing %s key", confKeyOwner) } - if _, ok := conf[keyProject]; !ok { - return fmt.Errorf("missing %s key", keyProject) + if _, ok := conf[confKeyProject]; !ok { + return fmt.Errorf("missing %s key", confKeyProject) } return nil } -func usernameValidator(name string, value string) (string, error) { +func usernameValidator(_ string, value string) (string, error) { ok, err := validateUsername(value) if err != nil { return "", err @@ -241,67 +243,36 @@ func randomFingerprint() string { } func promptTokenOptions(repo repository.RepoConfig, login, owner, project string) (auth.Credential, error) { - for { - creds, err := auth.List(repo, - auth.WithTarget(target), - auth.WithKind(auth.KindToken), - auth.WithMeta(auth.MetaKeyLogin, login), - ) - if err != nil { - return nil, err - } - - fmt.Println() - fmt.Println("[1]: enter my token") - fmt.Println("[2]: interactive token creation") - - if len(creds) > 0 { - sort.Sort(auth.ById(creds)) - - fmt.Println() - fmt.Println("Existing tokens for Github:") - for i, cred := range creds { - token := cred.(*auth.Token) - fmt.Printf("[%d]: %s => %s (login: %s, %s)\n", - i+3, - colors.Cyan(token.ID().Human()), - colors.Red(text.TruncateMax(token.Value, 10)), - token.Metadata()[auth.MetaKeyLogin], - token.CreateTime().Format(time.RFC822), - ) - } - } - - fmt.Println() - fmt.Print("Select option: ") + creds, err := auth.List(repo, + auth.WithTarget(target), + auth.WithKind(auth.KindToken), + auth.WithMeta(auth.MetaKeyLogin, login), + ) + if err != nil { + return nil, err + } - line, err := bufio.NewReader(os.Stdin).ReadString('\n') - fmt.Println() + cred, index, err := input.PromptCredential(target, "token", creds, []string{ + "enter my token", + "interactive token creation", + }) + switch { + case err != nil: + return nil, err + case cred != nil: + return cred, nil + case index == 0: + return promptToken() + case index == 1: + value, err := loginAndRequestToken(login, owner, project) if err != nil { return nil, err } - - line = strings.TrimSpace(line) - index, err := strconv.Atoi(line) - if err != nil || index < 1 || index > len(creds)+2 { - fmt.Println("invalid input") - continue - } - - switch index { - case 1: - return promptToken() - case 2: - value, err := loginAndRequestToken(login, owner, project) - if err != nil { - return nil, err - } - token := auth.NewToken(value, target) - token.SetMetadata(auth.MetaKeyLogin, login) - return token, nil - default: - return creds[index-3], nil - } + token := auth.NewToken(target, value) + token.SetMetadata(auth.MetaKeyLogin, login) + return token, nil + default: + panic("missed case") } } @@ -316,10 +287,7 @@ func promptToken() (*auth.Token, error) { fmt.Println(" - 'repo' : to be able to read private repositories") fmt.Println() - re, err := regexp.Compile(`^[a-zA-Z0-9]{40}$`) - if err != nil { - panic("regexp compile:" + err.Error()) - } + re := regexp.MustCompile(`^[a-zA-Z0-9]{40}$`) var login string @@ -327,7 +295,7 @@ func promptToken() (*auth.Token, error) { if !re.MatchString(value) { return "token has incorrect format", nil } - login, err = getLoginFromToken(auth.NewToken(value, target)) + login, err = getLoginFromToken(auth.NewToken(target, value)) if err != nil { return fmt.Sprintf("token is invalid: %v", err), nil } @@ -339,7 +307,7 @@ func promptToken() (*auth.Token, error) { return nil, err } - token := auth.NewToken(rawToken, target) + token := auth.NewToken(target, rawToken) token.SetMetadata(auth.MetaKeyLogin, login) return token, nil @@ -356,31 +324,19 @@ func loginAndRequestToken(login, owner, project string) (string, error) { fmt.Println() // prompt project visibility to know the token scope needed for the repository - i, err := input.PromptChoice("repository visibility", []string{"public", "private"}) + index, err := input.PromptChoice("repository visibility", []string{"public", "private"}) if err != nil { return "", err } - isPublic := i == 0 + scope := []string{"public_repo", "repo"}[index] password, err := input.PromptPassword("Password", "password", input.Required) if err != nil { return "", err } - var scope string - if isPublic { - // public_repo is requested to be able to read public repositories - scope = "public_repo" - } else { - // 'repo' is request to be able to read private repositories - // /!\ token will have read/write rights on every private repository you have access to - scope = "repo" - } - // Attempt to authenticate and create a token - note := fmt.Sprintf("git-bug - %s/%s", owner, project) - resp, err := requestToken(note, login, password, scope) if err != nil { return "", err @@ -413,73 +369,25 @@ func loginAndRequestToken(login, owner, project string) (string, error) { } func promptURL(repo repository.RepoCommon) (string, string, error) { - // remote suggestions - remotes, err := repo.GetRemotes() + validRemotes, err := getValidGithubRemoteURLs(repo) if err != nil { return "", "", err } - validRemotes := getValidGithubRemoteURLs(remotes) - if len(validRemotes) > 0 { - for { - fmt.Println("\nDetected projects:") - - // print valid remote github urls - for i, remote := range validRemotes { - fmt.Printf("[%d]: %v\n", i+1, remote) - } - - fmt.Printf("\n[0]: Another project\n\n") - fmt.Printf("Select option: ") - - line, err := bufio.NewReader(os.Stdin).ReadString('\n') - if err != nil { - return "", "", err - } - - line = strings.TrimSpace(line) - - index, err := strconv.Atoi(line) - if err != nil || index < 0 || index > len(validRemotes) { - fmt.Println("invalid input") - continue - } - - // if user want to enter another project url break this loop - if index == 0 { - break - } - - // get owner and project with index - owner, project, _ := splitURL(validRemotes[index-1]) - return owner, project, nil - } - } - - // manually enter github url - for { - fmt.Print("Github project URL: ") - - line, err := bufio.NewReader(os.Stdin).ReadString('\n') + validator := func(name, value string) (string, error) { + _, _, err := splitURL(value) if err != nil { - return "", "", err - } - - line = strings.TrimSpace(line) - if line == "" { - fmt.Println("URL is empty") - continue - } - - // get owner and project from url - owner, project, err := splitURL(line) - if err != nil { - fmt.Println(err) - continue + return err.Error(), nil } + return "", nil + } - return owner, project, nil + url, err := input.PromptURLWithRemote("Github project URL", "URL", validRemotes, input.Required, validator) + if err != nil { + return "", "", err } + + return splitURL(url) } // splitURL extract the owner and project from a github repository URL. It will remove the @@ -488,10 +396,7 @@ func promptURL(repo repository.RepoCommon) (string, string, error) { func splitURL(url string) (owner string, project string, err error) { cleanURL := strings.TrimSuffix(url, ".git") - re, err := regexp.Compile(`github\.com[/:]([a-zA-Z0-9\-_]+)/([a-zA-Z0-9\-_.]+)`) - if err != nil { - panic("regexp compile:" + err.Error()) - } + re := regexp.MustCompile(`github\.com[/:]([a-zA-Z0-9\-_]+)/([a-zA-Z0-9\-_.]+)`) res := re.FindStringSubmatch(cleanURL) if res == nil { @@ -503,7 +408,12 @@ func splitURL(url string) (owner string, project string, err error) { return } -func getValidGithubRemoteURLs(remotes map[string]string) []string { +func getValidGithubRemoteURLs(repo repository.RepoCommon) ([]string, error) { + remotes, err := repo.GetRemotes() + if err != nil { + return nil, err + } + urls := make([]string, 0, len(remotes)) for _, url := range remotes { // split url can work again with shortURL @@ -516,7 +426,7 @@ func getValidGithubRemoteURLs(remotes map[string]string) []string { sort.Strings(urls) - return urls + return urls, nil } func validateUsername(username string) (bool, error) { |