Debian Codegraph @

commands/config.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 "strings"
23 "time"
24
25 "github.com/bep/simplecobra"
26 "github.com/gohugoio/hugo/common/hmaps"
27 "github.com/gohugoio/hugo/config/allconfig"
28 "github.com/gohugoio/hugo/hugolib/sitesmatrix"
29 "github.com/gohugoio/hugo/modules"
30 "github.com/gohugoio/hugo/parser"
31 "github.com/gohugoio/hugo/parser/metadecoders"
32 "github.com/spf13/cobra"
33 )
34
35 // newConfigCommand creates a new config command and its subcommands.
36 func newConfigCommand() *configCommand {
37 return &configCommand{
38 commands: []simplecobra.Commander{
39 &configMountsCommand{},
40 },
41 }
42 }
43
44 type configCommand struct {
45 r *rootCommand
46
47 format string
48 lang string
49 printZero bool
50
51 commands []simplecobra.Commander
52 }
53
54 func (c *configCommand) Commands() []simplecobra.Commander {
55 return c.commands
56 }
57
58 func (c *configCommand) Name() string {
59 return "config"
60 }
61
62 func (c *configCommand) Run(ctx context.Context, cd *simplecobra.Commandeer, args []string) error {
63 conf, err := c.r.ConfigFromProvider(configKey{counter: c.r.configVersionID.Load()}, flagsToCfg(cd, nil))
64 if err != nil {
65 return err
66 }
67 var config *allconfig.Config
68 if c.lang != "" {
69 var found bool
70 config, found = conf.configs.LanguageConfigMap[c.lang]
71 if !found {
72 return fmt.Errorf("language %q not found", c.lang)
73 }
74 } else {
75 config = conf.configs.LanguageConfigMap[conf.configs.Base.DefaultContentLanguage]
76 }
77
78 var buf bytes.Buffer
79 dec := json.NewEncoder(&buf)
80 dec.SetIndent("", " ")
81 dec.SetEscapeHTML(false)
82
83 if err := dec.Encode(parser.ReplacingJSONMarshaller{Value: config, KeysToLower: true, OmitEmpty: !c.printZero}); err != nil {
84 return err
85 }
86
87 format := strings.ToLower(c.format)
88
89 switch format {
90 case "json":
91 os.Stdout.Write(buf.Bytes())
92 default:
93 // Decode the JSON to a map[string]interface{} and then unmarshal it again to the correct format.
94 var m map[string]any
95 if err := json.Unmarshal(buf.Bytes(), &m); err != nil {
96 return err
97 }
98 hmaps.ConvertFloat64WithNoDecimalsToInt(m)
99 switch format {
100 case "yaml":
101 return parser.InterfaceToConfig(m, metadecoders.YAML, os.Stdout)
102 case "toml":
103 return parser.InterfaceToConfig(m, metadecoders.TOML, os.Stdout)
104 default:
105 return fmt.Errorf("unsupported format: %q", format)
106 }
107 }
108
109 return nil
110 }
111
112 func (c *configCommand) Init(cd *simplecobra.Commandeer) error {
113 c.r = cd.Root.Command.(*rootCommand)
114 cmd := cd.CobraCommand
115 cmd.Short = "Display project configuration"
116 cmd.Long = `Display project configuration, both default and custom settings.`
117 cmd.Flags().StringVar(&c.format, "format", "toml", "preferred file format (toml, yaml or json)")
118 _ = cmd.RegisterFlagCompletionFunc("format", cobra.FixedCompletions([]string{"toml", "yaml", "json"}, cobra.ShellCompDirectiveNoFileComp))
119 cmd.Flags().StringVar(&c.lang, "lang", "", "the language to display config for (default is the default content language)")
120 cmd.Flags().BoolVar(&c.printZero, "printZero", false, `include config options with zero values (e.g. false, 0, "") in the output`)
121 _ = cmd.RegisterFlagCompletionFunc("lang", cobra.NoFileCompletions)
122 applyLocalFlagsBuildConfig(cmd, c.r)
123
124 return nil
125 }
126
127 func (c *configCommand) PreRun(cd, runner *simplecobra.Commandeer) error {
128 return nil
129 }
130
131 type configModMount struct {
132 Source string `json:"source"`
133 Target string `json:"target"`
134 Sites sitesmatrix.Sites `json:"sites,omitzero"`
135 }
136
137 type configModMounts struct {
138 verbose bool
139 m modules.Module
140 }
141
142 // MarshalJSON is for internal use only.
143 func (m *configModMounts) MarshalJSON() ([]byte, error) {
144 var mounts []configModMount
145
146 for _, mount := range m.m.Mounts() {
147 mounts = append(mounts, configModMount{
148 Source: mount.Source,
149 Target: mount.Target,
150 Sites: mount.Sites,
151 })
152 }
153
154 var ownerPath string
155 if m.m.Owner() != nil {
156 ownerPath = m.m.Owner().Path()
157 }
158
159 if m.verbose {
160 config := m.m.Config()
161 return json.Marshal(&struct {
162 Path string `json:"path"`
163 Version string `json:"version"`
164 Time time.Time `json:"time"`
165 Owner string `json:"owner"`
166 Dir string `json:"dir"`
167 Meta map[string]any `json:"meta"`
168 HugoVersion modules.HugoVersion `json:"hugoVersion"`
169
170 Mounts []configModMount `json:"mounts"`
171 }{
172 Path: m.m.Path(),
173 Version: m.m.Version(),
174 Time: m.m.Time(),
175 Owner: ownerPath,
176 Dir: m.m.Dir(),
177 Meta: config.Params,
178 HugoVersion: config.HugoVersion,
179 Mounts: mounts,
180 })
181 }
182
183 return json.Marshal(&struct {
184 Path string `json:"path"`
185 Version string `json:"version"`
186 Time time.Time `json:"time"`
187 Owner string `json:"owner"`
188 Dir string `json:"dir"`
189 Mounts []configModMount `json:"mounts"`
190 }{
191 Path: m.m.Path(),
192 Version: m.m.Version(),
193 Time: m.m.Time(),
194 Owner: ownerPath,
195 Dir: m.m.Dir(),
196 Mounts: mounts,
197 })
198 }
199
200 type configMountsCommand struct {
201 r *rootCommand
202 configCmd *configCommand
203 }
204
205 func (c *configMountsCommand) Commands() []simplecobra.Commander {
206 return nil
207 }
208
209 func (c *configMountsCommand) Name() string {
210 return "mounts"
211 }
212
213 func (c *configMountsCommand) Run(ctx context.Context, cd *simplecobra.Commandeer, args []string) error {
214 r := c.configCmd.r
215 conf, err := r.ConfigFromProvider(configKey{counter: c.r.configVersionID.Load()}, flagsToCfg(cd, nil))
216 if err != nil {
217 return err
218 }
219
220 for _, m := range conf.configs.Modules {
221 if err := parser.InterfaceToConfig(&configModMounts{m: m, verbose: r.isVerbose()}, metadecoders.JSON, os.Stdout); err != nil {
222 return err
223 }
224 }
225 return nil
226 }
227
228 func (c *configMountsCommand) Init(cd *simplecobra.Commandeer) error {
229 c.r = cd.Root.Command.(*rootCommand)
230 cmd := cd.CobraCommand
231 cmd.Short = "Print the configured file mounts"
232 cmd.ValidArgsFunction = cobra.NoFileCompletions
233 applyLocalFlagsBuildConfig(cmd, c.r)
234 return nil
235 }
236
237 func (c *configMountsCommand) PreRun(cd, runner *simplecobra.Commandeer) error {
238 c.configCmd = cd.Parent.Command.(*configCommand)
239 return nil
240 }