go.charczuk.com@v0.0.0-20240327042549-bc490516bd1a/sdk/logutil/flags.go (about) 1 /* 2 3 Copyright (c) 2023 - Present. Will Charczuk. All rights reserved. 4 Use of this source code is governed by a MIT license that can be found in the LICENSE file at the root of the repository. 5 6 */ 7 8 package logutil 9 10 import ( 11 "fmt" 12 "log" 13 ) 14 15 // MustFlags returns parsed flags and panics on error. 16 func MustFlags(flags ...string) int { 17 f, err := Flags(flags...) 18 if err != nil { 19 panic(err) 20 } 21 return f 22 } 23 24 // Flags returns parsed flags. 25 func Flags(flags ...string) (output int, err error) { 26 for _, f := range flags { 27 if f == "" { 28 continue 29 } 30 anti := f[0] == '-' 31 if anti { 32 f = f[1:] 33 } 34 value, ok := FlagString[f] 35 if !ok { 36 err = fmt.Errorf("invalid flag: %s", f) 37 return 38 } 39 if anti { 40 } else { 41 output = output | value 42 } 43 } 44 return 45 } 46 47 // FormatFlags returns a string for a given flags bitmask. 48 func FormatFlags(flags int) (output []string) { 49 for flagstr, flagval := range FlagString { 50 if flags&flagval != 0 { 51 output = append(output, flagstr) 52 } 53 } 54 return 55 } 56 57 // FlagString maps strings to flag values. 58 var FlagString = map[string]int{ 59 "Ldate": log.Ldate, 60 "Ltime": log.Ltime, 61 "Lmicroseconds": log.Lmicroseconds, 62 "Llongfile": log.Llongfile, 63 "Lshortfile": log.Lshortfile, 64 "Lmsgprefix": log.Lmsgprefix, 65 "Ldebug": Ldebug, 66 "Linfo": Linfo, 67 "Lwarn": Lwarn, 68 "Lerror": Lerror, 69 }