Skip to content

Instantly share code, notes, and snippets.

@phillipleblanc
Created August 16, 2021 11:57
Show Gist options
  • Save phillipleblanc/e1a6cf196af9242da9b67c7d8cbc993b to your computer and use it in GitHub Desktop.
Save phillipleblanc/e1a6cf196af9242da9b67c7d8cbc993b to your computer and use it in GitHub Desktop.
package output
import (
"log"
"strings"
"github.com/atomicgo/cursor"
)
type Output struct {
shouldReplace map[string]bool
}
var singleInstance *Output
func Get() *Output {
return singleInstance
}
func init() {
singleInstance = &Output{
shouldReplace: make(map[string]bool),
}
}
func (o *Output) Println(a ...interface{}) {
log.Println(a...)
o.resetReplaceMap()
}
func (o *Output) Printf(format string, a ...interface{}) {
log.Printf(format, a...)
o.resetReplaceMap()
}
func (o *Output) PrintfReplace(context string, format string, a ...interface{}) {
result, ok := o.shouldReplace[context]
shouldReplace := result && ok
if shouldReplace {
numLines := strings.Count(format, "\n")
cursor.ClearLinesUp(numLines)
cursor.StartOfLine()
}
log.Printf(format, a...)
o.shouldReplace[context] = true
}
func (o *Output) resetReplaceMap() {
for key := range o.shouldReplace {
o.shouldReplace[key] = false
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment