package cmd import ( "code.gitea.io/sdk/gitea" "errors" "gitea.com/jolheiser/beaver" "gitea.com/jolheiser/sip/modules/config" "github.com/AlecAivazis/survey/v2" "github.com/urfave/cli/v2" ) var TokensAdd = cli.Command{ Name: "add", 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: "token", Prompt: &survey.Input{Message: "Name for this token in Gitea", Default: "sip"}, Validate: survey.Required, }, { Name: "url", Prompt: &survey.Input{Message: "URL for the Gitea instance", Default: ctx.String("url")}, Validate: survey.Required, }, } answers := struct { Name string Token string URL string }{} if err := survey.Ask(questions, &answers); err != nil { return err } if token == "" { authQuestions := []*survey.Question{ { Name: "username", Prompt: &survey.Input{Message: "Username the Gitea instance"}, Validate: survey.Required, }, { Name: "password", Prompt: &survey.Password{Message: "Password for the Gitea instance"}, Validate: survey.Required, }, } authAnswers := struct { Username string Password string }{} if err := survey.Ask(authQuestions, &authAnswers); err != nil { return err } client := gitea.NewClient(answers.URL, "") t, err := client.CreateAccessToken(authAnswers.Username, authAnswers.Password, gitea.CreateAccessTokenOption{Name: answers.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) }