1
0
mirror of https://github.com/danog/gojekyll.git synced 2024-12-11 17:19:39 +01:00
gojekyll/utils/filepath.go

86 lines
2.0 KiB
Go
Raw Normal View History

2017-07-09 22:17:20 +02:00
package utils
import (
"path"
2017-07-02 03:12:22 +02:00
"path/filepath"
"strings"
2017-07-03 16:39:55 +02:00
"time"
)
2017-08-20 18:22:58 +02:00
// ParseFilenameDateTitle returns the date for a filename that uses Jekyll post convention.
2017-07-03 16:39:55 +02:00
// It also returns a bool indicating whether a date was found.
2017-08-20 18:22:58 +02:00
func ParseFilenameDateTitle(s string) (t time.Time, title string, found bool) {
2017-08-16 22:08:49 +02:00
var (
base = TrimExt(filepath.Base(s))
layout = "2006-01-02-"
)
if len(base) < len(layout) {
found = false
return
}
t, err := time.ParseInLocation(layout, base[:len(layout)], time.Local)
2017-08-16 22:08:49 +02:00
if err != nil {
return
}
2017-08-20 18:22:58 +02:00
title = Titleize(base[len(layout):])
found = true
2017-08-16 22:08:49 +02:00
return
2017-07-03 16:39:55 +02:00
}
2017-07-28 00:07:42 +02:00
// MatchList implement Jekyll include: and exclude: configurations.
// It reports whether any glob pattern matches the path.
2017-07-14 17:38:14 +02:00
// It panics with ErrBadPattern if any pattern is malformed.
2017-07-28 00:07:42 +02:00
// To match Jekyll, a string "dir/" matches that begins with this prefix.
2017-07-14 17:38:14 +02:00
func MatchList(patterns []string, name string) bool {
for _, p := range patterns {
match, err := filepath.Match(p, name)
if err != nil {
panic(err)
}
if match {
return true
}
2017-07-28 00:07:42 +02:00
if strings.HasSuffix(p, "/") && strings.HasPrefix(name, p) {
return true
}
2017-07-14 17:38:14 +02:00
}
return false
}
2017-07-03 17:48:06 +02:00
// MustAbs is like filepath.Abs, but panics instead of returning an error.
func MustAbs(path string) string {
abs, err := filepath.Abs(path)
if err != nil {
panic(err)
}
return abs
}
2017-07-02 03:12:22 +02:00
// MustRel is like filepath.Rel, but panics if the path cannot be relativized.
func MustRel(basepath, targpath string) string {
2017-07-03 17:48:06 +02:00
rel, err := filepath.Rel(basepath, targpath)
2017-07-02 03:12:22 +02:00
if err != nil {
panic(err)
}
2017-07-03 17:48:06 +02:00
return rel
2017-07-02 03:12:22 +02:00
}
// TrimExt returns a path without its extension, if any
func TrimExt(name string) string {
return name[:len(name)-len(path.Ext(name))]
}
// URLPathClean removes internal // etc. Unlike path.Clean, it
// leaves the final "/" intact.
2017-06-29 01:00:01 +02:00
func URLPathClean(url string) string {
finalSlash := false
if strings.HasSuffix(url, "/") && len(url) > 1 {
finalSlash = true
}
2017-06-29 01:00:01 +02:00
cleaned := path.Clean(url)
if finalSlash && !strings.HasSuffix(cleaned, "/") {
cleaned += "/"
}
return cleaned
}