Skip to content

Commit 662e12f

Browse files
committed
commands, create: Add .Site to the archetype templates
This commit completes the "The Revival of the Archetypes!" If `.Site` is used in the arcetype template, the site is built and added to the template context. Note that this may be potentially time consuming for big sites. A more complete example would then be for the section `newsletter` and the archetype file `archetypes/newsletter.md`: ``` --- title: "{{ replace .TranslationBaseName "-" " " | title }}" date: {{ .Date }} tags: - x categories: - x draft: true --- <!--more--> {{ range first 10 ( where .Site.RegularPages "Type" "cool" ) }} * {{ .Title }} {{ end }} ``` And then create a new post with: ```bash hugo new newsletter/the-latest-cool.stuff.md ``` **Hot Tip:** If you set the `newContentEditor` configuration variable to an editor on your `PATH`, the newly created article will be opened. The above _newsletter type archetype_ illustrates the possibilities: The full Hugo `.Site` and all of Hugo's template funcs can be used in the archetype file. Fixes #1629
1 parent 422057f commit 662e12f

File tree

6 files changed

+101
-30
lines changed

6 files changed

+101
-30
lines changed

‎commands/new.go‎

Lines changed: 31 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -115,13 +115,40 @@ func NewContent(cmd *cobra.Command, args []string) error {
115115
kind = contentType
116116
}
117117

118-
s, err := hugolib.NewSite(*cfg)
119-
118+
ps, err := helpers.NewPathSpec(cfg.Fs, cfg.Cfg)
120119
if err != nil {
121-
return newSystemError(err)
120+
return err
121+
}
122+
123+
// If a site isn't in use in the archetype template, we can skip the build.
124+
siteFactory := func(filename string, siteUsed bool) (*hugolib.Site, error) {
125+
if !siteUsed {
126+
return hugolib.NewSite(*cfg)
127+
}
128+
var s *hugolib.Site
129+
if err := c.initSites(); err != nil {
130+
return nil, err
131+
}
132+
133+
if err := Hugo.Build(hugolib.BuildCfg{SkipRender: true, PrintStats: false}); err != nil {
134+
return nil, err
135+
}
136+
137+
s = Hugo.Sites[0]
138+
139+
if len(Hugo.Sites) > 1 {
140+
// Find the best match.
141+
for _, ss := range Hugo.Sites {
142+
if strings.Contains(createPath, "."+ss.Language.Lang) {
143+
s = ss
144+
break
145+
}
146+
}
147+
}
148+
return s, nil
122149
}
123150

124-
return create.NewContent(s, kind, createPath)
151+
return create.NewContent(ps, siteFactory, kind, createPath)
125152
}
126153

