| 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 modules |
| 15 |
|
| 16 |
import ( |
| 17 |
"bufio" |
| 18 |
"bytes" |
| 19 |
"context" |
| 20 |
"encoding/json" |
| 21 |
"errors" |
| 22 |
"fmt" |
| 23 |
"io" |
| 24 |
"os" |
| 25 |
"os/exec" |
| 26 |
"path/filepath" |
| 27 |
"regexp" |
| 28 |
"sort" |
| 29 |
"strings" |
| 30 |
"time" |
| 31 |
|
| 32 |
"github.com/gohugoio/hugo/common/collections" |
| 33 |
"github.com/gohugoio/hugo/common/hashing" |
| 34 |
"github.com/gohugoio/hugo/common/herrors" |
| 35 |
"github.com/gohugoio/hugo/common/hexec" |
| 36 |
"github.com/gohugoio/hugo/common/hugio" |
| 37 |
"github.com/gohugoio/hugo/common/loggers" |
| 38 |
"github.com/gohugoio/hugo/config" |
| 39 |
|
| 40 |
hglob "github.com/gohugoio/hugo/hugofs/hglob" |
| 41 |
|
| 42 |
"github.com/gobwas/glob" |
| 43 |
|
| 44 |
"github.com/gohugoio/hugo/hugofs" |
| 45 |
|
| 46 |
"github.com/gohugoio/hugo/hugofs/files" |
| 47 |
|
| 48 |
"golang.org/x/mod/module" |
| 49 |
|
| 50 |
"github.com/spf13/afero" |
| 51 |
) |
| 52 |
|
| 53 |
var fileSeparator = string(os.PathSeparator) |
| 54 |
|
| 55 |
const ( |
| 56 |
goBinaryStatusOK goBinaryStatus = iota |
| 57 |
goBinaryStatusNotFound |
| 58 |
goBinaryStatusTooOld |
| 59 |
) |
| 60 |
|
| 61 |
// The "vendor" dir is reserved for Go Modules. |
| 62 |
const vendord = "_vendor" |
| 63 |
|
| 64 |
const ( |
| 65 |
goModFilename = "go.mod" |
| 66 |
goSumFilename = "go.sum" |
| 67 |
|
| 68 |
// Checksum file for direct dependencies only, |
| 69 |
// that is, module imports with version set. |
| 70 |
hugoDirectSumFilename = "hugo.direct.sum" |
| 71 |
) |
| 72 |
|
| 73 |
// NewClient creates a new Client that can be used to manage the Hugo Components |
| 74 |
// in a given workingDir. |
| 75 |
// The Client will resolve the dependencies recursively, but needs the top |
| 76 |
// level imports to start out. |
| 77 |
func NewClient(cfg ClientConfig) *Client { |
| 78 |
fs := cfg.Fs |
| 79 |
n := filepath.Join(cfg.WorkingDir, goModFilename) |
| 80 |
goModEnabled, _ := afero.Exists(fs, n) |
| 81 |
var goModFilename string |
| 82 |
if goModEnabled { |
| 83 |
goModFilename = n |
| 84 |
} |
| 85 |
|
| 86 |
logger := cfg.Logger |
| 87 |
if logger == nil { |
| 88 |
logger = loggers.NewDefault() |
| 89 |
} |
| 90 |
|
| 91 |
var noVendor glob.Glob |
| 92 |
if cfg.ModuleConfig.NoVendor != "" { |
| 93 |
noVendor, _ = hglob.GetGlob(hglob.NormalizePath(cfg.ModuleConfig.NoVendor)) |
| 94 |
} |
| 95 |
|
| 96 |
return &Client{ |
| 97 |
fs: fs, |
| 98 |
ccfg: cfg, |
| 99 |
logger: logger, |
| 100 |
noVendor: noVendor, |
| 101 |
moduleConfig: cfg.ModuleConfig, |
| 102 |
environ: cfg.toEnv(), |
| 103 |
GoModulesFilename: goModFilename, |
| 104 |
} |
| 105 |
} |
| 106 |
|
| 107 |
// Client contains most of the API provided by this package. |
| 108 |
type Client struct { |
| 109 |
fs afero.Fs |
| 110 |
logger loggers.Logger |
| 111 |
|
| 112 |
noVendor glob.Glob |
| 113 |
|
| 114 |
ccfg ClientConfig |
| 115 |
|
| 116 |
// The top level module config |
| 117 |
moduleConfig Config |
| 118 |
|
| 119 |
// Environment variables used in "go get" etc. |
| 120 |
environ []string |
| 121 |
|
| 122 |
// Set when Go modules are initialized in the current repo, that is: |
| 123 |
// a go.mod file exists. |
| 124 |
GoModulesFilename string |
| 125 |
|
| 126 |
// Set if we get a exec.ErrNotFound when running Go, which is most likely |
| 127 |
// due to being run on a system without Go installed. We record it here |
| 128 |
// so we can give an instructional error at the end if module/theme |
| 129 |
// resolution fails. |
| 130 |
goBinaryStatus goBinaryStatus |
| 131 |
} |
| 132 |
|
| 133 |
// Graph writes a module dependency graph to the given writer. |
| 134 |
func (c *Client) Graph(w io.Writer) error { |
| 135 |
mc, coll := c.collect(true) |
| 136 |
if coll.err != nil { |
| 137 |
return coll.err |
| 138 |
} |
| 139 |
for _, module := range mc.AllModules { |
| 140 |
if module.Owner() == nil { |
| 141 |
continue |
| 142 |
} |
| 143 |
|
| 144 |
dep := pathVersion(module.Owner()) + " " + pathVersion(module) |
| 145 |
if replace := module.Replace(); replace != nil { |
| 146 |
if replace.Version() != "" { |
| 147 |
dep += " => " + pathVersion(replace) |
| 148 |
} else { |
| 149 |
// Local dir. |
| 150 |
dep += " => " + replace.Dir() |
| 151 |
} |
| 152 |
} |
| 153 |
fmt.Fprintln(w, dep) |
| 154 |
} |
| 155 |
|
| 156 |
return nil |
| 157 |
} |
| 158 |
|
| 159 |
// Tidy can be used to remove unused dependencies from go.mod and go.sum. |
| 160 |
func (c *Client) Tidy() error { |
| 161 |
tc, coll := c.collect(false) |
| 162 |
if coll.err != nil { |
| 163 |
return coll.err |
| 164 |
} |
| 165 |
|
| 166 |
if coll.skipTidy { |
| 167 |
return nil |
| 168 |
} |
| 169 |
|
| 170 |
return c.tidy(tc.AllModules, false) |
| 171 |
} |
| 172 |
|
| 173 |
// Vendor writes all the module dependencies to a _vendor folder. |
| 174 |
// |
| 175 |
// Unlike Go, we support it for any level. |
| 176 |
// |
| 177 |
// We, by default, use the /_vendor folder first, if found. To disable, |
| 178 |
// run with |
| 179 |
// |
| 180 |
// hugo --ignoreVendorPaths=".*" |
| 181 |
// |
| 182 |
// Given a module tree, Hugo will pick the first module for a given path, |
| 183 |
// meaning that if the top-level module is vendored, that will be the full |
| 184 |
// set of dependencies. |
| 185 |
func (c *Client) Vendor() error { |
| 186 |
vendorDir := filepath.Join(c.ccfg.WorkingDir, vendord) |
| 187 |
if err := c.rmVendorDir(vendorDir); err != nil { |
| 188 |
return err |
| 189 |
} |
| 190 |
if err := c.fs.MkdirAll(vendorDir, 0o755); err != nil { |
| 191 |
return err |
| 192 |
} |
| 193 |
|
| 194 |
// Write the modules list to modules.txt. |
| 195 |
// |
| 196 |
// On the form: |
| 197 |
// |
| 198 |
// # github.com/alecthomas/chroma v0.6.3 |
| 199 |
// |
| 200 |
// This is how "go mod vendor" does it. Go also lists |
| 201 |
// the packages below it, but that is currently not applicable to us. |
| 202 |
// |
| 203 |
var modulesContent bytes.Buffer |
| 204 |
|
| 205 |
tc, coll := c.collect(true) |
| 206 |
if coll.err != nil { |
| 207 |
return coll.err |
| 208 |
} |
| 209 |
|
| 210 |
for _, t := range tc.AllModules { |
| 211 |
if t.Owner() == nil { |
| 212 |
// This is the project. |
| 213 |
continue |
| 214 |
} |
| 215 |
|
| 216 |
if c.shouldNotVendor(t.PathVersionQuery(false)) || c.shouldNotVendor(t.PathVersionQuery(true)) { |
| 217 |
continue |
| 218 |
} |
| 219 |
|
| 220 |
if !t.IsGoMod() && !t.Vendor() { |
| 221 |
// We currently do not vendor components living in the |
| 222 |
// theme directory, see https://github.com/gohugoio/hugo/issues/5993 |
| 223 |
continue |
| 224 |
} |
| 225 |
|
| 226 |
// See https://github.com/gohugoio/hugo/issues/8239 |
| 227 |
// This is an error situation. We need something to vendor. |
| 228 |
if t.Mounts() == nil { |
| 229 |
return fmt.Errorf("cannot vendor module %q, need at least one mount", t.PathVersionQuery(false)) |
| 230 |
} |
| 231 |
|
| 232 |
fmt.Fprintln(&modulesContent, "# "+t.PathVersionQuery(true)+" "+t.Version()) |
| 233 |
|
| 234 |
dir := t.Dir() |
| 235 |
|
| 236 |
for _, mount := range t.Mounts() { |
| 237 |
sourceFilename := filepath.Join(dir, mount.Source) |
| 238 |
targetFilename := filepath.Join(vendorDir, t.PathVersionQuery(true), mount.Source) |
| 239 |
fi, err := c.fs.Stat(sourceFilename) |
| 240 |
if err != nil { |
| 241 |
return fmt.Errorf("failed to vendor module: %w", err) |
| 242 |
} |
| 243 |
|
| 244 |
if fi.IsDir() { |
| 245 |
if err := hugio.CopyDir(c.fs, sourceFilename, targetFilename, nil); err != nil { |
| 246 |
return fmt.Errorf("failed to copy module to vendor dir: %w", err) |
| 247 |
} |
| 248 |
} else { |
| 249 |
targetDir := filepath.Dir(targetFilename) |
| 250 |
|
| 251 |
if err := c.fs.MkdirAll(targetDir, 0o755); err != nil { |
| 252 |
return fmt.Errorf("failed to make target dir: %w", err) |
| 253 |
} |
| 254 |
|
| 255 |
if err := hugio.CopyFile(c.fs, sourceFilename, targetFilename); err != nil { |
| 256 |
return fmt.Errorf("failed to copy module file to vendor: %w", err) |
| 257 |
} |
| 258 |
} |
| 259 |
} |
| 260 |
|
| 261 |
// Include the resource cache if present. |
| 262 |
resourcesDir := filepath.Join(dir, files.FolderResources) |
| 263 |
_, err := c.fs.Stat(resourcesDir) |
| 264 |
if err == nil { |
| 265 |
if err := hugio.CopyDir(c.fs, resourcesDir, filepath.Join(vendorDir, t.PathVersionQuery(true), files.FolderResources), nil); err != nil { |
| 266 |
return fmt.Errorf("failed to copy resources to vendor dir: %w", err) |
| 267 |
} |
| 268 |
} |
| 269 |
|
| 270 |
// Include the config directory if present. |
| 271 |
configDir := filepath.Join(dir, "config") |
| 272 |
_, err = c.fs.Stat(configDir) |
| 273 |
if err == nil { |
| 274 |
if err := hugio.CopyDir(c.fs, configDir, filepath.Join(vendorDir, t.PathVersionQuery(true), "config"), nil); err != nil { |
| 275 |
return fmt.Errorf("failed to copy config dir to vendor dir: %w", err) |
| 276 |
} |
| 277 |
} |
| 278 |
|
| 279 |
// Also include any theme.toml or config.* or hugo.* files in the root. |
| 280 |
configFiles, _ := afero.Glob(c.fs, filepath.Join(dir, "config.*")) |
| 281 |
configFiles2, _ := afero.Glob(c.fs, filepath.Join(dir, "hugo.*")) |
| 282 |
configFiles = append(configFiles, configFiles2...) |
| 283 |
configFiles = append(configFiles, filepath.Join(dir, "theme.toml")) |
| 284 |
for _, configFile := range configFiles { |
| 285 |
if err := hugio.CopyFile(c.fs, configFile, filepath.Join(vendorDir, t.PathVersionQuery(true), filepath.Base(configFile))); err != nil { |
| 286 |
if !herrors.IsNotExist(err) { |
| 287 |
return err |
| 288 |
} |
| 289 |
} |
| 290 |
} |
| 291 |
} |
| 292 |
|
| 293 |
if modulesContent.Len() > 0 { |
| 294 |
if err := afero.WriteFile(c.fs, filepath.Join(vendorDir, vendorModulesFilename), modulesContent.Bytes(), 0o666); err != nil { |
| 295 |
return err |
| 296 |
} |
| 297 |
} |
| 298 |
|
| 299 |
return nil |
| 300 |
} |
| 301 |
|
| 302 |
// Get runs "go get" with the supplied arguments. |
| 303 |
func (c *Client) Get(args ...string) error { |
| 304 |
if len(args) == 0 || (len(args) == 1 && strings.Contains(args[0], "-u")) { |
| 305 |
update := len(args) != 0 |
| 306 |
patch := update && (args[0] == "-u=patch") // |
| 307 |
|
| 308 |
// We need to be explicit about the modules to get. |
| 309 |
var modules []string |
| 310 |
// Update all active modules if the -u flag presents. |
| 311 |
if update { |
| 312 |
mc, coll := c.collect(true) |
| 313 |
if coll.err != nil { |
| 314 |
return coll.err |
| 315 |
} |
| 316 |
for _, m := range mc.AllModules { |
| 317 |
if m.Owner() == nil || !isProbablyModule(m.Path()) { |
| 318 |
continue |
| 319 |
} |
| 320 |
modules = append(modules, m.Path()) |
| 321 |
} |
| 322 |
} else { |
| 323 |
for _, m := range c.moduleConfig.Imports { |
| 324 |
if !isProbablyModule(m.Path) { |
| 325 |
// Skip themes/components stored below /themes etc. |
| 326 |
// There may be false positives in the above, but those |
| 327 |
// should be rare, and they will fail below with an |
| 328 |
// "cannot find module providing ..." message. |
| 329 |
continue |
| 330 |
} |
| 331 |
modules = append(modules, m.Path) |
| 332 |
} |
| 333 |
} |
| 334 |
|
| 335 |
for _, m := range modules { |
| 336 |
var args []string |
| 337 |
|
| 338 |
if update && !patch { |
| 339 |
args = append(args, "-u") |
| 340 |
} else if update && patch { |
| 341 |
args = append(args, "-u=patch") |
| 342 |
} |
| 343 |
args = append(args, m) |
| 344 |
|
| 345 |
if err := c.get(args...); err != nil { |
| 346 |
return err |
| 347 |
} |
| 348 |
} |
| 349 |
|
| 350 |
return nil |
| 351 |
} |
| 352 |
|
| 353 |
return c.get(args...) |
| 354 |
} |
| 355 |
|
| 356 |
func (c *Client) get(args ...string) error { |
| 357 |
if err := c.runGo(context.Background(), c.logger.StdOut(), append([]string{"get"}, args...)...); err != nil { |
| 358 |
return fmt.Errorf("failed to get %q: %w", args, err) |
| 359 |
} |
| 360 |
return nil |
| 361 |
} |
| 362 |
|
| 363 |
// Init initializes this as a Go Module with the given path. |
| 364 |
// If path is empty, Go will try to guess. |
| 365 |
// If this succeeds, this project will be marked as Go Module. |
| 366 |
func (c *Client) Init(path string) error { |
| 367 |
err := c.runGo(context.Background(), c.logger.StdOut(), "mod", "init", path) |
| 368 |
if err != nil { |
| 369 |
return fmt.Errorf("failed to init modules: %w", err) |
| 370 |
} |
| 371 |
|
| 372 |
c.GoModulesFilename = filepath.Join(c.ccfg.WorkingDir, goModFilename) |
| 373 |
|
| 374 |
return nil |
| 375 |
} |
| 376 |
|
| 377 |
var verifyErrorDirRe = regexp.MustCompile(`dir has been modified \((.*?)\)`) |
| 378 |
|
| 379 |
// Verify checks that the dependencies of the current module, |
| 380 |
// which are stored in a local downloaded source cache, have not been |
| 381 |
// modified since being downloaded. |
| 382 |
func (c *Client) Verify(clean bool) error { |
| 383 |
// TODO(bep) add path to mod clean |
| 384 |
err := c.runVerify() |
| 385 |
if err != nil { |
| 386 |
if clean { |
| 387 |
m := verifyErrorDirRe.FindAllStringSubmatch(err.Error(), -1) |
| 388 |
for i := range m { |
| 389 |
c, err := hugofs.MakeReadableAndRemoveAllModulePkgDir(c.fs, m[i][1]) |
| 390 |
if err != nil { |
| 391 |
return err |
| 392 |
} |
| 393 |
fmt.Println("Cleaned", c) |
| 394 |
} |
| 395 |
// Try to verify it again. |
| 396 |
err = c.runVerify() |
| 397 |
} |
| 398 |
} |
| 399 |
return err |
| 400 |
} |
| 401 |
|
| 402 |
func (c *Client) Clean(pattern string) error { |
| 403 |
mods, err := c.listGoMods() |
| 404 |
if err != nil { |
| 405 |
return err |
| 406 |
} |
| 407 |
|
| 408 |
var g glob.Glob |
| 409 |
|
| 410 |
if pattern != "" { |
| 411 |
var err error |
| 412 |
g, err = hglob.GetGlob(pattern) |
| 413 |
if err != nil { |
| 414 |
return err |
| 415 |
} |
| 416 |
} |
| 417 |
|
| 418 |
for _, m := range mods { |
| 419 |
if m.Replace != nil || m.Main { |
| 420 |
continue |
| 421 |
} |
| 422 |
|
| 423 |
if g != nil && !g.Match(m.Path) { |
| 424 |
continue |
| 425 |
} |
| 426 |
dirCount, err := hugofs.MakeReadableAndRemoveAllModulePkgDir(c.fs, m.Dir) |
| 427 |
if err == nil { |
| 428 |
c.logger.Printf("hugo: removed %d dirs in module cache for %q", dirCount, m.Path) |
| 429 |
} |
| 430 |
} |
| 431 |
return err |
| 432 |
} |
| 433 |
|
| 434 |
func (c *Client) runVerify() error { |
| 435 |
return c.runGo(context.Background(), io.Discard, "mod", "verify") |
| 436 |
} |
| 437 |
|
| 438 |
func isProbablyModule(path string) bool { |
| 439 |
return module.CheckPath(path) == nil |
| 440 |
} |
| 441 |
|
| 442 |
func (c *Client) downloadModuleVersion(path, version string) (*goModule, error) { |
| 443 |
// If it's already cached, use it. |
| 444 |
const keyPrefix = "downloadmoduleversion_" |
| 445 |
cacheKey := keyPrefix + hashing.XxHashFromStringHexEncoded(c.ccfg.CacheDir, path, version) + ".json" |
| 446 |
if b, _ := c.ccfg.ModuleQueriesCache.GetBytes(cacheKey); len(b) > 0 { |
| 447 |
var cm goModule |
| 448 |
if err := json.Unmarshal(b, &cm); err == nil && cm.Dir != "" { |
| 449 |
if c.isDirNonEmpty(cm.Dir) { |
| 450 |
return &cm, nil |
| 451 |
} |
| 452 |
} |
| 453 |
} |
| 454 |
|
| 455 |
// No valid cache, need to query. |
| 456 |
args := []string{"mod", "download", "-json", fmt.Sprintf("%s@%s", path, version)} |
| 457 |
|
| 458 |
b := &bytes.Buffer{} |
| 459 |
err := c.runGo(context.Background(), b, args...) |
| 460 |
if err != nil { |
| 461 |
// The -json flag makes Go output error details as JSON to stdout |
| 462 |
// even on failure. Try to extract the error message from the JSON output. |
| 463 |
if jsonErr := extractGoModDownloadError(b.Bytes()); jsonErr != "" { |
| 464 |
return nil, fmt.Errorf("failed to download module %s@%s: %s: %s", path, version, err, jsonErr) |
| 465 |
} |
| 466 |
return nil, fmt.Errorf("failed to download module %s@%s: %w", path, version, err) |
| 467 |
} |
| 468 |
|
| 469 |
jsonResult := b.Bytes() |
| 470 |
|
| 471 |
m := &goModule{} |
| 472 |
if err := json.NewDecoder(bytes.NewReader(jsonResult)).Decode(m); err != nil { |
| 473 |
return nil, fmt.Errorf("failed to decode module download result: %w", err) |
| 474 |
} |
| 475 |
|
| 476 |
if m.Error != nil { |
| 477 |
return nil, errors.New(m.Error.Err) |
| 478 |
} |
| 479 |
|
| 480 |
// Cache the successful result if it has a Dir field. |
| 481 |
if m.Dir != "" { |
| 482 |
_ = c.ccfg.ModuleQueriesCache.SetBytes(cacheKey, jsonResult) |
| 483 |
} |
| 484 |
|
| 485 |
return m, nil |
| 486 |
} |
| 487 |
|
| 488 |
// isDirNonEmpty returns true if dir exists and contains at least one file or subdirectory. |
| 489 |
func (c *Client) isDirNonEmpty(dir string) bool { |
| 490 |
f, err := c.fs.Open(dir) |
| 491 |
if err != nil { |
| 492 |
return false |
| 493 |
} |
| 494 |
defer f.Close() |
| 495 |
// Read just one entry to check if directory is non-empty. |
| 496 |
_, err = f.Readdirnames(1) |
| 497 |
return err == nil |
| 498 |
} |
| 499 |
|
| 500 |
func (c *Client) listGoMods() (goModules, error) { |
| 501 |
if c.GoModulesFilename == "" || !c.moduleConfig.hasModuleImport() { |
| 502 |
return nil, nil |
| 503 |
} |
| 504 |
|
| 505 |
downloadModules := func(modules ...string) error { |
| 506 |
args := []string{"mod", "download"} |
| 507 |
args = append(args, modules...) |
| 508 |
out := io.Discard |
| 509 |
err := c.runGo(context.Background(), out, args...) |
| 510 |
if err != nil { |
| 511 |
return fmt.Errorf("failed to download modules: %w", err) |
| 512 |
} |
| 513 |
return nil |
| 514 |
} |
| 515 |
|
| 516 |
if err := downloadModules(); err != nil { |
| 517 |
return nil, err |
| 518 |
} |
| 519 |
|
| 520 |
listAndDecodeModules := func(handle func(m *goModule) error, modules ...string) error { |
| 521 |
b := &bytes.Buffer{} |
| 522 |
args := []string{"list", "-m", "-json"} |
| 523 |
if len(modules) > 0 { |
| 524 |
args = append(args, modules...) |
| 525 |
} else { |
| 526 |
args = append(args, "all") |
| 527 |
} |
| 528 |
err := c.runGo(context.Background(), b, args...) |
| 529 |
if err != nil { |
| 530 |
return fmt.Errorf("failed to list modules: %w", err) |
| 531 |
} |
| 532 |
|
| 533 |
dec := json.NewDecoder(b) |
| 534 |
for { |
| 535 |
m := &goModule{} |
| 536 |
if err := dec.Decode(m); err != nil { |
| 537 |
if err == io.EOF { |
| 538 |
break |
| 539 |
} |
| 540 |
return fmt.Errorf("failed to decode modules list: %w", err) |
| 541 |
} |
| 542 |
|
| 543 |
if err := handle(m); err != nil { |
| 544 |
return err |
| 545 |
} |
| 546 |
} |
| 547 |
return nil |
| 548 |
} |
| 549 |
|
| 550 |
var modules goModules |
| 551 |
err := listAndDecodeModules(func(m *goModule) error { |
| 552 |
modules = append(modules, m) |
| 553 |
return nil |
| 554 |
}) |
| 555 |
if err != nil { |
| 556 |
return nil, err |
| 557 |
} |
| 558 |
|
| 559 |
// From Go 1.17, go lazy loads transitive dependencies. |
| 560 |
// That does not work for us. |
| 561 |
// So, download these modules and update the Dir in the modules list. |
| 562 |
var modulesToDownload []string |
| 563 |
for _, m := range modules { |
| 564 |
if m.Dir == "" { |
| 565 |
modulesToDownload = append(modulesToDownload, fmt.Sprintf("%s@%s", m.Path, m.Version)) |
| 566 |
} |
| 567 |
|
| 568 |
// See https://github.com/golang/go/issues/67363 |
| 569 |
// Origin isn't always set. |
| 570 |
if m.Origin == nil && m.GoMod != "" { |
| 571 |
// There's sometimes an Info field with a JSON filename with this info, but that is also not always set. |
| 572 |
// But we seem to always get the go.mod filename, so we can determine the info filename from that, |
| 573 |
// just replace the .mod suffix with .info. |
| 574 |
infoFilename := strings.TrimSuffix(m.GoMod, ".mod") + ".info" |
| 575 |
// JSON on the form {"Version":"v0.0.0-20260225095909-668663b54d09","Time":"2026-02-25T09:59:09Z","Origin":{"VCS":"git","URL":"https://github.com/bep/hugo-mod-testing-content","Hash":"668663b54d0937df05185d144765d13c3ffda489"}} |
| 576 |
if b, err := afero.ReadFile(c.fs, infoFilename); err == nil { |
| 577 |
var info struct { |
| 578 |
Version string |
| 579 |
Time time.Time |
| 580 |
Origin *goModuleOrigin |
| 581 |
} |
| 582 |
if err := json.Unmarshal(b, &info); err == nil { |
| 583 |
m.Origin = info.Origin |
| 584 |
} |
| 585 |
} |
| 586 |
} |
| 587 |
} |
| 588 |
|
| 589 |
if len(modulesToDownload) > 0 { |
| 590 |
if err := downloadModules(modulesToDownload...); err != nil { |
| 591 |
return nil, err |
| 592 |
} |
| 593 |
err := listAndDecodeModules(func(m *goModule) error { |
| 594 |
if mm := modules.GetByPath(m.Path); mm != nil { |
| 595 |
mm.Dir = m.Dir |
| 596 |
} |
| 597 |
return nil |
| 598 |
}, modulesToDownload...) |
| 599 |
if err != nil { |
| 600 |
return nil, err |
| 601 |
} |
| 602 |
} |
| 603 |
|
| 604 |
return modules, err |
| 605 |
} |
| 606 |
|
| 607 |
func (c *Client) writeHugoDirectSum(mods Modules) error { |
| 608 |
if c.GoModulesFilename == "" { |
| 609 |
return nil |
| 610 |
} |
| 611 |
var sums []modSum |
| 612 |
for _, m := range mods { |
| 613 |
if m.Owner() == nil { |
| 614 |
// This is the project. |
| 615 |
continue |
| 616 |
} |
| 617 |
if m.IsGoMod() && m.VersionQuery() != "" { |
| 618 |
sums = append(sums, modSum{pathVersionKey: pathVersionKey{path: m.Path(), version: m.Version()}, sum: m.Sum()}) |
| 619 |
} |
| 620 |
} |
| 621 |
|
| 622 |
// Read the existing sums. |
| 623 |
existingSums, err := c.readModSumFile(hugoDirectSumFilename) |
| 624 |
if err != nil { |
| 625 |
return err |
| 626 |
} |
| 627 |
if len(sums) == 0 && len(existingSums) == 0 { |
| 628 |
// Nothing to do. |
| 629 |
return nil |
| 630 |
} |
| 631 |
|
| 632 |
dirty := len(sums) != len(existingSums) |
| 633 |
for _, s1 := range sums { |
| 634 |
if s2, ok := existingSums[s1.pathVersionKey]; ok { |
| 635 |
if s1.sum != s2 { |
| 636 |
return fmt.Errorf("verifying %s@%s: checksum mismatch: %s != %s", s1.path, s1.version, s1.sum, s2) |
| 637 |
} |
| 638 |
} else if !dirty { |
| 639 |
dirty = true |
| 640 |
} |
| 641 |
} |
| 642 |
if !dirty { |
| 643 |
// Nothing changed. |
| 644 |
return nil |
| 645 |
} |
| 646 |
|
| 647 |
// Write the sums file. |
| 648 |
// First sort the sums for reproducible output. |
| 649 |
sort.Slice(sums, func(i, j int) bool { |
| 650 |
pvi, pvj := sums[i].pathVersionKey, sums[j].pathVersionKey |
| 651 |
return pvi.path < pvj.path || (pvi.path == pvj.path && pvi.version < pvj.version) |
| 652 |
}) |
| 653 |
|
| 654 |
f, err := c.fs.OpenFile(filepath.Join(c.ccfg.WorkingDir, hugoDirectSumFilename), os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o666) |
| 655 |
if err != nil { |
| 656 |
return err |
| 657 |
} |
| 658 |
defer f.Close() |
| 659 |
|
| 660 |
for _, s := range sums { |
| 661 |
fmt.Fprintf(f, "%s %s %s\n", s.pathVersionKey.path, s.pathVersionKey.version, s.sum) |
| 662 |
} |
| 663 |
|
| 664 |
return nil |
| 665 |
} |
| 666 |
|
| 667 |
func (c *Client) readModSumFile(filename string) (map[pathVersionKey]string, error) { |
| 668 |
b, err := afero.ReadFile(c.fs, filepath.Join(c.ccfg.WorkingDir, filename)) |
| 669 |
if err != nil { |
| 670 |
if herrors.IsNotExist(err) { |
| 671 |
return make(map[pathVersionKey]string), nil |
| 672 |
} |
| 673 |
return nil, err |
| 674 |
} |
| 675 |
lines := bytes.Split(b, []byte{'\n'}) |
| 676 |
sums := make(map[pathVersionKey]string) |
| 677 |
for _, line := range lines { |
| 678 |
parts := bytes.Fields(line) |
| 679 |
if len(parts) == 3 { |
| 680 |
sums[pathVersionKey{path: string(parts[0]), version: string(parts[1])}] = string(parts[2]) |
| 681 |
} |
| 682 |
} |
| 683 |
|
| 684 |
return sums, nil |
| 685 |
} |
| 686 |
|
| 687 |
func (c *Client) rewriteGoMod(name string, isGoMod map[string]bool) error { |
| 688 |
data, err := c.rewriteGoModRewrite(name, isGoMod) |
| 689 |
if err != nil { |
| 690 |
return err |
| 691 |
} |
| 692 |
if data != nil { |
| 693 |
if err := afero.WriteFile(c.fs, filepath.Join(c.ccfg.WorkingDir, name), data, 0o666); err != nil { |
| 694 |
return err |
| 695 |
} |
| 696 |
} |
| 697 |
|
| 698 |
return nil |
| 699 |
} |
| 700 |
|
| 701 |
func (c *Client) rewriteGoModRewrite(name string, isGoMod map[string]bool) ([]byte, error) { |
| 702 |
if name == goModFilename && c.GoModulesFilename == "" { |
| 703 |
// Already checked. |
| 704 |
return nil, nil |
| 705 |
} |
| 706 |
|
| 707 |
modlineSplitter := getModlineSplitter(name == goModFilename) |
| 708 |
|
| 709 |
b := &bytes.Buffer{} |
| 710 |
f, err := c.fs.Open(filepath.Join(c.ccfg.WorkingDir, name)) |
| 711 |
if err != nil { |
| 712 |
if herrors.IsNotExist(err) { |
| 713 |
// It's been deleted. |
| 714 |
return nil, nil |
| 715 |
} |
| 716 |
return nil, err |
| 717 |
} |
| 718 |
defer f.Close() |
| 719 |
|
| 720 |
scanner := bufio.NewScanner(f) |
| 721 |
var dirty bool |
| 722 |
|
| 723 |
for scanner.Scan() { |
| 724 |
line := scanner.Text() |
| 725 |
var doWrite bool |
| 726 |
|
| 727 |
if parts := modlineSplitter(line); parts != nil { |
| 728 |
modname, modver := parts[0], parts[1] |
| 729 |
modver = strings.TrimSuffix(modver, "/"+goModFilename) |
| 730 |
modnameVer := modname + " " + modver |
| 731 |
doWrite = isGoMod[modnameVer] |
| 732 |
} else { |
| 733 |
doWrite = true |
| 734 |
} |
| 735 |
|
| 736 |
if doWrite { |
| 737 |
fmt.Fprintln(b, line) |
| 738 |
} else { |
| 739 |
dirty = true |
| 740 |
} |
| 741 |
} |
| 742 |
|
| 743 |
if !dirty { |
| 744 |
// Nothing changed |
| 745 |
return nil, nil |
| 746 |
} |
| 747 |
|
| 748 |
return b.Bytes(), nil |
| 749 |
} |
| 750 |
|
| 751 |
func (c *Client) rmVendorDir(vendorDir string) error { |
| 752 |
modulestxt := filepath.Join(vendorDir, vendorModulesFilename) |
| 753 |
|
| 754 |
if _, err := c.fs.Stat(vendorDir); err != nil { |
| 755 |
return nil |
| 756 |
} |
| 757 |
|
| 758 |
_, err := c.fs.Stat(modulestxt) |
| 759 |
if err != nil { |
| 760 |
// If we have a _vendor dir without modules.txt it sounds like |
| 761 |
// a _vendor dir created by others. |
| 762 |
return errors.New("found _vendor dir without modules.txt, skip delete") |
| 763 |
} |
| 764 |
|
| 765 |
return c.fs.RemoveAll(vendorDir) |
| 766 |
} |
| 767 |
|
| 768 |
func (c *Client) runGo( |
| 769 |
ctx context.Context, |
| 770 |
stdout io.Writer, |
| 771 |
args ...string, |
| 772 |
) error { |
| 773 |
if c.goBinaryStatus != 0 { |
| 774 |
return nil |
| 775 |
} |
| 776 |
|
| 777 |
stderr := new(bytes.Buffer) |
| 778 |
|
| 779 |
argsv := collections.StringSliceToInterfaceSlice(args) |
| 780 |
argsv = append(argsv, hexec.WithEnviron(c.environ)) |
| 781 |
argsv = append(argsv, hexec.WithStderr(goOutputReplacerWriter{w: io.MultiWriter(stderr, os.Stderr)})) |
| 782 |
argsv = append(argsv, hexec.WithStdout(stdout)) |
| 783 |
argsv = append(argsv, hexec.WithDir(c.ccfg.WorkingDir)) |
| 784 |
argsv = append(argsv, hexec.WithContext(ctx)) |
| 785 |
|
| 786 |
cmd, err := c.ccfg.Exec.New("go", argsv...) |
| 787 |
if err != nil { |
| 788 |
return err |
| 789 |
} |
| 790 |
|
| 791 |
if err := cmd.Run(); err != nil { |
| 792 |
if ee, ok := err.(*exec.Error); ok && ee.Err == exec.ErrNotFound { |
| 793 |
c.goBinaryStatus = goBinaryStatusNotFound |
| 794 |
return nil |
| 795 |
} |
| 796 |
|
| 797 |
if strings.Contains(stderr.String(), "invalid version: unknown revision") { |
| 798 |
// See https://github.com/gohugoio/hugo/issues/6825 |
| 799 |
c.logger.Println(`An unknown revision most likely means that someone has deleted the remote ref (e.g. with a force push to GitHub). |
| 800 |
To resolve this, you need to manually edit your go.mod file and replace the version for the module in question with a valid ref. |
| 801 |
|
| 802 |
The easiest is to just enter a valid branch name there, e.g. master, which would be what you put in place of 'v0.5.1' in the example below. |
| 803 |
|
| 804 |
require github.com/gohugoio/hugo-mod-jslibs/instantpage v0.5.1 |
| 805 |
|
| 806 |
If you then run 'hugo mod graph' it should resolve itself to the most recent version (or commit if no semver versions are available).`) |
| 807 |
} |
| 808 |
|
| 809 |
_, ok := err.(*exec.ExitError) |
| 810 |
if !ok { |
| 811 |
return fmt.Errorf("failed to execute 'go %v': %s %T", args, err, err) |
| 812 |
} |
| 813 |
|
| 814 |
// Too old Go version |
| 815 |
if strings.Contains(stderr.String(), "flag provided but not defined") { |
| 816 |
c.goBinaryStatus = goBinaryStatusTooOld |
| 817 |
return nil |
| 818 |
} |
| 819 |
|
| 820 |
return fmt.Errorf("go command failed: %s", stderr) |
| 821 |
|
| 822 |
} |
| 823 |
|
| 824 |
return nil |
| 825 |
} |
| 826 |
|
| 827 |
var goOutputReplacer = strings.NewReplacer( |
| 828 |
"go: to add module requirements and sums:", "hugo: to add module requirements and sums:", |
| 829 |
"go mod tidy", "hugo mod tidy", |
| 830 |
) |
| 831 |
|
| 832 |
type goOutputReplacerWriter struct { |
| 833 |
w io.Writer |
| 834 |
} |
| 835 |
|
| 836 |
func (w goOutputReplacerWriter) Write(p []byte) (n int, err error) { |
| 837 |
s := goOutputReplacer.Replace(string(p)) |
| 838 |
_, err = w.w.Write([]byte(s)) |
| 839 |
if err != nil { |
| 840 |
return 0, err |
| 841 |
} |
| 842 |
return len(p), nil |
| 843 |
} |
| 844 |
|
| 845 |
func (c *Client) tidy(mods Modules, goModOnly bool) error { |
| 846 |
isGoMod := make(map[string]bool) |
| 847 |
for _, m := range mods { |
| 848 |
if m.Owner() == nil { |
| 849 |
continue |
| 850 |
} |
| 851 |
if m.IsGoMod() { |
| 852 |
// Matching the format in go.mod |
| 853 |
pathVer := m.Path() + " " + m.Version() |
| 854 |
isGoMod[pathVer] = true |
| 855 |
} |
| 856 |
} |
| 857 |
|
| 858 |
if err := c.rewriteGoMod(goModFilename, isGoMod); err != nil { |
| 859 |
return err |
| 860 |
} |
| 861 |
|
| 862 |
if goModOnly { |
| 863 |
return nil |
| 864 |
} |
| 865 |
|
| 866 |
if err := c.rewriteGoMod(goSumFilename, isGoMod); err != nil { |
| 867 |
return err |
| 868 |
} |
| 869 |
|
| 870 |
return nil |
| 871 |
} |
| 872 |
|
| 873 |
func (c *Client) shouldNotVendor(path string) bool { |
| 874 |
return c.noVendor != nil && c.noVendor.Match(path) |
| 875 |
} |
| 876 |
|
| 877 |
func (c *Client) createThemeDirname(modulePath string, isProjectMod bool) (string, error) { |
| 878 |
invalid := fmt.Errorf("invalid module path %q; must be relative to themesDir when defined outside of the project", modulePath) |
| 879 |
|
| 880 |
modulePath = filepath.Clean(modulePath) |
| 881 |
if filepath.IsAbs(modulePath) { |
| 882 |
if isProjectMod { |
| 883 |
return modulePath, nil |
| 884 |
} |
| 885 |
return "", invalid |
| 886 |
} |
| 887 |
|
| 888 |
moduleDir := filepath.Join(c.ccfg.ThemesDir, modulePath) |
| 889 |
if !isProjectMod && !strings.HasPrefix(moduleDir, c.ccfg.ThemesDir) { |
| 890 |
return "", invalid |
| 891 |
} |
| 892 |
return moduleDir, nil |
| 893 |
} |
| 894 |
|
| 895 |
// ClientConfig configures the module Client. |
| 896 |
type ClientConfig struct { |
| 897 |
Fs afero.Fs |
| 898 |
Logger loggers.Logger |
| 899 |
|
| 900 |
// If set, it will be run before we do any duplicate checks for modules |
| 901 |
// etc. |
| 902 |
HookBeforeFinalize func(m *ModulesConfig) error |
| 903 |
|
| 904 |
// Ignore any _vendor directory for module paths matching the given pattern. |
| 905 |
// This can be nil. |
| 906 |
IgnoreVendor glob.Glob |
| 907 |
|
| 908 |
// Ignore any module not found errors. |
| 909 |
IgnoreModuleDoesNotExist bool |
| 910 |
|
| 911 |
// Absolute path to the project dir. |
| 912 |
WorkingDir string |
| 913 |
|
| 914 |
// Absolute path to the project's themes dir. |
| 915 |
ThemesDir string |
| 916 |
|
| 917 |
// The publish dir. |
| 918 |
PublishDir string |
| 919 |
|
| 920 |
// Eg. "production" |
| 921 |
Environment string |
| 922 |
|
| 923 |
Exec *hexec.Exec |
| 924 |
|
| 925 |
CacheDir string // Module cache |
| 926 |
ModuleQueriesCache ModuleQueriesCache |
| 927 |
ModuleConfig Config |
| 928 |
} |
| 929 |
|
| 930 |
// ModuleQueriesCache is a cache for module version queries. |
| 931 |
type ModuleQueriesCache interface { |
| 932 |
GetBytes(id string) ([]byte, error) |
| 933 |
SetBytes(id string, data []byte) error |
| 934 |
} |
| 935 |
|
| 936 |
func (c ClientConfig) shouldIgnoreVendor(path string) bool { |
| 937 |
return c.IgnoreVendor != nil && c.IgnoreVendor.Match(path) |
| 938 |
} |
| 939 |
|
| 940 |
func (cfg ClientConfig) toEnv() []string { |
| 941 |
mcfg := cfg.ModuleConfig |
| 942 |
var env []string |
| 943 |
keyVals := []string{ |
| 944 |
"PWD", cfg.WorkingDir, |
| 945 |
"GO111MODULE", "on", |
| 946 |
"GOFLAGS", "-modcacherw", |
| 947 |
"GOPATH", cfg.CacheDir, |
| 948 |
"GOWORK", mcfg.Workspace, // Requires Go 1.18, see https://tip.golang.org/doc/go1.18 |
| 949 |
// GOCACHE was introduced in Go 1.15. This matches the location derived from GOPATH above. |
| 950 |
"GOCACHE", filepath.Join(cfg.CacheDir, "pkg", "mod"), |
| 951 |
} |
| 952 |
|
| 953 |
if mcfg.Proxy != "" { |
| 954 |
keyVals = append(keyVals, "GOPROXY", mcfg.Proxy) |
| 955 |
} |
| 956 |
if mcfg.Private != "" { |
| 957 |
keyVals = append(keyVals, "GOPRIVATE", mcfg.Private) |
| 958 |
} |
| 959 |
if mcfg.NoProxy != "" { |
| 960 |
keyVals = append(keyVals, "GONOPROXY", mcfg.NoProxy) |
| 961 |
} |
| 962 |
if mcfg.Auth != "" { |
| 963 |
// GOAUTH was introduced in Go 1.24, see https://tip.golang.org/doc/go1.24. |
| 964 |
keyVals = append(keyVals, "GOAUTH", mcfg.Auth) |
| 965 |
} |
| 966 |
|
| 967 |
config.SetEnvVars(&env, keyVals...) |
| 968 |
|
| 969 |
return env |
| 970 |
} |
| 971 |
|
| 972 |
type goBinaryStatus int |
| 973 |
|
| 974 |
type goModule struct { |
| 975 |
Path string // module path |
| 976 |
Version string // module version |
| 977 |
Versions []string // available module versions (with -versions) |
| 978 |
Replace *goModule // replaced by this module |
| 979 |
Time *time.Time // time version was created |
| 980 |
Update *goModule // available update, if any (with -u) |
| 981 |
Sum string // checksum |
| 982 |
GoModSum string // checksum for go.mod |
| 983 |
Main bool // is this the main module? |
| 984 |
Indirect bool // is this module only an indirect dependency of main module? |
| 985 |
Dir string // directory holding files for this module, if any |
| 986 |
GoMod string // path to go.mod file for this module, if any |
| 987 |
Error *goModuleError // error loading module |
| 988 |
Origin *goModuleOrigin |
| 989 |
} |
| 990 |
|
| 991 |
type goModuleOrigin struct { |
| 992 |
VCS string // version control system, e.g. "git" |
| 993 |
URL string // repository URL, e.g. "https://github.com/bep/hugo-testing-git-versions" |
| 994 |
Subdir string // subdirectory within the repo where the module lives, e.g. "site" |
| 995 |
Hash string // commit hash |
| 996 |
TagSum string |
| 997 |
Ref string // e.g. "refs/tags/v3.0.1" |
| 998 |
} |
| 999 |
|
| 1000 |
type goModuleError struct { |
| 1001 |
Err string // the error itself |
| 1002 |
} |
| 1003 |
|
| 1004 |
func extractGoModDownloadError(b []byte) string { |
| 1005 |
// go mod download -json outputs Error as a plain string, |
| 1006 |
// unlike go list -m -json which uses {"Err": "..."}. |
| 1007 |
var m struct { |
| 1008 |
Error string |
| 1009 |
} |
| 1010 |
if err := json.Unmarshal(b, &m); err == nil && m.Error != "" { |
| 1011 |
return m.Error |
| 1012 |
} |
| 1013 |
return "" |
| 1014 |
} |
| 1015 |
|
| 1016 |
type goModules []*goModule |
| 1017 |
|
| 1018 |
type modSum struct { |
| 1019 |
pathVersionKey |
| 1020 |
sum string |
| 1021 |
} |
| 1022 |
|
| 1023 |
func (modules goModules) GetByPath(p string) *goModule { |
| 1024 |
if modules == nil { |
| 1025 |
return nil |
| 1026 |
} |
| 1027 |
|
| 1028 |
for _, m := range modules { |
| 1029 |
if strings.EqualFold(p, m.Path) { |
| 1030 |
return m |
| 1031 |
} |
| 1032 |
} |
| 1033 |
|
| 1034 |
return nil |
| 1035 |
} |
| 1036 |
|
| 1037 |
func (modules goModules) GetMain() *goModule { |
| 1038 |
for _, m := range modules { |
| 1039 |
if m.Main { |
| 1040 |
return m |
| 1041 |
} |
| 1042 |
} |
| 1043 |
|
| 1044 |
return nil |
| 1045 |
} |
| 1046 |
|
| 1047 |
func getModlineSplitter(isGoMod bool) func(line string) []string { |
| 1048 |
if isGoMod { |
| 1049 |
var inRequireBlock bool |
| 1050 |
return func(line string) []string { |
| 1051 |
if strings.HasPrefix(line, "require (") { |
| 1052 |
inRequireBlock = true |
| 1053 |
return nil |
| 1054 |
} |
| 1055 |
if inRequireBlock { |
| 1056 |
if strings.HasPrefix(line, ")") { |
| 1057 |
inRequireBlock = false |
| 1058 |
return nil |
| 1059 |
} |
| 1060 |
if !strings.HasPrefix(line, "\t") { |
| 1061 |
return nil |
| 1062 |
} |
| 1063 |
} else if !strings.HasPrefix(line, "require ") { |
| 1064 |
return nil |
| 1065 |
} |
| 1066 |
line = strings.TrimPrefix(line, "require") |
| 1067 |
line = strings.TrimSpace(line) |
| 1068 |
line = strings.TrimSuffix(line, "// indirect") |
| 1069 |
|
| 1070 |
parts := strings.Fields(line) |
| 1071 |
if len(parts) < 2 { |
| 1072 |
return nil |
| 1073 |
} |
| 1074 |
return parts |
| 1075 |
} |
| 1076 |
} |
| 1077 |
|
| 1078 |
return func(line string) []string { |
| 1079 |
return strings.Fields(line) |
| 1080 |
} |
| 1081 |
} |
| 1082 |
|
| 1083 |
func pathVersion(m Module) string { |
| 1084 |
versionStr := m.Version() |
| 1085 |
if m.Vendor() { |
| 1086 |
versionStr += "+vendor" |
| 1087 |
} |
| 1088 |
if versionStr == "" { |
| 1089 |
return m.Path() |
| 1090 |
} |
| 1091 |
return fmt.Sprintf("%s@%s", m.Path(), versionStr) |
| 1092 |
} |