diff --git a/internal/template.go b/internal/template.go index 8d21b92..cb4b17b 100644 --- a/internal/template.go +++ b/internal/template.go @@ -3,6 +3,7 @@ package internal import ( "bytes" "fmt" + "math" "strings" "text/template" ) @@ -10,6 +11,7 @@ import ( var UtilFns = template.FuncMap{ "cut": cut, "head": head, + "tail": tail, "iter": iterItems, "iterMap": iterMap, "revCut": reverseCut, @@ -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 } diff --git a/internal/template_test.go b/internal/template_test.go index b519487..c8f9cad 100644 --- a/internal/template_test.go +++ b/internal/template_test.go @@ -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) { diff --git a/main.go b/main.go index 059058c..a1bc327 100644 --- a/main.go +++ b/main.go @@ -13,7 +13,7 @@ import ( ) const ( - version = "0.35.2" + version = "0.36.0" ) type args struct {