Debian Codegraph @

commands/gen.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 "bytes"
18 "context"
19 "encoding/json"
20 "fmt"
21 "os"
22 "path"
23 "path/filepath"
24 "strings"
25
26 "github.com/bep/simplecobra"
27 "github.com/goccy/go-yaml"
28 "github.com/gohugoio/hugo/common/hugo"
29 "github.com/gohugoio/hugo/docshelper"
30 "github.com/gohugoio/hugo/helpers"
31 "github.com/gohugoio/hugo/hugofs"
32 "github.com/gohugoio/hugo/hugolib"
33 "github.com/gohugoio/hugo/markup/highlight"
34 "github.com/gohugoio/hugo/parser"
35 "github.com/spf13/cobra"
36 "github.com/spf13/cobra/doc"
37 )
38
39 func newGenCommand() *genCommand {
40 var (
41 // Flags.
42 gendocdir string
43 genmandir string
44
45 // Chroma flags.
46 style string
47 mode string
48 modeSelector bool
49 classDark string
50 classLight string
51 highlightStyle string
52 lineNumbersInlineStyle string
53 lineNumbersTableStyle string
54 omitEmpty bool
55 omitClassComments bool
56 )
57
58 newChromaStyles := func() simplecobra.Commander {
59 return &simpleCommand{
60 name: "chromastyles",
61 short: "Generate CSS stylesheet for the Chroma code highlighter",
62 long: `Generate CSS stylesheet for the Chroma code highlighter for a given style. This stylesheet is needed if markup.highlight.noClasses is disabled in config.
63
64 See https://gohugo.io/quick-reference/syntax-highlighting-styles/ for a preview of the available styles.`,
65
66 run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error {
67 if omitEmpty {
68 // See https://github.com/alecthomas/chroma/commit/5b2a4c5a26c503c79bc86ba3c4ae5b330028bd3d
69 hugo.Deprecate("--omitEmpty", "Flag is no longer needed, empty classes are now always omitted.", "v0.149.0")
70 }
71 css, err := highlight.ChromaStylesCSS(highlight.ChromaStylesOptions{
72 Style: style,
73 Mode: mode,
74 ModeSelector: modeSelector,
75 ClassDark: classDark,
76 ClassLight: classLight,
77 HighlightStyle: highlightStyle,
78 LineNumbersInlineStyle: lineNumbersInlineStyle,
79 LineNumbersTableStyle: lineNumbersTableStyle,
80 OmitClassComments: omitClassComments,
81 })
82 if err != nil {
83 return err
84 }
85
86 fmt.Printf("/* Generated using: hugo %s */\n\n", strings.Join(os.Args[1:], " "))
87 fmt.Print(css)
88 return nil
89 },
90 withc: func(cmd *cobra.Command, r *rootCommand) {
91 cmd.ValidArgsFunction = cobra.NoFileCompletions
92 cmd.PersistentFlags().StringVar(&style, "style", "friendly", "highlighter style")
93 _ = cmd.RegisterFlagCompletionFunc("style", cobra.NoFileCompletions)
94 cmd.PersistentFlags().StringVar(&mode, "mode", "", `style mode ("light", "dark")`)
95 _ = cmd.RegisterFlagCompletionFunc("mode", cobra.FixedCompletions([]string{"light", "dark"}, cobra.ShellCompDirectiveNoFileComp))
96 cmd.PersistentFlags().BoolVar(&modeSelector, "modeSelector", false, `scope selectors under a top level mode class, e.g. ".dark .chroma"`)
97 _ = cmd.RegisterFlagCompletionFunc("modeSelector", cobra.NoFileCompletions)
98 cmd.PersistentFlags().StringVar(&classDark, "classDark", "dark", `class name used by --modeSelector for dark styles`)
99 _ = cmd.RegisterFlagCompletionFunc("classDark", cobra.NoFileCompletions)
100 cmd.PersistentFlags().StringVar(&classLight, "classLight", "light", `class name used by --modeSelector for light styles`)
101 _ = cmd.RegisterFlagCompletionFunc("classLight", cobra.NoFileCompletions)
102 cmd.PersistentFlags().StringVar(&highlightStyle, "highlightStyle", "", `foreground and background colors for highlighted lines, e.g. --highlightStyle "#fff000 bg:#000fff"`)
103 _ = cmd.RegisterFlagCompletionFunc("highlightStyle", cobra.NoFileCompletions)
104 cmd.PersistentFlags().StringVar(&lineNumbersInlineStyle, "lineNumbersInlineStyle", "", `foreground and background colors for inline line numbers, e.g. --lineNumbersInlineStyle "#fff000 bg:#000fff"`)
105 _ = cmd.RegisterFlagCompletionFunc("lineNumbersInlineStyle", cobra.NoFileCompletions)
106 cmd.PersistentFlags().StringVar(&lineNumbersTableStyle, "lineNumbersTableStyle", "", `foreground and background colors for table line numbers, e.g. --lineNumbersTableStyle "#fff000 bg:#000fff"`)
107 _ = cmd.RegisterFlagCompletionFunc("lineNumbersTableStyle", cobra.NoFileCompletions)
108 cmd.PersistentFlags().BoolVar(&omitEmpty, "omitEmpty", false, `omit empty CSS rules (deprecated, no longer needed)`)
109 _ = cmd.RegisterFlagCompletionFunc("omitEmpty", cobra.NoFileCompletions)
110 cmd.PersistentFlags().BoolVar(&omitClassComments, "omitClassComments", false, `omit CSS class comment prefixes in the generated CSS`)
111 _ = cmd.RegisterFlagCompletionFunc("omitClassComments", cobra.NoFileCompletions)
112 },
113 }
114 }
115
116 newMan := func() simplecobra.Commander {
117 return &simpleCommand{
118 name: "man",
119 short: "Generate man pages for the Hugo CLI",
120 long: `This command automatically generates up-to-date man pages of Hugo's
121 command-line interface. By default, it creates the man page files
122 in the "man" directory under the current directory.`,
123
124 run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error {
125 header := &doc.GenManHeader{
126 Section: "1",
127 Manual: "Hugo Manual",
128 Source: fmt.Sprintf("Hugo %s", hugo.CurrentVersion),
129 }
130 if !strings.HasSuffix(genmandir, helpers.FilePathSeparator) {
131 genmandir += helpers.FilePathSeparator
132 }
133 if found, _ := helpers.Exists(genmandir, hugofs.Os); !found {
134 r.Println("Directory", genmandir, "does not exist, creating...")
135 if err := hugofs.Os.MkdirAll(genmandir, 0o777); err != nil {
136 return err
137 }
138 }
139 cd.CobraCommand.Root().DisableAutoGenTag = true
140
141 r.Println("Generating Hugo man pages in", genmandir, "...")
142 doc.GenManTree(cd.CobraCommand.Root(), header, genmandir)
143
144 r.Println("Done.")
145
146 return nil
147 },
148 withc: func(cmd *cobra.Command, r *rootCommand) {
149 cmd.ValidArgsFunction = cobra.NoFileCompletions
150 cmd.PersistentFlags().StringVar(&genmandir, "dir", "man/", "the directory to write the man pages.")
151 _ = cmd.MarkFlagDirname("dir")
152 },
153 }
154 }
155
156 newGen := func() simplecobra.Commander {
157 const gendocFrontmatterTemplate = `---
158 title: "%s"
159 slug: %s
160 url: %s
161 ---
162 `
163
164 return &simpleCommand{
165 name: "doc",
166 short: "Generate Markdown documentation for the Hugo CLI",
167 long: `Generate Markdown documentation for the Hugo CLI.
168 This command is, mostly, used to create up-to-date documentation
169 of Hugo's command-line interface for https://gohugo.io/.
170
171 It creates one Markdown file per command with front matter suitable
172 for rendering in Hugo.`,
173 run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error {
174 cd.CobraCommand.VisitParents(func(c *cobra.Command) {
175 // Disable the "Auto generated by spf13/cobra on DATE"
176 // as it creates a lot of diffs.
177 c.DisableAutoGenTag = true
178 })
179 if !strings.HasSuffix(gendocdir, helpers.FilePathSeparator) {
180 gendocdir += helpers.FilePathSeparator
181 }
182 if found, _ := helpers.Exists(gendocdir, hugofs.Os); !found {
183 r.Println("Directory", gendocdir, "does not exist, creating...")
184 if err := hugofs.Os.MkdirAll(gendocdir, 0o777); err != nil {
185 return err
186 }
187 }
188 prepender := func(filename string) string {
189 name := filepath.Base(filename)
190 base := strings.TrimSuffix(name, path.Ext(name))
191 url := "/docs/reference/commands/" + strings.ToLower(base) + "/"
192 return fmt.Sprintf(gendocFrontmatterTemplate, strings.Replace(base, "_", " ", -1), base, url)
193 }
194
195 linkHandler := func(name string) string {
196 base := strings.TrimSuffix(name, path.Ext(name))
197 return "/docs/reference/commands/" + strings.ToLower(base) + "/"
198 }
199 r.Println("Generating Hugo command-line documentation in", gendocdir, "...")
200 doc.GenMarkdownTreeCustom(cd.CobraCommand.Root(), gendocdir, prepender, linkHandler)
201 r.Println("Done.")
202
203 return nil
204 },
205 withc: func(cmd *cobra.Command, r *rootCommand) {
206 cmd.ValidArgsFunction = cobra.NoFileCompletions
207 cmd.PersistentFlags().StringVar(&gendocdir, "dir", "/tmp/hugodoc/", "the directory to write the doc.")
208 _ = cmd.MarkFlagDirname("dir")
209 },
210 }
211 }
212
213 var docsHelperTarget string
214
215 newDocsHelper := func() simplecobra.Commander {
216 return &simpleCommand{
217 name: "docshelper",
218 short: "Generate some data files for the Hugo docs",
219
220 run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error {
221 r.Println("Generate docs data to", docsHelperTarget)
222
223 var buf bytes.Buffer
224 jsonEnc := json.NewEncoder(&buf)
225
226 configProvider := func() docshelper.DocProvider {
227 conf := hugolib.DefaultConfig()
228 conf.CacheDir = "" // The default value does not make sense in the docs.
229 defaultConfig := parser.NullBoolJSONMarshaller{Wrapped: parser.LowerCaseCamelJSONMarshaller{Value: conf}}
230 return docshelper.DocProvider{"config": defaultConfig}
231 }
232
233 docshelper.AddDocProviderFunc(configProvider)
234 if err := jsonEnc.Encode(docshelper.GetDocProvider()); err != nil {
235 return err
236 }
237
238 // Decode the JSON to a map[string]interface{} and then unmarshal it again to the correct format.
239 var m map[string]any
240 if err := json.Unmarshal(buf.Bytes(), &m); err != nil {
241 return err
242 }
243
244 targetFile := filepath.Join(docsHelperTarget, "docs.yaml")
245
246 f, err := os.Create(targetFile)
247 if err != nil {
248 return err
249 }
250 defer f.Close()
251 yamlEnc := yaml.NewEncoder(f, yaml.UseSingleQuote(true), yaml.AutoInt())
252 if err := yamlEnc.Encode(m); err != nil {
253 return err
254 }
255
256 r.Println("Done!")
257 return nil
258 },
259 withc: func(cmd *cobra.Command, r *rootCommand) {
260 cmd.Hidden = true
261 cmd.ValidArgsFunction = cobra.NoFileCompletions
262 cmd.PersistentFlags().StringVarP(&docsHelperTarget, "dir", "", "docs/data", "data dir")
263 },
264 }
265 }
266
267 return &genCommand{
268 commands: []simplecobra.Commander{
269 newChromaStyles(),
270 newGen(),
271 newMan(),
272 newDocsHelper(),
273 },
274 }
275 }
276
277 type genCommand struct {
278 rootCmd *rootCommand
279
280 commands []simplecobra.Commander
281 }
282
283 func (c *genCommand) Commands() []simplecobra.Commander {
284 return c.commands
285 }
286
287 func (c *genCommand) Name() string {
288 return "gen"
289 }
290
291 func (c *genCommand) Run(ctx context.Context, cd *simplecobra.Commandeer, args []string) error {
292 return nil
293 }
294
295 func (c *genCommand) Init(cd *simplecobra.Commandeer) error {
296 cmd := cd.CobraCommand
297 cmd.Short = "Generate documentation and syntax highlighting styles"
298 cmd.Long = "Generate documentation for your project using Hugo's documentation engine, including syntax highlighting for various programming languages."
299
300 cmd.RunE = nil
301 return nil
302 }
303
304 func (c *genCommand) PreRun(cd, runner *simplecobra.Commandeer) error {
305 c.rootCmd = cd.Root.Command.(*rootCommand)
306 return nil
307 }