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

94 lines
2.1 KiB
Go
Raw Normal View History

package cmd
import (
"code.gitea.io/sdk/gitea"
"errors"
"gitea.com/jolheiser/tea/modules/config"
"github.com/urfave/cli/v2"
"os/exec"
"strings"
"sync"
)
var (
Flags = []cli.Flag{
&cli.StringFlag{
Name: "url",
Aliases: []string{"u"},
Usage: "The base URL to the Gitea instance",
Value: getRepo()[0],
},
&cli.StringFlag{
Name: "owner",
Aliases: []string{"o"},
Usage: "The owner to target",
Value: getRepo()[1],
},
&cli.StringFlag{
Name: "repo",
Aliases: []string{"r"},
Usage: "The repo to target",
Value: getRepo()[2],
},
&cli.StringFlag{
Name: "login",
Aliases: []string{"l"},
Usage: "The login token to use (by name)",
},
}
once sync.Once
repo []string
)
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 getRepo() []string {
once.Do(func() {
cmd := exec.Command("git", "remote", "get-url", "origin")
out, err := cmd.Output()
if err != nil {
repo = []string{"", ""}
}
remote := strings.TrimSpace(string(out))
if strings.Contains(remote, "@") { // SSH
remote = remote[strings.Index(remote, "@")+1:]
parts := strings.Split(remote, ":")
domain := "https://" + parts[0]
ownerRepo := strings.Split(parts[1], "/")
repo = []string{domain, ownerRepo[0], strings.TrimRight(ownerRepo[1], ".git")}
} else { // HTTP(S)
parts := strings.Split(remote, "/")
domain := parts[:len(parts)-2]
ownerRepo := parts[len(parts)-2:]
repo = []string{strings.Join(domain, "/"), ownerRepo[0], strings.TrimRight(ownerRepo[1], ".git")}
}
})
return repo
}
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
}