github.com/henvic/wedeploycli@v1.7.6-0.20200319005353-3630f582f284/verbose/verbose.go (about) 1 package verbose 2 3 import ( 4 "bytes" 5 "fmt" 6 "io" 7 "os" 8 "sync" 9 10 "github.com/henvic/wedeploycli/color" 11 "github.com/henvic/wedeploycli/envs" 12 ) 13 14 var ( 15 // Enabled flag 16 Enabled = false 17 18 // Deferred flag to only print debugging on end of program execution 19 Deferred = false 20 21 // ErrStream is the stream for errors 22 ErrStream io.Writer = os.Stderr 23 24 unsafeVerbose = false 25 26 bufDeferredVerbose bytes.Buffer 27 m sync.RWMutex 28 ) 29 30 func init() { 31 unsafeVerbose = IsUnsafeMode() 32 } 33 34 // IsUnsafeMode checks if the unsafe verbose mode is on 35 func IsUnsafeMode() bool { 36 if unsafe, _ := os.LookupEnv(envs.UnsafeVerbose); unsafe == "true" { 37 return true 38 } 39 40 return false 41 } 42 43 // SafeEscape string 44 func SafeEscape(value string) string { 45 if unsafeVerbose { 46 return value 47 } 48 49 return color.Format(color.BgYellow, " hidden value ") 50 } 51 52 // SafeEscapeSlice of strings 53 func SafeEscapeSlice(values []string) string { 54 if unsafeVerbose { 55 return fmt.Sprintf("%v", values) 56 } 57 58 var plural string 59 60 if len(values) != 1 { 61 plural = "s" 62 } 63 64 return color.Format(color.BgYellow, " %d hidden value%s ", len(values), plural) 65 } 66 67 // Debug prints verbose messages to stderr on verbose mode 68 func Debug(a ...interface{}) { 69 m.Lock() 70 defer m.Unlock() 71 72 if !Enabled { 73 return 74 } 75 76 if !Deferred { 77 _, _ = fmt.Fprintln(ErrStream, a...) 78 return 79 } 80 81 bufDeferredVerbose.WriteString(fmt.Sprintln(a...)) 82 } 83 84 // PrintDeferred debug messages 85 func PrintDeferred() { 86 m.Lock() 87 defer m.Unlock() 88 89 if !Deferred { 90 return 91 } 92 93 if bufDeferredVerbose.Len() != 0 { 94 _, _ = fmt.Fprintf(ErrStream, "\n%v\n", color.Format(color.BgHiBlue, " Deferred verbose messages below ")) 95 _, _ = bufDeferredVerbose.WriteTo(ErrStream) 96 } 97 }