| 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 |
"os" |
| 21 |
"path/filepath" |
| 22 |
"runtime" |
| 23 |
"runtime/pprof" |
| 24 |
"runtime/trace" |
| 25 |
"strings" |
| 26 |
"sync" |
| 27 |
"sync/atomic" |
| 28 |
"time" |
| 29 |
|
| 30 |
"github.com/bep/debounce" |
| 31 |
"github.com/bep/simplecobra" |
| 32 |
"github.com/fsnotify/fsnotify" |
| 33 |
"github.com/gohugoio/hugo/common/herrors" |
| 34 |
"github.com/gohugoio/hugo/common/hmaps" |
| 35 |
"github.com/gohugoio/hugo/common/hstrings" |
| 36 |
"github.com/gohugoio/hugo/common/htime" |
| 37 |
"github.com/gohugoio/hugo/common/hugo" |
| 38 |
"github.com/gohugoio/hugo/common/loggers" |
| 39 |
"github.com/gohugoio/hugo/common/paths" |
| 40 |
"github.com/gohugoio/hugo/common/terminal" |
| 41 |
"github.com/gohugoio/hugo/common/types" |
| 42 |
"github.com/gohugoio/hugo/config" |
| 43 |
"github.com/gohugoio/hugo/helpers" |
| 44 |
"github.com/gohugoio/hugo/hugofs" |
| 45 |
"github.com/gohugoio/hugo/hugolib" |
| 46 |
"github.com/gohugoio/hugo/hugolib/filesystems" |
| 47 |
"github.com/gohugoio/hugo/identity" |
| 48 |
"github.com/gohugoio/hugo/livereload" |
| 49 |
"github.com/gohugoio/hugo/resources/page" |
| 50 |
"github.com/gohugoio/hugo/watcher" |
| 51 |
"github.com/spf13/afero" |
| 52 |
"github.com/spf13/fsync" |
| 53 |
"golang.org/x/sync/errgroup" |
| 54 |
"golang.org/x/sync/semaphore" |
| 55 |
) |
| 56 |
|
| 57 |
type hugoBuilder struct { |
| 58 |
r *rootCommand |
| 59 |
|
| 60 |
confmu sync.Mutex |
| 61 |
confOld *commonConfig |
| 62 |
conf *commonConfig |
| 63 |
|
| 64 |
// May be nil. |
| 65 |
s *serverCommand |
| 66 |
|
| 67 |
// Currently only set when in "fast render mode". |
| 68 |
changeDetector *fileChangeDetector |
| 69 |
visitedURLs *types.EvictingQueue[string] |
| 70 |
|
| 71 |
fullRebuildSem *semaphore.Weighted |
| 72 |
debounce func(f func()) |
| 73 |
|
| 74 |
onConfigLoaded func(reloaded bool) error |
| 75 |
|
| 76 |
fastRenderMode bool |
| 77 |
showErrorInBrowser bool |
| 78 |
|
| 79 |
errState hugoBuilderErrState |
| 80 |
} |
| 81 |
|
| 82 |
var errConfigNotSet = errors.New("config not set") |
| 83 |
|
| 84 |
func (c *hugoBuilder) withConfE(fn func(conf *commonConfig) error) error { |
| 85 |
c.confmu.Lock() |
| 86 |
defer c.confmu.Unlock() |
| 87 |
if c.conf == nil { |
| 88 |
return errConfigNotSet |
| 89 |
} |
| 90 |
return fn(c.conf) |
| 91 |
} |
| 92 |
|
| 93 |
func (c *hugoBuilder) withConf(fn func(conf *commonConfig)) { |
| 94 |
c.confmu.Lock() |
| 95 |
defer c.confmu.Unlock() |
| 96 |
fn(c.conf) |
| 97 |
} |
| 98 |
|
| 99 |
func (c *hugoBuilder) withConfOrOldConf(fn func(conf *commonConfig)) { |
| 100 |
c.confmu.Lock() |
| 101 |
defer c.confmu.Unlock() |
| 102 |
if c.conf != nil { |
| 103 |
fn(c.conf) |
| 104 |
} else if c.confOld != nil { |
| 105 |
fn(c.confOld) |
| 106 |
} |
| 107 |
} |
| 108 |
|
| 109 |
func (c *hugoBuilder) withConfOrOldConfE(fn func(conf *commonConfig) error) error { |
| 110 |
c.confmu.Lock() |
| 111 |
defer c.confmu.Unlock() |
| 112 |
if c.conf != nil { |
| 113 |
return fn(c.conf) |
| 114 |
} else if c.confOld != nil { |
| 115 |
return fn(c.confOld) |
| 116 |
} |
| 117 |
return errConfigNotSet |
| 118 |
} |
| 119 |
|
| 120 |
type hugoBuilderErrState struct { |
| 121 |
mu sync.Mutex |
| 122 |
paused bool |
| 123 |
builderr error |
| 124 |
waserr bool |
| 125 |
} |
| 126 |
|
| 127 |
func (e *hugoBuilderErrState) setPaused(p bool) { |
| 128 |
e.mu.Lock() |
| 129 |
defer e.mu.Unlock() |
| 130 |
e.paused = p |
| 131 |
} |
| 132 |
|
| 133 |
func (e *hugoBuilderErrState) isPaused() bool { |
| 134 |
e.mu.Lock() |
| 135 |
defer e.mu.Unlock() |
| 136 |
return e.paused |
| 137 |
} |
| 138 |
|
| 139 |
func (e *hugoBuilderErrState) setBuildErr(err error) { |
| 140 |
e.mu.Lock() |
| 141 |
defer e.mu.Unlock() |
| 142 |
e.builderr = err |
| 143 |
} |
| 144 |
|
| 145 |
func (e *hugoBuilderErrState) buildErr() error { |
| 146 |
e.mu.Lock() |
| 147 |
defer e.mu.Unlock() |
| 148 |
return e.builderr |
| 149 |
} |
| 150 |
|
| 151 |
func (e *hugoBuilderErrState) setWasErr(w bool) { |
| 152 |
e.mu.Lock() |
| 153 |
defer e.mu.Unlock() |
| 154 |
e.waserr = w |
| 155 |
} |
| 156 |
|
| 157 |
func (e *hugoBuilderErrState) wasErr() bool { |
| 158 |
e.mu.Lock() |
| 159 |
defer e.mu.Unlock() |
| 160 |
return e.waserr |
| 161 |
} |
| 162 |
|
| 163 |
// getDirList provides NewWatcher() with a list of directories to watch for changes. |
| 164 |
func (c *hugoBuilder) getDirList() ([]string, error) { |
| 165 |
h, err := c.hugo() |
| 166 |
if err != nil { |
| 167 |
return nil, err |
| 168 |
} |
| 169 |
|
| 170 |
return hstrings.UniqueStringsSorted(h.PathSpec.BaseFs.WatchFilenames()), nil |
| 171 |
} |
| 172 |
|
| 173 |
func (c *hugoBuilder) initCPUProfile() (func(), error) { |
| 174 |
if c.r.cpuprofile == "" { |
| 175 |
return nil, nil |
| 176 |
} |
| 177 |
|
| 178 |
f, err := os.Create(c.r.cpuprofile) |
| 179 |
if err != nil { |
| 180 |
return nil, fmt.Errorf("failed to create CPU profile: %w", err) |
| 181 |
} |
| 182 |
if err := pprof.StartCPUProfile(f); err != nil { |
| 183 |
f.Close() |
| 184 |
return nil, fmt.Errorf("failed to start CPU profile: %w", err) |
| 185 |
} |
| 186 |
return func() { |
| 187 |
pprof.StopCPUProfile() |
| 188 |
f.Close() |
| 189 |
}, nil |
| 190 |
} |
| 191 |
|
| 192 |
func (c *hugoBuilder) initMemProfile() { |
| 193 |
if c.r.memprofile == "" { |
| 194 |
return |
| 195 |
} |
| 196 |
|
| 197 |
f, err := os.Create(c.r.memprofile) |
| 198 |
if err != nil { |
| 199 |
c.r.logger.Errorf("could not create memory profile: %s", err) |
| 200 |
} |
| 201 |
defer f.Close() |
| 202 |
runtime.GC() // get up-to-date statistics |
| 203 |
if err := pprof.WriteHeapProfile(f); err != nil { |
| 204 |
c.r.logger.Errorf("could not write memory profile: %s", err) |
| 205 |
} |
| 206 |
} |
| 207 |
|
| 208 |
func (c *hugoBuilder) initMemTicker() func() { |
| 209 |
memticker := time.NewTicker(5 * time.Second) |
| 210 |
quit := make(chan struct{}) |
| 211 |
printMem := func() { |
| 212 |
var m runtime.MemStats |
| 213 |
runtime.ReadMemStats(&m) |
| 214 |
fmt.Printf("\n\nAlloc = %v\nTotalAlloc = %v\nSys = %v\nNumGC = %v\n\n", formatByteCount(m.Alloc), formatByteCount(m.TotalAlloc), formatByteCount(m.Sys), m.NumGC) |
| 215 |
} |
| 216 |
|
| 217 |
go func() { |
| 218 |
for { |
| 219 |
select { |
| 220 |
case <-memticker.C: |
| 221 |
printMem() |
| 222 |
case <-quit: |
| 223 |
memticker.Stop() |
| 224 |
printMem() |
| 225 |
return |
| 226 |
} |
| 227 |
} |
| 228 |
}() |
| 229 |
|
| 230 |
return func() { |
| 231 |
close(quit) |
| 232 |
} |
| 233 |
} |
| 234 |
|
| 235 |
func (c *hugoBuilder) initMutexProfile() (func(), error) { |
| 236 |
if c.r.mutexprofile == "" { |
| 237 |
return nil, nil |
| 238 |
} |
| 239 |
|
| 240 |
f, err := os.Create(c.r.mutexprofile) |
| 241 |
if err != nil { |
| 242 |
return nil, err |
| 243 |
} |
| 244 |
|
| 245 |
runtime.SetMutexProfileFraction(1) |
| 246 |
|
| 247 |
return func() { |
| 248 |
pprof.Lookup("mutex").WriteTo(f, 0) |
| 249 |
f.Close() |
| 250 |
}, nil |
| 251 |
} |
| 252 |
|
| 253 |
func (c *hugoBuilder) initProfiling() (func(), error) { |
| 254 |
stopCPUProf, err := c.initCPUProfile() |
| 255 |
if err != nil { |
| 256 |
return nil, err |
| 257 |
} |
| 258 |
|
| 259 |
stopMutexProf, err := c.initMutexProfile() |
| 260 |
if err != nil { |
| 261 |
return nil, err |
| 262 |
} |
| 263 |
|
| 264 |
stopTraceProf, err := c.initTraceProfile() |
| 265 |
if err != nil { |
| 266 |
return nil, err |
| 267 |
} |
| 268 |
|
| 269 |
var stopMemTicker func() |
| 270 |
if c.r.printm { |
| 271 |
stopMemTicker = c.initMemTicker() |
| 272 |
} |
| 273 |
|
| 274 |
return func() { |
| 275 |
c.initMemProfile() |
| 276 |
|
| 277 |
if stopCPUProf != nil { |
| 278 |
stopCPUProf() |
| 279 |
} |
| 280 |
if stopMutexProf != nil { |
| 281 |
stopMutexProf() |
| 282 |
} |
| 283 |
|
| 284 |
if stopTraceProf != nil { |
| 285 |
stopTraceProf() |
| 286 |
} |
| 287 |
|
| 288 |
if stopMemTicker != nil { |
| 289 |
stopMemTicker() |
| 290 |
} |
| 291 |
}, nil |
| 292 |
} |
| 293 |
|
| 294 |
func (c *hugoBuilder) initTraceProfile() (func(), error) { |
| 295 |
if c.r.traceprofile == "" { |
| 296 |
return nil, nil |
| 297 |
} |
| 298 |
|
| 299 |
f, err := os.Create(c.r.traceprofile) |
| 300 |
if err != nil { |
| 301 |
return nil, fmt.Errorf("failed to create trace file: %w", err) |
| 302 |
} |
| 303 |
|
| 304 |
if err := trace.Start(f); err != nil { |
| 305 |
return nil, fmt.Errorf("failed to start trace: %w", err) |
| 306 |
} |
| 307 |
|
| 308 |
return func() { |
| 309 |
trace.Stop() |
| 310 |
f.Close() |
| 311 |
}, nil |
| 312 |
} |
| 313 |
|
| 314 |
// newWatcher creates a new watcher to watch filesystem events. |
| 315 |
func (c *hugoBuilder) newWatcher(pollIntervalStr string, dirList ...string) (*watcher.Batcher, error) { |
| 316 |
staticSyncer := &staticSyncer{c: c} |
| 317 |
|
| 318 |
var pollInterval time.Duration |
| 319 |
poll := pollIntervalStr != "" |
| 320 |
if poll { |
| 321 |
pollInterval, err := types.ToDurationE(pollIntervalStr) |
| 322 |
if err != nil { |
| 323 |
return nil, fmt.Errorf("invalid value for flag poll: %s", err) |
| 324 |
} |
| 325 |
c.r.logger.Printf("Use watcher with poll interval %v", pollInterval) |
| 326 |
} |
| 327 |
|
| 328 |
if pollInterval == 0 { |
| 329 |
pollInterval = 500 * time.Millisecond |
| 330 |
} |
| 331 |
|
| 332 |
watcher, err := watcher.New(500*time.Millisecond, pollInterval, poll) |
| 333 |
if err != nil { |
| 334 |
return nil, err |
| 335 |
} |
| 336 |
|
| 337 |
h, err := c.hugo() |
| 338 |
if err != nil { |
| 339 |
return nil, err |
| 340 |
} |
| 341 |
spec := h.Deps.SourceSpec |
| 342 |
|
| 343 |
for _, d := range dirList { |
| 344 |
if d != "" { |
| 345 |
if spec.IgnoreFile(d) { |
| 346 |
continue |
| 347 |
} |
| 348 |
_ = watcher.Add(d) |
| 349 |
} |
| 350 |
} |
| 351 |
|
| 352 |
// Identifies changes to config (config.toml) files. |
| 353 |
configSet := make(map[string]bool) |
| 354 |
var configFiles []string |
| 355 |
c.withConf(func(conf *commonConfig) { |
| 356 |
configFiles = conf.configs.LoadingInfo.ConfigFiles |
| 357 |
}) |
| 358 |
|
| 359 |
c.r.Println("Watching for config changes in", strings.Join(configFiles, ", ")) |
| 360 |
for _, configFile := range configFiles { |
| 361 |
watcher.Add(configFile) |
| 362 |
configSet[configFile] = true |
| 363 |
} |
| 364 |
|
| 365 |
go func() { |
| 366 |
for { |
| 367 |
select { |
| 368 |
case changes := <-c.r.changesFromBuild: |
| 369 |
unlock, err := h.LockBuild() |
| 370 |
if err != nil { |
| 371 |
c.r.logger.Errorf("Failed to acquire a build lock: %s", err) |
| 372 |
return |
| 373 |
} |
| 374 |
c.changeDetector.PrepareNew() |
| 375 |
err = c.rebuildSitesForChanges(changes) |
| 376 |
if err != nil { |
| 377 |
c.r.logger.Errorln("Error while watching:", err) |
| 378 |
} |
| 379 |
if c.s != nil && c.s.doLiveReload { |
| 380 |
doReload := c.changeDetector == nil || len(c.changeDetector.changed()) > 0 |
| 381 |
doReload = doReload || c.showErrorInBrowser && c.errState.buildErr() != nil |
| 382 |
if doReload { |
| 383 |
livereload.ForceRefresh() |
| 384 |
} |
| 385 |
} |
| 386 |
unlock() |
| 387 |
|
| 388 |
case evs := <-watcher.Events: |
| 389 |
unlock, err := h.LockBuild() |
| 390 |
if err != nil { |
| 391 |
c.r.logger.Errorf("Failed to acquire a build lock: %s", err) |
| 392 |
return |
| 393 |
} |
| 394 |
c.handleEvents(watcher, staticSyncer, evs, configSet) |
| 395 |
if c.showErrorInBrowser && c.errState.buildErr() != nil { |
| 396 |
// Need to reload browser to show the error |
| 397 |
livereload.ForceRefresh() |
| 398 |
} |
| 399 |
unlock() |
| 400 |
case err := <-watcher.Errors(): |
| 401 |
if err != nil && !herrors.IsNotExist(err) { |
| 402 |
c.r.logger.Errorln("Error while watching:", err) |
| 403 |
} |
| 404 |
} |
| 405 |
} |
| 406 |
}() |
| 407 |
|
| 408 |
return watcher, nil |
| 409 |
} |
| 410 |
|
| 411 |
func (c *hugoBuilder) build() error { |
| 412 |
stopProfiling, err := c.initProfiling() |
| 413 |
if err != nil { |
| 414 |
return err |
| 415 |
} |
| 416 |
|
| 417 |
defer func() { |
| 418 |
if stopProfiling != nil { |
| 419 |
stopProfiling() |
| 420 |
} |
| 421 |
}() |
| 422 |
|
| 423 |
if err := c.fullBuild(false); err != nil { |
| 424 |
return err |
| 425 |
} |
| 426 |
|
| 427 |
if !c.r.quiet { |
| 428 |
c.r.Println() |
| 429 |
h, err := c.hugo() |
| 430 |
if err != nil { |
| 431 |
return err |
| 432 |
} |
| 433 |
|
| 434 |
h.PrintProcessingStats(os.Stdout) |
| 435 |
c.r.Println() |
| 436 |
} |
| 437 |
|
| 438 |
return nil |
| 439 |
} |
| 440 |
|
| 441 |
func (c *hugoBuilder) buildSites(noBuildLock bool) (err error) { |
| 442 |
defer func() { |
| 443 |
c.errState.setBuildErr(err) |
| 444 |
}() |
| 445 |
|
| 446 |
var h *hugolib.HugoSites |
| 447 |
h, err = c.hugo() |
| 448 |
if err != nil { |
| 449 |
return |
| 450 |
} |
| 451 |
err = h.Build(hugolib.BuildCfg{NoBuildLock: noBuildLock}) |
| 452 |
return |
| 453 |
} |
| 454 |
|
| 455 |
func (c *hugoBuilder) copyStatic() (map[string]uint64, error) { |
| 456 |
return c.doWithPublishDirs(c.copyStaticTo) |
| 457 |
} |
| 458 |
|
| 459 |
func (c *hugoBuilder) copyStaticTo(sourceFs *filesystems.SourceFilesystem) (uint64, error) { |
| 460 |
infol := c.r.logger.InfoCommand("static") |
| 461 |
publishDir := helpers.FilePathSeparator |
| 462 |
|
| 463 |
if sourceFs.PublishFolder != "" { |
| 464 |
publishDir = filepath.Join(publishDir, sourceFs.PublishFolder) |
| 465 |
} |
| 466 |
|
| 467 |
fs := &countingStatFs{Fs: sourceFs.Fs} |
| 468 |
|
| 469 |
syncer := fsync.NewSyncer() |
| 470 |
var clean config.CleanDestinationDir |
| 471 |
c.withConf(func(conf *commonConfig) { |
| 472 |
syncer.NoTimes = conf.configs.Base.NoTimes |
| 473 |
syncer.NoChmod = conf.configs.Base.NoChmod |
| 474 |
syncer.ChmodFilter = chmodFilter |
| 475 |
|
| 476 |
syncer.DestFs = conf.fs.PublishDirStatic |
| 477 |
clean = conf.configs.Base.Build.CleanDestinationDir |
| 478 |
}) |
| 479 |
|
| 480 |
syncer.SrcFs = fs |
| 481 |
|
| 482 |
start := time.Now() |
| 483 |
|
| 484 |
// because we are using a baseFs (to get the union right). |
| 485 |
// set sync src to root |
| 486 |
if _, err := fs.Stat(helpers.FilePathSeparator); err == nil { |
| 487 |
if err := syncer.Sync(publishDir, helpers.FilePathSeparator); err != nil { |
| 488 |
return 0, err |
| 489 |
} |
| 490 |
} else if !herrors.IsNotExist(err) { |
| 491 |
return 0, err |
| 492 |
} |
| 493 |
|
| 494 |
if clean.Enable { |
| 495 |
infol.Logf("removing stale files from destination") |
| 496 |
if err := removeStale(syncer.DestFs, sourceFs.Fs, publishDir, helpers.FilePathSeparator, clean.Keep); err != nil { |
| 497 |
return 0, err |
| 498 |
} |
| 499 |
} |
| 500 |
|
| 501 |
loggers.TimeTrackf(infol, start, nil, "syncing static files to %s", publishDir) |
| 502 |
|
| 503 |
// Sync runs Stat 2 times for every source file. |
| 504 |
numFiles := fs.statCounter / 2 |
| 505 |
|
| 506 |
return numFiles, nil |
| 507 |
} |
| 508 |
|
| 509 |
// removeStale removes entries in dstDir on dst that keep reports as false and |
| 510 |
// that don't exist in srcDir on src. Unlike fsync's delete pass, it applies |
| 511 |
// keep at every level, so kept files survive inside stale directories. |
| 512 |
// keep gets the slash separated path relative to srcDir's root, e.g. "dir/.gitignore". |
| 513 |
func removeStale(dst, src afero.Fs, dstDir, srcDir string, keep func(path string, isDir bool) bool) error { |
| 514 |
entries, err := afero.ReadDir(dst, dstDir) |
| 515 |
if err != nil { |
| 516 |
if herrors.IsNotExist(err) { |
| 517 |
return nil |
| 518 |
} |
| 519 |
return err |
| 520 |
} |
| 521 |
for _, entry := range entries { |
| 522 |
dstPath := filepath.Join(dstDir, entry.Name()) |
| 523 |
srcPath := filepath.Join(srcDir, entry.Name()) |
| 524 |
if keep(strings.TrimPrefix(filepath.ToSlash(srcPath), "/"), entry.IsDir()) { |
| 525 |
continue |
| 526 |
} |
| 527 |
if _, err := src.Stat(srcPath); err == nil { |
| 528 |
if entry.IsDir() { |
| 529 |
if err := removeStale(dst, src, dstPath, srcPath, keep); err != nil { |
| 530 |
return err |
| 531 |
} |
| 532 |
} |
| 533 |
continue |
| 534 |
} else if !herrors.IsNotExist(err) { |
| 535 |
return err |
| 536 |
} |
| 537 |
if entry.IsDir() { |
| 538 |
if err := removeStale(dst, src, dstPath, srcPath, keep); err != nil { |
| 539 |
return err |
| 540 |
} |
| 541 |
remaining, err := afero.ReadDir(dst, dstPath) |
| 542 |
if err != nil { |
| 543 |
if herrors.IsNotExist(err) { |
| 544 |
continue |
| 545 |
} |
| 546 |
return err |
| 547 |
} |
| 548 |
if len(remaining) > 0 { |
| 549 |
continue |
| 550 |
} |
| 551 |
} |
| 552 |
if err := dst.RemoveAll(dstPath); err != nil { |
| 553 |
return err |
| 554 |
} |
| 555 |
} |
| 556 |
return nil |
| 557 |
} |
| 558 |
|
| 559 |
func (c *hugoBuilder) doWithPublishDirs(f func(sourceFs *filesystems.SourceFilesystem) (uint64, error)) (map[string]uint64, error) { |
| 560 |
langCount := make(map[string]uint64) |
| 561 |
|
| 562 |
h, err := c.hugo() |
| 563 |
if err != nil { |
| 564 |
return nil, err |
| 565 |
} |
| 566 |
staticFilesystems := h.BaseFs.SourceFilesystems.Static |
| 567 |
|
| 568 |
if len(staticFilesystems) == 0 { |
| 569 |
c.r.logger.Infoln("No static directories found to sync") |
| 570 |
return langCount, nil |
| 571 |
} |
| 572 |
|
| 573 |
for lang, fs := range staticFilesystems { |
| 574 |
cnt, err := f(fs) |
| 575 |
if err != nil { |
| 576 |
return langCount, err |
| 577 |
} |
| 578 |
if lang == "" { |
| 579 |
// Not multihost |
| 580 |
c.withConf(func(conf *commonConfig) { |
| 581 |
for _, l := range conf.configs.Languages { |
| 582 |
langCount[l.Lang] = cnt |
| 583 |
} |
| 584 |
}) |
| 585 |
} else { |
| 586 |
langCount[lang] = cnt |
| 587 |
} |
| 588 |
} |
| 589 |
|
| 590 |
return langCount, nil |
| 591 |
} |
| 592 |
|
| 593 |
func (c *hugoBuilder) progressIntermediate() { |
| 594 |
terminal.ReportProgress(c.r.StdOut, terminal.ProgressIntermediate, 0) |
| 595 |
} |
| 596 |
|
| 597 |
func (c *hugoBuilder) progressHidden() { |
| 598 |
terminal.ReportProgress(c.r.StdOut, terminal.ProgressHidden, 0) |
| 599 |
} |
| 600 |
|
| 601 |
func (c *hugoBuilder) fullBuild(noBuildLock bool) error { |
| 602 |
var ( |
| 603 |
g errgroup.Group |
| 604 |
langCount map[string]uint64 |
| 605 |
) |
| 606 |
|
| 607 |
c.r.logger.Println("Start building sites … ") |
| 608 |
c.r.logger.Println(hugo.BuildVersionString()) |
| 609 |
c.r.logger.Println() |
| 610 |
if terminal.IsTerminal(os.Stdout) { |
| 611 |
defer func() { |
| 612 |
fmt.Print(showCursor + clearLine) |
| 613 |
}() |
| 614 |
} |
| 615 |
|
| 616 |
copyStaticFunc := func() error { |
| 617 |
cnt, err := c.copyStatic() |
| 618 |
if err != nil { |
| 619 |
return fmt.Errorf("error copying static files: %w", err) |
| 620 |
} |
| 621 |
langCount = cnt |
| 622 |
return nil |
| 623 |
} |
| 624 |
buildSitesFunc := func() error { |
| 625 |
if err := c.buildSites(noBuildLock); err != nil { |
| 626 |
return fmt.Errorf("error building site: %w", err) |
| 627 |
} |
| 628 |
return nil |
| 629 |
} |
| 630 |
// Do not copy static files and build sites in parallel if cleanDestinationDir is enabled. |
| 631 |
// This flag deletes all static resources in /public folder that are missing in /static, |
| 632 |
// and it does so at the end of copyStatic() call. |
| 633 |
var cleanDestinationDir bool |
| 634 |
c.withConf(func(conf *commonConfig) { |
| 635 |
cleanDestinationDir = conf.configs.Base.Build.CleanDestinationDir.Enable |
| 636 |
}) |
| 637 |
if cleanDestinationDir { |
| 638 |
if err := copyStaticFunc(); err != nil { |
| 639 |
return err |
| 640 |
} |
| 641 |
if err := buildSitesFunc(); err != nil { |
| 642 |
return err |
| 643 |
} |
| 644 |
} else { |
| 645 |
g.Go(copyStaticFunc) |
| 646 |
g.Go(buildSitesFunc) |
| 647 |
if err := g.Wait(); err != nil { |
| 648 |
return err |
| 649 |
} |
| 650 |
} |
| 651 |
|
| 652 |
h, err := c.hugo() |
| 653 |
if err != nil { |
| 654 |
return err |
| 655 |
} |
| 656 |
for _, s := range h.Sites { |
| 657 |
s.ProcessingStats.Static = langCount[s.Language().Lang] |
| 658 |
} |
| 659 |
|
| 660 |
if c.r.gc { |
| 661 |
count, err := h.GC() |
| 662 |
if err != nil { |
| 663 |
return err |
| 664 |
} |
| 665 |
for _, s := range h.Sites { |
| 666 |
// We have no way of knowing what site the garbage belonged to. |
| 667 |
s.ProcessingStats.Cleaned = uint64(count) |
| 668 |
} |
| 669 |
} |
| 670 |
|
| 671 |
return nil |
| 672 |
} |
| 673 |
|
| 674 |
func (c *hugoBuilder) fullRebuild(changeType string) { |
| 675 |
if changeType == configChangeGoMod { |
| 676 |
// go.mod may be changed during the build itself, and |
| 677 |
// we really want to prevent superfluous builds. |
| 678 |
if !c.fullRebuildSem.TryAcquire(1) { |
| 679 |
return |
| 680 |
} |
| 681 |
c.fullRebuildSem.Release(1) |
| 682 |
} |
| 683 |
|
| 684 |
c.fullRebuildSem.Acquire(context.Background(), 1) |
| 685 |
|
| 686 |
go func() { |
| 687 |
defer c.fullRebuildSem.Release(1) |
| 688 |
|
| 689 |
c.printChangeDetected(changeType) |
| 690 |
|
| 691 |
defer func() { |
| 692 |
// Allow any file system events to arrive basimplecobra. |
| 693 |
// This will block any rebuild on config changes for the |
| 694 |
// duration of the sleep. |
| 695 |
time.Sleep(2 * time.Second) |
| 696 |
}() |
| 697 |
|
| 698 |
defer c.postBuild("Rebuilt", time.Now()) |
| 699 |
|
| 700 |
err := c.reloadConfig() |
| 701 |
if err != nil { |
| 702 |
// Set the processing on pause until the state is recovered. |
| 703 |
c.errState.setPaused(true) |
| 704 |
c.handleBuildErr(err, "Failed to reload config") |
| 705 |
if c.s.doLiveReload { |
| 706 |
livereload.ForceRefresh() |
| 707 |
} |
| 708 |
} else { |
| 709 |
c.errState.setPaused(false) |
| 710 |
} |
| 711 |
|
| 712 |
if !c.errState.isPaused() { |
| 713 |
_, err := c.copyStatic() |
| 714 |
if err != nil { |
| 715 |
c.r.logger.Errorln(err) |
| 716 |
return |
| 717 |
} |
| 718 |
err = c.buildSites(false) |
| 719 |
if err != nil { |
| 720 |
c.r.logger.Errorln(err) |
| 721 |
} else if c.s != nil && c.s.doLiveReload { |
| 722 |
livereload.ForceRefresh() |
| 723 |
} |
| 724 |
} |
| 725 |
}() |
| 726 |
} |
| 727 |
|
| 728 |
func (c *hugoBuilder) handleBuildErr(err error, msg string) { |
| 729 |
c.errState.setBuildErr(err) |
| 730 |
c.r.logger.Errorln(msg + ": " + cleanErrorLog(err.Error())) |
| 731 |
} |
| 732 |
|
| 733 |
func (c *hugoBuilder) handleEvents(watcher *watcher.Batcher, |
| 734 |
staticSyncer *staticSyncer, |
| 735 |
evs []fsnotify.Event, |
| 736 |
configSet map[string]bool, |
| 737 |
) { |
| 738 |
defer func() { |
| 739 |
c.errState.setWasErr(false) |
| 740 |
}() |
| 741 |
|
| 742 |
var isHandled bool |
| 743 |
|
| 744 |
// Filter out ghost events (from deleted, renamed directories). |
| 745 |
// This seems to be a bug in fsnotify, or possibly MacOS. |
| 746 |
var n int |
| 747 |
for _, ev := range evs { |
| 748 |
keep := true |
| 749 |
// Write and rename operations are often followed by CHMOD. |
| 750 |
// There may be valid use cases for rebuilding the site on CHMOD, |
| 751 |
// but that will require more complex logic than this simple conditional. |
| 752 |
// On OS X this seems to be related to Spotlight, see: |
| 753 |
// https://github.com/go-fsnotify/fsnotify/issues/15 |
| 754 |
// A workaround is to put your site(s) on the Spotlight exception list, |
| 755 |
// but that may be a little mysterious for most end users. |
| 756 |
// So, for now, we skip reload on CHMOD. |
| 757 |
// We do have to check for WRITE though. On slower laptops a Chmod |
| 758 |
// could be aggregated with other important events, and we still want |
| 759 |
// to rebuild on those |
| 760 |
if ev.Op == fsnotify.Chmod { |
| 761 |
keep = false |
| 762 |
} else if ev.Has(fsnotify.Create) || ev.Has(fsnotify.Write) { |
| 763 |
if _, err := os.Stat(ev.Name); err != nil { |
| 764 |
keep = false |
| 765 |
} |
| 766 |
} |
| 767 |
if keep { |
| 768 |
evs[n] = ev |
| 769 |
n++ |
| 770 |
} |
| 771 |
} |
| 772 |
evs = evs[:n] |
| 773 |
|
| 774 |
for _, ev := range evs { |
| 775 |
isConfig := configSet[ev.Name] |
| 776 |
configChangeType := configChangeConfig |
| 777 |
if isConfig { |
| 778 |
if strings.Contains(ev.Name, "go.mod") { |
| 779 |
configChangeType = configChangeGoMod |
| 780 |
} |
| 781 |
if strings.Contains(ev.Name, ".work") { |
| 782 |
configChangeType = configChangeGoWork |
| 783 |
} |
| 784 |
} |
| 785 |
if !isConfig { |
| 786 |
// It may be one of the /config folders |
| 787 |
dirname := filepath.Dir(ev.Name) |
| 788 |
if dirname != "." && configSet[dirname] { |
| 789 |
isConfig = true |
| 790 |
} |
| 791 |
} |
| 792 |
|
| 793 |
if isConfig { |
| 794 |
isHandled = true |
| 795 |
|
| 796 |
if ev.Op&fsnotify.Chmod == fsnotify.Chmod { |
| 797 |
continue |
| 798 |
} |
| 799 |
|
| 800 |
if ev.Op&fsnotify.Remove == fsnotify.Remove || ev.Op&fsnotify.Rename == fsnotify.Rename { |
| 801 |
c.withConf(func(conf *commonConfig) { |
| 802 |
for _, configFile := range conf.configs.LoadingInfo.ConfigFiles { |
| 803 |
counter := 0 |
| 804 |
for watcher.Add(configFile) != nil { |
| 805 |
counter++ |
| 806 |
if counter >= 100 { |
| 807 |
break |
| 808 |
} |
| 809 |
time.Sleep(100 * time.Millisecond) |
| 810 |
} |
| 811 |
} |
| 812 |
}) |
| 813 |
} |
| 814 |
|
| 815 |
// Config file(s) changed. Need full rebuild. |
| 816 |
c.fullRebuild(configChangeType) |
| 817 |
|
| 818 |
return |
| 819 |
} |
| 820 |
} |
| 821 |
|
| 822 |
if isHandled { |
| 823 |
return |
| 824 |
} |
| 825 |
|
| 826 |
if c.errState.isPaused() { |
| 827 |
// Wait for the server to get into a consistent state before |
| 828 |
// we continue with processing. |
| 829 |
return |
| 830 |
} |
| 831 |
|
| 832 |
if len(evs) > 50 { |
| 833 |
// This is probably a mass edit of the content dir. |
| 834 |
// Schedule a full rebuild for when it slows down. |
| 835 |
c.debounce(func() { |
| 836 |
c.fullRebuild("") |
| 837 |
}) |
| 838 |
return |
| 839 |
} |
| 840 |
|
| 841 |
c.r.logger.Debugln("Received System Events:", evs) |
| 842 |
|
| 843 |
staticEvents := []fsnotify.Event{} |
| 844 |
dynamicEvents := []fsnotify.Event{} |
| 845 |
|
| 846 |
filterDuplicateEvents := func(evs []fsnotify.Event) []fsnotify.Event { |
| 847 |
seen := make(map[string]bool) |
| 848 |
var n int |
| 849 |
for _, ev := range evs { |
| 850 |
if seen[ev.Name] { |
| 851 |
continue |
| 852 |
} |
| 853 |
seen[ev.Name] = true |
| 854 |
evs[n] = ev |
| 855 |
n++ |
| 856 |
} |
| 857 |
return evs[:n] |
| 858 |
} |
| 859 |
|
| 860 |
h, err := c.hugo() |
| 861 |
if err != nil { |
| 862 |
c.r.logger.Errorln("Error getting the Hugo object:", err) |
| 863 |
return |
| 864 |
} |
| 865 |
n = 0 |
| 866 |
for _, ev := range evs { |
| 867 |
if h.ShouldSkipFileChangeEvent(ev) { |
| 868 |
continue |
| 869 |
} |
| 870 |
evs[n] = ev |
| 871 |
n++ |
| 872 |
} |
| 873 |
evs = evs[:n] |
| 874 |
|
| 875 |
for _, ev := range evs { |
| 876 |
ext := filepath.Ext(ev.Name) |
| 877 |
baseName := filepath.Base(ev.Name) |
| 878 |
istemp := strings.HasSuffix(ext, "~") || |
| 879 |
(ext == ".swp") || // vim |
| 880 |
(ext == ".swx") || // vim |
| 881 |
(ext == ".bck") || // helix |
| 882 |
(ext == ".tmp") || // generic temp file |
| 883 |
(ext == ".DS_Store") || // OSX Thumbnail |
| 884 |
baseName == "4913" || // vim |
| 885 |
strings.HasPrefix(ext, ".goutputstream") || // gnome |
| 886 |
strings.HasSuffix(ext, "jb_old___") || // intelliJ |
| 887 |
strings.HasSuffix(ext, "jb_tmp___") || // intelliJ |
| 888 |
strings.HasSuffix(ext, "jb_bak___") || // intelliJ |
| 889 |
strings.HasPrefix(ext, ".sb-") || // byword |
| 890 |
strings.HasPrefix(baseName, ".#") || // emacs |
| 891 |
strings.HasPrefix(baseName, "#") // emacs |
| 892 |
if istemp { |
| 893 |
continue |
| 894 |
} |
| 895 |
|
| 896 |
if h.Deps.SourceSpec.IgnoreFile(ev.Name) { |
| 897 |
continue |
| 898 |
} |
| 899 |
// Sometimes during rm -rf operations a '"": REMOVE' is triggered. Just ignore these |
| 900 |
if ev.Name == "" { |
| 901 |
continue |
| 902 |
} |
| 903 |
|
| 904 |
walkAdder := func(ctx context.Context, path string, f hugofs.FileMetaInfo) error { |
| 905 |
if f.IsDir() { |
| 906 |
c.r.logger.Println("adding created directory to watchlist", path) |
| 907 |
if err := watcher.Add(path); err != nil { |
| 908 |
return err |
| 909 |
} |
| 910 |
} else if !staticSyncer.isStatic(h, path) { |
| 911 |
// Hugo's rebuilding logic is entirely file based. When you drop a new folder into |
| 912 |
// /content on OSX, the above logic will handle future watching of those files, |
| 913 |
// but the initial CREATE is lost. |
| 914 |
dynamicEvents = append(dynamicEvents, fsnotify.Event{Name: path, Op: fsnotify.Create}) |
| 915 |
} |
| 916 |
return nil |
| 917 |
} |
| 918 |
|
| 919 |
// recursively add new directories to watch list |
| 920 |
if ev.Has(fsnotify.Create) || ev.Has(fsnotify.Rename) { |
| 921 |
c.withConf(func(conf *commonConfig) { |
| 922 |
if s, err := conf.fs.Source.Stat(ev.Name); err == nil && s.Mode().IsDir() { |
| 923 |
_ = helpers.Walk(conf.fs.Source, ev.Name, walkAdder) |
| 924 |
} |
| 925 |
}) |
| 926 |
} |
| 927 |
|
| 928 |
if staticSyncer.isStatic(h, ev.Name) { |
| 929 |
staticEvents = append(staticEvents, ev) |
| 930 |
} else { |
| 931 |
dynamicEvents = append(dynamicEvents, ev) |
| 932 |
} |
| 933 |
} |
| 934 |
|
| 935 |
lrl := c.r.logger.InfoCommand("livereload") |
| 936 |
|
| 937 |
staticEvents = filterDuplicateEvents(staticEvents) |
| 938 |
dynamicEvents = filterDuplicateEvents(dynamicEvents) |
| 939 |
|
| 940 |
if len(staticEvents) > 0 { |
| 941 |
c.printChangeDetected("Static files") |
| 942 |
|
| 943 |
if c.r.forceSyncStatic { |
| 944 |
c.r.logger.Printf("Syncing all static files\n") |
| 945 |
_, err := c.copyStatic() |
| 946 |
if err != nil { |
| 947 |
c.r.logger.Errorln("Error copying static files to publish dir:", err) |
| 948 |
return |
| 949 |
} |
| 950 |
} else { |
| 951 |
if err := staticSyncer.syncsStaticEvents(staticEvents); err != nil { |
| 952 |
c.r.logger.Errorln("Error syncing static files to publish dir:", err) |
| 953 |
return |
| 954 |
} |
| 955 |
} |
| 956 |
|
| 957 |
if c.s != nil && c.s.doLiveReload { |
| 958 |
// Will block forever trying to write to a channel that nobody is reading if livereload isn't initialized |
| 959 |
|
| 960 |
if !c.errState.wasErr() && len(staticEvents) == 1 { |
| 961 |
h, err := c.hugo() |
| 962 |
if err != nil { |
| 963 |
c.r.logger.Errorln("Error getting the Hugo object:", err) |
| 964 |
return |
| 965 |
} |
| 966 |
|
| 967 |
path := h.BaseFs.SourceFilesystems.MakeStaticPathRelative(staticEvents[0].Name) |
| 968 |
path = h.RelURL(paths.ToSlashTrimLeading(path), false) |
| 969 |
|
| 970 |
lrl.Logf("refreshing static file %q", path) |
| 971 |
livereload.RefreshPath(path) |
| 972 |
} else { |
| 973 |
lrl.Logf("got %d static file change events, force refresh", len(staticEvents)) |
| 974 |
livereload.ForceRefresh() |
| 975 |
} |
| 976 |
} |
| 977 |
} |
| 978 |
|
| 979 |
if len(dynamicEvents) > 0 { |
| 980 |
partitionedEvents := partitionDynamicEvents( |
| 981 |
h.BaseFs.SourceFilesystems, |
| 982 |
dynamicEvents, |
| 983 |
) |
| 984 |
|
| 985 |
onePageName := pickOneWriteOrCreatePath(h.Conf.ContentTypes(), partitionedEvents.ContentEvents) |
| 986 |
|
| 987 |
c.printChangeDetected("") |
| 988 |
c.changeDetector.PrepareNew() |
| 989 |
|
| 990 |
func() { |
| 991 |
defer c.postBuild("Total", time.Now()) |
| 992 |
if err := c.rebuildSites(dynamicEvents); err != nil { |
| 993 |
c.handleBuildErr(err, "Rebuild failed") |
| 994 |
} |
| 995 |
}() |
| 996 |
|
| 997 |
if c.s != nil && c.s.doLiveReload { |
| 998 |
if c.errState.wasErr() { |
| 999 |
livereload.ForceRefresh() |
| 1000 |
return |
| 1001 |
} |
| 1002 |
|
| 1003 |
changed := c.changeDetector.changed() |
| 1004 |
if c.changeDetector != nil { |
| 1005 |
if len(changed) >= 10 { |
| 1006 |
lrl.Logf("build changed %d files", len(changed)) |
| 1007 |
} else { |
| 1008 |
lrl.Logf("build changed %d files: %q", len(changed), changed) |
| 1009 |
} |
| 1010 |
if len(changed) == 0 { |
| 1011 |
// Nothing has changed. |
| 1012 |
return |
| 1013 |
} |
| 1014 |
} |
| 1015 |
|
| 1016 |
// If this change set also contains one or more CSS files, we need to |
| 1017 |
// refresh these as well. |
| 1018 |
var cssChanges []string |
| 1019 |
var otherChanges []string |
| 1020 |
|
| 1021 |
for _, ev := range changed { |
| 1022 |
if strings.HasSuffix(ev, ".css") { |
| 1023 |
cssChanges = append(cssChanges, ev) |
| 1024 |
} else { |
| 1025 |
otherChanges = append(otherChanges, ev) |
| 1026 |
} |
| 1027 |
} |
| 1028 |
|
| 1029 |
if len(partitionedEvents.ContentEvents) > 0 { |
| 1030 |
navigate := c.s != nil && c.s.navigateToChanged |
| 1031 |
// We have fetched the same page above, but it may have |
| 1032 |
// changed. |
| 1033 |
var p page.Page |
| 1034 |
|
| 1035 |
if navigate { |
| 1036 |
if onePageName != "" { |
| 1037 |
p = h.GetContentPage(onePageName) |
| 1038 |
} |
| 1039 |
} |
| 1040 |
|
| 1041 |
if p != nil && p.RelPermalink() != "" { |
| 1042 |
link, port := p.RelPermalink(), p.Site().ServerPort() |
| 1043 |
lrl.Logf("navigating to %q using port %d", link, port) |
| 1044 |
livereload.NavigateToPathForPort(link, port) |
| 1045 |
} else { |
| 1046 |
lrl.Logf("no page to navigate to, force refresh") |
| 1047 |
livereload.ForceRefresh() |
| 1048 |
} |
| 1049 |
} else if len(otherChanges) > 0 || len(cssChanges) > 0 { |
| 1050 |
if len(otherChanges) == 1 { |
| 1051 |
// Allow single changes to be refreshed without a full page reload. |
| 1052 |
pathToRefresh := h.PathSpec.RelURL(paths.ToSlashTrimLeading(otherChanges[0]), false) |
| 1053 |
lrl.Logf("refreshing %q", pathToRefresh) |
| 1054 |
livereload.RefreshPath(pathToRefresh) |
| 1055 |
} else if len(cssChanges) == 0 || len(otherChanges) > 1 { |
| 1056 |
lrl.Logf("force refresh") |
| 1057 |
livereload.ForceRefresh() |
| 1058 |
} |
| 1059 |
} else { |
| 1060 |
lrl.Logf("force refresh") |
| 1061 |
livereload.ForceRefresh() |
| 1062 |
} |
| 1063 |
|
| 1064 |
if len(cssChanges) > 0 { |
| 1065 |
// Allow some time for the live reload script to get reconnected. |
| 1066 |
if len(otherChanges) > 0 { |
| 1067 |
time.Sleep(200 * time.Millisecond) |
| 1068 |
} |
| 1069 |
for _, ev := range cssChanges { |
| 1070 |
pathToRefresh := h.PathSpec.RelURL(paths.ToSlashTrimLeading(ev), false) |
| 1071 |
lrl.Logf("refreshing CSS %q", pathToRefresh) |
| 1072 |
livereload.RefreshPath(pathToRefresh) |
| 1073 |
} |
| 1074 |
} |
| 1075 |
} |
| 1076 |
} |
| 1077 |
} |
| 1078 |
|
| 1079 |
func (c *hugoBuilder) postBuild(what string, start time.Time) { |
| 1080 |
if h, err := c.hugo(); err == nil && h.Conf.Running() { |
| 1081 |
h.LogServerAddresses() |
| 1082 |
} |
| 1083 |
c.r.timeTrack(start, what) |
| 1084 |
} |
| 1085 |
|
| 1086 |
func (c *hugoBuilder) hugo() (*hugolib.HugoSites, error) { |
| 1087 |
var h *hugolib.HugoSites |
| 1088 |
if err := c.withConfE(func(conf *commonConfig) error { |
| 1089 |
var err error |
| 1090 |
h, err = c.r.HugFromConfig(conf) |
| 1091 |
return err |
| 1092 |
}); err != nil { |
| 1093 |
return nil, err |
| 1094 |
} |
| 1095 |
|
| 1096 |
if c.s != nil { |
| 1097 |
// A running server, register the media types. |
| 1098 |
for _, s := range h.Sites { |
| 1099 |
s.RegisterMediaTypes() |
| 1100 |
} |
| 1101 |
} |
| 1102 |
return h, nil |
| 1103 |
} |
| 1104 |
|
| 1105 |
func (c *hugoBuilder) hugoTry() *hugolib.HugoSites { |
| 1106 |
var h *hugolib.HugoSites |
| 1107 |
c.withConf(func(conf *commonConfig) { |
| 1108 |
h, _ = c.r.HugFromConfig(conf) |
| 1109 |
}) |
| 1110 |
return h |
| 1111 |
} |
| 1112 |
|
| 1113 |
func (c *hugoBuilder) loadConfig(cd *simplecobra.Commandeer, running bool) error { |
| 1114 |
if terminal.PrintANSIColors(os.Stdout) { |
| 1115 |
defer c.progressHidden() |
| 1116 |
// If the configuration takes a while to load, we want to show some progress. |
| 1117 |
// This is typically loading of external modules. |
| 1118 |
d := debounce.New(500 * time.Millisecond) |
| 1119 |
d(func() { |
| 1120 |
c.progressIntermediate() |
| 1121 |
}) |
| 1122 |
defer d(func() {}) |
| 1123 |
} |
| 1124 |
|
| 1125 |
cfg := config.New() |
| 1126 |
cfg.Set("renderToMemory", c.r.renderToMemory) |
| 1127 |
watch := c.r.buildWatch || (c.s != nil && c.s.serverWatch) |
| 1128 |
// We need to set the environment as early as possible because we need it to load the correct config. |
| 1129 |
c.r.resolveEnvironment(c.s != nil) |
| 1130 |
cfg.Set("environment", c.r.environment) |
| 1131 |
|
| 1132 |
cfg.Set("internal", hmaps.Params{ |
| 1133 |
"running": running, |
| 1134 |
"watch": watch, |
| 1135 |
"verbose": c.r.isVerbose(), |
| 1136 |
"fastRenderMode": c.fastRenderMode, |
| 1137 |
}) |
| 1138 |
|
| 1139 |
conf, err := c.r.ConfigFromProvider(configKey{counter: c.r.configVersionID.Load()}, flagsToCfg(cd, cfg)) |
| 1140 |
if err != nil { |
| 1141 |
return err |
| 1142 |
} |
| 1143 |
|
| 1144 |
c.conf = conf |
| 1145 |
c.confOld = conf |
| 1146 |
if c.onConfigLoaded != nil { |
| 1147 |
if err := c.onConfigLoaded(false); err != nil { |
| 1148 |
return err |
| 1149 |
} |
| 1150 |
} |
| 1151 |
|
| 1152 |
return nil |
| 1153 |
} |
| 1154 |
|
| 1155 |
var rebuildCounter atomic.Uint64 |
| 1156 |
|
| 1157 |
func (c *hugoBuilder) printChangeDetected(typ string) { |
| 1158 |
msg := "\nChange" |
| 1159 |
if typ != "" { |
| 1160 |
msg += " of " + typ |
| 1161 |
} |
| 1162 |
msg += fmt.Sprintf(" detected, rebuilding site (#%d).", rebuildCounter.Add(1)) |
| 1163 |
|
| 1164 |
c.r.logger.Println(msg) |
| 1165 |
const layout = "2006-01-02 15:04:05.000 -0700" |
| 1166 |
c.r.logger.Println(htime.Now().Format(layout)) |
| 1167 |
} |
| 1168 |
|
| 1169 |
func (c *hugoBuilder) rebuildSites(events []fsnotify.Event) (err error) { |
| 1170 |
defer func() { |
| 1171 |
c.errState.setBuildErr(err) |
| 1172 |
}() |
| 1173 |
if err := c.errState.buildErr(); err != nil { |
| 1174 |
ferrs := herrors.UnwrapFileErrorsWithErrorContext(err) |
| 1175 |
for _, err := range ferrs { |
| 1176 |
events = append(events, fsnotify.Event{Name: err.Position().Filename, Op: fsnotify.Write}) |
| 1177 |
} |
| 1178 |
} |
| 1179 |
var h *hugolib.HugoSites |
| 1180 |
h, err = c.hugo() |
| 1181 |
if err != nil { |
| 1182 |
return |
| 1183 |
} |
| 1184 |
err = h.Build(hugolib.BuildCfg{NoBuildLock: true, RecentlyTouched: c.visitedURLs, ErrRecovery: c.errState.wasErr()}, events...) |
| 1185 |
return |
| 1186 |
} |
| 1187 |
|
| 1188 |
func (c *hugoBuilder) rebuildSitesForChanges(ids []identity.Identity) (err error) { |
| 1189 |
defer func() { |
| 1190 |
c.errState.setBuildErr(err) |
| 1191 |
}() |
| 1192 |
|
| 1193 |
var h *hugolib.HugoSites |
| 1194 |
h, err = c.hugo() |
| 1195 |
if err != nil { |
| 1196 |
return |
| 1197 |
} |
| 1198 |
whatChanged := &hugolib.WhatChanged{} |
| 1199 |
whatChanged.Add(ids...) |
| 1200 |
err = h.Build(hugolib.BuildCfg{NoBuildLock: true, WhatChanged: whatChanged, RecentlyTouched: c.visitedURLs, ErrRecovery: c.errState.wasErr()}) |
| 1201 |
|
| 1202 |
return |
| 1203 |
} |
| 1204 |
|
| 1205 |
func (c *hugoBuilder) reloadConfig() error { |
| 1206 |
c.r.resetLogs() |
| 1207 |
c.r.configVersionID.Add(1) |
| 1208 |
|
| 1209 |
if err := c.withConfOrOldConfE(func(conf *commonConfig) error { |
| 1210 |
oldConf := conf |
| 1211 |
c.conf = nil |
| 1212 |
newConf, err := c.r.ConfigFromConfig(configKey{counter: c.r.configVersionID.Load()}, conf) |
| 1213 |
if err != nil { |
| 1214 |
return err |
| 1215 |
} |
| 1216 |
sameLen := len(oldConf.configs.Languages) == len(newConf.configs.Languages) |
| 1217 |
if !sameLen { |
| 1218 |
if oldConf.configs.IsMultihost || newConf.configs.IsMultihost { |
| 1219 |
return errors.New("multihost change detected, please restart server") |
| 1220 |
} |
| 1221 |
} |
| 1222 |
c.conf = newConf |
| 1223 |
return nil |
| 1224 |
}); err != nil { |
| 1225 |
return err |
| 1226 |
} |
| 1227 |
|
| 1228 |
if c.onConfigLoaded != nil { |
| 1229 |
if err := c.onConfigLoaded(true); err != nil { |
| 1230 |
return err |
| 1231 |
} |
| 1232 |
} |
| 1233 |
|
| 1234 |
return nil |
| 1235 |
} |