Debian Codegraph @

commands/new.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 "path/filepath"
20 "strings"
21
22 "github.com/bep/simplecobra"
23 "github.com/gohugoio/hugo/common/paths"
24 "github.com/gohugoio/hugo/config"
25 "github.com/gohugoio/hugo/create"
26 "github.com/gohugoio/hugo/create/skeletons"
27 "github.com/spf13/cobra"
28 )
29
30 func newNewCommand() *newCommand {
31 var (
32 force bool
33 contentType string
34 format string
35 )
36
37 var c *newCommand
38 c = &newCommand{
39 commands: []simplecobra.Commander{
40 &simpleCommand{
41 name: "content",
42 use: "content [path]",
43 short: "Create new content",
44 long: `Create a new content file and automatically set the date and title.
45 It will guess which kind of file to create based on the path provided.
46
47 You can also specify the kind with ` + "`-k KIND`" + `.
48
49 If archetypes are provided in your theme or project, they will be used.
50
51 Ensure you run this within the root directory of your project.`,
52 run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error {
53 if len(args) < 1 {
54 return newUserError("path needs to be provided")
55 }
56 cfg := flagsToCfg(cd, nil)
57 cfg.Set("BuildFuture", true)
58 h, err := r.Hugo(cfg)
59 if err != nil {
60 return err
61 }
62 return create.NewContent(h, contentType, args[0], force)
63 },
64 withc: func(cmd *cobra.Command, r *rootCommand) {
65 cmd.ValidArgsFunction = func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
66 if len(args) != 0 {
67 return []string{}, cobra.ShellCompDirectiveNoFileComp
68 }
69 return []string{}, cobra.ShellCompDirectiveNoFileComp | cobra.ShellCompDirectiveFilterDirs
70 }
71 cmd.Flags().StringVarP(&contentType, "kind", "k", "", "content type to create")
72 cmd.Flags().String("editor", "", "edit new content with this editor, if provided")
73 _ = cmd.RegisterFlagCompletionFunc("editor", cobra.NoFileCompletions)
74 cmd.Flags().BoolVarP(&force, "force", "f", false, "overwrite file if it already exists")
75 applyLocalFlagsBuildConfig(cmd, r)
76 },
77 },
78 &simpleCommand{
79 name: "project",
80 use: "project [path]",
81 short: "Create a new project",
82 long: `Create a new project at the specified path.`,
83 aliases: []string{"site"},
84 run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error {
85 if len(args) < 1 {
86 return newUserError("path needs to be provided")
87 }
88 createpath, err := filepath.Abs(filepath.Clean(args[0]))
89 if err != nil {
90 return err
91 }
92
93 cfg := config.New()
94 cfg.Set("workingDir", createpath)
95 cfg.Set("publishDir", "public")
96
97 conf, err := r.ConfigFromProvider(configKey{counter: r.configVersionID.Load()}, flagsToCfg(cd, cfg))
98 if err != nil {
99 return err
100 }
101 sourceFs := conf.fs.Source
102
103 err = skeletons.CreateProject(createpath, sourceFs, force, format)
104 if err != nil {
105 return err
106 }
107
108 r.Printf("Congratulations! Your new Hugo project was created in %s.\n\n", createpath)
109 r.Println(c.newProjectNextStepsText(createpath, format))
110
111 return nil
112 },
113 withc: func(cmd *cobra.Command, r *rootCommand) {
114 cmd.ValidArgsFunction = func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
115 if len(args) != 0 {
116 return []string{}, cobra.ShellCompDirectiveNoFileComp
117 }
118 return []string{}, cobra.ShellCompDirectiveNoFileComp | cobra.ShellCompDirectiveFilterDirs
119 }
120 cmd.Flags().BoolVarP(&force, "force", "f", false, "init inside non-empty directory")
121 cmd.Flags().StringVar(&format, "format", "toml", "preferred file format (toml, yaml or json)")
122 _ = cmd.RegisterFlagCompletionFunc("format", cobra.FixedCompletions([]string{"toml", "yaml", "json"}, cobra.ShellCompDirectiveNoFileComp))
123 },
124 },
125 &simpleCommand{
126 name: "theme",
127 use: "theme [name]",
128 short: "Create a new theme",
129 long: `Create a new theme with the specified name in the ./themes directory.
130 This generates a functional theme including template examples and sample content.`,
131 run: func(ctx context.Context, cd *simplecobra.Commandeer, r *rootCommand, args []string) error {
132 if len(args) < 1 {
133 return newUserError("theme name needs to be provided")
134 }
135 cfg := config.New()
136 cfg.Set("publishDir", "public")
137
138 conf, err := r.ConfigFromProvider(configKey{counter: r.configVersionID.Load()}, flagsToCfg(cd, cfg))
139 if err != nil {
140 return err
141 }
142 sourceFs := conf.fs.Source
143 createpath := paths.AbsPathify(conf.configs.Base.WorkingDir, filepath.Join(conf.configs.Base.ThemesDir, args[0]))
144 r.Println("Creating new theme in", createpath)
145
146 err = skeletons.CreateTheme(createpath, sourceFs, format)
147 if err != nil {
148 return err
149 }
150
151 return nil
152 },
153 withc: func(cmd *cobra.Command, r *rootCommand) {
154 cmd.ValidArgsFunction = func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
155 if len(args) != 0 {
156 return []string{}, cobra.ShellCompDirectiveNoFileComp
157 }
158 return []string{}, cobra.ShellCompDirectiveNoFileComp | cobra.ShellCompDirectiveFilterDirs
159 }
160 cmd.Flags().StringVar(&format, "format", "toml", "preferred file format (toml, yaml or json)")
161 _ = cmd.RegisterFlagCompletionFunc("format", cobra.FixedCompletions([]string{"toml", "yaml", "json"}, cobra.ShellCompDirectiveNoFileComp))
162 },
163 },
164 },
165 }
166
167 return c
168 }
169
170 type newCommand struct {
171 rootCmd *rootCommand
172
173 commands []simplecobra.Commander
174 }
175
176 func (c *newCommand) Commands() []simplecobra.Commander {
177 return c.commands
178 }
179
180 func (c *newCommand) Name() string {
181 return "new"
182 }
183
184 func (c *newCommand) Run(ctx context.Context, cd *simplecobra.Commandeer, args []string) error {
185 return nil
186 }
187
188 func (c *newCommand) Init(cd *simplecobra.Commandeer) error {
189 cmd := cd.CobraCommand
190 cmd.Short = "Create new content"
191 cmd.Long = `Create a new content file and automatically set the date and title.
192 It will guess which kind of file to create based on the path provided.
193
194 You can also specify the kind with ` + "`-k KIND`" + `.
195
196 If archetypes are provided in your theme or project, they will be used.
197
198 Ensure you run this within the root directory of your project.`
199
200 cmd.RunE = nil
201 return nil
202 }
203
204 func (c *newCommand) PreRun(cd, runner *simplecobra.Commandeer) error {
205 c.rootCmd = cd.Root.Command.(*rootCommand)
206 return nil
207 }
208
209 func (c *newCommand) newProjectNextStepsText(path string, format string) string {
210 format = strings.ToLower(format)
211 var nextStepsText bytes.Buffer
212
213 nextStepsText.WriteString(`Just a few more steps...
214
215 1. Change the current directory to ` + path + `.
216 2. Create or install a theme:
217 - Create a new theme with the command "hugo new theme <THEMENAME>"
218 - Or, install a theme from https://themes.gohugo.io/
219 3. Edit hugo.` + format + `, setting the "theme" property to the theme name.
220 4. Create new content with the command "hugo new content `)
221
222 nextStepsText.WriteString(filepath.Join("<SECTIONNAME>", "<FILENAME>.<FORMAT>"))
223
224 nextStepsText.WriteString(`".
225 5. Start the embedded web server with the command "hugo server --buildDrafts".
226
227 See documentation at https://gohugo.io/.`)
228
229 return nextStepsText.String()
230 }