1
0
mirror of https://github.com/danog/gojekyll.git synced 2024-11-26 23:24:39 +01:00

Rename path -> name or relpath

This commit is contained in:
Oliver Steele 2017-06-16 20:06:55 -04:00
parent 9695a57374
commit 20cde62eff
16 changed files with 119 additions and 107 deletions

View File

@ -11,7 +11,7 @@ import (
// Clean the destination. Remove files that aren't in keep_files, and resulting empty diretories.
// It attends to the global options.dry_run.
func (s *Site) Clean() error {
removeFiles := func(path string, info os.FileInfo, err error) error {
removeFiles := func(name string, info os.FileInfo, err error) error {
switch {
case err != nil && os.IsNotExist(err):
return nil
@ -19,12 +19,12 @@ func (s *Site) Clean() error {
return err
case info.IsDir():
return nil
case s.KeepFile(path):
case s.KeepFile(name):
return nil
case options.dryRun:
fmt.Println("rm", path)
fmt.Println("rm", name)
default:
return os.Remove(path)
return os.Remove(name)
}
return nil
}
@ -51,24 +51,24 @@ func (s *Site) Build() (count int, err error) {
// WritePage writes a page to the destination directory.
func (s *Site) WritePage(page Page) error {
src := filepath.Join(s.Source, page.Path())
dst := filepath.Join(s.Destination, page.Permalink())
if !page.Static() && filepath.Ext(dst) == "" {
dst = filepath.Join(dst, "/index.html")
from := filepath.Join(s.Source, page.Path())
to := filepath.Join(s.Destination, page.Permalink())
if !page.Static() && filepath.Ext(to) == "" {
to = filepath.Join(to, "/index.html")
}
// nolint: gas
if err := os.MkdirAll(filepath.Dir(dst), 0755); err != nil {
if err := os.MkdirAll(filepath.Dir(to), 0755); err != nil {
return err
}
switch {
case options.dryRun:
fmt.Println("create", dst, "from", page.Source())
fmt.Println("create", to, "from", page.Source())
return nil
case page.Static() && options.useHardLinks:
return os.Link(src, dst)
return os.Link(from, to)
case page.Static():
return CopyFileContents(dst, src, 0644)
return CopyFileContents(to, from, 0644)
default:
return VisitCreatedFile(dst, page.Write)
return VisitCreatedFile(to, page.Write)
}
}

View File

@ -15,6 +15,7 @@ type Collection struct {
Pages []Page
}
// NewCollection creates a new Collection with defaults d
func NewCollection(s *Site, name string, d VariableMap) *Collection {
return &Collection{
Site: s,
@ -65,7 +66,7 @@ func (c *Collection) ReadPages() error {
"collection": c.Name,
})
walkFn := func(path string, info os.FileInfo, err error) error {
walkFn := func(name string, info os.FileInfo, err error) error {
if err != nil {
// if the issue is simply that the directory doesn't exist, warn instead of error
if os.IsNotExist(err) {
@ -76,7 +77,7 @@ func (c *Collection) ReadPages() error {
}
return err
}
rel, err := filepath.Rel(basePath, path)
rel, err := filepath.Rel(basePath, name)
switch {
case err != nil:
return err
@ -88,7 +89,7 @@ func (c *Collection) ReadPages() error {
case err != nil:
return err
case p.Static():
fmt.Printf("skipping static file inside collection: %s\n", path)
fmt.Printf("skipping static file inside collection: %s\n", name)
case p.Published():
c.Site.Paths[p.Permalink()] = p
c.Pages = append(c.Pages, p)

View File

@ -25,7 +25,7 @@ func (p *DynamicPage) Static() bool { return false }
// NewDynamicPage reads the front matter from a file to create a new DynamicPage.
func NewDynamicPage(fields pageFields) (p *DynamicPage, err error) {
data, err := ioutil.ReadFile(filepath.Join(fields.site.Source, fields.path))
data, err := ioutil.ReadFile(filepath.Join(fields.site.Source, fields.relpath))
if err != nil {
return
}
@ -56,7 +56,7 @@ func readFrontMatter(sourcePtr *[]byte) (frontMatter VariableMap, err error) {
start = match[1]
}
// This fixes the line numbers for template errors
// TODO find a less hacky solution
// TODO find a less hack-ey solution
*sourcePtr = append(
regexp.MustCompile(`[^\n\r]+`).ReplaceAllLiteral(source[:start], []byte{}),
source[start:]...)
@ -66,14 +66,14 @@ func readFrontMatter(sourcePtr *[]byte) (frontMatter VariableMap, err error) {
// TemplateObject returns the attributes of the template page object.
func (p *DynamicPage) TemplateObject() VariableMap {
var (
path = p.path
ext = filepath.Ext(path)
root = p.path[:len(path)-len(ext)]
relpath = p.relpath
ext = filepath.Ext(relpath)
root = PathWithoutExtension(p.relpath)
base = filepath.Base(root)
)
data := VariableMap{
"path": p.path,
"path": relpath,
"url": p.Permalink(),
// TODO content output
@ -134,7 +134,7 @@ func (p *DynamicPage) Write(w io.Writer) (err error) {
return
}
if p.Site().IsMarkdown(p.path) {
if p.Site().IsMarkdown(p.relpath) {
body = blackfriday.MarkdownCommon(body)
body, err = p.applyLayout(p.frontMatter, body)
if err != nil {
@ -142,7 +142,7 @@ func (p *DynamicPage) Write(w io.Writer) (err error) {
}
}
if p.Site().IsSassPath(p.path) {
if p.Site().IsSassPath(p.relpath) {
return p.writeSass(w, body)
}

View File

@ -47,8 +47,8 @@ func CopyFileContents(dst, src string, perm os.FileMode) error {
}
// ReadFileMagic returns the first four bytes of the file, with final '\r' replaced by '\n'.
func ReadFileMagic(p string) (data []byte, err error) {
f, err := os.Open(p)
func ReadFileMagic(name string) (data []byte, err error) {
f, err := os.Open(name)
if err != nil {
return
}
@ -63,19 +63,19 @@ func ReadFileMagic(p string) (data []byte, err error) {
// PostfixWalk is like filepath.Walk, but visits each directory after visiting its children instead of before.
// It does not implement SkipDir.
func PostfixWalk(path string, walkFn filepath.WalkFunc) error {
if files, err := ioutil.ReadDir(path); err == nil {
func PostfixWalk(root string, walkFn filepath.WalkFunc) error {
if files, err := ioutil.ReadDir(root); err == nil {
for _, stat := range files {
if stat.IsDir() {
if err = PostfixWalk(filepath.Join(path, stat.Name()), walkFn); err != nil {
if err = PostfixWalk(filepath.Join(root, stat.Name()), walkFn); err != nil {
return err
}
}
}
}
info, err := os.Stat(path)
return walkFn(path, info, err)
info, err := os.Stat(root)
return walkFn(root, info, err)
}
// IsNotEmpty returns a boolean indicating whether the error is known to report that a directory is not empty.
@ -87,8 +87,8 @@ func IsNotEmpty(err error) bool {
}
// RemoveEmptyDirectories recursively removes empty directories.
func RemoveEmptyDirectories(path string) error {
walkFn := func(path string, info os.FileInfo, err error) error {
func RemoveEmptyDirectories(root string) error {
walkFn := func(name string, info os.FileInfo, err error) error {
switch {
case err != nil && os.IsNotExist(err):
// It's okay to call this on a directory that doesn't exist.
@ -97,7 +97,7 @@ func RemoveEmptyDirectories(path string) error {
case err != nil:
return err
case info.IsDir():
err := os.Remove(path)
err := os.Remove(name)
switch {
case err == nil:
return nil
@ -111,5 +111,5 @@ func RemoveEmptyDirectories(path string) error {
}
return nil
}
return PostfixWalk(path, walkFn)
return PostfixWalk(root, walkFn)
}

8
helpers/pathname.go Normal file
View File

@ -0,0 +1,8 @@
package helpers
import "path/filepath"
// PathWithoutExtension returns a path without its extension, if any
func PathWithoutExtension(name string) string {
return name[:len(name)-len(filepath.Ext(name))]
}

View File

@ -19,37 +19,9 @@ func TestLeftPad(t *testing.T) {
require.Equal(t, " abc", LeftPad("abc", 6))
}
func TestGetXXX(t *testing.T) {
d := VariableMap{
"t": true,
"f": false,
"s": "ss",
}
require.Equal(t, true, d.Bool("t", true))
require.Equal(t, true, d.Bool("t", false))
require.Equal(t, false, d.Bool("f", true))
require.Equal(t, false, d.Bool("f", true))
require.Equal(t, true, d.Bool("-", true))
require.Equal(t, false, d.Bool("-", false))
require.Equal(t, true, d.Bool("s", true))
require.Equal(t, false, d.Bool("s", false))
require.Equal(t, "ss", d.String("s", "-"))
require.Equal(t, "--", d.String("-", "--"))
require.Equal(t, "--", d.String("t", "--"))
}
func TestMergeVariableMaps(t *testing.T) {
m1 := VariableMap{"a": 1, "b": 2}
m2 := VariableMap{"b": 3, "c": 4}
expected := VariableMap{"a": 1, "b": 3, "c": 4}
actual := MergeVariableMaps(m1, m2)
require.Equal(t, expected, actual)
}
func TestStringArrayToMap(t *testing.T) {
input := []string{"a", "b", "c"}
expected := map[string]bool{"a": true, "b": true, "c": true}
actual := stringArrayToMap(input)
actual := StringArrayToMap(input)
require.Equal(t, expected, actual)
}

View File

@ -13,20 +13,20 @@ import (
)
// FindLayout returns a template for the named layout.
func (s *Site) FindLayout(name string, fm *VariableMap) (t *liquid.Template, err error) {
func (s *Site) FindLayout(base string, fm *VariableMap) (t *liquid.Template, err error) {
exts := []string{"", ".html"}
for _, ext := range strings.SplitN(s.config.MarkdownExt, `,`, -1) {
exts = append(exts, "."+ext)
}
var (
path string
name string
content []byte
found bool
)
for _, ext := range exts {
// TODO respect layout config
path = filepath.Join(s.Source, "_layouts", name+ext)
content, err = ioutil.ReadFile(path)
name = filepath.Join(s.Source, "_layouts", base+ext)
content, err = ioutil.ReadFile(name)
if err == nil {
found = true
break
@ -36,7 +36,7 @@ func (s *Site) FindLayout(name string, fm *VariableMap) (t *liquid.Template, err
}
}
if !found {
panic(fmt.Errorf("no template for %s", name))
panic(fmt.Errorf("no template for %s", base))
}
*fm, err = readFrontMatter(&content)
if err != nil {

View File

@ -13,11 +13,10 @@ func LinkFactory(p *core.Parser, config *core.Configuration) (core.Tag, error) {
start := p.Position
p.SkipPastTag()
end := p.Position - 2
path := strings.TrimSpace(string(p.Data[start:end]))
url, ok := site.GetFileURL(path)
name := strings.TrimSpace(string(p.Data[start:end]))
url, ok := site.GetFileURL(name)
if !ok {
return nil, fmt.Errorf("link tag: %s not found", path)
return nil, fmt.Errorf("link tag: %s not found", name)
}
return &Link{url}, nil

View File

@ -25,12 +25,12 @@ func printSetting(label string, value string) {
fmt.Printf("%s %s\n", LeftPad(label, len(configurationFileLabel)), value)
}
func printPathSetting(label string, path string) {
path, err := filepath.Abs(path)
func printPathSetting(label string, name string) {
name, err := filepath.Abs(name)
if err != nil {
panic("Couldn't convert to absolute path")
}
printSetting(label, path)
printSetting(label, name)
}
func main() {

View File

@ -8,8 +8,8 @@ import (
)
// IsMarkdown returns a boolean indicating whether the file is a Markdown file, according to the current project.
func (s *Site) IsMarkdown(path string) bool {
ext := filepath.Ext(path)
func (s *Site) IsMarkdown(name string) bool {
ext := filepath.Ext(name)
return s.MarkdownExtensions()[strings.TrimLeft(ext, ".")]
}

33
page.go
View File

@ -32,32 +32,29 @@ type Page interface {
}
type pageFields struct {
relpath string // relative to site source, e.g. "_post/base.ext"
permalink string // cached permalink
frontMatter VariableMap // page front matter, merged with defaults
site *Site
path string // this is the relative path
permalink string
frontMatter VariableMap
}
func (p *pageFields) String() string {
return fmt.Sprintf("%s{Path=%v, Permalink=%v}",
reflect.TypeOf(p).Name(), p.path, p.permalink)
return fmt.Sprintf("%s{Path=%v, Permalink=%v}", reflect.TypeOf(p).Name(), p.relpath, p.permalink)
}
func (p *pageFields) Path() string { return p.path }
func (p *pageFields) Path() string { return p.relpath }
func (p *pageFields) Permalink() string { return p.permalink }
func (p *pageFields) Published() bool {
return p.frontMatter.Bool("published", true)
}
func (p *pageFields) Published() bool { return p.frontMatter.Bool("published", true) }
func (p *pageFields) Site() *Site { return p.site }
// ReadPage reads a Page from a file, using defaults as the default front matter.
func ReadPage(site *Site, rel string, defaults VariableMap) (p Page, err error) {
magic, err := ReadFileMagic(filepath.Join(site.Source, rel))
func ReadPage(site *Site, relpath string, defaults VariableMap) (p Page, err error) {
magic, err := ReadFileMagic(filepath.Join(site.Source, relpath))
if err != nil {
return
}
fields := pageFields{site: site, path: rel, frontMatter: defaults}
fields := pageFields{site: site, relpath: relpath, frontMatter: defaults}
if string(magic) == "---\n" {
p, err = NewDynamicPage(fields)
if err != nil {
@ -87,16 +84,16 @@ func (p *StaticPage) Write(w io.Writer) error {
// See https://jekyllrb.com/docs/variables/#page-variables
func (p *pageFields) TemplateObject() VariableMap {
var (
path = "/" + p.path
base = filepath.Base(path)
ext = filepath.Ext(path)
relpath = "/" + p.relpath
base = filepath.Base(relpath)
ext = filepath.Ext(relpath)
)
return VariableMap{
"path": path,
"path": "/" + p.relpath,
"modified_time": 0, // TODO
"name": base,
"basename": base[:len(base)-len(ext)],
"basename": PathWithoutExtension(base),
"extname": ext,
}
}
@ -109,7 +106,7 @@ func (p *pageFields) DebugVariables() VariableMap {
// Source returns the file path of the page source.
func (p *pageFields) Source() string {
return filepath.Join(p.site.Source, p.path)
return filepath.Join(p.site.Source, p.relpath)
}
// StaticPage is a static page.

View File

@ -39,10 +39,10 @@ var templateVariableMatcher = regexp.MustCompile(`:\w+\b`)
func (p *pageFields) permalinkTemplateVariables() map[string]string {
var (
collectionName string
path = p.path
path = p.relpath
ext = filepath.Ext(path)
outputExt = ext
root = path[:len(path)-len(ext)]
root = PathWithoutExtension(path)
name = filepath.Base(root)
title = p.frontMatter.String("title", name)
)

View File

@ -14,7 +14,7 @@ func TestExpandPermalinkPattern(t *testing.T) {
testPermalinkPattern := func(pattern, path string, data VariableMap) (string, error) {
vs := MergeVariableMaps(data, VariableMap{"permalink": pattern})
p := pageFields{site, path, "", vs}
p := pageFields{site: site, relpath: path, frontMatter: vs}
return p.expandPermalink()
}

View File

@ -15,8 +15,8 @@ import (
)
// IsSassPath returns a boolean indicating whether the file is a Sass (".sass" or ".scss") file.
func (s *Site) IsSassPath(path string) bool {
return strings.HasSuffix(path, ".sass") || strings.HasSuffix(path, ".scss")
func (s *Site) IsSassPath(name string) bool {
return strings.HasSuffix(name, ".sass") || strings.HasSuffix(name, ".scss")
}
func (p *DynamicPage) writeSass(w io.Writer, data []byte) error {

View File

@ -14,22 +14,22 @@ func server() error {
}
func handler(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path
urlpath := r.URL.Path
// w.Header().Set("Content-Type", "text/plain; charset=utf-8")
p, found := site.Paths[path]
p, found := site.Paths[urlpath]
if !found {
w.WriteHeader(http.StatusNotFound)
p, found = site.Paths["404.html"]
}
if !found {
fmt.Fprintf(w, "404 page not found: %s", path)
fmt.Fprintf(w, "404 page not found: %s", urlpath)
return
}
err := p.Write(w)
if err != nil {
fmt.Printf("Error rendering %s: %s", path, err)
fmt.Printf("Error rendering %s: %s", urlpath, err)
}
}

35
variable_map_test.go Normal file
View File

@ -0,0 +1,35 @@
package main
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestGetXXX(t *testing.T) {
d := VariableMap{
"t": true,
"f": false,
"s": "ss",
}
require.Equal(t, true, d.Bool("t", true))
require.Equal(t, true, d.Bool("t", false))
require.Equal(t, false, d.Bool("f", true))
require.Equal(t, false, d.Bool("f", true))
require.Equal(t, true, d.Bool("-", true))
require.Equal(t, false, d.Bool("-", false))
require.Equal(t, true, d.Bool("s", true))
require.Equal(t, false, d.Bool("s", false))
require.Equal(t, "ss", d.String("s", "-"))
require.Equal(t, "--", d.String("-", "--"))
require.Equal(t, "--", d.String("t", "--"))
}
func TestMergeVariableMaps(t *testing.T) {
m1 := VariableMap{"a": 1, "b": 2}
m2 := VariableMap{"b": 3, "c": 4}
expected := VariableMap{"a": 1, "b": 3, "c": 4}
actual := MergeVariableMaps(m1, m2)
require.Equal(t, expected, actual)
}