diff options
author | Cameron Moore <moorereason@gmail.com> | 2017-03-13 17:55:02 -0500 |
---|---|---|
committer | Bjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com> | 2017-04-30 10:56:38 +0200 |
commit | de7c32a1a880820252e922e0c9fcf69e109c0d1b (patch) | |
tree | 07d813f2617dd4a889aaebb885a9c1281a229960 /tpl/data | |
parent | 154e18ddb9ad205055d5bd4827c87f3f0daf499f (diff) |
tpl: Add template function namespaces
This commit moves almost all of the template functions into separate
packages under tpl/ and adds a namespace framework. All changes should
be backward compatible for end users, as all existing function names in
the template funcMap are left intact.
Seq and DoArithmatic have been moved out of the helpers package and into
template namespaces.
Most of the tests involved have been refactored, and many new tests have
been written. There's still work to do, but this is a big improvement.
I got a little overzealous and added some new functions along the way:
- strings.Contains
- strings.ContainsAny
- strings.HasSuffix
- strings.TrimPrefix
- strings.TrimSuffix
Documentation is forthcoming.
Fixes #3042
Diffstat (limited to 'tpl/data')
-rw-r--r-- | tpl/data/data.go | 31 | ||||
-rw-r--r-- | tpl/data/resources.go | 265 | ||||
-rw-r--r-- | tpl/data/resources_test.go | 358 |
3 files changed, 654 insertions, 0 deletions
diff --git a/tpl/data/data.go b/tpl/data/data.go new file mode 100644 index 000000000..39cbc9b19 --- /dev/null +++ b/tpl/data/data.go @@ -0,0 +1,31 @@ +// Copyright 2017 The Hugo Authors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package data + +import "github.com/spf13/hugo/deps" + +// New returns a new instance of the data-namespaced template functions. +func New(deps *deps.Deps) *Namespace { + return &Namespace{ + deps: deps, + } +} + +// Namespace provides template functions for the "data" namespace. +type Namespace struct { + deps *deps.Deps +} + +// Namespace returns a pointer to the current namespace instance. +func (ns *Namespace) Namespace() *Namespace { return ns } diff --git a/tpl/data/resources.go b/tpl/data/resources.go new file mode 100644 index 000000000..272e2474e --- /dev/null +++ b/tpl/data/resources.go @@ -0,0 +1,265 @@ +// Copyright 2016 The Hugo Authors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package data + +import ( + "bytes" + "encoding/csv" + "encoding/json" + "errors" + "io/ioutil" + "net/http" + "net/url" + "path/filepath" + "strings" + "sync" + "time" + + "github.com/spf13/afero" + "github.com/spf13/hugo/config" + "github.com/spf13/hugo/helpers" + jww "github.com/spf13/jwalterweatherman" +) + +var ( + remoteURLLock = &remoteLock{m: make(map[string]*sync.Mutex)} + resSleep = time.Second * 2 // if JSON decoding failed sleep for n seconds before retrying + resRetries = 1 // number of retries to load the JSON from URL or local file system + resCacheMu sync.RWMutex +) + +type remoteLock struct { + sync.RWMutex + m map[string]*sync.Mutex +} + +// URLLock locks an URL during download +func (l *remoteLock) URLLock(url string) { + var ( + lock *sync.Mutex + ok bool + ) + l.Lock() + if lock, ok = l.m[url]; !ok { + lock = &sync.Mutex{} + l.m[url] = lock + } + l.Unlock() + lock.Lock() +} + +// URLUnlock unlocks an URL when the download has been finished. Use only in defer calls. +func (l *remoteLock) URLUnlock(url string) { + l.RLock() + defer l.RUnlock() + if um, ok := l.m[url]; ok { + um.Unlock() + } +} + +// getCacheFileID returns the cache ID for a string +func getCacheFileID(cfg config.Provider, id string) string { + return cfg.GetString("cacheDir") + url.QueryEscape(id) +} + +// resGetCache returns the content for an ID from the file cache or an error +// if the file is not found returns nil,nil +func resGetCache(id string, fs afero.Fs, cfg config.Provider, ignoreCache bool) ([]byte, error) { + resCacheMu.RLock() + defer resCacheMu.RUnlock() + + if ignoreCache { + return nil, nil + } + fID := getCacheFileID(cfg, id) + isExists, err := helpers.Exists(fID, fs) + if err != nil { + return nil, err + } + if !isExists { + return nil, nil + } + + return afero.ReadFile(fs, fID) + +} + +// resWriteCache writes bytes to an ID into the file cache +func resWriteCache(id string, c []byte, fs afero.Fs, cfg config.Provider, ignoreCache bool) error { + resCacheMu.Lock() + defer resCacheMu.Unlock() + + if ignoreCache { + return nil + } + fID := getCacheFileID(cfg, id) + f, err := fs.Create(fID) + if err != nil { + return errors.New("Error: " + err.Error() + ". Failed to create file: " + fID) + } + defer f.Close() + n, err := f.Write(c) + if n == 0 { + return errors.New("No bytes written to file: " + fID) + } + if err != nil { + return errors.New("Error: " + err.Error() + ". Failed to write to file: " + fID) + } + return nil +} + +func resDeleteCache(id string, fs afero.Fs, cfg config.Provider) error { + return fs.Remove(getCacheFileID(cfg, id)) +} + +// resGetRemote loads the content of a remote file. This method is thread safe. +func resGetRemote(url string, fs afero.Fs, cfg config.Provider, hc *http.Client) ([]byte, error) { + c, err := resGetCache(url, fs, cfg, cfg.GetBool("ignoreCache")) + if c != nil && err == nil { + return c, nil + } + if err != nil { + return nil, err + } + + // avoid race condition with locks, block other goroutines if the current url is processing + remoteURLLock.URLLock(url) + defer func() { remoteURLLock.URLUnlock(url) }() + + // avoid multiple locks due to calling resGetCache twice + c, err = resGetCache(url, fs, cfg, cfg.GetBool("ignoreCache")) + if c != nil && err == nil { + return c, nil + } + if err != nil { + return nil, err + } + + jww.INFO.Printf("Downloading: %s ...", url) + res, err := hc.Get(url) + if err != nil { + return nil, err + } + c, err = ioutil.ReadAll(res.Body) + res.Body.Close() + if err != nil { + return nil, err + } + err = resWriteCache(url, c, fs, cfg, cfg.GetBool("ignoreCache")) + if err != nil { + return nil, err + } + jww.INFO.Printf("... and cached to: %s", getCacheFileID(cfg, url)) + return c, nil +} + +// resGetLocal loads the content of a local file +func resGetLocal(url string, fs afero.Fs, cfg config.Provider) ([]byte, error) { + filename := filepath.Join(cfg.GetString("workingDir"), url) + if e, err := helpers.Exists(filename, fs); !e { + return nil, err + } + + return afero.ReadFile(fs, filename) + +} + +// resGetResource loads the content of a local or remote file +func (ns *Namespace) resGetResource(url string) ([]byte, error) { + if url == "" { + return nil, nil + } + if strings.Contains(url, "://") { + return resGetRemote(url, ns.deps.Fs.Source, ns.deps.Cfg, http.DefaultClient) + } + return resGetLocal(url, ns.deps.Fs.Source, ns.deps.Cfg) +} + +// GetJSON expects one or n-parts of a URL to a resource which can either be a local or a remote one. +// If you provide multiple parts they will be joined together to the final URL. +// GetJSON returns nil or parsed JSON to use in a short code. +func (ns *Namespace) GetJSON(urlParts ...string) interface{} { + var v interface{} + url := strings.Join(urlParts, "") + + for i := 0; i <= resRetries; i++ { + c, err := ns.resGetResource(url) + if err != nil { + jww.ERROR.Printf("Failed to get json resource %s with error message %s", url, err) + return nil + } + + err = json.Unmarshal(c, &v) + if err != nil { + jww.ERROR.Printf("Cannot read json from resource %s with error message %s", url, err) + jww.ERROR.Printf("Retry #%d for %s and sleeping for %s", i, url, resSleep) + time.Sleep(resSleep) + resDeleteCache(url, ns.deps.Fs.Source, ns.deps.Cfg) + continue + } + break + } + return v +} + +// parseCSV parses bytes of CSV data into a slice slice string or an error +func parseCSV(c []byte, sep string) ([][]string, error) { + if len(sep) != 1 { + return nil, errors.New("Incorrect length of csv separator: " + sep) + } + b := bytes.NewReader(c) + r := csv.NewReader(b) + rSep := []rune(sep) + r.Comma = rSep[0] + r.FieldsPerRecord = 0 + return r.ReadAll() +} + +// GetCSV expects a data separator and one or n-parts of a URL to a resource which +// can either be a local or a remote one. +// The data separator can be a comma, semi-colon, pipe, etc, but only one character. +// If you provide multiple parts for the URL they will be joined together to the final URL. +// GetCSV returns nil or a slice slice to use in a short code. +func (ns *Namespace) GetCSV(sep string, urlParts ...string) [][]string { + var d [][]string + url := strings.Join(urlParts, "") + + var clearCacheSleep = func(i int, u string) { + jww.ERROR.Printf("Retry #%d for %s and sleeping for %s", i, url, resSleep) + time.Sleep(resSleep) + resDeleteCache(url, ns.deps.Fs.Source, ns.deps.Cfg) + } + + for i := 0; i <= resRetries; i++ { + c, err := ns.resGetResource(url) + + if err == nil && !bytes.Contains(c, []byte(sep)) { + err = errors.New("Cannot find separator " + sep + " in CSV.") + } + + if err != nil { + jww.ERROR.Printf("Failed to read csv resource %s with error message %s", url, err) + clearCacheSleep(i, url) + continue + } + + if d, err = parseCSV(c, sep); err != nil { + jww.ERROR.Printf("Failed to parse csv file %s with error message %s", url, err) + clearCacheSleep(i, url) + continue + } + break + } + return d +} diff --git a/tpl/data/resources_test.go b/tpl/data/resources_test.go new file mode 100644 index 000000000..f0d7cfd17 --- /dev/null +++ b/tpl/data/resources_test.go @@ -0,0 +1,358 @@ +// Copyright 2016 The Hugo Authors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package data + +import ( + "bytes" + "fmt" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "sync" + "testing" + "time" + + "github.com/spf13/afero" + "github.com/spf13/hugo/config" + "github.com/spf13/hugo/deps" + "github.com/spf13/hugo/helpers" + "github.com/spf13/hugo/hugofs" + "github.com/spf13/viper" + "github.com/stretchr/testify/assert" +) + +func TestScpCache(t *testing.T) { + t.Parallel() + + tests := []struct { + path string + content []byte + ignore bool + }{ + {"http://Foo.Bar/foo_Bar-Foo", []byte(`T€st Content 123`), false}, + {"fOO,bar:foo%bAR", []byte(`T€st Content 123 fOO,bar:foo%bAR`), false}, + {"FOo/BaR.html", []byte(`FOo/BaR.html T€st Content 123`), false}, + {"трям/трям", []byte(`T€st трям/трям Content 123`), false}, + {"은행", []byte(`T€st C은행ontent 123`), false}, + {"Банковский кассир", []byte(`Банковский кассир T€st Content 123`), false}, + {"Банковский кассир", []byte(`Банковский кассир T€st Content 456`), true}, + } + + fs := new(afero.MemMapFs) + + for _, test := range tests { + cfg := viper.New() + c, err := resGetCache(test.path, fs, cfg, test.ignore) + if err != nil { + t.Errorf("Error getting cache: %s", err) + } + if c != nil { + t.Errorf("There is content where there should not be anything: %s", string(c)) + } + + err = resWriteCache(test.path, test.content, fs, cfg, test.ignore) + if err != nil { + t.Errorf("Error writing cache: %s", err) + } + + c, err = resGetCache(test.path, fs, cfg, test.ignore) + if err != nil { + t.Errorf("Error getting cache after writing: %s", err) + } + if test.ignore { + if c != nil { + t.Errorf("Cache ignored but content is not nil: %s", string(c)) + } + } else { + if !bytes.Equal(c, test.content) { + t.Errorf("\nExpected: %s\nActual: %s\n", string(test.content), string(c)) + } + } + } +} + +func TestScpGetLocal(t *testing.T) { + t.Parallel() + v := viper.New() + fs := hugofs.NewMem(v) + ps := helpers.FilePathSeparator + + tests := []struct { + path string + content []byte + }{ + {"testpath" + ps + "test.txt", []byte(`T€st Content 123 fOO,bar:foo%bAR`)}, + {"FOo" + ps + "BaR.html", []byte(`FOo/BaR.html T€st Content 123`)}, + {"трям" + ps + "трям", []byte(`T€st трям/трям Content 123`)}, + {"은행", []byte(`T€st C은행ontent 123`)}, + {"Банковский кассир", []byte(`Банковский кассир T€st Content 123`)}, + } + + for _, test := range tests { + r := bytes.NewReader(test.content) + err := helpers.WriteToDisk(test.path, r, fs.Source) + if err != nil { + t.Error(err) + } + + c, err := resGetLocal(test.path, fs.Source, v) + if err != nil { + t.Errorf("Error getting resource content: %s", err) + } + if !bytes.Equal(c, test.content) { + t.Errorf("\nExpected: %s\nActual: %s\n", string(test.content), string(c)) + } + } + +} + +func getTestServer(handler func(w http.ResponseWriter, r *http.Request)) (*httptest.Server, *http.Client) { + testServer := httptest.NewServer(http.HandlerFunc(handler)) + client := &http.Client{ + Transport: &http.Transport{Proxy: func(r *http.Request) (*url.URL, error) { + // Remove when https://github.com/golang/go/issues/13686 is fixed + r.Host = "gohugo.io" + return url.Parse(testServer.URL) + }}, + } + return testServer, client +} + +func TestScpGetRemote(t *testing.T) { + t.Parallel() + fs := new(afero.MemMapFs) + + tests := []struct { + path string + content []byte + ignore bool + }{ + {"http://Foo.Bar/foo_Bar-Foo", []byte(`T€st Content 123`), false}, + {"http://Doppel.Gänger/foo_Bar-Foo", []byte(`T€st Cont€nt 123`), false}, + {"http://Doppel.Gänger/Fizz_Bazz-Foo", []byte(`T€st Банковский кассир Cont€nt 123`), false}, + {"http://Doppel.Gänger/Fizz_Bazz-Bar", []byte(`T€st Банковский кассир Cont€nt 456`), true}, + } + + for _, test := range tests { + + srv, cl := getTestServer(func(w http.ResponseWriter, r *http.Request) { + w.Write(test.content) + }) + defer func() { srv.Close() }() + + cfg := viper.New() + + c, err := resGetRemote(test.path, fs, cfg, cl) + if err != nil { + t.Errorf("Error getting resource content: %s", err) + } + if !bytes.Equal(c, test.content) { + t.Errorf("\nNet Expected: %s\nNet Actual: %s\n", string(test.content), string(c)) + } + cc, cErr := resGetCache(test.path, fs, cfg, test.ignore) + if cErr != nil { + t.Error(cErr) + } + if test.ignore { + if cc != nil { + t.Errorf("Cache ignored but content is not nil: %s", string(cc)) + } + } else { + if !bytes.Equal(cc, test.content) { + t.Errorf("\nCache Expected: %s\nCache Actual: %s\n", string(test.content), string(cc)) + } + } + } +} + +func TestScpGetRemoteParallel(t *testing.T) { + t.Parallel() + fs := new(afero.MemMapFs) + content := []byte(`T€st Content 123`) + url := "http://Foo.Bar/foo_Bar-Foo" + srv, cl := getTestServer(func(w http.ResponseWriter, r *http.Request) { + w.Write(content) + }) + defer func() { srv.Close() }() + + for _, ignoreCache := range []bool{false, true} { + + cfg := viper.New() + cfg.Set("ignoreCache", ignoreCache) + + var wg sync.WaitGroup + + for i := 0; i < 50; i++ { + wg.Add(1) + go func(gor int) { + defer wg.Done() + for j := 0; j < 10; j++ { + c, err := resGetRemote(url, fs, cfg, cl) + if err != nil { + t.Errorf("Error getting resource content: %s", err) + } + if !bytes.Equal(c, content) { + t.Errorf("\nNet Expected: %s\nNet Actual: %s\n", string(content), string(c)) + } + + time.Sleep(23 * time.Millisecond) + } + }(i) + } + + wg.Wait() + } + + t.Log("Done!") +} + +func TestParseCSV(t *testing.T) { + t.Parallel() + + tests := []struct { + csv []byte + sep string + exp string + err bool + }{ + {[]byte("a,b,c\nd,e,f\n"), "", "", true}, + {[]byte("a,b,c\nd,e,f\n"), "~/", "", true}, + {[]byte("a,b,c\nd,e,f"), "|", "a,b,cd,e,f", false}, + {[]byte("q,w,e\nd,e,f"), ",", "qwedef", false}, + {[]byte("a|b|c\nd|e|f|g"), "|", "abcdefg", true}, + {[]byte("z|y|c\nd|e|f"), "|", "zycdef", false}, + } + for _, test := range tests { + csv, err := parseCSV(test.csv, test.sep) + if test.err && err == nil { + t.Error("Expecting an error") + } + if test.err { + continue + } + if !test.err && err != nil { + t.Error(err) + } + + act := "" + for _, v := range csv { + act = act + strings.Join(v, "") + } + + if act != test.exp { + t.Errorf("\nExpected: %s\nActual: %s\n%#v\n", test.exp, act, csv) + } + + } +} + +func TestGetJSONFailParse(t *testing.T) { + t.Parallel() + + ns := New(newDeps(viper.New())) + + reqCount := 0 + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if reqCount > 0 { + w.Header().Add("Content-type", "application/json") + fmt.Fprintln(w, `{"gomeetup":["Sydney", "San Francisco", "Stockholm"]}`) + } else { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprintln(w, `ERROR 500`) + } + reqCount++ + })) + defer ts.Close() + url := ts.URL + "/test.json" + + want := map[string]interface{}{"gomeetup": []interface{}{"Sydney", "San Francisco", "Stockholm"}} + have := ns.GetJSON(url) + assert.NotNil(t, have) + if have != nil { + assert.EqualValues(t, want, have) + } +} + +func TestGetCSVFailParseSep(t *testing.T) { + t.Parallel() + + ns := New(newDeps(viper.New())) + + reqCount := 0 + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if reqCount > 0 { + w.Header().Add("Content-type", "application/json") + fmt.Fprintln(w, `gomeetup,city`) + fmt.Fprintln(w, `yes,Sydney`) + fmt.Fprintln(w, `yes,San Francisco`) + fmt.Fprintln(w, `yes,Stockholm`) + } else { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprintln(w, `ERROR 500`) + } + reqCount++ + })) + defer ts.Close() + url := ts.URL + "/test.csv" + + want := [][]string{{"gomeetup", "city"}, {"yes", "Sydney"}, {"yes", "San Francisco"}, {"yes", "Stockholm"}} + have := ns.GetCSV(",", url) + assert.NotNil(t, have) + if have != nil { + assert.EqualValues(t, want, have) + } +} + +func TestGetCSVFailParse(t *testing.T) { + t.Parallel() + + ns := New(newDeps(viper.New())) + + reqCount := 0 + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Add("Content-type", "application/json") + if reqCount > 0 { + fmt.Fprintln(w, `gomeetup,city`) + fmt.Fprintln(w, `yes,Sydney`) + fmt.Fprintln(w, `yes,San Francisco`) + fmt.Fprintln(w, `yes,Stockholm`) + } else { + fmt.Fprintln(w, `gomeetup,city`) + fmt.Fprintln(w, `yes,Sydney,Bondi,`) // wrong number of fields in line + fmt.Fprintln(w, `yes,San Francisco`) + fmt.Fprintln(w, `yes,Stockholm`) + } + reqCount++ + })) + defer ts.Close() + url := ts.URL + "/test.csv" + + want := [][]string{{"gomeetup", "city"}, {"yes", "Sydney"}, {"yes", "San Francisco"}, {"yes", "Stockholm"}} + have := ns.GetCSV(",", url) + assert.NotNil(t, have) + if have != nil { + assert.EqualValues(t, want, have) + } +} + +func newDeps(cfg config.Provider) *deps.Deps { + l := helpers.NewLanguage("en", cfg) + l.Set("i18nDir", "i18n") + return &deps.Deps{ + Cfg: cfg, + Fs: hugofs.NewMem(l), + ContentSpec: helpers.NewContentSpec(l), + } +} |