124 lines
2.5 KiB
Go
124 lines
2.5 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"strings"
|
|
)
|
|
|
|
type options struct {
|
|
searchValue string
|
|
searchSet bool
|
|
includeDesc bool
|
|
prettyOutput bool
|
|
temperatureU string
|
|
clearCache bool
|
|
refresh bool
|
|
iconTest bool
|
|
radarMode bool
|
|
discussion bool
|
|
wayland bool
|
|
}
|
|
|
|
func parseArgs(args []string) (options, error) {
|
|
opts := options{temperatureU: "F"}
|
|
|
|
nextValue := func(i *int) (string, error) {
|
|
if *i+1 >= len(args) {
|
|
return "", fmt.Errorf("missing value for %s", args[*i])
|
|
}
|
|
*i = *i + 1
|
|
return args[*i], nil
|
|
}
|
|
|
|
for i := 0; i < len(args); i++ {
|
|
arg := args[i]
|
|
if !strings.HasPrefix(arg, "-") {
|
|
return opts, fmt.Errorf("unexpected argument: %s", arg)
|
|
}
|
|
|
|
if strings.HasPrefix(arg, "--") {
|
|
key, val, hasVal := strings.Cut(strings.TrimPrefix(arg, "--"), "=")
|
|
switch key {
|
|
case "search":
|
|
opts.searchSet = true
|
|
if hasVal {
|
|
opts.searchValue = val
|
|
} else if i+1 < len(args) && !strings.HasPrefix(args[i+1], "-") {
|
|
val, _ = nextValue(&i)
|
|
opts.searchValue = val
|
|
}
|
|
case "desc":
|
|
opts.includeDesc = true
|
|
case "pretty":
|
|
opts.prettyOutput = true
|
|
case "units":
|
|
if hasVal {
|
|
opts.temperatureU = val
|
|
} else {
|
|
val, err := nextValue(&i)
|
|
if err != nil {
|
|
return opts, err
|
|
}
|
|
opts.temperatureU = val
|
|
}
|
|
case "clear-cache":
|
|
opts.clearCache = true
|
|
case "refresh":
|
|
opts.refresh = true
|
|
case "icon-test":
|
|
opts.iconTest = true
|
|
case "radar":
|
|
opts.radarMode = true
|
|
case "discussion":
|
|
opts.discussion = true
|
|
case "wayland":
|
|
opts.wayland = true
|
|
default:
|
|
return opts, fmt.Errorf("unknown flag: --%s", key)
|
|
}
|
|
continue
|
|
}
|
|
|
|
switch arg {
|
|
case "-s":
|
|
opts.searchSet = true
|
|
if i+1 < len(args) && !strings.HasPrefix(args[i+1], "-") {
|
|
val, _ := nextValue(&i)
|
|
opts.searchValue = val
|
|
}
|
|
case "-d":
|
|
opts.includeDesc = true
|
|
case "-p":
|
|
opts.prettyOutput = true
|
|
case "-u":
|
|
val, err := nextValue(&i)
|
|
if err != nil {
|
|
return opts, err
|
|
}
|
|
opts.temperatureU = val
|
|
case "-c":
|
|
opts.clearCache = true
|
|
case "-r":
|
|
opts.refresh = true
|
|
case "-i":
|
|
opts.iconTest = true
|
|
case "-R":
|
|
opts.radarMode = true
|
|
case "-D":
|
|
opts.discussion = true
|
|
default:
|
|
return opts, fmt.Errorf("unknown flag: %s", arg)
|
|
}
|
|
}
|
|
|
|
opts.temperatureU = strings.ToUpper(strings.TrimSpace(opts.temperatureU))
|
|
if opts.temperatureU == "" {
|
|
opts.temperatureU = "F"
|
|
}
|
|
if opts.temperatureU != "F" && opts.temperatureU != "C" {
|
|
return opts, fmt.Errorf("invalid unit: %s", opts.temperatureU)
|
|
}
|
|
|
|
return opts, nil
|
|
}
|