| 1 |
// Copyright 2024 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 commands |
| 15 |
|
| 16 |
import ( |
| 17 |
"bytes" |
| 18 |
"context" |
| 19 |
"fmt" |
| 20 |
"path/filepath" |
| 21 |
"slices" |
| 22 |
"strings" |
| 23 |
"time" |
| 24 |
|
| 25 |
"github.com/bep/simplecobra" |
| 26 |
"github.com/gohugoio/hugo/common/hugio" |
| 27 |
"github.com/gohugoio/hugo/config" |
| 28 |
"github.com/gohugoio/hugo/helpers" |
| 29 |
"github.com/gohugoio/hugo/hugofs" |
| 30 |
"github.com/gohugoio/hugo/hugolib" |
| 31 |
"github.com/gohugoio/hugo/parser" |
| 32 |
"github.com/gohugoio/hugo/parser/metadecoders" |
| 33 |
"github.com/gohugoio/hugo/parser/pageparser" |
| 34 |
"github.com/gohugoio/hugo/resources/page" |
| 35 |
"github.com/spf13/cobra" |
| 36 |
) |
| 37 |
|
| 38 |
func newConvertCommand() *convertCommand { |
| 39 |
var c *convertCommand |
| 40 |
c = &convertCommand{ |
| 41 |
commands: []simplecobra.Commander{ |
| 42 |
&simpleCommand{ |
| 43 |
name: "toJSON", |
| 44 |
short: "Convert front matter to JSON", |
| 45 |
long: `toJSON converts all front matter in the content directory |
| 46 |
to use JSON for the front matter.`, |
| 47 |
run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error { |
| 48 |
return c.convertContents(metadecoders.JSON) |
| 49 |
}, |
| 50 |
withc: func(cmd *cobra.Command, r *rootCommand) { |
| 51 |
cmd.ValidArgsFunction = cobra.NoFileCompletions |
| 52 |
}, |
| 53 |
}, |
| 54 |
&simpleCommand{ |
| 55 |
name: "toTOML", |
| 56 |
short: "Convert front matter to TOML", |
| 57 |
long: `toTOML converts all front matter in the content directory |
| 58 |
to use TOML for the front matter.`, |
| 59 |
run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error { |
| 60 |
return c.convertContents(metadecoders.TOML) |
| 61 |
}, |
| 62 |
withc: func(cmd *cobra.Command, r *rootCommand) { |
| 63 |
cmd.ValidArgsFunction = cobra.NoFileCompletions |
| 64 |
}, |
| 65 |
}, |
| 66 |
&simpleCommand{ |
| 67 |
name: "toYAML", |
| 68 |
short: "Convert front matter to YAML", |
| 69 |
long: `toYAML converts all front matter in the content directory |
| 70 |
to use YAML for the front matter.`, |
| 71 |
run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error { |
| 72 |
return c.convertContents(metadecoders.YAML) |
| 73 |
}, |
| 74 |
withc: func(cmd *cobra.Command, r *rootCommand) { |
| 75 |
cmd.ValidArgsFunction = cobra.NoFileCompletions |
| 76 |
}, |
| 77 |
}, |
| 78 |
}, |
| 79 |
} |
| 80 |
return c |
| 81 |
} |
| 82 |
|
| 83 |
type convertCommand struct { |
| 84 |
// Flags. |
| 85 |
outputDir string |
| 86 |
unsafe bool |
| 87 |
|
| 88 |
// Deps. |
| 89 |
r *rootCommand |
| 90 |
h *hugolib.HugoSites |
| 91 |
|
| 92 |
// Commands. |
| 93 |
commands []simplecobra.Commander |
| 94 |
} |
| 95 |
|
| 96 |
func (c *convertCommand) Commands() []simplecobra.Commander { |
| 97 |
return c.commands |
| 98 |
} |
| 99 |
|
| 100 |
func (c *convertCommand) Name() string { |
| 101 |
return "convert" |
| 102 |
} |
| 103 |
|
| 104 |
func (c *convertCommand) Run(ctx context.Context, cd *simplecobra.Commandeer, args []string) error { |
| 105 |
return nil |
| 106 |
} |
| 107 |
|
| 108 |
func (c *convertCommand) Init(cd *simplecobra.Commandeer) error { |
| 109 |
cmd := cd.CobraCommand |
| 110 |
cmd.Short = "Convert front matter to another format" |
| 111 |
cmd.Long = `Convert front matter to another format. |
| 112 |
|
| 113 |
See convert's subcommands toJSON, toTOML and toYAML for more information.` |
| 114 |
|
| 115 |
cmd.PersistentFlags().StringVarP(&c.outputDir, "output", "o", "", "filesystem path to write files to") |
| 116 |
_ = cmd.MarkFlagDirname("output") |
| 117 |
cmd.PersistentFlags().BoolVar(&c.unsafe, "unsafe", false, "enable less safe operations, please backup first") |
| 118 |
|
| 119 |
cmd.RunE = nil |
| 120 |
return nil |
| 121 |
} |
| 122 |
|
| 123 |
func (c *convertCommand) PreRun(cd, runner *simplecobra.Commandeer) error { |
| 124 |
c.r = cd.Root.Command.(*rootCommand) |
| 125 |
cfg := config.New() |
| 126 |
cfg.Set("buildDrafts", true) |
| 127 |
h, err := c.r.Hugo(flagsToCfg(cd, cfg)) |
| 128 |
if err != nil { |
| 129 |
return err |
| 130 |
} |
| 131 |
c.h = h |
| 132 |
return nil |
| 133 |
} |
| 134 |
|
| 135 |
func (c *convertCommand) convertAndSavePage(p page.Page, site *hugolib.Site, targetFormat metadecoders.Format) error { |
| 136 |
// The resources are not in .Site.AllPages. |
| 137 |
for _, r := range p.Resources().ByType("page") { |
| 138 |
if err := c.convertAndSavePage(r.(page.Page), site, targetFormat); err != nil { |
| 139 |
return err |
| 140 |
} |
| 141 |
} |
| 142 |
|
| 143 |
if p.File() == nil { |
| 144 |
// No content file. |
| 145 |
return nil |
| 146 |
} |
| 147 |
|
| 148 |
errMsg := fmt.Errorf("error processing file %q", p.File().Path()) |
| 149 |
|
| 150 |
site.Log.Infoln("attempting to convert", p.File().Filename()) |
| 151 |
|
| 152 |
f := p.File() |
| 153 |
file, err := f.FileInfo().Meta().Open() |
| 154 |
if err != nil { |
| 155 |
site.Log.Errorln(errMsg) |
| 156 |
file.Close() |
| 157 |
return nil |
| 158 |
} |
| 159 |
|
| 160 |
pf, err := pageparser.ParseFrontMatterAndContent(file) |
| 161 |
if err != nil { |
| 162 |
site.Log.Errorln(errMsg) |
| 163 |
file.Close() |
| 164 |
return err |
| 165 |
} |
| 166 |
|
| 167 |
file.Close() |
| 168 |
|
| 169 |
// better handling of dates in formats that don't have support for them |
| 170 |
if pf.FrontMatterFormat == metadecoders.JSON || pf.FrontMatterFormat == metadecoders.YAML || pf.FrontMatterFormat == metadecoders.TOML { |
| 171 |
for k, v := range pf.FrontMatter { |
| 172 |
switch vv := v.(type) { |
| 173 |
case time.Time: |
| 174 |
pf.FrontMatter[k] = vv.Format(time.RFC3339) |
| 175 |
} |
| 176 |
} |
| 177 |
} |
| 178 |
|
| 179 |
var newContent bytes.Buffer |
| 180 |
err = parser.InterfaceToFrontMatter(pf.FrontMatter, targetFormat, &newContent) |
| 181 |
if err != nil { |
| 182 |
site.Log.Errorln(errMsg) |
| 183 |
return err |
| 184 |
} |
| 185 |
|
| 186 |
newContent.Write(pf.Content) |
| 187 |
|
| 188 |
newFilename := p.File().Filename() |
| 189 |
|
| 190 |
if c.outputDir != "" { |
| 191 |
contentDir := strings.TrimSuffix(newFilename, p.File().Path()) |
| 192 |
contentDir = filepath.Base(contentDir) |
| 193 |
|
| 194 |
newFilename = filepath.Join(c.outputDir, contentDir, p.File().Path()) |
| 195 |
} |
| 196 |
|
| 197 |
fs := hugofs.Os |
| 198 |
if err := helpers.WriteToDisk(newFilename, &newContent, fs); err != nil { |
| 199 |
return fmt.Errorf("failed to save file %q:: %w", newFilename, err) |
| 200 |
} |
| 201 |
|
| 202 |
return nil |
| 203 |
} |
| 204 |
|
| 205 |
func (c *convertCommand) copyContentDirsForOutput(pagesBackedByFile page.Pages) error { |
| 206 |
contentDirs := make(map[string]bool) |
| 207 |
for _, p := range pagesBackedByFile { |
| 208 |
filename := p.File().Filename() |
| 209 |
contentDir := strings.TrimSuffix(filename, p.File().Path()) |
| 210 |
if contentDir == filename { |
| 211 |
continue |
| 212 |
} |
| 213 |
contentDirs[filepath.Clean(contentDir)] = true |
| 214 |
} |
| 215 |
|
| 216 |
var contentDirList []string |
| 217 |
for contentDir := range contentDirs { |
| 218 |
contentDirList = append(contentDirList, contentDir) |
| 219 |
} |
| 220 |
slices.Sort(contentDirList) |
| 221 |
|
| 222 |
outputDirAbs, err := filepath.Abs(c.outputDir) |
| 223 |
if err != nil { |
| 224 |
return fmt.Errorf("failed to resolve output path %q: %w", c.outputDir, err) |
| 225 |
} |
| 226 |
|
| 227 |
for _, contentDir := range contentDirList { |
| 228 |
outputContentDirAbs := filepath.Join(outputDirAbs, filepath.Base(contentDir)) |
| 229 |
|
| 230 |
skipDirs := make(map[string]bool) |
| 231 |
relToOutputDir, err := filepath.Rel(contentDir, outputDirAbs) |
| 232 |
if err == nil && relToOutputDir != ".." && !strings.HasPrefix(relToOutputDir, ".."+string(filepath.Separator)) { |
| 233 |
skipDirs[filepath.Clean(outputDirAbs)] = true |
| 234 |
} |
| 235 |
relToOutputContentDir, err := filepath.Rel(contentDir, outputContentDirAbs) |
| 236 |
if err == nil && relToOutputContentDir != ".." && !strings.HasPrefix(relToOutputContentDir, ".."+string(filepath.Separator)) { |
| 237 |
skipDirs[filepath.Clean(outputContentDirAbs)] = true |
| 238 |
} |
| 239 |
|
| 240 |
var shouldCopy func(filename string) bool |
| 241 |
if len(skipDirs) > 0 { |
| 242 |
shouldCopy = func(filename string) bool { |
| 243 |
return !skipDirs[filepath.Clean(filename)] |
| 244 |
} |
| 245 |
} |
| 246 |
|
| 247 |
if err := hugio.CopyDir(hugofs.Os, contentDir, outputContentDirAbs, shouldCopy); err != nil { |
| 248 |
return fmt.Errorf("failed to copy %q to %q: %w", contentDir, outputContentDirAbs, err) |
| 249 |
} |
| 250 |
} |
| 251 |
|
| 252 |
return nil |
| 253 |
} |
| 254 |
|
| 255 |
func (c *convertCommand) convertContents(format metadecoders.Format) error { |
| 256 |
if c.outputDir == "" && !c.unsafe { |
| 257 |
return newUserError("Unsafe operation not allowed, use --unsafe or set a different output path") |
| 258 |
} |
| 259 |
|
| 260 |
if err := c.h.Build(hugolib.BuildCfg{SkipRender: true}); err != nil { |
| 261 |
return err |
| 262 |
} |
| 263 |
|
| 264 |
site := c.h.Sites[0] |
| 265 |
|
| 266 |
workingDir := c.h.Sites[0].Deps.Conf.WorkingDir() + string(filepath.Separator) |
| 267 |
|
| 268 |
isConvertible := func(p page.Page) bool { |
| 269 |
// Skip pages not backed by a content file. |
| 270 |
if p.File() == nil { |
| 271 |
return false |
| 272 |
} |
| 273 |
// Skip content adapters. |
| 274 |
if p.File().IsContentAdapter() { |
| 275 |
return false |
| 276 |
} |
| 277 |
// Skip content files provided by modules, including vendored modules. |
| 278 |
if !p.File().FileInfo().Meta().IsProject { |
| 279 |
return false |
| 280 |
} |
| 281 |
// Skip content files in project mounts outside the working directory. |
| 282 |
if !strings.HasPrefix(p.File().Filename(), workingDir) { |
| 283 |
return false |
| 284 |
} |
| 285 |
return true |
| 286 |
} |
| 287 |
|
| 288 |
seen := make(map[string]bool) |
| 289 |
var pagesBackedByFile page.Pages |
| 290 |
for _, p := range c.h.Pages() { |
| 291 |
if !isConvertible(p) { |
| 292 |
continue |
| 293 |
} |
| 294 |
filename := p.File().Filename() |
| 295 |
if seen[filename] { |
| 296 |
continue |
| 297 |
} |
| 298 |
seen[filename] = true |
| 299 |
pagesBackedByFile = append(pagesBackedByFile, p) |
| 300 |
} |
| 301 |
|
| 302 |
if c.outputDir != "" { |
| 303 |
if err := c.copyContentDirsForOutput(pagesBackedByFile); err != nil { |
| 304 |
return err |
| 305 |
} |
| 306 |
} |
| 307 |
|
| 308 |
site.Log.Println("processing", len(pagesBackedByFile), "content files") |
| 309 |
for _, p := range pagesBackedByFile { |
| 310 |
if err := c.convertAndSavePage(p, site, format); err != nil { |
| 311 |
return err |
| 312 |
} |
| 313 |
} |
| 314 |
return nil |
| 315 |
} |