1
0
mirror of https://gitea.com/jolheiser/sip synced 2024-11-23 04:12:00 +01:00
sip/cmd/cmd.go

121 lines
2.6 KiB
Go
Raw Normal View History

package cmd
import (
"code.gitea.io/sdk/gitea"
"errors"
"fmt"
"gitea.com/jolheiser/sip/modules/config"
"gitea.com/jolheiser/sip/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: "token",
Aliases: []string{"t"},
Usage: "The access 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("token") {
return getToken(ctx.String("token")), nil
}
tokenMap := make(map[string]config.Token)
opts := make([]string, len(config.Tokens))
for idx, token := range config.Tokens {
key := fmt.Sprintf("%s (%s)", token.Name, token.URL)
tokenMap[key] = token
opts[idx] = key
}
question := &survey.Select{Message: "This action requires an access token", Options: opts}
var answer string
if err := survey.AskOne(question, &answer); err != nil {
return "", err
}
return tokenMap[answer].Token, nil
}
func getToken(name string) string {
for _, token := range config.Tokens {
if name == token.Name {
return token.Token
}
}
return ""
}
func getClient(ctx *cli.Context) *gitea.Client {
return gitea.NewClient(ctx.String("url"), getToken(ctx.String("token")))
}
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
}