package cmd import ( "code.gitea.io/sdk/gitea" "errors" "fmt" "gitea.com/jolheiser/tea/modules/config" "gitea.com/jolheiser/tea/modules/git" "github.com/AlecAivazis/survey/v2" "github.com/urfave/cli/v2" "strings" "sync" ) var ( Flags = []cli.Flag{ &cli.StringFlag{ Name: "origin", Usage: "The origin remote", Value: config.Origin, }, &cli.StringFlag{ Name: "upstream", Usage: "The upstream remote", Value: config.Upstream, }, &cli.StringFlag{ Name: "url", Aliases: []string{"u"}, Usage: "The base URL to the Gitea instance", Value: getUpstreamRepo()[0], }, &cli.StringFlag{ Name: "owner", Aliases: []string{"o"}, Usage: "The owner to target", Value: getUpstreamRepo()[1], }, &cli.StringFlag{ Name: "repo", Aliases: []string{"r"}, Usage: "The repo to target", Value: getUpstreamRepo()[2], }, &cli.StringFlag{ Name: "login", Aliases: []string{"l"}, Usage: "The login token to use (by name)", }, } originOnce sync.Once originRepo []string upstreamOnce sync.Once upstreamRepo []string ) func requireToken(ctx *cli.Context) (string, error) { if ctx.IsSet("login") { return getToken(ctx.String("login")), nil } loginMap := make(map[string]config.Login) opts := make([]string, len(config.Logins)) for idx, login := range config.Logins { key := fmt.Sprintf("%s (%s)", login.Name, login.URL) loginMap[key] = login opts[idx] = key } question := &survey.Select{Message: "This action requires a login token", Options: opts} var answer string if err := survey.AskOne(question, &answer); err != nil { return "", err } return loginMap[answer].Token, nil } func getToken(name string) string { for _, login := range config.Logins { if name == login.Name { return login.Token } } return "" } func getClient(ctx *cli.Context) *gitea.Client { return gitea.NewClient(ctx.String("url"), getToken(ctx.String("login"))) } func getUpstreamRepo() []string { upstreamOnce.Do(func() { upstreamRepo = git.GetRepo(config.Upstream) if upstreamRepo == nil { upstreamRepo = git.GetRepo(config.Origin) } }) return upstreamRepo } func getOriginRepo() []string { originOnce.Do(func() { originRepo = git.GetRepo(config.Origin) }) return originRepo } func fullName(ctx *cli.Context) string { return ctx.String("owner") + "/" + ctx.String("repo") } func validateFullName(ans interface{}) error { fullName := ans.(string) ownerRepo := strings.Split(fullName, "/") if len(ownerRepo) != 2 { return errors.New("full repo name should be in form `owner/repo`") } return nil }