1
0
mirror of https://gitea.com/jolheiser/sip synced 2024-11-26 07:33:48 +01:00
sip/cmd/token_add.go
John Olheiser bb773780df Update Beaver and fix bugs (#6)
Fix CI test

Fix origin names in PR create

Add aliases for new issue/PR and fix issues search

Update beaver and squash some bugs

Signed-off-by: jolheiser <john.olheiser@gmail.com>

Co-authored-by: jolheiser <john.olheiser@gmail.com>
Reviewed-on: https://gitea.com/jolheiser/sip/pulls/6
2020-02-27 02:53:11 +00:00

104 lines
2.3 KiB
Go

package cmd
import (
"code.gitea.io/sdk/gitea"
"errors"
"gitea.com/jolheiser/sip/modules/config"
"github.com/AlecAivazis/survey/v2"
"github.com/urfave/cli/v2"
"go.jolheiser.com/beaver"
)
var TokensAdd = cli.Command{
Name: "add",
Aliases: []string{"create"},
Usage: "Add a new access token",
Action: doTokenAdd,
}
func doTokenAdd(ctx *cli.Context) error {
token := ctx.Args().First()
questions := []*survey.Question{
{
Name: "name",
Prompt: &survey.Input{Message: "Local nickname for this token", Default: "gitea"},
Validate: validateTokenName,
},
{
Name: "url",
Prompt: &survey.Input{Message: "URL for the Gitea instance", Default: ctx.String("url")},
Validate: survey.Required,
},
}
answers := struct {
Name string
URL string
}{}
if err := survey.Ask(questions, &answers); err != nil {
return err
}
if token == "" {
giteaQuestions := []*survey.Question{
{
Name: "token",
Prompt: &survey.Input{Message: "Name for this token in Gitea", Default: "sip"},
Validate: survey.Required,
},
{
Name: "username",
Prompt: &survey.Input{Message: "Username for the Gitea instance"},
Validate: survey.Required,
},
{
Name: "password",
Prompt: &survey.Password{Message: "Password for the Gitea instance"},
Validate: survey.Required,
},
}
giteaAnswers := struct {
Token string
Username string
Password string
}{}
if err := survey.Ask(giteaQuestions, &giteaAnswers); err != nil {
return err
}
client := gitea.NewClient(answers.URL, "")
t, err := client.CreateAccessToken(giteaAnswers.Username, giteaAnswers.Password, gitea.CreateAccessTokenOption{Name: giteaAnswers.Token})
if err != nil {
return err
}
token = t.Token
}
config.Tokens = append(config.Tokens, config.Token{
Name: answers.Name,
URL: answers.URL,
Token: token,
})
if err := config.Save(); err != nil {
return err
}
beaver.Infof("Token saved! You can refer to it by using `--token %s` with commands!", answers.Name)
return nil
}
func validateTokenName(ans interface{}) error {
name := ans.(string)
for _, token := range config.Tokens {
if name == token.Name {
return errors.New("token already exists")
}
}
return survey.Required(ans)
}