github.com/maresnic/mr-kong@v1.0.0/util.go (about) 1 package kong 2 3 import ( 4 "fmt" 5 "os" 6 "reflect" 7 ) 8 9 // ConfigFlag uses the configured (via kong.Configuration(loader)) configuration loader to load configuration 10 // from a file specified by a flag. 11 // 12 // Use this as a flag value to support loading of custom configuration via a flag. 13 type ConfigFlag string 14 15 // BeforeResolve adds a resolver. 16 func (c ConfigFlag) BeforeResolve(kong *Kong, ctx *Context, trace *Path) error { 17 if kong.loader == nil { 18 return fmt.Errorf("kong must be configured with kong.Configuration(...)") 19 } 20 path := string(ctx.FlagValue(trace.Flag).(ConfigFlag)) //nolint 21 resolver, err := kong.LoadConfig(path) 22 if err != nil { 23 return err 24 } 25 ctx.AddResolver(resolver) 26 return nil 27 } 28 29 // VersionFlag is a flag type that can be used to display a version number, stored in the "version" variable. 30 type VersionFlag bool 31 32 // BeforeReset writes the version variable and terminates with a 0 exit status. 33 func (v VersionFlag) BeforeReset(app *Kong, vars Vars) error { 34 fmt.Fprintln(app.Stdout, vars["version"]) 35 app.Exit(0) 36 return nil 37 } 38 39 // ChangeDirFlag changes the current working directory to a path specified by a flag 40 // early in the parsing process, changing how other flags resolve relative paths. 41 // 42 // Use this flag to provide a "git -C" like functionality. 43 // 44 // It is not compatible with custom named decoders, e.g., existingdir. 45 type ChangeDirFlag string 46 47 // Decode is used to create a side effect of changing the current working directory. 48 func (c ChangeDirFlag) Decode(ctx *DecodeContext) error { 49 var path string 50 err := ctx.Scan.PopValueInto("string", &path) 51 if err != nil { 52 return err 53 } 54 path = ExpandPath(path) 55 ctx.Value.Target.Set(reflect.ValueOf(ChangeDirFlag(path))) 56 return os.Chdir(path) 57 }