Skip to content

Commit

Permalink
Merge pull request #7 from moul/dev/moul/uptime-duration
Browse files Browse the repository at this point in the history
feat: add {{.Uptime}} and {{.Duration}}
  • Loading branch information
moul committed Sep 8, 2020
2 parents 0976165 + c28644b commit e99e4ae
Show file tree
Hide file tree
Showing 4 changed files with 18 additions and 6 deletions.
1 change: 0 additions & 1 deletion cmd/prefix/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ func run(args []string) error {
var input io.Reader
{
remainingArgs := flags.Args()
fmt.Println(remainingArgs)
switch {
case len(remainingArgs) == 0:
input = os.Stdin
Expand Down
2 changes: 1 addition & 1 deletion go.mod

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions go.sum

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

17 changes: 15 additions & 2 deletions prefix.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@ import (
"bytes"
"fmt"
"text/template"
"time"

"github.com/Masterminds/sprig"
"moul.io/u"
)

/// Public API
Expand All @@ -22,7 +24,9 @@ type linePrefixer struct {
Format string
LineNumber int

t *template.Template
t *template.Template
startedAt time.Time // used by {{.Uptime}}
lastTime time.Time // used by {{.Duration}}
}

func New(format string) LinePrefixer {
Expand All @@ -35,14 +39,17 @@ func New(format string) LinePrefixer {
Format: DefaultFormat,
LineNumber: 0,

t: template.Must(template.New("").Funcs(funcMap).Parse(format)),
t: template.Must(template.New("").Funcs(funcMap).Parse(format)),
startedAt: time.Now(),
lastTime: time.Now(),
}
}

func (p *linePrefixer) PrefixLine(line string) string {
p.LineNumber++
var prefix bytes.Buffer
_ = p.t.Execute(&prefix, p)
p.lastTime = time.Now()
return prefix.String() + line
}

Expand All @@ -51,3 +58,9 @@ func (p *linePrefixer) PrefixLine(line string) string {
func (p *linePrefixer) LineNumber3() string { return fmt.Sprintf("%-3d", p.LineNumber) }
func (p *linePrefixer) LineNumber4() string { return fmt.Sprintf("%-4d", p.LineNumber) }
func (p *linePrefixer) LineNumber5() string { return fmt.Sprintf("%-5d", p.LineNumber) }
func (p *linePrefixer) Uptime() string {
return fmt.Sprintf("%-7s", u.ShortDuration(time.Since(p.startedAt)))
}
func (p *linePrefixer) Duration() string {
return fmt.Sprintf("%-7s", u.ShortDuration(time.Since(p.lastTime)))
}

0 comments on commit e99e4ae

Please sign in to comment.