Skip to content

Commit

Permalink
feat: tail function for templates
Browse files Browse the repository at this point in the history
  • Loading branch information
femnad committed Apr 17, 2024
1 parent c40011b commit 6ac5e95
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 1 deletion.
17 changes: 17 additions & 0 deletions internal/template.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,15 @@ package internal
import (
"bytes"
"fmt"
"math"
"strings"
"text/template"
)

var UtilFns = template.FuncMap{
"cut": cut,
"head": head,
"tail": tail,
"iter": iterItems,
"iterMap": iterMap,
"revCut": reverseCut,
Expand Down Expand Up @@ -47,6 +49,21 @@ func head(i int, s string) (string, error) {
return splitBy("\n", i, s)
}

func tail(i int, s string) (string, error) {
if i < 0 {
headIdx := math.Abs(float64(i))
return head(int(headIdx)-1, s)
}
lines := strings.Split(s, "\n")
numLines := len(lines)
if i > numLines-1 {
return "", fmt.Errorf("invalid tail index %d for %s", i, s)
}

fwdIdx := numLines - 1 - i
return lines[fwdIdx], nil
}

func iterItems(items ...string) []string {
return items
}
Expand Down
29 changes: 29 additions & 0 deletions internal/template_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,35 @@ baz`,
},
want: "v123",
},
{
name: "Simple tail",
args: args{
proc: "tail 0",
input: `foo
bar
baz`,
},
want: "baz",
},
{
name: "Negative tail",
args: args{
proc: "tail -1",
input: `foo
bar
baz`,
},
want: "foo",
},
{
name: "Tail error",
args: args{
proc: "tail 3",
input: `bar
baz`,
},
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
Expand Down
2 changes: 1 addition & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import (
)

const (
version = "0.35.2"
version = "0.36.0"
)

type args struct {
Expand Down

0 comments on commit 6ac5e95

Please sign in to comment.