shithub: hugo

Download patch

ref: 880ca19f209e68e6a8daa6686b361515ecacc91e
parent: 01b72eb592d0e0aefc5f7ae42f9f6ff112883bb6
author: Bjørn Erik Pedersen <[email protected]>
date: Sun Apr 15 17:06:57 EDT 2018

tpl/path: Add path.Join

--- a/tpl/path/init.go
+++ b/tpl/path/init.go
@@ -14,7 +14,11 @@
 package path
 
 import (
+	"fmt"
+	"path/filepath"
+
 	"github.com/gohugoio/hugo/deps"
+	"github.com/gohugoio/hugo/helpers"
 	"github.com/gohugoio/hugo/tpl/internal"
 )
 
@@ -33,6 +37,15 @@
 			nil,
 			[][2]string{
 				{`{{ "/my/path/filename.txt" | path.Split }}`, `/my/path/|filename.txt`},
+				{fmt.Sprintf(`{{ %q | path.Split }}`, filepath.FromSlash("/my/path/filename.txt")), `/my/path/|filename.txt`},
+			},
+		)
+
+		ns.AddMethodMapping(ctx.Join,
+			nil,
+			[][2]string{
+				{fmt.Sprintf(`{{ slice %q "filename.txt" | path.Join  }}`, "my"+helpers.FilePathSeparator+"path"), `my/path/filename.txt`},
+				{`{{  path.Join "my" "path" "filename.txt" }}`, `my/path/filename.txt`},
 			},
 		)
 
--- a/tpl/path/path.go
+++ b/tpl/path/path.go
@@ -16,6 +16,7 @@
 import (
 	"fmt"
 	_path "path"
+	"path/filepath"
 
 	"github.com/gohugoio/hugo/deps"
 	"github.com/spf13/cast"
@@ -48,6 +49,8 @@
 // separating it into a directory and file name component.
 // If there is no slash in path, Split returns an empty dir and
 // file set to path.
+// The input path is passed into filepath.ToSlash converting any Windows slashes
+// to forward slashes.
 // The returned values have the property that path = dir+file.
 func (ns *Namespace) Split(path interface{}) (DirFile, error) {
 	spath, err := cast.ToStringE(path)
@@ -54,7 +57,37 @@
 	if err != nil {
 		return DirFile{}, err
 	}
+	spath = filepath.ToSlash(spath)
 	dir, file := _path.Split(spath)
 
 	return DirFile{Dir: dir, File: file}, nil
+}
+
+// Join joins any number of path elements into a single path, adding a
+// separating slash if necessary. All the input
+// path elements are passed into filepath.ToSlash converting any Windows slashes
+// to forward slashes.
+// The result is Cleaned; in particular,
+// all empty strings are ignored.
+func (ns *Namespace) Join(elements ...interface{}) (string, error) {
+	var pathElements []string
+	for _, elem := range elements {
+		switch v := elem.(type) {
+		case []interface{}:
+			for _, e := range v {
+				elemStr, err := cast.ToStringE(e)
+				if err != nil {
+					return "", err
+				}
+				pathElements = append(pathElements, filepath.ToSlash(elemStr))
+			}
+		default:
+			elemStr, err := cast.ToStringE(elem)
+			if err != nil {
+				return "", err
+			}
+			pathElements = append(pathElements, filepath.ToSlash(elemStr))
+		}
+	}
+	return _path.Join(pathElements...), nil
 }