127154
func doNewSite(fs *hugofs.Fs, basepath string, force bool) error {

‎create/content.go‎

Lines changed: 29 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -27,15 +27,31 @@ import (
2727

2828
// NewContent creates a new content file in the content directory based upon the
2929
// given kind, which is used to lookup an archetype.
30-
func NewContent(s *hugolib.Site, kind, targetPath string) error {
30+
func NewContent(
31+
ps *helpers.PathSpec,
32+
siteFactory func(filename string, siteUsed bool) (*hugolib.Site, error), kind, targetPath string) error {
33+
3134
jww.INFO.Println("attempting to create ", targetPath, "of", kind)
3235

33-
archetypeFilename := findArchetype(s, kind)
36+
archetypeFilename := findArchetype(ps, kind)
37+
38+
f, err := ps.Fs.Source.Open(archetypeFilename)
39+
if err != nil {
40+
return err
41+
}
42+
defer f.Close()
43+
// Building the sites can be expensive, so only do it if really needed.
44+
siteUsed := false
45+
if helpers.ReaderContains(f, []byte(".Site")) {
46+
siteUsed = true
47+
}
48+
49+
s, err := siteFactory(targetPath, siteUsed)
50+
if err != nil {
51+
return err
52+
}
3453

35-
var (
36-
content []byte
37-
err error
38-
)
54+
var content []byte
3955

4056
content, err = executeArcheTypeAsTemplate(s, kind, targetPath, archetypeFilename)
4157
if err != nil {
@@ -68,13 +84,13 @@ func NewContent(s *hugolib.Site, kind, targetPath string) error {
6884
// FindArchetype takes a given kind/archetype of content and returns an output
6985
// path for that archetype. If no archetype is found, an empty string is
7086
// returned.
71-
func findArchetype(s *hugolib.Site, kind string) (outpath string) {
72-
search := []string{s.PathSpec.AbsPathify(s.Cfg.GetString("archetypeDir"))}
87+
func findArchetype(ps *helpers.PathSpec, kind string) (outpath string) {
88+
search := []string{ps.AbsPathify(ps.Cfg.GetString("archetypeDir"))}
7389

74-
if s.Cfg.GetString("theme") != "" {
75-
themeDir := filepath.Join(s.PathSpec.AbsPathify(s.Cfg.GetString("themesDir")+"/"+s.Cfg.GetString("theme")), "/archetypes/")
76-
if _, err := s.Fs.Source.Stat(themeDir); os.IsNotExist(err) {
77-
jww.ERROR.Printf("Unable to find archetypes directory for theme %q at %q", s.Cfg.GetString("theme"), themeDir)
90+
if ps.Cfg.GetString("theme") != "" {
91+
themeDir := filepath.Join(ps.AbsPathify(ps.Cfg.GetString("themesDir")+"/"+ps.Cfg.GetString("theme")), "/archetypes/")
92+
if _, err := ps.Fs.Source.Stat(themeDir); os.IsNotExist(err) {
93+
jww.ERROR.Printf("Unable to find archetypes directory for theme %q at %q", ps.Cfg.GetString("theme"), themeDir)
7894
} else {
7995
search = append(search, themeDir)
8096
}
@@ -94,7 +110,7 @@ func findArchetype(s *hugolib.Site, kind string) (outpath string) {
94110
for _, p := range pathsToCheck {
95111
curpath := filepath.Join(x, p)
96112
jww.DEBUG.Println("checking", curpath, "for archetypes")
97-
if exists, _ := helpers.Exists(curpath, s.Fs.Source); exists {
113+
if exists, _ := helpers.Exists(curpath, ps.Fs.Source); exists {
98114
jww.INFO.Println("curpath: " + curpath)
99115
return curpath
100116
}

‎create/content_template_handler.go‎

Lines changed: 28 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -18,16 +18,38 @@ import (
1818
"fmt"
1919
"time"
2020

21+
"github.com/gohugoio/hugo/helpers"
2122
"github.com/gohugoio/hugo/source"
2223

2324
"github.com/gohugoio/hugo/hugolib"
2425
"github.com/gohugoio/hugo/tpl"
2526
"github.com/spf13/afero"
2627
)
2728

29+
// ArchetypeFileData represents the data available to an archetype template.
30+
type ArchetypeFileData struct {
31+
// The archetype content type, either given as --kind option or extracted
32+
// from the target path's section, i.e. "blog/mypost.md" will resolve to
33+
// "blog".
34+
Type string
35+
36+
// The current date and time as a RFC3339 formatted string, suitable for use in front matter.
37+
Date string
38+
39+
// The Site, fully equipped with all the pages etc. Note: This will only be set if it is actually
40+
// used in the archetype template. Also, if this is a multilingual setup,
41+
// this site is the site that best matches the target content file, based
42+
// on the presence of language code in the filename.
43+
Site *hugolib.Site
44+
45+
// The target content file. Note that the .Content will be empty, as that
46+
// has not been created yet.
47+
*source.File
48+
}
49+
2850
const (
2951
archetypeTemplateTemplate = `+++
30-
title = "{{ replace .BaseFileName "-" " " | title }}"
52+
title = "{{ replace .TranslationBaseName "-" " " | title }}"
3153
date = {{ .Date }}
3254
draft = true
3355
+++`
@@ -44,14 +66,11 @@ func executeArcheTypeAsTemplate(s *hugolib.Site, kind, targetPath, archetypeFile
4466
sp := source.NewSourceSpec(s.Deps.Cfg, s.Deps.Fs)
4567
f := sp.NewFile(targetPath)
4668

47-
data := struct {
48-
Type string
49-
Date string
50-
*source.File
51-
}{
69+
data := ArchetypeFileData{
5270
Type: kind,
5371
Date: time.Now().Format(time.RFC3339),
5472
File: f,
73+
Site: s,
5574
}
5675

5776
if archetypeFilename == "" {
@@ -67,11 +86,12 @@ func executeArcheTypeAsTemplate(s *hugolib.Site, kind, targetPath, archetypeFile
6786

6887
// Reuse the Hugo template setup to get the template funcs properly set up.
6988
templateHandler := s.Deps.Tmpl.(tpl.TemplateHandler)
70-
if err := templateHandler.AddTemplate("_text/archetype", string(archetypeTemplate)); err != nil {
89+
templateName := "_text/" + helpers.Filename(archetypeFilename)
90+
if err := templateHandler.AddTemplate(templateName, string(archetypeTemplate)); err != nil {
7191
return nil, fmt.Errorf("Failed to parse archetype file %q: %s", archetypeFilename, err)
7292
}
7393

74-
templ := templateHandler.Lookup("_text/archetype")
94+
templ := templateHandler.Lookup(templateName)
7595

7696
var buff bytes.Buffer
7797
if err := templ.Execute(&buff, data); err != nil {

‎create/content_test.go‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -52,13 +52,17 @@ func TestNewContent(t *testing.T) {
5252

5353
for _, c := range cases {
5454
cfg, fs := newTestCfg()
55+
ps, err := helpers.NewPathSpec(fs, cfg)
56+
require.NoError(t, err)
5557
h, err := hugolib.NewHugoSites(deps.DepsCfg{Cfg: cfg, Fs: fs})
5658
require.NoError(t, err)
5759
require.NoError(t, initFs(fs))
5860

59-
s := h.Sites[0]
61+
siteFactory := func(filename string, siteUsed bool) (*hugolib.Site, error) {
62+
return h.Sites[0], nil
63+
}
6064

61-
require.NoError(t, create.NewContent(s, c.kind, c.path))
65+
require.NoError(t, create.NewContent(ps, siteFactory, c.kind, c.path))
6266

6367
fname := filepath.Join("content", filepath.FromSlash(c.path))
6468
content := readFileFromFs(t, fs.Source, fname)

‎helpers/path.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -215,7 +215,7 @@ func (p *PathSpec) getThemeDirPath(path string) (string, error) {
215215
}
216216

217217
themeDir := filepath.Join(p.GetThemeDir(), path)
218-
if _, err := p.fs.Source.Stat(themeDir); os.IsNotExist(err) {
218+
if _, err := p.Fs.Source.Stat(themeDir); os.IsNotExist(err) {
219219
return "", fmt.Errorf("Unable to find %s directory for theme %s in %s", path, p.theme, themeDir)
220220
}
221221

‎helpers/pathspec.go‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,10 @@ type PathSpec struct {
5252
multilingual bool
5353

5454
// The file systems to use
55-
fs *hugofs.Fs
55+
Fs *hugofs.Fs
56+
57+
// The config provider to use
58+
Cfg config.Provider
5659
}
5760

5861
func (p PathSpec) String() string {
@@ -70,7 +73,8 @@ func NewPathSpec(fs *hugofs.Fs, cfg config.Provider) (*PathSpec, error) {
7073
}
7174

7275
ps := &PathSpec{
73-
fs: fs,
76+
Fs: fs,
77+
Cfg: cfg,
7478
disablePathToLower: cfg.GetBool("disablePathToLower"),
7579
removePathAccents: cfg.GetBool("removePathAccents"),
7680
uglyURLs: cfg.GetBool("uglyURLs"),

0 commit comments

Comments
 (0)