Debian Codegraph @

commands/mod.go

raw
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 "os"
20 "path/filepath"
21
22 "github.com/bep/simplecobra"
23 "github.com/gohugoio/hugo/config"
24 "github.com/gohugoio/hugo/hugolib"
25 "github.com/gohugoio/hugo/modules/npm"
26 "github.com/spf13/cobra"
27 )
28
29 const commonUsageMod = `
30 Note that Hugo will always start out by resolving the components defined in the project
31 configuration, provided by a _vendor directory (if no --ignoreVendorPaths flag provided),
32 Go Modules, or a folder inside the themes directory, in that order.
33
34 See https://gohugo.io/hugo-modules/ for more information.
35
36 `
37
38 // buildConfigCommands creates a new config command and its subcommands.
39 func newModCommands() *modCommands {
40 var (
41 clean bool
42 pattern string
43 all bool
44 )
45
46 npmCommand := &simpleCommand{
47 name: "npm",
48 short: "Various npm helpers",
49 long: `Various npm (Node package manager) helpers.`,
50 commands: []simplecobra.Commander{
51 &simpleCommand{
52 name: "pack",
53 short: "Merges module Node.js dependencies into an npm workspace",
54 long: `Merges Node.js dependencies from all Hugo modules into a "packages/hugoautogen" npm workspace.
55
56 The merged dependencies are written to packages/hugoautogen/package.json, and the root package.json
57 is updated with a "workspaces" entry pointing to "packages/hugoautogen".
58
59 The source entries are read from either package.hugo.json or package.json in the module root, with package.hugo.json taking precedence if both exist.
60
61 See [Node.js dependencies](/hugo-modules/nodejs-dependencies/) for more information.
62 `,
63 withc: func(cmd *cobra.Command, r *rootCommand) {
64 cmd.ValidArgsFunction = cobra.NoFileCompletions
65 applyLocalFlagsBuildConfig(cmd, r)
66 },
67 run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error {
68 cfg := flagsToCfg(cd, nil)
69 k := configKey{counter: r.configVersionID.Load(), skipNpmCheck: true}
70 h, _, err := r.hugoSites.GetOrCreate(k, func(key configKey) (*hugolib.HugoSites, error) {
71 conf, err := r.ConfigFromProvider(key, cfg)
72 if err != nil {
73 return nil, err
74 }
75 return hugolib.NewHugoSites(r.newDepsConfig(conf))
76 })
77 if err != nil {
78 return err
79 }
80 return npm.Pack(h.BaseFs.ProjectSourceFs, h.BaseFs.AssetsWithDuplicatesPreserved.Fs, h.Configs.Modules)
81 },
82 },
83 },
84 }
85
86 return &modCommands{
87 commands: []simplecobra.Commander{
88 &simpleCommand{
89 name: "init",
90 short: "Initialize this project as a Hugo Module",
91 long: `Initialize this project as a Hugo Module.
92 It will try to guess the module path, but you may help by passing it as an argument, e.g:
93
94 hugo mod init github.com/gohugoio/testshortcodes
95
96 Note that Hugo Modules supports multi-module projects, so you can initialize a Hugo Module
97 inside a subfolder on GitHub, as one example.
98 `,
99 withc: func(cmd *cobra.Command, r *rootCommand) {
100 cmd.ValidArgsFunction = cobra.NoFileCompletions
101 applyLocalFlagsBuildConfig(cmd, r)
102 },
103 run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error {
104 h, err := r.getOrCreateHugo(flagsToCfg(cd, nil), true)
105 if err != nil {
106 return err
107 }
108 var initPath string
109 if len(args) >= 1 {
110 initPath = args[0]
111 }
112 c := h.Configs.ModulesClient
113 if err := c.Init(initPath); err != nil {
114 return err
115 }
116 return nil
117 },
118 },
119 &simpleCommand{
120 name: "verify",
121 short: "Verify dependencies",
122 long: `Verify checks that the dependencies of the current module, which are stored in a local downloaded source cache, have not been modified since being downloaded.`,
123 withc: func(cmd *cobra.Command, r *rootCommand) {
124 cmd.ValidArgsFunction = cobra.NoFileCompletions
125 applyLocalFlagsBuildConfig(cmd, r)
126 cmd.Flags().BoolVarP(&clean, "clean", "", false, "delete module cache for dependencies that fail verification")
127 },
128 run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error {
129 conf, err := r.ConfigFromProvider(configKey{counter: r.configVersionID.Load()}, flagsToCfg(cd, nil))
130 if err != nil {
131 return err
132 }
133 client := conf.configs.ModulesClient
134 return client.Verify(clean)
135 },
136 },
137 &simpleCommand{
138 name: "graph",
139 short: "Print a module dependency graph",
140 long: `Print a module dependency graph with information about module status (disabled, vendored).
141 Note that for vendored modules, that is the version listed and not the one from go.mod.
142 `,
143 withc: func(cmd *cobra.Command, r *rootCommand) {
144 cmd.ValidArgsFunction = cobra.NoFileCompletions
145 applyLocalFlagsBuildConfig(cmd, r)
146 cmd.Flags().BoolVarP(&clean, "clean", "", false, "delete module cache for dependencies that fail verification")
147 },
148 run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error {
149 conf, err := r.ConfigFromProvider(configKey{counter: r.configVersionID.Load()}, flagsToCfg(cd, nil))
150 if err != nil {
151 return err
152 }
153 client := conf.configs.ModulesClient
154 return client.Graph(os.Stdout)
155 },
156 },
157 &simpleCommand{
158 name: "clean",
159 short: "Delete the Hugo Module cache for the current project",
160 long: `Delete the Hugo Module cache for the current project.`,
161 withc: func(cmd *cobra.Command, r *rootCommand) {
162 cmd.ValidArgsFunction = cobra.NoFileCompletions
163 applyLocalFlagsBuildConfig(cmd, r)
164 cmd.Flags().StringVarP(&pattern, "pattern", "", "", `pattern matching module paths to clean (all if not set), e.g. "**hugo*"`)
165 _ = cmd.RegisterFlagCompletionFunc("pattern", cobra.NoFileCompletions)
166 cmd.Flags().BoolVarP(&all, "all", "", false, "clean entire module cache")
167 },
168 run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error {
169 h, err := r.Hugo(flagsToCfg(cd, nil))
170 if err != nil {
171 return err
172 }
173 if all {
174 modCache := h.ResourceSpec.FileCaches.ModulesCache()
175 count, err := modCache.Prune(true)
176 r.Printf("Deleted %d directories from module cache.", count)
177 return err
178 }
179
180 return h.Configs.ModulesClient.Clean(pattern)
181 },
182 },
183 &simpleCommand{
184 name: "tidy",
185 short: "Remove unused entries in go.mod and go.sum",
186 withc: func(cmd *cobra.Command, r *rootCommand) {
187 cmd.ValidArgsFunction = cobra.NoFileCompletions
188 applyLocalFlagsBuildConfig(cmd, r)
189 },
190 run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error {
191 h, err := r.Hugo(flagsToCfg(cd, nil))
192 if err != nil {
193 return err
194 }
195 return h.Configs.ModulesClient.Tidy()
196 },
197 },
198 &simpleCommand{
199 name: "vendor",
200 short: "Vendor all module dependencies into the _vendor directory",
201 long: `Vendor all module dependencies into the _vendor directory.
202 If a module is vendored, that is where Hugo will look for it's dependencies.
203 `,
204 withc: func(cmd *cobra.Command, r *rootCommand) {
205 cmd.ValidArgsFunction = cobra.NoFileCompletions
206 applyLocalFlagsBuildConfig(cmd, r)
207 },
208 run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error {
209 h, err := r.Hugo(flagsToCfg(cd, nil))
210 if err != nil {
211 return err
212 }
213 return h.Configs.ModulesClient.Vendor()
214 },
215 },
216
217 &simpleCommand{
218 name: "get",
219 short: "Resolves dependencies in your current Hugo project",
220 long: `
221 Resolves dependencies in your current Hugo project.
222
223 Some examples:
224
225 Install the latest version possible for a given module:
226
227 hugo mod get github.com/gohugoio/testshortcodes
228
229 Install a specific version:
230
231 hugo mod get github.com/gohugoio/[email protected]
232
233 Install the latest versions of all direct module dependencies:
234
235 hugo mod get
236 hugo mod get ./... (recursive)
237
238 Install the latest versions of all module dependencies (direct and indirect):
239
240 hugo mod get -u
241 hugo mod get -u ./... (recursive)
242
243 Run "go help get" for more information. All flags available for "go get" is also relevant here.
244 ` + commonUsageMod,
245 withc: func(cmd *cobra.Command, r *rootCommand) {
246 cmd.DisableFlagParsing = true
247 cmd.ValidArgsFunction = cobra.NoFileCompletions
248 },
249 run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error {
250 // We currently just pass on the flags we get to Go and
251 // need to do the flag handling manually.
252 if len(args) == 1 && (args[0] == "-h" || args[0] == "--help") {
253 return errHelp
254 }
255
256 var lastArg string
257 if len(args) != 0 {
258 lastArg = args[len(args)-1]
259 }
260
261 if lastArg == "./..." {
262 args = args[:len(args)-1]
263 // Do a recursive update.
264 dirname, err := os.Getwd()
265 if err != nil {
266 return err
267 }
268
269 // Sanity chesimplecobra. We do recursive walking and want to avoid
270 // accidents.
271 if len(dirname) < 5 {
272 return errors.New("must not be run from the file system root")
273 }
274
275 filepath.Walk(dirname, func(path string, info os.FileInfo, err error) error {
276 if info.IsDir() {
277 return nil
278 }
279 if info.Name() == "go.mod" {
280 // Found a module.
281 dir := filepath.Dir(path)
282
283 cfg := config.New()
284 cfg.Set("workingDir", dir)
285 conf, err := r.ConfigFromProvider(configKey{counter: r.configVersionID.Add(1)}, flagsToCfg(cd, cfg))
286 if err != nil {
287 return err
288 }
289 r.Println("Update module in", conf.configs.Base.WorkingDir)
290 client := conf.configs.ModulesClient
291 return client.Get(args...)
292
293 }
294 return nil
295 })
296 return nil
297 } else {
298 conf, err := r.ConfigFromProvider(configKey{counter: r.configVersionID.Load()}, flagsToCfg(cd, nil))
299 if err != nil {
300 return err
301 }
302 client := conf.configs.ModulesClient
303 if err := client.Get(args...); err != nil {
304 return err
305 }
306 return nil
307 }
308 },
309 },
310 npmCommand,
311 },
312 }
313 }
314
315 type modCommands struct {
316 r *rootCommand
317
318 commands []simplecobra.Commander
319 }
320
321 func (c *modCommands) Commands() []simplecobra.Commander {
322 return c.commands
323 }
324
325 func (c *modCommands) Name() string {
326 return "mod"
327 }
328
329 func (c *modCommands) Run(ctx context.Context, cd *simplecobra.Commandeer, args []string) error {
330 _, err := c.r.ConfigFromProvider(configKey{counter: c.r.configVersionID.Load()}, nil)
331 if err != nil {
332 return err
333 }
334 // config := conf.configs.Base
335
336 return nil
337 }
338
339 func (c *modCommands) Init(cd *simplecobra.Commandeer) error {
340 cmd := cd.CobraCommand
341 cmd.Short = "Manage modules"
342 cmd.Long = `Various helpers to help manage the modules in your project's dependency graph.
343 Most operations here requires a Go version installed on your system (>= Go 1.12) and the relevant VCS client (typically Git).
344 This is not needed if you only operate on modules inside /themes or if you have vendored them via "hugo mod vendor".
345
346 ` + commonUsageMod
347 cmd.RunE = nil
348 return nil
349 }
350
351 func (c *modCommands) PreRun(cd, runner *simplecobra.Commandeer) error {
352 c.r = cd.Root.Command.(*rootCommand)
353 return nil
354 }