Skip to content

Commit

Permalink
commands: Fix config environment handling
Browse files Browse the repository at this point in the history
  • Loading branch information
bep committed Jan 31, 2020
1 parent b3f0674 commit e71389d
Show file tree
Hide file tree
Showing 12 changed files with 201 additions and 185 deletions.
7 changes: 7 additions & 0 deletions commands/=/content/p1.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"title": "P1",
"weight": 1
}

Content

14 changes: 10 additions & 4 deletions commands/commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,12 +47,12 @@ func (b *commandsBuilder) addAll() *commandsBuilder {
b.newServerCmd(),
newVersionCmd(),
newEnvCmd(),
newConfigCmd(),
b.newConfigCmd(),
newCheckCmd(),
newDeployCmd(),
newConvertCmd(),
b.newDeployCmd(),
b.newConvertCmd(),
b.newNewCmd(),
newListCmd(),
b.newListCmd(),
newImportCmd(),
newGenCmd(),
createReleaser(),
Expand Down Expand Up @@ -111,6 +111,12 @@ func (b *commandsBuilder) newBuilderCmd(cmd *cobra.Command) *baseBuilderCmd {
return bcmd
}

func (b *commandsBuilder) newBuilderBasicCmd(cmd *cobra.Command) *baseBuilderCmd {
bcmd := &baseBuilderCmd{commandsBuilder: b, baseCmd: &baseCmd{cmd: cmd}}
bcmd.hugoBuilderCommon.handleCommonBuilderFlags(cmd)
return bcmd
}

func (c *baseCmd) flagsToConfig(cfg config.Provider) {
initializeFlags(c.cmd, cfg)
}
Expand Down
135 changes: 125 additions & 10 deletions commands/commands_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ import (
"path/filepath"
"testing"

"github.com/spf13/afero"

"github.com/gohugoio/hugo/hugofs"

"github.com/gohugoio/hugo/common/types"

"github.com/spf13/cobra"
Expand All @@ -32,18 +36,119 @@ func TestExecute(t *testing.T) {

c := qt.New(t)

dir, err := createSimpleTestSite(t, testSiteConfig{})
c.Assert(err, qt.IsNil)
createSite := func(c *qt.C) (string, func()) {
dir, err := createSimpleTestSite(t, testSiteConfig{})
c.Assert(err, qt.IsNil)
return dir, func() {
os.RemoveAll(dir)
}
}

defer func() {
os.RemoveAll(dir)
}()
c.Run("hugo", func(c *qt.C) {
dir, clean := createSite(c)
defer clean()
resp := Execute([]string{"-s=" + dir})
c.Assert(resp.Err, qt.IsNil)
result := resp.Result
c.Assert(len(result.Sites) == 1, qt.Equals, true)
c.Assert(len(result.Sites[0].RegularPages()) == 1, qt.Equals, true)
c.Assert(result.Sites[0].Info.Params()["myparam"], qt.Equals, "paramproduction")
})

c.Run("hugo, set environment", func(c *qt.C) {
dir, clean := createSite(c)
defer clean()
resp := Execute([]string{"-s=" + dir, "-e=staging"})
c.Assert(resp.Err, qt.IsNil)
result := resp.Result
c.Assert(result.Sites[0].Info.Params()["myparam"], qt.Equals, "paramstaging")
})

c.Run("convert toJSON", func(c *qt.C) {
dir, clean := createSite(c)
output := filepath.Join(dir, "myjson")
defer clean()
resp := Execute([]string{"convert", "toJSON", "-s=" + dir, "-e=staging", "-o=" + output})
c.Assert(resp.Err, qt.IsNil)
converted := readFileFrom(c, filepath.Join(output, "content", "p1.md"))
c.Assert(converted, qt.Equals, "{\n \"title\": \"P1\",\n \"weight\": 1\n}\n\nContent\n\n", qt.Commentf(converted))
})

c.Run("config, set environment", func(c *qt.C) {
dir, clean := createSite(c)
defer clean()
out, err := captureStdout(func() error {
resp := Execute([]string{"config", "-s=" + dir, "-e=staging"})
return resp.Err
})
c.Assert(err, qt.IsNil)
c.Assert(out, qt.Contains, "params = map[myparam:paramstaging]", qt.Commentf(out))
})

c.Run("deploy, environment set", func(c *qt.C) {
dir, clean := createSite(c)
defer clean()
resp := Execute([]string{"deploy", "-s=" + dir, "-e=staging", "--target=mydeployment", "--dryRun"})
c.Assert(resp.Err, qt.Not(qt.IsNil))
c.Assert(resp.Err.Error(), qt.Contains, "open bucket gs://hugotestbucket: google: could not find default credentials")
})

c.Run("list", func(c *qt.C) {
dir, clean := createSite(c)
defer clean()
out, err := captureStdout(func() error {
resp := Execute([]string{"list", "all", "-s=" + dir, "-e=staging"})
return resp.Err
})
c.Assert(err, qt.IsNil)
c.Assert(out, qt.Contains, "p1.md")
})

c.Run("new theme", func(c *qt.C) {
dir, clean := createSite(c)
defer clean()
themesDir := filepath.Join(dir, "mythemes")
resp := Execute([]string{"new", "theme", "mytheme", "-s=" + dir, "-e=staging", "--themesDir=" + themesDir})
c.Assert(resp.Err, qt.IsNil)
themeTOML := readFileFrom(c, filepath.Join(themesDir, "mytheme", "theme.toml"))
c.Assert(themeTOML, qt.Contains, "name = \"Mytheme\"")
})

c.Run("new site", func(c *qt.C) {
dir, clean := createSite(c)
defer clean()
siteDir := filepath.Join(dir, "mysite")
resp := Execute([]string{"new", "site", siteDir, "-e=staging"})
c.Assert(resp.Err, qt.IsNil)
config := readFileFrom(c, filepath.Join(siteDir, "config.toml"))
c.Assert(config, qt.Contains, "baseURL = \"http://example.org/\"")
checkNewSiteInited(c, siteDir)
})

}

func checkNewSiteInited(c *qt.C, basepath string) {
paths := []string{
filepath.Join(basepath, "layouts"),
filepath.Join(basepath, "content"),
filepath.Join(basepath, "archetypes"),
filepath.Join(basepath, "static"),
filepath.Join(basepath, "data"),
filepath.Join(basepath, "config.toml"),
}

for _, path := range paths {
_, err := os.Stat(path)
c.Assert(err, qt.IsNil)
}
}

resp := Execute([]string{"-s=" + dir})
c.Assert(resp.Err, qt.IsNil)
result := resp.Result
c.Assert(len(result.Sites) == 1, qt.Equals, true)
c.Assert(len(result.Sites[0].RegularPages()) == 1, qt.Equals, true)
func readFileFrom(c *qt.C, filename string) string {
c.Helper()
filename = filepath.Clean(filename)
b, err := afero.ReadFile(hugofs.Os, filename)
c.Assert(err, qt.IsNil)
return string(b)
}

func TestCommandsPersistentFlags(t *testing.T) {
Expand Down Expand Up @@ -233,6 +338,7 @@ func createSimpleTestSite(t *testing.T, cfg testSiteConfig) (string, error) {
baseURL = "https://example.org"
title = "Hugo Commands"
`

contentDir := "content"
Expand All @@ -246,6 +352,15 @@ title = "Hugo Commands"

// Just the basic. These are for CLI tests, not site testing.
writeFile(t, filepath.Join(d, "config.toml"), cfgStr)
writeFile(t, filepath.Join(d, "config", "staging", "params.toml"), `myparam="paramstaging"`)
writeFile(t, filepath.Join(d, "config", "staging", "deployment.toml"), `
[[targets]]
name = "mydeployment"
URL = "gs://hugotestbucket"
`)

writeFile(t, filepath.Join(d, "config", "testing", "params.toml"), `myparam="paramtesting"`)
writeFile(t, filepath.Join(d, "config", "production", "params.toml"), `myparam="paramproduction"`)

writeFile(t, filepath.Join(d, contentDir, "p1.md"), `
---
Expand Down
21 changes: 10 additions & 11 deletions commands/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ package commands

import (
"encoding/json"
"fmt"
"os"
"reflect"
"regexp"
Expand All @@ -27,35 +28,33 @@ import (
"github.com/gohugoio/hugo/modules"

"github.com/spf13/cobra"
jww "github.com/spf13/jwalterweatherman"
"github.com/spf13/viper"
)

var _ cmder = (*configCmd)(nil)

type configCmd struct {
hugoBuilderCommon
*baseCmd
*baseBuilderCmd
}

func newConfigCmd() *configCmd {
func (b *commandsBuilder) newConfigCmd() *configCmd {
cc := &configCmd{}
cc.baseCmd = newBaseCmd(&cobra.Command{
cmd := &cobra.Command{
Use: "config",
Short: "Print the site configuration",
Long: `Print the site configuration, both default and custom settings.`,
RunE: cc.printConfig,
})

cc.cmd.PersistentFlags().StringVarP(&cc.source, "source", "s", "", "filesystem path to read files relative from")
}

printMountsCmd := &cobra.Command{
Use: "mounts",
Short: "Print the configured file mounts",
RunE: cc.printMounts,
}

cc.cmd.AddCommand(printMountsCmd)
cmd.AddCommand(printMountsCmd)

cc.baseBuilderCmd = b.newBuilderBasicCmd(cmd)

return cc
}
Expand Down Expand Up @@ -105,9 +104,9 @@ func (c *configCmd) printConfig(cmd *cobra.Command, args []string) error {
for _, k := range keys {
kv := reflect.ValueOf(allSettings[k])
if kv.Kind() == reflect.String {
jww.FEEDBACK.Printf("%s%s\"%+v\"\n", k, separator, allSettings[k])
fmt.Printf("%s%s\"%+v\"\n", k, separator, allSettings[k])
} else {
jww.FEEDBACK.Printf("%s%s%+v\n", k, separator, allSettings[k])
fmt.Printf("%s%s%+v\n", k, separator, allSettings[k])
}
}

Expand Down
20 changes: 9 additions & 11 deletions commands/convert.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,27 +44,25 @@ var (
)

type convertCmd struct {
hugoBuilderCommon

outputDir string
unsafe bool

*baseCmd
*baseBuilderCmd
}

func newConvertCmd() *convertCmd {
func (b *commandsBuilder) newConvertCmd() *convertCmd {
cc := &convertCmd{}

cc.baseCmd = newBaseCmd(&cobra.Command{
cmd := &cobra.Command{
Use: "convert",
Short: "Convert your content to different formats",
Long: `Convert your content (e.g. front matter) to different formats.
See convert's subcommands toJSON, toTOML and toYAML for more information.`,
RunE: nil,
})
}

cc.cmd.AddCommand(
cmd.AddCommand(
&cobra.Command{
Use: "toJSON",
Short: "Convert front matter to JSON",
Expand Down Expand Up @@ -94,10 +92,10 @@ to use YAML for the front matter.`,
},
)

cc.cmd.PersistentFlags().StringVarP(&cc.outputDir, "output", "o", "", "filesystem path to write files to")
cc.cmd.PersistentFlags().StringVarP(&cc.source, "source", "s", "", "filesystem path to read files relative from")
cc.cmd.PersistentFlags().BoolVar(&cc.unsafe, "unsafe", false, "enable less safe operations, please backup first")
cc.cmd.PersistentFlags().SetAnnotation("source", cobra.BashCompSubdirsInDir, []string{})
cmd.PersistentFlags().StringVarP(&cc.outputDir, "output", "o", "", "filesystem path to write files to")
cmd.PersistentFlags().BoolVar(&cc.unsafe, "unsafe", false, "enable less safe operations, please backup first")

cc.baseBuilderCmd = b.newBuilderBasicCmd(cmd)

return cc
}
Expand Down
23 changes: 12 additions & 11 deletions commands/deploy.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,7 @@ var _ cmder = (*deployCmd)(nil)

// deployCmd supports deploying sites to Cloud providers.
type deployCmd struct {
hugoBuilderCommon
*baseCmd
*baseBuilderCmd
}

// TODO: In addition to the "deploy" command, consider adding a "--deploy"
Expand All @@ -38,10 +37,10 @@ type deployCmd struct {
// run "hugo && hugo deploy" again and again and upload new stuff every time. Is
// this intended?

func newDeployCmd() *deployCmd {
func (b *commandsBuilder) newDeployCmd() *deployCmd {
cc := &deployCmd{}

cc.baseCmd = newBaseCmd(&cobra.Command{
cmd := &cobra.Command{
Use: "deploy",
Short: "Deploy your site to a Cloud provider.",
Long: `Deploy your site to a Cloud provider.
Expand All @@ -64,14 +63,16 @@ documentation.
}
return deployer.Deploy(context.Background())
},
})
}

cc.cmd.Flags().String("target", "", "target deployment from deployments section in config file; defaults to the first one")
cc.cmd.Flags().Bool("confirm", false, "ask for confirmation before making changes to the target")
cc.cmd.Flags().Bool("dryRun", false, "dry run")
cc.cmd.Flags().Bool("force", false, "force upload of all files")
cc.cmd.Flags().Bool("invalidateCDN", true, "invalidate the CDN cache listed in the deployment target")
cc.cmd.Flags().Int("maxDeletes", 256, "maximum # of files to delete, or -1 to disable")
cmd.Flags().String("target", "", "target deployment from deployments section in config file; defaults to the first one")
cmd.Flags().Bool("confirm", false, "ask for confirmation before making changes to the target")
cmd.Flags().Bool("dryRun", false, "dry run")
cmd.Flags().Bool("force", false, "force upload of all files")
cmd.Flags().Bool("invalidateCDN", true, "invalidate the CDN cache listed in the deployment target")
cmd.Flags().Int("maxDeletes", 256, "maximum # of files to delete, or -1 to disable")

cc.baseBuilderCmd = b.newBuilderBasicCmd(cmd)

return cc
}
Loading

0 comments on commit e71389d

Please sign in to comment.