Skip to content

Commit

Permalink
tpl: Add errorf template function
Browse files Browse the repository at this point in the history
Add template function that will build a string from the given format
string and arguments, then log it to ERROR. This has an intended
side-effect of causing the build to fail, when executed.

Resolves gohugoio#3817
  • Loading branch information
bmon committed Sep 30, 2017
1 parent 47fdfd5 commit cc1cad2
Show file tree
Hide file tree
Showing 4 changed files with 53 additions and 1 deletion.
26 changes: 26 additions & 0 deletions docs/content/functions/errorf.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
---
title: errorf
linktitle: errorf
description: Evaluates a format string and logs it to ERROR.
date: 2017-09-30
publishdate: 2017-09-30
lastmod: 2017-09-30
categories: [functions]
menu:
docs:
parent: "functions"
keywords: [strings, log, error]
signature: ["errorf FORMAT INPUT"]
workson: []
hugoversion:
relatedfuncs: [printf]
deprecated: false
aliases: []
---

`errorf` will evaluate a format string, then output the result to the ERROR log.
This will also cause the build to fail.

```
{{ errorf "Something went horribly wrong! %s" err }}
```
6 changes: 6 additions & 0 deletions tpl/fmt/fmt.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ package fmt

import (
_fmt "fmt"
jww "github.com/spf13/jwalterweatherman"
)

// New returns a new instance of the fmt-namespaced template functions.
Expand All @@ -41,3 +42,8 @@ func (ns *Namespace) Printf(format string, a ...interface{}) string {
func (ns *Namespace) Println(a ...interface{}) string {
return _fmt.Sprintln(a...)
}

func (ns *Namespace) Errorf(format string, a ...interface{}) string {
jww.ERROR.Printf(format, a...)
return _fmt.Sprintf(format, a...)
}
14 changes: 14 additions & 0 deletions tpl/fmt/fmt_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package fmt

import (
jww "github.com/spf13/jwalterweatherman"
"github.com/stretchr/testify/assert"
"testing"
)

func TestErrorf(t *testing.T) {
errorCount := jww.LogCountForLevel(jww.LevelError)
ns := &Namespace{}
assert.EqualValues(t, ns.Errorf("%s\n", "test error, please ignore."), "test error, please ignore.\n", "")
assert.EqualValues(t, errorCount+1, jww.LogCountForLevel(jww.LevelError), "Error log count not incremented")
}
8 changes: 7 additions & 1 deletion tpl/fmt/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,14 @@ func init() {
},
)

return ns
ns.AddMethodMapping(ctx.Errorf,
[]string{"errorf"},
[][2]string{
{`{{ errorf "%s." "failed" }}`, `failed.`},
},
)

return ns
}

internal.AddTemplateFuncsNamespace(f)
Expand Down

0 comments on commit cc1cad2

Please sign in to comment.