| 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 |
"context" |
| 18 |
"errors" |
| 19 |
"fmt" |
| 20 |
"io" |
| 21 |
"log" |
| 22 |
"os" |
| 23 |
"os/signal" |
| 24 |
"path/filepath" |
| 25 |
"runtime" |
| 26 |
"strings" |
| 27 |
"sync" |
| 28 |
"sync/atomic" |
| 29 |
"syscall" |
| 30 |
"time" |
| 31 |
|
| 32 |
"go.uber.org/automaxprocs/maxprocs" |
| 33 |
|
| 34 |
"github.com/bep/clocks" |
| 35 |
"github.com/bep/lazycache" |
| 36 |
"github.com/bep/logg" |
| 37 |
"github.com/bep/overlayfs" |
| 38 |
"github.com/bep/simplecobra" |
| 39 |
|
| 40 |
"github.com/gohugoio/hugo/common/hstrings" |
| 41 |
"github.com/gohugoio/hugo/common/htime" |
| 42 |
"github.com/gohugoio/hugo/common/hugo" |
| 43 |
"github.com/gohugoio/hugo/common/loggers" |
| 44 |
"github.com/gohugoio/hugo/common/paths" |
| 45 |
"github.com/gohugoio/hugo/common/types" |
| 46 |
"github.com/gohugoio/hugo/config" |
| 47 |
"github.com/gohugoio/hugo/config/allconfig" |
| 48 |
"github.com/gohugoio/hugo/deps" |
| 49 |
"github.com/gohugoio/hugo/helpers" |
| 50 |
"github.com/gohugoio/hugo/hugofs" |
| 51 |
"github.com/gohugoio/hugo/hugolib" |
| 52 |
"github.com/gohugoio/hugo/identity" |
| 53 |
"github.com/gohugoio/hugo/resources/kinds" |
| 54 |
"github.com/spf13/afero" |
| 55 |
"github.com/spf13/cobra" |
| 56 |
) |
| 57 |
|
| 58 |
var errHelp = errors.New("help requested") |
| 59 |
|
| 60 |
// Execute executes a command. |
| 61 |
func Execute(args []string) error { |
| 62 |
// Default GOMAXPROCS to be CPU limit aware, still respecting GOMAXPROCS env. |
| 63 |
maxprocs.Set() |
| 64 |
x, err := newExec() |
| 65 |
if err != nil { |
| 66 |
return err |
| 67 |
} |
| 68 |
args = mapLegacyArgs(args) |
| 69 |
cd, err := x.Execute(context.Background(), args) |
| 70 |
if cd != nil { |
| 71 |
if closer, ok := cd.Root.Command.(types.Closer); ok { |
| 72 |
closer.Close() |
| 73 |
} |
| 74 |
} |
| 75 |
|
| 76 |
if err != nil { |
| 77 |
if err == errHelp { |
| 78 |
cd.CobraCommand.Help() |
| 79 |
fmt.Println() |
| 80 |
return nil |
| 81 |
} |
| 82 |
if simplecobra.IsCommandError(err) { |
| 83 |
// Print the help, but also return the error to fail the command. |
| 84 |
cd.CobraCommand.Help() |
| 85 |
fmt.Println() |
| 86 |
} |
| 87 |
} |
| 88 |
return err |
| 89 |
} |
| 90 |
|
| 91 |
type commonConfig struct { |
| 92 |
mu *sync.Mutex |
| 93 |
configs *allconfig.Configs |
| 94 |
cfg config.Provider |
| 95 |
fs *hugofs.Fs |
| 96 |
} |
| 97 |
|
| 98 |
type configKey struct { |
| 99 |
counter int32 |
| 100 |
ignoreModulesDoesNotExists bool |
| 101 |
skipNpmCheck bool |
| 102 |
} |
| 103 |
|
| 104 |
// This is the root command. |
| 105 |
type rootCommand struct { |
| 106 |
Printf func(format string, v ...any) |
| 107 |
Println func(a ...any) |
| 108 |
StdOut io.Writer |
| 109 |
StdErr io.Writer |
| 110 |
|
| 111 |
logger loggers.Logger |
| 112 |
|
| 113 |
// The main cache busting key for the caches below. |
| 114 |
configVersionID atomic.Int32 |
| 115 |
|
| 116 |
// Some, but not all commands need access to these. |
| 117 |
// Some needs more than one, so keep them in a small cache. |
| 118 |
commonConfigs *lazycache.Cache[configKey, *commonConfig] |
| 119 |
hugoSites *lazycache.Cache[configKey, *hugolib.HugoSites] |
| 120 |
|
| 121 |
// changesFromBuild received from Hugo in watch mode. |
| 122 |
changesFromBuild chan []identity.Identity |
| 123 |
|
| 124 |
commands []simplecobra.Commander |
| 125 |
|
| 126 |
// Flags |
| 127 |
source string |
| 128 |
buildWatch bool |
| 129 |
environment string |
| 130 |
|
| 131 |
// Common build flags. |
| 132 |
baseURL string |
| 133 |
gc bool |
| 134 |
poll string |
| 135 |
forceSyncStatic bool |
| 136 |
panicOnWarning bool |
| 137 |
|
| 138 |
// Profile flags (for debugging of performance problems) |
| 139 |
cpuprofile string |
| 140 |
memprofile string |
| 141 |
mutexprofile string |
| 142 |
traceprofile string |
| 143 |
printm bool |
| 144 |
|
| 145 |
logLevel string |
| 146 |
|
| 147 |
quiet bool |
| 148 |
devMode bool // Hidden flag. |
| 149 |
|
| 150 |
renderToMemory bool |
| 151 |
|
| 152 |
cfgFile string |
| 153 |
cfgDir string |
| 154 |
} |
| 155 |
|
| 156 |
// resolveEnvironment sets r.environment if not already set. |
| 157 |
// server indicates whether the server command is running (defaults to development). |
| 158 |
func (r *rootCommand) resolveEnvironment(server bool) { |
| 159 |
if r.environment != "" { |
| 160 |
return |
| 161 |
} |
| 162 |
if env := os.Getenv("HUGO_ENVIRONMENT"); env != "" { |
| 163 |
r.environment = env |
| 164 |
} else if env := os.Getenv("HUGO_ENV"); env != "" { |
| 165 |
r.environment = env |
| 166 |
} else if server { |
| 167 |
r.environment = hugo.EnvironmentDevelopment |
| 168 |
} else { |
| 169 |
r.environment = hugo.EnvironmentProduction |
| 170 |
} |
| 171 |
} |
| 172 |
|
| 173 |
func (r *rootCommand) isVerbose() bool { |
| 174 |
return r.logger.Level() <= logg.LevelInfo |
| 175 |
} |
| 176 |
|
| 177 |
func (r *rootCommand) Close() error { |
| 178 |
if r.hugoSites != nil { |
| 179 |
r.hugoSites.DeleteFunc(func(key configKey, value *hugolib.HugoSites) bool { |
| 180 |
if value != nil { |
| 181 |
value.Close() |
| 182 |
} |
| 183 |
return false |
| 184 |
}) |
| 185 |
} |
| 186 |
return nil |
| 187 |
} |
| 188 |
|
| 189 |
func (r *rootCommand) Build(cd *simplecobra.Commandeer, bcfg hugolib.BuildCfg, cfg config.Provider) (*hugolib.HugoSites, error) { |
| 190 |
h, err := r.Hugo(cfg) |
| 191 |
if err != nil { |
| 192 |
return nil, err |
| 193 |
} |
| 194 |
if err := h.Build(bcfg); err != nil { |
| 195 |
return nil, err |
| 196 |
} |
| 197 |
|
| 198 |
return h, nil |
| 199 |
} |
| 200 |
|
| 201 |
func (r *rootCommand) Commands() []simplecobra.Commander { |
| 202 |
return r.commands |
| 203 |
} |
| 204 |
|
| 205 |
func (r *rootCommand) ConfigFromConfig(key configKey, oldConf *commonConfig) (*commonConfig, error) { |
| 206 |
cc, _, err := r.commonConfigs.GetOrCreate(key, func(key configKey) (*commonConfig, error) { |
| 207 |
fs := oldConf.fs |
| 208 |
configs, err := allconfig.LoadConfig( |
| 209 |
allconfig.ConfigSourceDescriptor{ |
| 210 |
Flags: oldConf.cfg, |
| 211 |
Fs: fs.Source, |
| 212 |
Filename: r.cfgFile, |
| 213 |
ConfigDir: r.cfgDir, |
| 214 |
Logger: r.logger, |
| 215 |
Environment: r.environment, |
| 216 |
IgnoreModuleDoesNotExist: key.ignoreModulesDoesNotExists, |
| 217 |
SkipNpmCheck: key.skipNpmCheck, |
| 218 |
}, |
| 219 |
) |
| 220 |
if err != nil { |
| 221 |
return nil, err |
| 222 |
} |
| 223 |
|
| 224 |
if !configs.Base.C.Clock.IsZero() { |
| 225 |
// TODO(bep) find a better place for this. |
| 226 |
htime.Clock = clocks.Start(configs.Base.C.Clock) |
| 227 |
} |
| 228 |
|
| 229 |
return &commonConfig{ |
| 230 |
mu: oldConf.mu, |
| 231 |
configs: configs, |
| 232 |
cfg: oldConf.cfg, |
| 233 |
fs: fs, |
| 234 |
}, nil |
| 235 |
}) |
| 236 |
|
| 237 |
return cc, err |
| 238 |
} |
| 239 |
|
| 240 |
func (r *rootCommand) ConfigFromProvider(key configKey, cfg config.Provider) (*commonConfig, error) { |
| 241 |
if cfg == nil { |
| 242 |
panic("cfg must be set") |
| 243 |
} |
| 244 |
r.resolveEnvironment(false) |
| 245 |
cc, _, err := r.commonConfigs.GetOrCreate(key, func(key configKey) (*commonConfig, error) { |
| 246 |
var dir string |
| 247 |
if r.source != "" { |
| 248 |
dir, _ = filepath.Abs(r.source) |
| 249 |
} else { |
| 250 |
dir, _ = os.Getwd() |
| 251 |
} |
| 252 |
|
| 253 |
if cfg == nil { |
| 254 |
cfg = config.New() |
| 255 |
} |
| 256 |
|
| 257 |
if !cfg.IsSet("workingDir") { |
| 258 |
cfg.Set("workingDir", dir) |
| 259 |
} else { |
| 260 |
if err := os.MkdirAll(cfg.GetString("workingDir"), 0o777); err != nil { |
| 261 |
return nil, fmt.Errorf("failed to create workingDir: %w", err) |
| 262 |
} |
| 263 |
} |
| 264 |
|
| 265 |
// Load the config first to allow publishDir to be configured in config file. |
| 266 |
configs, err := allconfig.LoadConfig( |
| 267 |
allconfig.ConfigSourceDescriptor{ |
| 268 |
Flags: cfg, |
| 269 |
Fs: hugofs.Os, |
| 270 |
Filename: r.cfgFile, |
| 271 |
ConfigDir: r.cfgDir, |
| 272 |
Environment: r.environment, |
| 273 |
Logger: r.logger, |
| 274 |
IgnoreModuleDoesNotExist: key.ignoreModulesDoesNotExists, |
| 275 |
SkipNpmCheck: key.skipNpmCheck, |
| 276 |
}, |
| 277 |
) |
| 278 |
if err != nil { |
| 279 |
return nil, err |
| 280 |
} |
| 281 |
|
| 282 |
base := configs.Base |
| 283 |
|
| 284 |
cfg.Set("publishDir", base.PublishDir) |
| 285 |
cfg.Set("publishDirStatic", base.PublishDir) |
| 286 |
cfg.Set("publishDirDynamic", base.PublishDir) |
| 287 |
|
| 288 |
renderStaticToDisk := cfg.GetBool("renderStaticToDisk") |
| 289 |
|
| 290 |
sourceFs := hugofs.Os |
| 291 |
var destinationFs afero.Fs |
| 292 |
if cfg.GetBool("renderToMemory") { |
| 293 |
destinationFs = afero.NewMemMapFs() |
| 294 |
if renderStaticToDisk { |
| 295 |
// Hybrid, render dynamic content to Root. |
| 296 |
cfg.Set("publishDirDynamic", "/") |
| 297 |
} else { |
| 298 |
// Rendering to memoryFS, publish to Root regardless of publishDir. |
| 299 |
cfg.Set("publishDirDynamic", "/") |
| 300 |
cfg.Set("publishDirStatic", "/") |
| 301 |
} |
| 302 |
} else { |
| 303 |
destinationFs = hugofs.Os |
| 304 |
} |
| 305 |
|
| 306 |
fs := hugofs.NewFromSourceAndDestination(sourceFs, destinationFs, cfg) |
| 307 |
|
| 308 |
if renderStaticToDisk { |
| 309 |
dynamicFs := fs.PublishDir |
| 310 |
publishDirStatic := cfg.GetString("publishDirStatic") |
| 311 |
workingDir := cfg.GetString("workingDir") |
| 312 |
absPublishDirStatic := paths.AbsPathify(workingDir, publishDirStatic) |
| 313 |
staticFs := hugofs.NewBasePathFs(afero.NewOsFs(), absPublishDirStatic) |
| 314 |
|
| 315 |
// Serve from both the static and dynamic fs, |
| 316 |
// the first will take priority. |
| 317 |
// THis is a read-only filesystem, |
| 318 |
// we do all the writes to |
| 319 |
// fs.Destination and fs.DestinationStatic. |
| 320 |
fs.PublishDirServer = overlayfs.New( |
| 321 |
overlayfs.Options{ |
| 322 |
Fss: []afero.Fs{ |
| 323 |
dynamicFs, |
| 324 |
staticFs, |
| 325 |
}, |
| 326 |
}, |
| 327 |
) |
| 328 |
fs.PublishDirStatic = staticFs |
| 329 |
|
| 330 |
} |
| 331 |
|
| 332 |
if !base.C.Clock.IsZero() { |
| 333 |
// TODO(bep) find a better place for this. |
| 334 |
htime.Clock = clocks.Start(configs.Base.C.Clock) |
| 335 |
} |
| 336 |
|
| 337 |
if base.PrintPathWarnings { |
| 338 |
// Note that we only care about the "dynamic creates" here, |
| 339 |
// so skip the static fs. |
| 340 |
fs.PublishDir = hugofs.NewCreateCountingFs(fs.PublishDir) |
| 341 |
} |
| 342 |
|
| 343 |
commonConfig := &commonConfig{ |
| 344 |
mu: &sync.Mutex{}, |
| 345 |
configs: configs, |
| 346 |
cfg: cfg, |
| 347 |
fs: fs, |
| 348 |
} |
| 349 |
|
| 350 |
return commonConfig, nil |
| 351 |
}) |
| 352 |
|
| 353 |
return cc, err |
| 354 |
} |
| 355 |
|
| 356 |
func (r *rootCommand) HugFromConfig(conf *commonConfig) (*hugolib.HugoSites, error) { |
| 357 |
if conf == nil { |
| 358 |
return nil, fmt.Errorf("conf must be set") |
| 359 |
} |
| 360 |
k := configKey{counter: r.configVersionID.Load()} |
| 361 |
h, _, err := r.hugoSites.GetOrCreate(k, func(key configKey) (*hugolib.HugoSites, error) { |
| 362 |
depsCfg := r.newDepsConfig(conf) |
| 363 |
return hugolib.NewHugoSites(depsCfg) |
| 364 |
}) |
| 365 |
return h, err |
| 366 |
} |
| 367 |
|
| 368 |
func (r *rootCommand) Hugo(cfg config.Provider) (*hugolib.HugoSites, error) { |
| 369 |
return r.getOrCreateHugo(cfg, false) |
| 370 |
} |
| 371 |
|
| 372 |
func (r *rootCommand) getOrCreateHugo(cfg config.Provider, ignoreModuleDoesNotExist bool) (*hugolib.HugoSites, error) { |
| 373 |
k := configKey{counter: r.configVersionID.Load(), ignoreModulesDoesNotExists: ignoreModuleDoesNotExist} |
| 374 |
h, _, err := r.hugoSites.GetOrCreate(k, func(key configKey) (*hugolib.HugoSites, error) { |
| 375 |
conf, err := r.ConfigFromProvider(key, cfg) |
| 376 |
if err != nil { |
| 377 |
return nil, err |
| 378 |
} |
| 379 |
depsCfg := r.newDepsConfig(conf) |
| 380 |
return hugolib.NewHugoSites(depsCfg) |
| 381 |
}) |
| 382 |
return h, err |
| 383 |
} |
| 384 |
|
| 385 |
func (r *rootCommand) newDepsConfig(conf *commonConfig) deps.DepsCfg { |
| 386 |
return deps.DepsCfg{Configs: conf.configs, Fs: conf.fs, StdOut: r.logger.StdOut(), StdErr: r.logger.StdErr(), LogLevel: r.logger.Level(), ChangesFromBuild: r.changesFromBuild} |
| 387 |
} |
| 388 |
|
| 389 |
func (r *rootCommand) Name() string { |
| 390 |
return "hugo" |
| 391 |
} |
| 392 |
|
| 393 |
func (r *rootCommand) Run(ctx context.Context, cd *simplecobra.Commandeer, args []string) error { |
| 394 |
b := newHugoBuilder(r, nil) |
| 395 |
|
| 396 |
if !r.buildWatch { |
| 397 |
defer b.postBuild("Total", time.Now()) |
| 398 |
} |
| 399 |
|
| 400 |
if err := b.loadConfig(cd, false); err != nil { |
| 401 |
return err |
| 402 |
} |
| 403 |
|
| 404 |
err := func() error { |
| 405 |
if r.buildWatch { |
| 406 |
defer r.timeTrack(time.Now(), "Built") |
| 407 |
} |
| 408 |
err := b.build() |
| 409 |
if err != nil { |
| 410 |
return err |
| 411 |
} |
| 412 |
return nil |
| 413 |
}() |
| 414 |
if err != nil { |
| 415 |
return err |
| 416 |
} |
| 417 |
|
| 418 |
if !r.buildWatch { |
| 419 |
// Done. |
| 420 |
return nil |
| 421 |
} |
| 422 |
|
| 423 |
watchDirs, err := b.getDirList() |
| 424 |
if err != nil { |
| 425 |
return err |
| 426 |
} |
| 427 |
|
| 428 |
watchGroups := helpers.ExtractAndGroupRootPaths(watchDirs) |
| 429 |
|
| 430 |
r.Printf("Watching for changes in %s\n", strings.Join(watchGroups, ", ")) |
| 431 |
watcher, err := b.newWatcher(r.poll, watchDirs...) |
| 432 |
if err != nil { |
| 433 |
return err |
| 434 |
} |
| 435 |
|
| 436 |
defer watcher.Close() |
| 437 |
|
| 438 |
r.Println("Press Ctrl+C to stop") |
| 439 |
|
| 440 |
sigs := make(chan os.Signal, 1) |
| 441 |
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM) |
| 442 |
|
| 443 |
<-sigs |
| 444 |
|
| 445 |
return nil |
| 446 |
} |
| 447 |
|
| 448 |
func (r *rootCommand) PreRun(cd, runner *simplecobra.Commandeer) error { |
| 449 |
r.StdOut = os.Stdout |
| 450 |
r.StdErr = os.Stderr |
| 451 |
if r.quiet { |
| 452 |
r.StdOut = io.Discard |
| 453 |
r.StdErr = io.Discard |
| 454 |
} |
| 455 |
// Used by mkcert (server). |
| 456 |
log.SetOutput(r.StdOut) |
| 457 |
|
| 458 |
r.Printf = func(format string, v ...any) { |
| 459 |
if !r.quiet { |
| 460 |
fmt.Fprintf(r.StdOut, format, v...) |
| 461 |
} |
| 462 |
} |
| 463 |
r.Println = func(a ...any) { |
| 464 |
if !r.quiet { |
| 465 |
fmt.Fprintln(r.StdOut, a...) |
| 466 |
} |
| 467 |
} |
| 468 |
_, running := runner.Command.(*serverCommand) |
| 469 |
var err error |
| 470 |
r.logger, err = r.createLogger(running) |
| 471 |
if err != nil { |
| 472 |
return err |
| 473 |
} |
| 474 |
// Set up the global logger early to allow info deprecations during config load. |
| 475 |
loggers.SetGlobalLogger(r.logger) |
| 476 |
|
| 477 |
r.changesFromBuild = make(chan []identity.Identity, 10) |
| 478 |
|
| 479 |
r.commonConfigs = lazycache.New(lazycache.Options[configKey, *commonConfig]{MaxEntries: 5}) |
| 480 |
// We don't want to keep stale HugoSites in memory longer than needed. |
| 481 |
r.hugoSites = lazycache.New(lazycache.Options[configKey, *hugolib.HugoSites]{ |
| 482 |
MaxEntries: 1, |
| 483 |
OnEvict: func(key configKey, value *hugolib.HugoSites) { |
| 484 |
value.Close() |
| 485 |
runtime.GC() |
| 486 |
}, |
| 487 |
}) |
| 488 |
|
| 489 |
return nil |
| 490 |
} |
| 491 |
|
| 492 |
func (r *rootCommand) createLogger(running bool) (loggers.Logger, error) { |
| 493 |
level := logg.LevelWarn |
| 494 |
|
| 495 |
if r.devMode { |
| 496 |
level = logg.LevelTrace |
| 497 |
} else { |
| 498 |
if r.logLevel != "" { |
| 499 |
switch strings.ToLower(r.logLevel) { |
| 500 |
case "debug": |
| 501 |
level = logg.LevelDebug |
| 502 |
case "info": |
| 503 |
level = logg.LevelInfo |
| 504 |
case "warn", "warning": |
| 505 |
level = logg.LevelWarn |
| 506 |
case "error": |
| 507 |
level = logg.LevelError |
| 508 |
default: |
| 509 |
return nil, fmt.Errorf("invalid log level: %q, must be one of debug, warn, info or error", r.logLevel) |
| 510 |
} |
| 511 |
} |
| 512 |
} |
| 513 |
|
| 514 |
var logHookLast func(e *logg.Entry) error |
| 515 |
if r.panicOnWarning { |
| 516 |
logHookLast = loggers.PanicOnWarningHook |
| 517 |
} |
| 518 |
|
| 519 |
optsLogger := loggers.Options{ |
| 520 |
DistinctLevel: logg.LevelWarn, |
| 521 |
Level: level, |
| 522 |
StdOut: r.StdOut, |
| 523 |
StdErr: r.StdErr, |
| 524 |
StoreErrors: running, |
| 525 |
HandlerPost: logHookLast, |
| 526 |
} |
| 527 |
|
| 528 |
return loggers.New(optsLogger), nil |
| 529 |
} |
| 530 |
|
| 531 |
func (r *rootCommand) resetLogs() { |
| 532 |
r.logger.Reset() |
| 533 |
loggers.Log().Reset() |
| 534 |
} |
| 535 |
|
| 536 |
// IsTestRun reports whether the command is running as a test. |
| 537 |
func (r *rootCommand) IsTestRun() bool { |
| 538 |
return os.Getenv("HUGO_TESTRUN") != "" |
| 539 |
} |
| 540 |
|
| 541 |
func (r *rootCommand) Init(cd *simplecobra.Commandeer) error { |
| 542 |
return r.initRootCommand("", cd) |
| 543 |
} |
| 544 |
|
| 545 |
func (r *rootCommand) initRootCommand(subCommandName string, cd *simplecobra.Commandeer) error { |
| 546 |
cmd := cd.CobraCommand |
| 547 |
commandName := "hugo" |
| 548 |
if subCommandName != "" { |
| 549 |
commandName = subCommandName |
| 550 |
} |
| 551 |
cmd.Use = fmt.Sprintf("%s [flags]", commandName) |
| 552 |
cmd.Short = "Build your project" |
| 553 |
cmd.Long = `COMMAND_NAME is the main command, used to build your Hugo project. |
| 554 |
|
| 555 |
Hugo is a Fast and Flexible Static Site Generator |
| 556 |
built with love by spf13 and friends in Go. |
| 557 |
|
| 558 |
Complete documentation is available at https://gohugo.io/.` |
| 559 |
|
| 560 |
cmd.Long = strings.ReplaceAll(cmd.Long, "COMMAND_NAME", commandName) |
| 561 |
|
| 562 |
// Configure persistent flags |
| 563 |
cmd.PersistentFlags().StringVarP(&r.source, "source", "s", "", "filesystem path to read files relative from") |
| 564 |
_ = cmd.MarkFlagDirname("source") |
| 565 |
cmd.PersistentFlags().StringP("destination", "d", "", "filesystem path to write files to") |
| 566 |
_ = cmd.MarkFlagDirname("destination") |
| 567 |
|
| 568 |
cmd.PersistentFlags().StringVarP(&r.environment, "environment", "e", "", "build environment") |
| 569 |
_ = cmd.RegisterFlagCompletionFunc("environment", cobra.NoFileCompletions) |
| 570 |
cmd.PersistentFlags().StringP("themesDir", "", "", "filesystem path to themes directory") |
| 571 |
_ = cmd.MarkFlagDirname("themesDir") |
| 572 |
cmd.PersistentFlags().StringP("ignoreVendorPaths", "", "", "ignores any _vendor for module paths matching the given Glob pattern") |
| 573 |
cmd.PersistentFlags().BoolP("noBuildLock", "", false, "don't create .hugo_build.lock file") |
| 574 |
_ = cmd.RegisterFlagCompletionFunc("ignoreVendorPaths", cobra.NoFileCompletions) |
| 575 |
cmd.PersistentFlags().String("clock", "", "set the clock used by Hugo, e.g. --clock 2021-11-06T22:30:00.00+09:00") |
| 576 |
_ = cmd.RegisterFlagCompletionFunc("clock", cobra.NoFileCompletions) |
| 577 |
|
| 578 |
cmd.PersistentFlags().StringVar(&r.cfgFile, "config", "", "config file (default is hugo.yaml|json|toml)") |
| 579 |
_ = cmd.MarkFlagFilename("config", config.ValidConfigFileExtensions...) |
| 580 |
cmd.PersistentFlags().StringVar(&r.cfgDir, "configDir", "config", "config dir") |
| 581 |
_ = cmd.MarkFlagDirname("configDir") |
| 582 |
cmd.PersistentFlags().BoolVar(&r.quiet, "quiet", false, "build in quiet mode") |
| 583 |
cmd.PersistentFlags().BoolVarP(&r.renderToMemory, "renderToMemory", "M", false, "render to memory (mostly useful when running the server)") |
| 584 |
|
| 585 |
cmd.PersistentFlags().BoolVarP(&r.devMode, "devMode", "", false, "only used for internal testing, flag hidden.") |
| 586 |
cmd.PersistentFlags().StringVar(&r.logLevel, "logLevel", "", "log level (debug|info|warn|error)") |
| 587 |
_ = cmd.RegisterFlagCompletionFunc("logLevel", cobra.FixedCompletions([]string{"debug", "info", "warn", "error"}, cobra.ShellCompDirectiveNoFileComp)) |
| 588 |
cmd.Flags().BoolVarP(&r.buildWatch, "watch", "w", false, "watch filesystem for changes and recreate as needed") |
| 589 |
|
| 590 |
cmd.PersistentFlags().MarkHidden("devMode") |
| 591 |
|
| 592 |
// Configure local flags |
| 593 |
applyLocalFlagsBuild(cmd, r) |
| 594 |
|
| 595 |
return nil |
| 596 |
} |
| 597 |
|
| 598 |
// A sub set of the complete build flags. These flags are used by new and mod. |
| 599 |
func applyLocalFlagsBuildConfig(cmd *cobra.Command, r *rootCommand) { |
| 600 |
cmd.Flags().StringSliceP("theme", "t", []string{}, "themes to use (located in /themes/THEMENAME/)") |
| 601 |
_ = cmd.MarkFlagDirname("theme") |
| 602 |
cmd.Flags().StringVarP(&r.baseURL, "baseURL", "b", "", "hostname (and path) to the root, e.g. https://spf13.com/") |
| 603 |
cmd.Flags().StringP("cacheDir", "", "", "filesystem path to cache directory") |
| 604 |
_ = cmd.MarkFlagDirname("cacheDir") |
| 605 |
cmd.Flags().StringP("contentDir", "c", "", "filesystem path to content directory") |
| 606 |
cmd.Flags().StringSliceP("renderSegments", "", []string{}, "named segments to render (configured in the segments config)") |
| 607 |
} |
| 608 |
|
| 609 |
// Flags needed to do a build (used by hugo and hugo server commands) |
| 610 |
func applyLocalFlagsBuild(cmd *cobra.Command, r *rootCommand) { |
| 611 |
applyLocalFlagsBuildConfig(cmd, r) |
| 612 |
cmd.Flags().Bool("cleanDestinationDir", false, "remove files from destination not found in static directories") |
| 613 |
cmd.Flags().BoolP("buildDrafts", "D", false, "include content marked as draft") |
| 614 |
cmd.Flags().BoolP("buildFuture", "F", false, "include content with publishdate in the future") |
| 615 |
cmd.Flags().BoolP("buildExpired", "E", false, "include expired content") |
| 616 |
cmd.Flags().BoolP("ignoreCache", "", false, "ignore the configured file caches") |
| 617 |
cmd.Flags().Bool("enableGitInfo", false, "add Git revision, date, author, and CODEOWNERS info to the pages") |
| 618 |
cmd.Flags().StringP("layoutDir", "l", "", "filesystem path to layout directory") |
| 619 |
_ = cmd.MarkFlagDirname("layoutDir") |
| 620 |
cmd.Flags().BoolVar(&r.gc, "gc", false, "enable to run some cleanup tasks (remove unused cache files) after the build") |
| 621 |
cmd.Flags().StringVar(&r.poll, "poll", "", "set this to a poll interval, e.g --poll 700ms, to use a poll based approach to watch for file system changes") |
| 622 |
_ = cmd.RegisterFlagCompletionFunc("poll", cobra.NoFileCompletions) |
| 623 |
cmd.Flags().BoolVar(&r.panicOnWarning, "panicOnWarning", false, "panic on first WARNING log") |
| 624 |
cmd.Flags().Bool("templateMetrics", false, "display metrics about template executions") |
| 625 |
cmd.Flags().Bool("templateMetricsHints", false, "calculate some improvement hints when combined with --templateMetrics") |
| 626 |
cmd.Flags().BoolVar(&r.forceSyncStatic, "forceSyncStatic", false, "copy all files when static is changed.") |
| 627 |
cmd.Flags().BoolP("noTimes", "", false, "don't sync modification time of files") |
| 628 |
cmd.Flags().BoolP("noChmod", "", false, "don't sync permission mode of files") |
| 629 |
cmd.Flags().BoolP("printI18nWarnings", "", false, "print missing translations") |
| 630 |
cmd.Flags().BoolP("printPathWarnings", "", false, "print warnings on duplicate target paths etc.") |
| 631 |
cmd.Flags().BoolP("printUnusedTemplates", "", false, "print warnings on unused templates.") |
| 632 |
cmd.Flags().StringVarP(&r.cpuprofile, "profile-cpu", "", "", "write cpu profile to `file`") |
| 633 |
cmd.Flags().StringVarP(&r.memprofile, "profile-mem", "", "", "write memory profile to `file`") |
| 634 |
cmd.Flags().BoolVarP(&r.printm, "printMemoryUsage", "", false, "print memory usage to screen at intervals") |
| 635 |
cmd.Flags().StringVarP(&r.mutexprofile, "profile-mutex", "", "", "write Mutex profile to `file`") |
| 636 |
cmd.Flags().StringVarP(&r.traceprofile, "trace", "", "", "write trace to `file` (not useful in general)") |
| 637 |
|
| 638 |
// Hide these for now. |
| 639 |
cmd.Flags().MarkHidden("profile-cpu") |
| 640 |
cmd.Flags().MarkHidden("profile-mem") |
| 641 |
cmd.Flags().MarkHidden("profile-mutex") |
| 642 |
|
| 643 |
cmd.Flags().StringSlice("disableKinds", []string{}, "disable different kind of pages (home, RSS etc.)") |
| 644 |
_ = cmd.RegisterFlagCompletionFunc("disableKinds", cobra.FixedCompletions(kinds.AllKinds, cobra.ShellCompDirectiveNoFileComp)) |
| 645 |
cmd.Flags().Bool("minify", false, "minify any supported output format (HTML, XML etc.)") |
| 646 |
} |
| 647 |
|
| 648 |
func (r *rootCommand) timeTrack(start time.Time, name string) { |
| 649 |
elapsed := time.Since(start) |
| 650 |
r.Printf("%s in %v ms\n", name, int(1000*elapsed.Seconds())) |
| 651 |
} |
| 652 |
|
| 653 |
type simpleCommand struct { |
| 654 |
use string |
| 655 |
name string |
| 656 |
short string |
| 657 |
long string |
| 658 |
aliases []string |
| 659 |
run func(ctx context.Context, cd *simplecobra.Commandeer, rootCmd *rootCommand, args []string) error |
| 660 |
withc func(cmd *cobra.Command, r *rootCommand) |
| 661 |
initc func(cd *simplecobra.Commandeer) error |
| 662 |
|
| 663 |
commands []simplecobra.Commander |
| 664 |
|
| 665 |
rootCmd *rootCommand |
| 666 |
} |
| 667 |
|
| 668 |
func (c *simpleCommand) Commands() []simplecobra.Commander { |
| 669 |
return c.commands |
| 670 |
} |
| 671 |
|
| 672 |
func (c *simpleCommand) Name() string { |
| 673 |
return c.name |
| 674 |
} |
| 675 |
|
| 676 |
func (c *simpleCommand) Run(ctx context.Context, cd *simplecobra.Commandeer, args []string) error { |
| 677 |
if c.run == nil { |
| 678 |
return nil |
| 679 |
} |
| 680 |
return c.run(ctx, cd, c.rootCmd, args) |
| 681 |
} |
| 682 |
|
| 683 |
func (c *simpleCommand) Init(cd *simplecobra.Commandeer) error { |
| 684 |
c.rootCmd = cd.Root.Command.(*rootCommand) |
| 685 |
cmd := cd.CobraCommand |
| 686 |
cmd.Short = c.short |
| 687 |
cmd.Long = c.long |
| 688 |
cmd.Aliases = c.aliases |
| 689 |
if c.use != "" { |
| 690 |
cmd.Use = c.use |
| 691 |
} |
| 692 |
if c.withc != nil { |
| 693 |
c.withc(cmd, c.rootCmd) |
| 694 |
} |
| 695 |
return nil |
| 696 |
} |
| 697 |
|
| 698 |
func (c *simpleCommand) PreRun(cd, runner *simplecobra.Commandeer) error { |
| 699 |
if c.initc != nil { |
| 700 |
return c.initc(cd) |
| 701 |
} |
| 702 |
return nil |
| 703 |
} |
| 704 |
|
| 705 |
func mapLegacyArgs(args []string) []string { |
| 706 |
if len(args) > 1 && args[0] == "new" && !hstrings.EqualAny(args[1], "project", "site", "theme", "content") { |
| 707 |
// Insert "content" as the second argument |
| 708 |
args = append(args[:1], append([]string{"content"}, args[1:]...)...) |
| 709 |
} |
| 710 |
return args |
| 711 |
} |