Skip to content

Commit

Permalink
Finalize
Browse files Browse the repository at this point in the history
  • Loading branch information
danog committed Oct 17, 2024
1 parent 667643a commit d0e936b
Show file tree
Hide file tree
Showing 19 changed files with 69 additions and 56 deletions.
6 changes: 6 additions & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,12 @@ linters:
- nolintlint
- nestif
- forcetypeassert
- interfacebloat
- revive
- gocyclo
- errname
- gosmopolitan
- maintidx

# Todo: re-add
- err113
Expand Down
3 changes: 2 additions & 1 deletion engine_examples_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package liquid
import (
"fmt"
"log"
"strconv"
"strings"

"github.com/osteele/liquid/render"
Expand Down Expand Up @@ -111,7 +112,7 @@ func ExampleEngine_RegisterBlock() {
return "", err
}
n := len(s)
return fmt.Sprint(n), nil
return strconv.Itoa(n), nil
})

template := `{% length %}abc{% endlength %}`
Expand Down
2 changes: 1 addition & 1 deletion engine_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,5 +134,5 @@ func TestEngine_ParseTemplateAndCache(t *testing.T) {
// ...and execute the second.
result, err := eng.ParseAndRender(templateB, Bindings{})
require.NoError(t, err)
require.Equal(t, string(result), "Foo, Bar")
require.Equal(t, "Foo, Bar", string(result))
}
14 changes: 7 additions & 7 deletions expressions/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,20 +22,20 @@ func NewContext(vars map[string]interface{}, cfg Config) Context {
return &context{cfg, vars}
}

