Debian Codegraph @

create/content.go

raw
1 // Copyright 2019 The Hugo Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 // Package create provides functions to create new content.
15 package create
16
17 import (
18 "bytes"
19 "context"
20 "errors"
21 "fmt"
22 "io"
23 "os"
24 "path/filepath"
25 "strings"
26
27 "github.com/gohugoio/hugo/common/hexec"
28 "github.com/gohugoio/hugo/common/paths"
29 "github.com/gohugoio/hugo/hugofs/hglob"
30
31 "github.com/gohugoio/hugo/hugofs"
32
33 "github.com/gohugoio/hugo/helpers"
34 "github.com/gohugoio/hugo/hugolib"
35 "github.com/spf13/afero"
36 )
37
38 const (
39 // DefaultArchetypeTemplateTemplate is the template used in 'hugo new project'
40 // and the template we use as a fall back.
41 DefaultArchetypeTemplateTemplate = `---
42 title: "{{ replace .File.ContentBaseName "-" " " | title }}"
43 date: {{ .Date }}
44 draft: true
45 ---
46
47 `
48 )
49
50 // NewContent creates a new content file in h (or a full bundle if the archetype is a directory)
51 // in targetPath.
52 func NewContent(h *hugolib.HugoSites, kind, targetPath string, force bool) error {
53 if _, err := h.BaseFs.Content.Fs.Stat(""); err != nil {
54 return errors.New("no existing content directory configured for this project")
55 }
56
57 cf := hugolib.NewContentFactory(h)
58
59 if kind == "" {
60 var err error
61 kind, err = cf.SectionFromFilename(targetPath)
62 if err != nil {
63 return err
64 }
65 }
66
67 b := &contentBuilder{
68 archeTypeFs: h.PathSpec.BaseFs.Archetypes.Fs,
69 sourceFs: h.PathSpec.Fs.Source,
70 ps: h.PathSpec,
71 h: h,
72 cf: cf,
73
74 kind: kind,
75 targetPath: targetPath,
76 force: force,
77 }
78
79 ext := paths.Ext(targetPath)
80
81 b.setArcheTypeFilenameToUse(ext)
82
83 withBuildLock := func() (string, error) {
84 if !h.Configs.Base.NoBuildLock {
85 unlock, err := h.BaseFs.LockBuild()
86 if err != nil {
87 return "", fmt.Errorf("failed to acquire a build lock: %s", err)
88 }
89 defer unlock()
90 }
91
92 if b.isDir {
93 return "", b.buildDir()
94 }
95
96 if ext == "" {
97 return "", fmt.Errorf("failed to resolve %q to an archetype template", targetPath)
98 }
99
100 if !h.Conf.ContentTypes().IsContentFile(b.targetPath) {
101 return "", fmt.Errorf("target path %q is not a known content format", b.targetPath)
102 }
103
104 return b.buildFile()
105 }
106
107 filename, err := withBuildLock()
108 if err != nil {
109 return err
110 }
111
112 if filename != "" {
113 return b.openInEditorIfConfigured(filename)
114 }
115
116 return nil
117 }
118
119 type contentBuilder struct {
120 archeTypeFs afero.Fs
121 sourceFs afero.Fs
122
123 ps *helpers.PathSpec
124 h *hugolib.HugoSites
125 cf hugolib.ContentFactory
126
127 // Builder state
128 archetypeFi hugofs.FileMetaInfo
129 targetPath string
130 kind string
131 isDir bool
132 dirMap archetypeMap
133 force bool
134 }
135
136 func (b *contentBuilder) buildDir() error {
137 // Split the dir into content files and the rest.
138 if err := b.mapArcheTypeDir(); err != nil {
139 return err
140 }
141
142 var contentTargetFilenames []string
143 var baseDir string
144
145 for _, fi := range b.dirMap.contentFiles {
146
147 targetFilename := filepath.Join(b.targetPath, strings.TrimPrefix(fi.Meta().PathInfo.Path(), b.archetypeFi.Meta().PathInfo.Path()))
148
149 // ===> post/my-post/pages/bio.md
150 abs, err := b.cf.CreateContentPlaceHolder(targetFilename, b.force)
151 if err != nil {
152 return err
153 }
154 if baseDir == "" {
155 baseDir = strings.TrimSuffix(abs, targetFilename)
156 }
157
158 contentTargetFilenames = append(contentTargetFilenames, abs)
159 }
160
161 var contentInclusionFilter *hglob.FilenameFilter
162 if !b.dirMap.siteUsed {
163 // We don't need to build everything.
164 contentInclusionFilter = hglob.NewFilenameFilterForInclusionFunc(func(filename string) bool {
165 for _, cn := range contentTargetFilenames {
166 if strings.HasSuffix(cn, filename) {
167 return true
168 }
169 }
170 return false
171 })
172 }
173
174 if err := b.h.Build(hugolib.BuildCfg{NoBuildLock: true, SkipRender: true, ContentInclusionFilter: contentInclusionFilter}); err != nil {
175 return err
176 }
177
178 for i, filename := range contentTargetFilenames {
179 if err := b.applyArcheType(filename, b.dirMap.contentFiles[i]); err != nil {
180 return err
181 }
182 }
183
184 // Copy the rest as is.
185 for _, fi := range b.dirMap.otherFiles {
186 meta := fi.Meta()
187
188 in, err := meta.Open()
189 if err != nil {
190 return fmt.Errorf("failed to open non-content file: %w", err)
191 }
192 targetFilename := filepath.Join(baseDir, b.targetPath, strings.TrimPrefix(fi.Meta().Filename, b.archetypeFi.Meta().Filename))
193 targetDir := filepath.Dir(targetFilename)
194
195 if err := b.sourceFs.MkdirAll(targetDir, 0o777); err != nil && !os.IsExist(err) {
196 return fmt.Errorf("failed to create target directory for %q: %w", targetDir, err)
197 }
198
199 out, err := b.sourceFs.Create(targetFilename)
200 if err != nil {
201 return err
202 }
203
204 _, err = io.Copy(out, in)
205 if err != nil {
206 return err
207 }
208
209 in.Close()
210 out.Close()
211 }
212
213 b.h.Log.Printf("Content dir %q created", filepath.Join(baseDir, b.targetPath))
214
215 return nil
216 }
217
218 func (b *contentBuilder) buildFile() (string, error) {
219 contentPlaceholderAbsFilename, err := b.cf.CreateContentPlaceHolder(b.targetPath, b.force)
220 if err != nil {
221 if fi, serr := b.sourceFs.Stat(contentPlaceholderAbsFilename); serr == nil && !fi.IsDir() {
222 return "", errTargetConflict(contentPlaceholderAbsFilename)
223 }
224 return "", err
225 }
226
227 usesSite, err := b.usesSiteVar(b.archetypeFi)
228 if err != nil {
229 return "", err
230 }
231
232 var contentInclusionFilter *hglob.FilenameFilter
233 if !usesSite {
234 // We don't need to build everything.
235 contentInclusionFilter = hglob.NewFilenameFilterForInclusionFunc(func(filename string) bool {
236 return strings.HasSuffix(contentPlaceholderAbsFilename, filename)
237 })
238 }
239
240 // If a directory with the target's name (sans extension) exists, this file
241 // would produce a URL conflict with the existing section or leaf bundle.
242 targetDir := strings.TrimSuffix(contentPlaceholderAbsFilename, filepath.Ext(contentPlaceholderAbsFilename))
243 if fi, err := b.sourceFs.Stat(targetDir); err == nil && fi.IsDir() {
244 return "", errTargetConflict(contentPlaceholderAbsFilename)
245 }
246
247 if err := b.h.Build(hugolib.BuildCfg{NoBuildLock: true, SkipRender: true, ContentInclusionFilter: contentInclusionFilter}); err != nil {
248 return "", err
249 }
250
251 if err := b.applyArcheType(contentPlaceholderAbsFilename, b.archetypeFi); err != nil {
252 return "", err
253 }
254
255 b.h.Log.Printf("Content %q created", contentPlaceholderAbsFilename)
256
257 return contentPlaceholderAbsFilename, nil
258 }
259
260 func (b *contentBuilder) setArcheTypeFilenameToUse(ext string) {
261 var pathsToCheck []string
262
263 if b.kind != "" {
264 pathsToCheck = append(pathsToCheck, b.kind+ext)
265 }
266
267 pathsToCheck = append(pathsToCheck, "default"+ext)
268
269 for _, p := range pathsToCheck {
270 fi, err := b.archeTypeFs.Stat(p)
271 if err == nil {
272 b.archetypeFi = fi.(hugofs.FileMetaInfo)
273 b.isDir = fi.IsDir()
274 return
275 }
276 }
277 }
278
279 func errTargetConflict(path string) error {
280 return fmt.Errorf("no page found for %q; the target path conflicts with existing content", path)
281 }
282
283 func (b *contentBuilder) applyArcheType(contentFilename string, archetypeFi hugofs.FileMetaInfo) error {
284 p := b.h.GetContentPage(contentFilename)
285 if p == nil {
286 return errTargetConflict(contentFilename)
287 }
288
289 f, err := b.sourceFs.Create(contentFilename)
290 if err != nil {
291 return err
292 }
293 defer f.Close()
294
295 if archetypeFi == nil {
296 return b.cf.ApplyArchetypeTemplate(f, p, b.kind, DefaultArchetypeTemplateTemplate)
297 }
298
299 return b.cf.ApplyArchetypeFi(f, p, b.kind, archetypeFi)
300 }
301
302 func (b *contentBuilder) mapArcheTypeDir() error {
303 var m archetypeMap
304
305 walkFn := func(ctx context.Context, path string, fim hugofs.FileMetaInfo) error {
306 if fim.IsDir() {
307 return nil
308 }
309
310 pi := fim.Meta().PathInfo
311
312 if pi.IsContent() {
313 m.contentFiles = append(m.contentFiles, fim)
314 if !m.siteUsed {
315 var err error
316 m.siteUsed, err = b.usesSiteVar(fim)
317 if err != nil {
318 return err
319 }
320 }
321 return nil
322 }
323
324 m.otherFiles = append(m.otherFiles, fim)
325
326 return nil
327 }
328
329 walkCfg := hugofs.WalkwayConfig{
330 WalkFn: walkFn,
331 Fs: b.archeTypeFs,
332 Root: filepath.FromSlash(b.archetypeFi.Meta().PathInfo.Path()),
333 }
334
335 w := hugofs.NewWalkway(walkCfg)
336
337 if err := w.Walk(); err != nil {
338 return fmt.Errorf("failed to walk archetype dir %q: %w", b.archetypeFi.Meta().Filename, err)
339 }
340
341 b.dirMap = m
342
343 return nil
344 }
345
346 func (b *contentBuilder) openInEditorIfConfigured(filename string) error {
347 editor := b.h.Conf.NewContentEditor()
348 if editor == "" {
349 return nil
350 }
351
352 editorExec := strings.Fields(editor)[0]
353 editorFlags := strings.Fields(editor)[1:]
354
355 var args []any
356 for _, editorFlag := range editorFlags {
357 args = append(args, editorFlag)
358 }
359 args = append(
360 args,
361 filename,
362 hexec.WithStdin(os.Stdin),
363 hexec.WithStderr(os.Stderr),
364 hexec.WithStdout(os.Stdout),
365 )
366
367 b.h.Log.Printf("Editing %q with %q ...\n", filename, editorExec)
368
369 cmd, err := b.h.Deps.ExecHelper.New(editorExec, args...)
370 if err != nil {
371 return err
372 }
373
374 return cmd.Run()
375 }
376
377 func (b *contentBuilder) usesSiteVar(fi hugofs.FileMetaInfo) (bool, error) {
378 if fi == nil {
379 return false, nil
380 }
381 f, err := fi.Meta().Open()
382 if err != nil {
383 return false, err
384 }
385 defer f.Close()
386 bb, err := io.ReadAll(f)
387 if err != nil {
388 return false, fmt.Errorf("failed to read archetype file: %w", err)
389 }
390
391 return bytes.Contains(bb, []byte(".Site")) || bytes.Contains(bb, []byte("site.")), nil
392 }
393
394 type archetypeMap struct {
395 // These needs to be parsed and executed as Go templates.
396 contentFiles []hugofs.FileMetaInfo
397 // These are just copied to destination.
398 otherFiles []hugofs.FileMetaInfo
399 // If the templates needs a fully built site. This can potentially be
400 // expensive, so only do when needed.
401 siteUsed bool
402 }