go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/client/internal/common/flags.go (about) 1 // Copyright 2015 The LUCI Authors. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package common 16 17 import ( 18 "context" 19 "errors" 20 "flag" 21 "io" 22 "log" 23 24 "go.chromium.org/luci/common/logging" 25 "go.chromium.org/luci/common/logging/gologger" 26 ) 27 28 // Flags contains values parsed from command line arguments. 29 type Flags struct { 30 Quiet bool 31 Verbose bool 32 } 33 34 // Init registers flags in a given flag set. 35 func (d *Flags) Init(f *flag.FlagSet) { 36 f.BoolVar(&d.Quiet, "quiet", false, "Get less output") 37 f.BoolVar(&d.Verbose, "verbose", false, "Get more output") 38 } 39 40 // Parse applies changes specified by command line flags. 41 func (d *Flags) Parse() error { 42 if !d.Verbose { 43 log.SetFlags(0) 44 log.SetOutput(io.Discard) 45 } 46 if d.Quiet && d.Verbose { 47 return errors.New("can't use both -quiet and -verbose") 48 } 49 return nil 50 } 51 52 // MakeLoggingContext makes a luci-go/common/logging compatible context using 53 // gologger onto the given writer. 54 // 55 // The default logging level will be Info, with Warning and Debug corresponding 56 // to quiet/verbose respectively. 57 func (d *Flags) MakeLoggingContext(out io.Writer) context.Context { 58 ret := (&gologger.LoggerConfig{ 59 Out: out, 60 Format: gologger.PickStdFormat(out), 61 }).Use(context.Background()) 62 if d.Quiet { 63 ret = logging.SetLevel(ret, logging.Warning) 64 } else if d.Verbose { 65 ret = logging.SetLevel(ret, logging.Debug) 66 } else { 67 ret = logging.SetLevel(ret, logging.Info) 68 } 69 return ret 70 }