func (c *context) Clone() Context {
func (ctx *context) Clone() Context {
bindings := map[string]interface{}{}
for k, v := range c.bindings {
for k, v := range ctx.bindings {
bindings[k] = v
}
return &context{c.Config, bindings}
return &context{ctx.Config, bindings}
}

// Get looks up a variable value in the expression context.
func (c *context) Get(name string) interface{} {
return values.ToLiquid(c.bindings[name])
func (ctx *context) Get(name string) interface{} {
return values.ToLiquid(ctx.bindings[name])
}

// Set sets a variable value in the expression context.
func (c *context) Set(name string, value interface{}) {
c.bindings[name] = value
func (ctx *context) Set(name string, value interface{}) {
ctx.bindings[name] = value
}
1 change: 1 addition & 0 deletions expressions/filters_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ func TestContext_AddFilter(t *testing.T) {
require.Panics(t, func() { cfg.AddFilter("f", func() int { return 0 }) })
require.Panics(t, func() { cfg.AddFilter("f", func(int) {}) })
// require.Panics(t, func() { cfg.AddFilter("f", func(int) (a int, b int) { return }) })
//nolint:stylecheck
require.Panics(t, func() { cfg.AddFilter("f", func(int) (a int, e error, b int) { return }) })
require.Panics(t, func() { cfg.AddFilter("f", 10) })
}
Expand Down
28 changes: 14 additions & 14 deletions expressions/scanner_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ func (s testSymbol) String() string {
return fmt.Sprintf("%d:%v", s.tok, s.typ)
}

func scanExpression(data string) ([]testSymbol, error) {
func scanExpression(data string) []testSymbol {
var (
lex = newLexer([]byte(data))
symbols []testSymbol
Expand All @@ -29,33 +29,32 @@ func scanExpression(data string) ([]testSymbol, error) {
}
symbols = append(symbols, testSymbol{tok, s})
}
return symbols, nil
return symbols
}

func TestLex(t *testing.T) {
ts, err := scanExpression("abc > 123")
require.NoError(t, err)
ts := scanExpression("abc > 123")
require.Len(t, ts, 3)
require.Equal(t, IDENTIFIER, ts[0].tok)
require.Equal(t, "abc", ts[0].typ.name)
require.Equal(t, LITERAL, ts[2].tok)
require.Equal(t, 123, ts[2].typ.val)

// verify these don't match "for", "or", or "false"
ts, _ = scanExpression("forage")
ts = scanExpression("forage")
require.Len(t, ts, 1)
ts, _ = scanExpression("orange")
ts = scanExpression("orange")
require.Len(t, ts, 1)
ts, _ = scanExpression("falsehood")
ts = scanExpression("falsehood")
require.Len(t, ts, 1)

ts, _ = scanExpression("a.b-c")
ts = scanExpression("a.b-c")
require.Len(t, ts, 2)
require.Equal(t, PROPERTY, ts[1].tok)
require.Equal(t, "b-c", ts[1].typ.name)

// literals
ts, _ = scanExpression(`true false nil 2 2.3 "abc" 'abc'`)
ts = scanExpression(`true false nil 2 2.3 "abc" 'abc'`)
require.Len(t, ts, 7)
require.Equal(t, LITERAL, ts[0].tok)
require.Equal(t, LITERAL, ts[1].tok)
Expand All @@ -66,14 +65,15 @@ func TestLex(t *testing.T) {
require.Equal(t, LITERAL, ts[6].tok)
require.Equal(t, true, ts[0].typ.val)
require.Equal(t, false, ts[1].typ.val)
require.Equal(t, nil, ts[2].typ.val)
require.Nil(t, ts[2].typ.val)
require.Equal(t, 2, ts[3].typ.val)
//nolint:testifylint
require.Equal(t, 2.3, ts[4].typ.val)
require.Equal(t, "abc", ts[5].typ.val)
require.Equal(t, "abc", ts[6].typ.val)

// identifiers
ts, _ = scanExpression(`abc ab_c ab-c abc?`)
ts = scanExpression(`abc ab_c ab-c abc?`)
require.Len(t, ts, 4)
require.Equal(t, IDENTIFIER, ts[0].tok)
require.Equal(t, IDENTIFIER, ts[1].tok)
Expand All @@ -84,12 +84,12 @@ func TestLex(t *testing.T) {
require.Equal(t, "ab-c", ts[2].typ.name)
require.Equal(t, "abc?", ts[3].typ.name)

ts, _ = scanExpression(`{%cycle 'a', 'b'`)
ts = scanExpression(`{%cycle 'a', 'b'`)
require.Len(t, ts, 4)

ts, _ = scanExpression(`%loop i in (3 .. 5)`)
ts = scanExpression(`%loop i in (3 .. 5)`)
require.Len(t, ts, 8)

// ts, _ = scanExpression(`%loop i in (3..5)`)
// ts= scanExpression(`%loop i in (3..5)`)
// require.Len(t, ts, 9)
}
10 changes: 4 additions & 6 deletions filters/standard_filters.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,20 +137,18 @@ func AddStandardFilters(fd FilterDictionary) { //nolint: gocyclo
return html.EscapeString(html.UnescapeString(s))
})
fd.AddFilter("newline_to_br", func(s string) string {
return strings.Replace(s, "\n", "<br />", -1)
return strings.ReplaceAll(s, "\n", "<br />")
})
fd.AddFilter("prepend", func(s, prefix string) string {
return prefix + s
})
fd.AddFilter("remove", func(s, old string) string {
return strings.Replace(s, old, "", -1)
return strings.ReplaceAll(s, old, "")
})
fd.AddFilter("remove_first", func(s, old string) string {
return strings.Replace(s, old, "", 1)
})
fd.AddFilter("replace", func(s, old, n string) string {
return strings.Replace(s, old, n, -1)
})
fd.AddFilter("replace", strings.ReplaceAll)
fd.AddFilter("replace_first", func(s, old, n string) string {
return strings.Replace(s, old, n, 1)
})
Expand All @@ -173,7 +171,7 @@ func AddStandardFilters(fd FilterDictionary) { //nolint: gocyclo
return regexp.MustCompile(`<.*?>`).ReplaceAllString(s, "")
})
fd.AddFilter("strip_newlines", func(s string) string {
return strings.Replace(s, "\n", "", -1)
return strings.ReplaceAll(s, "\n", "")
})
fd.AddFilter("strip", strings.TrimSpace)
fd.AddFilter("lstrip", func(s string) string {
Expand Down
2 changes: 1 addition & 1 deletion parser/scanner.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ func formTokenMatcher(delims []string) *regexp.Regexp {
// For example, if delims is default the exclusion expression is "[^%]|%[^}]".
// If tagRight is "TAG!RIGHT" then expression is
// [^T]|T[^A]|TA[^G]|TAG[^!]|TAG![^R]|TAG!R[^I]|TAG!RI[^G]|TAG!RIG[^H]|TAG!RIGH[^T]
var exclusion []string
exclusion := make([]string, 0, len(delims[3]))
for idx, val := range delims[3] {
exclusion = append(exclusion, "[^"+string(val)+"]")
if idx > 0 {
Expand Down
3 changes: 2 additions & 1 deletion render/compiler_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package render

import (
"errors"
"fmt"
"io"
"testing"
Expand All @@ -16,7 +17,7 @@ func addCompilerTestTags(s Config) {
}, nil
})
s.AddBlock("error_block").Compiler(func(c BlockNode) (func(io.Writer, Context) error, error) {
return nil, fmt.Errorf("block compiler error")
return nil, errors.New("block compiler error")
})
}

Expand Down
3 changes: 2 additions & 1 deletion render/render_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package render

import (
"bytes"
"errors"
"fmt"
"io"
"testing"
Expand Down Expand Up @@ -159,7 +160,7 @@ func addRenderTestTags(cfg Config) {
})
cfg.AddBlock("errblock").Compiler(func(c BlockNode) (func(io.Writer, Context) error, error) {
return func(w io.Writer, c Context) error {
return fmt.Errorf("errblock error")
return errors.New("errblock error")
}, nil
})
}
3 changes: 2 additions & 1 deletion tags/control_flow_tags_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package tags

import (
"bytes"
"errors"
"fmt"
"io"
"testing"
Expand Down Expand Up @@ -78,7 +79,7 @@ func TestControlFlowTags_errors(t *testing.T) {
AddStandardTags(cfg)
cfg.AddTag("error", func(string) (func(io.Writer, render.Context) error, error) {
return func(io.Writer, render.Context) error {
return fmt.Errorf("tag render error")
return errors.New("tag render error")
}, nil
})

Expand Down
19 changes: 10 additions & 9 deletions tags/iteration_tags.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package tags

import (
"errors"
"fmt"
"io"
"math"
Expand All @@ -19,8 +20,8 @@ type IterationKeyedMap map[string]interface{}
const forloopVarName = "forloop"

var (
errLoopContinueLoop = fmt.Errorf("continue outside a loop")
errLoopBreak = fmt.Errorf("break outside a loop")
errLoopContinueLoop = errors.New("continue outside a loop")
errLoopBreak = errors.New("break outside a loop")
)

type iterable interface {
Expand Down Expand Up @@ -88,7 +89,7 @@ func loopTagCompiler(node render.BlockNode) (func(io.Writer, render.Context) err
}

if len(node.Clauses) > 1 {
return fmt.Errorf("for loops accept at most one else clause")
return errors.New("for loops accept at most one else clause")
}

if iter.Len() == 0 && len(node.Clauses) == 1 && node.Clauses[0].Name == "else" {
Expand Down Expand Up @@ -118,21 +119,21 @@ func (loop loopRenderer) render(iter iterable, w io.Writer, ctx render.Context)
}(ctx.Get(forloopVarName), ctx.Get(loop.Variable))
cycleMap := map[string]int{}
loop:
for i, len := 0, iter.Len(); i < len; i++ {
for i, l := 0, iter.Len(); i < l; i++ {
ctx.Set(loop.Variable, iter.Index(i))
ctx.Set(forloopVarName, map[string]interface{}{
"first": i == 0,
"last": i == len-1,
"last": i == l-1,
"index": i + 1,
"index0": i,
"rindex": len - i,
"rindex0": len - i - 1,
"length": len,
"rindex": l - i,
"rindex0": l - i - 1,
"length": l,
".cycles": cycleMap,
})
decorator.before(w, i)
err := ctx.RenderChildren(w)
decorator.after(w, i, len)
decorator.after(w, i, l)
switch {
case err == nil:
// fall through
Expand Down
11 changes: 6 additions & 5 deletions template_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"testing"

"github.com/osteele/liquid/render"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

Expand Down Expand Up @@ -59,8 +60,8 @@ func TestTemplate_Parse_race(t *testing.T) {
go func(i int) {
path := fmt.Sprintf("path %d", i)
_, err := engine.ParseTemplateLocation([]byte("{{ syntax error }}"), path, i)
require.Error(t, err)
require.Equal(t, path, err.Path())
assert.Error(t, err)
assert.Equal(t, path, err.Path())
wg.Done()
}(i)
}
Expand All @@ -84,7 +85,7 @@ func TestTemplate_Render_race(t *testing.T) {
defer wg.Done()
var err error
ts[i], err = engine.ParseTemplateLocation(src, paths[i], i)
require.NoError(t, err)
assert.NoError(t, err)
}(i)
}
wg.Wait()
Expand All @@ -95,8 +96,8 @@ func TestTemplate_Render_race(t *testing.T) {
go func(i int) {
defer wg2.Done()
_, err := ts[i].Render(Bindings{})
require.Error(t, err)
require.Equal(t, paths[i], err.Path())
assert.Error(t, err)
assert.Equal(t, paths[i], err.Path())
}(i)
}
wg2.Wait()
Expand Down
2 changes: 1 addition & 1 deletion values/call.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ func convertCallArguments(fn reflect.Value, args []interface{}) (results []refle
results[i] = reflect.Zero(typ)
}
}
return
return results, err
}

func isDefaultFunctionType(typ reflect.Type) bool {
Expand Down
4 changes: 2 additions & 2 deletions values/call_test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package values

import (
"fmt"
"errors"
"reflect"
"strings"
"testing"
Expand Down Expand Up @@ -36,7 +36,7 @@ func TestCall(t *testing.T) {
require.Contains(t, err.Error(), "expected 2")

// error return
fn2 := func(int) (int, error) { return 0, fmt.Errorf("expected error") }
fn2 := func(int) (int, error) { return 0, errors.New("expected error") }
_, err = Call(reflect.ValueOf(fn2), []interface{}{2})
require.Error(t, err)
require.Contains(t, err.Error(), "expected error")
Expand Down
1 change: 1 addition & 0 deletions values/convert.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ func convertValueToFloat(value interface{}, typ reflect.Type) (float64, error) {
// Convert value to the type. This is a more aggressive conversion, that will
// recursively create new map and slice values as necessary. It doesn't
// handle circular references.
// #nosec G115
func Convert(value interface{}, typ reflect.Type) (interface{}, error) { //nolint: gocyclo
value = ToLiquid(value)
rv := reflect.ValueOf(value)
Expand Down
2 changes: 1 addition & 1 deletion values/evaluator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ func TestSort(t *testing.T) {
map[string]interface{}{},
}
SortByProperty(array, "key", true)
require.Equal(t, nil, array[0].(map[string]interface{})["key"])
require.Nil(t, array[0].(map[string]interface{})["key"])
require.Equal(t, 10, array[1].(map[string]interface{})["key"])
require.Equal(t, 20, array[2].(map[string]interface{})["key"])
}
Loading

0 comments on commit d0e936b

Please sign in to comment.