gospt/cmd/root.go

104 lines
2.3 KiB
Go
Raw Permalink Normal View History

2023-01-09 23:52:21 +00:00
package cmd
import (
2023-02-17 22:08:25 +00:00
"context"
2023-01-09 23:52:21 +00:00
"fmt"
"os"
2023-01-10 21:38:28 +00:00
"os/exec"
2023-01-09 23:52:21 +00:00
"path/filepath"
2023-01-10 21:38:28 +00:00
"strings"
2023-01-09 23:52:21 +00:00
2023-03-10 07:48:02 +00:00
cmds "git.asdf.cafe/abs3nt/gospt/src/commands"
2023-02-17 22:08:25 +00:00
2023-03-10 07:48:02 +00:00
"git.asdf.cafe/abs3nt/gospt/src/config"
"git.asdf.cafe/abs3nt/gospt/src/gctx"
2023-02-17 21:31:19 +00:00
"tuxpa.in/a/zlog"
2023-01-09 23:52:21 +00:00
"github.com/cristalhq/aconfig"
"github.com/cristalhq/aconfig/aconfigyaml"
"github.com/spf13/cobra"
)
var (
// Used for flags.
2023-04-07 01:11:06 +00:00
ctx *gctx.Context
commands *cmds.Commands
cfgFile string
verbose bool
2023-01-09 23:52:21 +00:00
rootCmd = &cobra.Command{
Use: "gospt",
Short: "A spotify TUI and CLI to manage playback, browse library, and generate radios",
Long: `A spotify TUI and CLI to manage playback, borwse library, and generate radios written in go`,
}
)
// Execute executes the root command.
func Execute(defCmd string) {
if len(os.Args) == 1 {
args := append([]string{defCmd}, os.Args[1:]...)
rootCmd.SetArgs(args)
}
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func init() {
2023-02-17 21:31:19 +00:00
zlog.SetGlobalLevel(zlog.DebugLevel)
2023-01-14 06:43:35 +00:00
if len(os.Args) > 1 {
if os.Args[1] == "completion" || os.Args[1] == "__complete" {
return
}
}
2023-02-17 21:31:19 +00:00
rootCmd.PersistentFlags().BoolVarP(&verbose, "verbose", "v", false, "enable verbose logging")
cobra.OnInitialize(func() {
if verbose {
zlog.SetGlobalLevel(zlog.TraceLevel)
}
})
2023-02-17 22:08:25 +00:00
ctx = gctx.NewContext(context.Background())
commands = &cmds.Commands{Context: ctx}
cobra.OnInitialize(initConfig)
2023-01-14 06:27:38 +00:00
}
2023-01-09 23:52:21 +00:00
func initConfig() {
2023-01-14 06:27:38 +00:00
configDir, _ := os.UserConfigDir()
cfgFile = filepath.Join(configDir, "gospt/client.yml")
2023-01-09 23:52:21 +00:00
yamlDecoder := aconfigyaml.New()
loader := aconfig.LoaderFor(&config.Values, aconfig.Config{
AllowUnknownFields: true,
AllowUnknownEnvs: true,
AllowUnknownFlags: true,
SkipFlags: true,
DontGenerateTags: true,
MergeFiles: true,
EnvPrefix: "",
FlagPrefix: "",
Files: []string{
cfgFile,
},
FileDecoders: map[string]aconfig.FileDecoder{
".yml": yamlDecoder,
},
})
if err := loader.Load(); err != nil {
panic(err)
}
2023-01-10 21:38:28 +00:00
if config.Values.ClientSecretCmd != "" {
args := strings.Fields(config.Values.ClientSecretCmd)
2023-04-07 01:11:06 +00:00
cmd := args[0]
secret_command := exec.Command(cmd)
if len(args) > 1 {
secret_command.Args = args
}
secret, err := secret_command.Output()
2023-01-10 21:38:28 +00:00
if err != nil {
panic(err)
}
config.Values.ClientSecret = strings.TrimSpace(string(secret))
}
2023-01-09 23:52:21 +00:00
}