package flag import ( "fmt" "os" "strings" "forge.cadoles.com/Cadoles/emissary/internal/format" "forge.cadoles.com/Cadoles/emissary/internal/format/table" "github.com/pkg/errors" "github.com/urfave/cli/v2" ) const ( AuthTokenDefaultHomePath = "$HOME/.config/emissary/auth-token" AuthTokenDefaultLocalPath = ".emissary-token" ) func ComposeFlags(flags ...cli.Flag) []cli.Flag { baseFlags := []cli.Flag{ &cli.StringFlag{ Name: "server", Aliases: []string{"s"}, Usage: "use `SERVER` as server url", Value: "http://127.0.0.1:3000", }, &cli.StringFlag{ Name: "format", Aliases: []string{"f"}, Usage: fmt.Sprintf("use `FORMAT` as output format (available: %s)", format.Available()), Value: string(table.Format), }, &cli.StringFlag{ Name: "output-mode", Aliases: []string{"m"}, Usage: fmt.Sprintf("use `MODE` as output mode (available: %s)", []format.OutputMode{format.OutputModeCompact, format.OutputModeWide}), Value: string(format.OutputModeCompact), }, &cli.StringFlag{ Name: "token", Aliases: []string{"t"}, Usage: "use `TOKEN` as authentication token", }, &cli.StringSliceFlag{ Name: "token-file", Usage: "use `TOKEN_FILE` as file containing the authentication token", Value: cli.NewStringSlice(AuthTokenDefaultLocalPath, AuthTokenDefaultHomePath), TakesFile: true, }, } flags = append(flags, baseFlags...) return flags } type BaseFlags struct { ServerURL string Format format.Format OutputMode format.OutputMode Token string TokenFiles []string } func GetBaseFlags(ctx *cli.Context) *BaseFlags { serverURL := ctx.String("server") rawFormat := ctx.String("format") rawOutputMode := ctx.String("output-mode") tokenFiles := ctx.StringSlice("token-file") token := ctx.String("token") return &BaseFlags{ ServerURL: serverURL, Format: format.Format(rawFormat), OutputMode: format.OutputMode(rawOutputMode), Token: token, TokenFiles: tokenFiles, } } func GetToken(flags *BaseFlags) (string, error) { if flags.Token != "" { return flags.Token, nil } for _, tokenFile := range flags.TokenFiles { tokenFile = os.ExpandEnv(tokenFile) rawToken, err := os.ReadFile(tokenFile) if err != nil && !errors.Is(err, os.ErrNotExist) { return "", errors.WithStack(err) } if rawToken == nil { continue } return strings.TrimSpace(string(rawToken)), nil } return "", nil }