treefmt/cli/mappers.go
Brian McGee 1b517c6502
feat: add --on-unmatched
By default, if a path does not match any formatter a log message at WARN level will be emitted. A user can change this by providing the `--on-unmatched` or `-u` flag and specifying a log level `debug,info,warn,error,fatal`.

If fatal, the process will exit with an error on the first unmatched path encountered.

Closes #302

Signed-off-by: Brian McGee <brian@bmcgee.ie>
2024-05-29 10:32:02 +01:00

40 lines
780 B
Go

package cli
import (
"fmt"
"reflect"
"github.com/alecthomas/kong"
"github.com/charmbracelet/log"
)
var Options []kong.Option
func init() {
Options = []kong.Option{
kong.TypeMapper(reflect.TypeOf(log.DebugLevel), logLevelDecoder()),
}
}
func logLevelDecoder() kong.MapperFunc {
return func(ctx *kong.DecodeContext, target reflect.Value) error {
t, err := ctx.Scan.PopValue("string")
if err != nil {
return err
}
var str string
switch v := t.Value.(type) {
case string:
str = v
default:
return fmt.Errorf("expected a string but got %q (%T)", t, t.Value)
}
level, err := log.ParseLevel(str)
if err != nil {
return fmt.Errorf("failed to parse '%v' as log level: %w", level, err)
}
target.Set(reflect.ValueOf(level))
return nil
}
}