1
0
mirror of https://github.com/danog/gojekyll.git synced 2025-01-22 20:51:24 +01:00
This commit is contained in:
Oliver Steele 2017-07-03 13:03:45 -04:00
parent 18c715c2be
commit c60af75d06
10 changed files with 59 additions and 46 deletions

View File

@ -4,6 +4,7 @@ import (
"fmt"
"os"
"path/filepath"
"reflect"
"sort"
"strings"
"time"
@ -108,30 +109,40 @@ func pageFromPathOrRoute(s *sites.Site, path string) (pages.Document, error) {
}
func varsCommand(site *sites.Site) error {
printSetting("Variables:", "")
siteData := site.ToLiquid().(map[string]interface{})
// The YAML representation including collections is impractically large for debugging.
// Neuter it. This destroys it as Liquid data, but that's okay in this context.
// for _, c := range site.Collections {
// siteData[c.Name] = fmt.Sprintf("<elided page data for %d items>", len(siteData[c.Name].([]pages.Page)))
// }
var data interface{}
switch {
case *siteVariable:
data = siteData
case *dataVariable:
data = siteData["data"]
default:
case strings.HasPrefix(*variablePath, "site"):
data = site
for _, name := range strings.Split(*variablePath, ".")[1:] {
if drop, ok := data.(liquid.Drop); ok {
data = drop.ToLiquid()
}
if reflect.TypeOf(data).Kind() == reflect.Map {
item := reflect.ValueOf(data).MapIndex(reflect.ValueOf(name))
if item.CanInterface() && !item.IsNil() {
data = item.Interface()
continue
}
}
return fmt.Errorf("no such property: %q", name)
}
case *variablePath != "":
page, err := pageFromPathOrRoute(site, *variablePath)
if err != nil {
return err
}
data = page.(liquid.Drop).ToLiquid()
default:
data = site
}
if drop, ok := data.(liquid.Drop); ok {
data = drop
}
b, err := yaml.Marshal(data)
if err != nil {
return err
}
printSetting("Variables:", "")
fmt.Println(string(b))
return nil
}

View File

@ -30,21 +30,19 @@ var (
build = app.Command("build", "Build your site").Alias("b")
clean = app.Command("clean", "Clean the site (removes site output) without building.")
serve = app.Command("serve", "Serve your site locally").Alias("server").Alias("s")
open = serve.Flag("open-url", "Launch your site in a browser").Short('o').Bool()
benchmark = app.Command("profile", "Repeat build for ten seconds. Implies --profile.")
variables = app.Command("variables", "Display a file or URL path's variables").Alias("v").Alias("var").Alias("vars")
dataVariable = variables.Flag("data", "Display site.data").Bool()
siteVariable = variables.Flag("site", "Display site variables instead of page variables").Bool()
variablePath = variables.Arg("PATH", "Path or URL").String()
render = app.Command("render", "Render a file or URL path to standard output")
renderPath = render.Arg("PATH", "Path or URL").String()
routes = app.Command("routes", "Display site permalinks and associated files")
dynamicRoutes = routes.Flag("dynamic", "Only show routes to non-static files").Bool()
render = app.Command("render", "Render a file or URL path to standard output")
renderPath = render.Arg("PATH", "Path or URL").String()
serve = app.Command("serve", "Serve your site locally").Alias("server").Alias("s")
open = serve.Flag("open-url", "Launch your site in a browser").Short('o').Bool()
variables = app.Command("variables", "Display a file or URL path's variables").Alias("v").Alias("var").Alias("vars")
variablePath = variables.Arg("PATH", "Path, URL, site, or site...").String()
)
func init() {

View File

@ -12,8 +12,10 @@ import (
type Collection struct {
Name string
Metadata map[string]interface{}
site Site
pages []pages.Page
config *config.Config
pages []pages.Page
site Site
}
// Site is the interface a site provides to collections it contains.
@ -27,14 +29,11 @@ func NewCollection(s Site, name string, metadata map[string]interface{}) *Collec
return &Collection{
Name: name,
Metadata: metadata,
config: s.Config(),
site: s,
}
}
func (c *Collection) Config() *config.Config {
return c.site.Config()
}
// OutputExt is in the page.Container interface.
func (c *Collection) OutputExt(pathname string) string {
return c.site.OutputExt(pathname)
@ -42,7 +41,7 @@ func (c *Collection) OutputExt(pathname string) string {
// AbsDir is in the page.Container interface.
func (c *Collection) AbsDir() string {
return filepath.Join(c.Config().SourceDir(), c.PathPrefix())
return filepath.Join(c.config.SourceDir(), c.PathPrefix())
}
// PathPrefix is in the page.Container interface.

View File

@ -40,16 +40,16 @@ func TestPermalinkPattern(t *testing.T) {
func TestReadPosts(t *testing.T) {
site := siteMock{config.FromString("source: testdata")}
c := NewCollection(site, "posts", map[string]interface{}{})
c.ReadPages()
require.NoError(t, c.ReadPages())
require.Len(t, c.Pages(), 1)
site = siteMock{config.FromString("source: testdata\nunpublished: true")}
c = NewCollection(site, "posts", map[string]interface{}{})
c.ReadPages()
require.NoError(t, c.ReadPages())
require.Len(t, c.Pages(), 2)
site = siteMock{config.FromString("source: testdata\nfuture: true")}
c = NewCollection(site, "posts", map[string]interface{}{})
c.ReadPages()
require.NoError(t, c.ReadPages())
require.Len(t, c.Pages(), 2)
}

View File

@ -16,7 +16,7 @@ const draftsPath = "_drafts"
// ReadPages scans the file system for collection pages, and adds them to c.Pages.
func (c *Collection) ReadPages() error {
sitePath := c.Config().Source
sitePath := c.config.Source
pageDefaults := map[string]interface{}{
"collection": c.Name,
"permalink": c.PermalinkPattern(),
@ -41,16 +41,22 @@ func (c *Collection) ReadPages() error {
case info.IsDir():
return nil
}
fm := templates.MergeVariableMaps(pageDefaults, c.Config().GetFrontMatterDefaults(c.Name, relname))
fm := templates.MergeVariableMaps(pageDefaults, c.config.GetFrontMatterDefaults(c.Name, relname))
return c.readFile(filename, relname, fm)
}
if c.IsPostsCollection() && c.Config().Drafts {
if c.IsPostsCollection() && c.config.Drafts {
if err := filepath.Walk(filepath.Join(sitePath, draftsPath), walkFn); err != nil {
return err
}
}
if err := filepath.Walk(filepath.Join(sitePath, c.PathPrefix()), walkFn); err != nil {
return err
}
fmt.Println("is", c.Name, c.IsPostsCollection())
if c.IsPostsCollection() {
sort.Sort(pagesByDate{c.pages})
}
return filepath.Walk(filepath.Join(sitePath, c.PathPrefix()), walkFn)
return nil
}
// readFile mutates fm.
@ -59,7 +65,7 @@ func (c *Collection) readFile(abs string, rel string, fm map[string]interface{})
switch {
case !strategy.collectible(rel):
return nil
case strategy.future(rel) && !c.Config().Future:
case strategy.future(rel) && !c.config.Future:
return nil
default:
strategy.addDate(rel, fm)
@ -70,7 +76,7 @@ func (c *Collection) readFile(abs string, rel string, fm map[string]interface{})
return err
case f.Static():
return nil
case f.Published() || c.Config().Unpublished:
case f.Published() || c.config.Unpublished:
p := f.(pages.Page)
c.pages = append(c.pages, p)
}

View File

@ -1,6 +1,8 @@
package collections
import "github.com/osteele/gojekyll/pages"
import (
"github.com/osteele/gojekyll/pages"
)
type pagesByDate struct{ pages []pages.Page }
@ -12,7 +14,7 @@ func (p pagesByDate) Len() int {
// Less is part of sort.Interface.
func (p pagesByDate) Less(i, j int) bool {
a, b := p.pages[i].PostDate(), p.pages[j].PostDate()
return a.Before(b)
return a.After(b)
}
// Swap is part of sort.Interface.

View File

@ -20,11 +20,11 @@ func TestDefaultConfig(t *testing.T) {
func TestPlugins(t *testing.T) {
c := Default()
Unmarshal([]byte(`plugins: ['a']`), &c)
require.NoError(t, Unmarshal([]byte(`plugins: ['a']`), &c))
require.Equal(t, []string{"a"}, c.Plugins)
c = Default()
Unmarshal([]byte(`gems: ['a']`), &c)
require.NoError(t, Unmarshal([]byte(`gems: ['a']`), &c))
require.Equal(t, []string{"a"}, c.Plugins)
}

View File

@ -25,7 +25,7 @@ func TestFilenameDate(t *testing.T) {
require.True(t, found)
require.Equal(t, timeMustParse("2017-07-02T00:00:00Z"), d)
d, found = FilenameDate("not-post.html")
_, found = FilenameDate("not-post.html")
require.False(t, found)
}

View File

@ -22,7 +22,7 @@ func TestSafeReplaceAllStringFunc(t *testing.T) {
require.NoError(t, err)
require.Equal(t, "true > false", out)
out, err = SafeReplaceAllStringFunc(re, "1 > 0", func(m string) (string, error) {
_, err = SafeReplaceAllStringFunc(re, "1 > 0", func(m string) (string, error) {
return "", fmt.Errorf("an expected error")
})
require.Error(t, err)

View File

@ -1,8 +1,6 @@
package sites
import (
"fmt"
"github.com/osteele/gojekyll/collections"
"github.com/osteele/gojekyll/pages"
)
@ -13,7 +11,6 @@ func (s *Site) findPostCollection() *collections.Collection {
return c
}
}
panic(fmt.Errorf("no posts!"))
return nil
}