vanity/cmd/vanity-cli/cmd.go

128 lines
3.0 KiB
Go
Raw Permalink Normal View History

package main
import (
"context"
"flag"
"fmt"
"net/url"
"strings"
"go.jolheiser.com/vanity/sdk"
"github.com/AlecAivazis/survey/v2"
"github.com/peterbourgon/ff/v3"
"github.com/peterbourgon/ff/v3/ffcli"
"github.com/peterbourgon/ff/v3/fftoml"
)
func New() *ffcli.Command {
fs := flag.NewFlagSet("vanity", flag.ExitOnError)
serverFlag := fs.String("server", sdk.DefaultServer, "vanity server to use")
tokenFlag := fs.String("token", "", "vanity auth token to use")
cmd := &ffcli.Command{
Name: "vanity",
ShortUsage: "vanity [add|update|remove]",
ShortHelp: "Vanity CLI",
LongHelp: "Vanity CLI to work with a remote Vanity server",
FlagSet: fs,
Options: []ff.Option{
ff.WithEnvVarPrefix("VANITY"),
ff.WithAllowMissingConfigFile(true),
ff.WithConfigFileFlag("config"),
ff.WithConfigFileParser(fftoml.New().Parse),
},
Subcommands: []*ffcli.Command{
{
Name: "add",
ShortHelp: "add package",
LongHelp: "add a package to the vanity server",
Exec: add(tokenFlag, serverFlag),
},
{
Name: "remove",
ShortHelp: "remove package",
LongHelp: "remove a package from the vanity server",
Exec: remove(tokenFlag, serverFlag),
},
{
Name: "update",
ShortHelp: "update package",
LongHelp: "update a package on the vanity server",
Exec: update(tokenFlag, serverFlag),
},
},
}
return cmd
}
func listPackages(token, server string) ([]sdk.Package, error) {
client := sdk.New(token, sdk.WithServer(server))
info, err := client.Info(context.Background())
if err != nil {
return nil, err
}
return info.Packages, nil
}
func pkgPrompt(def sdk.Package) (sdk.Package, error) {
if def.Branch == "" {
def.Branch = "main"
}
var pkg sdk.Package
questions := []*survey.Question{
{
Name: "name",
Prompt: &survey.Input{Message: "Name", Default: def.Name},
Validate: survey.Required,
},
{
Name: "description",
Prompt: &survey.Multiline{Message: "Description", Default: def.Description},
Validate: survey.Required,
},
{
Name: "branch",
Prompt: &survey.Input{Message: "Branch", Default: def.Branch},
Validate: survey.Required,
},
{
Name: "weburl",
Prompt: &survey.Input{Message: "Web URL", Default: def.WebURL},
Validate: validURL,
},
}
if err := survey.Ask(questions, &pkg); err != nil {
return pkg, err
}
defHTTP, defSSH := def.CloneHTTP, def.CloneSSH
if def.WebURL != pkg.WebURL {
u, err := url.Parse(pkg.WebURL)
if err != nil {
return pkg, err
}
defHTTP = pkg.WebURL + ".git"
defSSH = fmt.Sprintf("git@%s:%s.git", u.Host, strings.TrimPrefix(u.Path, "/"))
}
questions = []*survey.Question{
{
Name: "clonehttp",
Prompt: &survey.Input{Message: "HTTP(S) CLone URL", Default: defHTTP},
Validate: validURL,
},
{
Name: "clonessh",
Prompt: &survey.Input{Message: "SSH CLone URL", Default: defSSH},
Validate: survey.Required,
},
}
if err := survey.Ask(questions, &pkg); err != nil {
return pkg, err
}
return pkg, nil
}