...

Source file src/golang.conradwood.net/go-easyops/utils/debugflag.go

Documentation: golang.conradwood.net/go-easyops/utils

     1  package utils
     2  
     3  import (
     4  	"flag"
     5  	"fmt"
     6  	"strings"
     7  )
     8  
     9  func DebugFlag(name string) *debugFlag {
    10  	res := &debugFlag{name: name}
    11  	helptext := fmt.Sprintf("Enable debug mode for \"%s\"", name)
    12  	flag.Var(res, "debug_"+name, helptext)
    13  	return res
    14  }
    15  
    16  type debugFlag struct {
    17  	name  string
    18  	value bool
    19  	isset bool
    20  }
    21  
    22  func (t *debugFlag) Set(s string) error {
    23  	x := strings.ToLower(s)
    24  	if x == "true" || x == "on" {
    25  		t.value = true
    26  	} else if x == "false" || x == "off" {
    27  		t.value = false
    28  	} else {
    29  		return fmt.Errorf("value \"%s\" not valid for a boolean value", s)
    30  	}
    31  	t.isset = true
    32  	return nil
    33  }
    34  func (t *debugFlag) String() string {
    35  	if t == nil {
    36  		return "debugflag description"
    37  	}
    38  	if !t.isset {
    39  		return "undefined"
    40  	}
    41  	return fmt.Sprintf("%v", t.value)
    42  }
    43  func (t *debugFlag) Value() string {
    44  	return fmt.Sprintf("%v", t.value)
    45  }
    46  func (t *debugFlag) IsBoolFlag() bool {
    47  	return true
    48  }
    49  
    50  func (t *debugFlag) IsSet() bool {
    51  	return t.isset
    52  }
    53  func (t *debugFlag) BoolValue() bool {
    54  	return t.value
    55  
    56  }
    57  
    58  func (t *debugFlag) Printf(format string, args ...any) {
    59  	prefix := fmt.Sprintf("[%s] ", t.name)
    60  	txt := fmt.Sprintf(format, args...)
    61  	fmt.Print(prefix + txt)
    62  }
    63  func (t *debugFlag) Debugf(format string, args ...any) {
    64  	if !t.value {
    65  		return
    66  	}
    67  	t.Printf(format, args...)
    68  }
    69  

View as plain text