lume/cmd/main.go

107 lines
1.9 KiB
Go
Raw Normal View History

package lumecmd
import (
"errors"
"flag"
"fmt"
"os"
2021-02-14 00:42:47 +00:00
"strings"
"git.kill0.net/chill9/lifx-go"
"github.com/BurntSushi/toml"
)
2021-02-14 00:42:47 +00:00
var userAgent string
2021-02-11 04:16:15 +00:00
2021-02-03 00:37:26 +00:00
func init() {
2021-02-14 00:42:47 +00:00
userAgent = initUserAgent()
2021-02-17 05:24:32 +00:00
RegisterCommand(NewCmdHelp())
RegisterCommand(NewCmdLs())
RegisterCommand(NewCmdPoweroff())
RegisterCommand(NewCmdPoweron())
RegisterCommand(NewCmdSetColor())
RegisterCommand(NewCmdSetState())
RegisterCommand(NewCmdSetWhite())
RegisterCommand(NewCmdShow())
RegisterCommand(NewCmdToggle())
2021-02-28 04:42:09 +00:00
RegisterCommand(NewCmdVersion())
2021-02-03 00:37:26 +00:00
}
2021-03-11 03:39:47 +00:00
var Version string
2021-03-03 02:41:18 +00:00
var BuildDate string
2021-03-11 03:39:47 +00:00
var GitCommit string
2021-02-28 04:42:09 +00:00
func Main(args []string) (int, error) {
var config Config
var err error
if len(args) == 1 {
args = append(args, "help")
}
configPath := getConfigPath()
if configPath == "" {
err = errors.New("fatal: ~/.lumerc was not found")
2021-01-31 17:08:24 +00:00
return ExitFailure, err
}
if _, err := toml.DecodeFile(configPath, &config); err != nil {
err = fmt.Errorf("fatal: failed to parse %s; %w", configPath, err)
2021-01-31 17:08:24 +00:00
return ExitFailure, err
}
envAccessToken := os.Getenv("LIFX_ACCESS_TOKEN")
if envAccessToken != "" {
config.AccessToken = envAccessToken
}
2021-01-21 05:09:37 +00:00
if err = config.Validate(); err != nil {
2021-01-31 17:08:24 +00:00
return ExitFailure, fmt.Errorf("fatal: %s", err)
}
flag.Parse()
command := args[1]
c := lifx.NewClient(
config.AccessToken,
lifx.WithUserAgent(userAgent),
)
cmdArgs := CmdArgs{
Client: c,
Config: config,
2021-03-04 05:31:27 +00:00
Args: args[2:],
}
cmd, ok := GetCommand(command)
if !ok {
err = fmt.Errorf("lume: '%s' is not lume command. See 'lume help'", command)
2021-01-31 17:08:24 +00:00
return ExitFailure, err
}
2021-03-04 05:31:27 +00:00
fs := cmd.Flags
if fs != nil {
fs.Parse(args[2:])
cmdArgs.Flags = Flags{FlagSet: fs}
}
2021-02-07 23:31:19 +00:00
cmdArgs.Name = command
2021-03-04 05:31:27 +00:00
exitCode, err := cmd.Func(cmdArgs)
if err != nil {
err = fmt.Errorf("fatal: %s", err)
}
return exitCode, err
}
2021-02-14 00:42:47 +00:00
func initUserAgent() string {
var b strings.Builder
b.WriteString("lume")
b.WriteRune('/')
b.WriteString(Version)
return b.String()
}