Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix [#263] - --init creates config if one does not exist #264

Merged
merged 1 commit into from
Aug 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 1 addition & 41 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,8 @@ package cmd

import (
"fmt"
"os"
"strings"

"github.com/lets-cli/lets/upgrade"
"github.com/lets-cli/lets/upgrade/registry"
"github.com/lets-cli/lets/workdir"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)

Expand All @@ -19,7 +14,7 @@ func newRootCmd(version string) *cobra.Command {
Short: "A CLI task runner",
Args: cobra.ArbitraryArgs,
RunE: func(cmd *cobra.Command, args []string) error {
return runRoot(cmd, version)
return PrintHelpMessage(cmd)
},
TraverseChildren: true,
FParseErrWhitelist: cobra.FParseErrWhitelist{UnknownFlags: true},
Expand Down Expand Up @@ -64,38 +59,3 @@ func PrintVersionMessage(cmd *cobra.Command) error {
_, err := fmt.Fprintf(cmd.OutOrStdout(), "lets version %s\n", cmd.Version)
return err
}

func runRoot(cmd *cobra.Command, version string) error {
selfUpgrade, err := cmd.Flags().GetBool("upgrade")
if err != nil {
return fmt.Errorf("can not get flag 'upgrade': %w", err)
}

if selfUpgrade {
upgrader, err := upgrade.NewBinaryUpgrader(registry.NewGithubRegistry(cmd.Context()), version)
if err != nil {
return fmt.Errorf("can not upgrade lets: %w", err)
}

return upgrader.Upgrade()
}

init, err := cmd.Flags().GetBool("init")
if err != nil {
return fmt.Errorf("can not get flag 'init': %w", err)
}

if init {
wd, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
if err := workdir.InitLetsFile(wd, version); err != nil {
log.Fatal(err)
}

return nil
}

return PrintHelpMessage(cmd)
}
6 changes: 3 additions & 3 deletions examples/python/lets.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -26,17 +26,17 @@ commands:
depends:
- build-server
cmd: |
docker-compose up server
docker compose up server

postgres:
description: Run postgres
cmd: docker-compose up postgres
cmd: docker compose up postgres

ishell:
description: Run ipython shell
depends:
- build-server
cmd: docker-compose run --rm -T ishell
cmd: docker compose run --rm -T ishell

init-venv:
description: Run to init python virtual env in this repo
Expand Down
7 changes: 4 additions & 3 deletions lets.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@ commands:
description: Run unit tests
depends: [build-lets-image]
cmd:
- docker-compose
- docker
- compose
- run
- --rm
- test
Expand All @@ -46,7 +47,7 @@ commands:
Example:
lets test-bats config_version.bats
lets test-bats config_version.bats --opts="-f <regexp>"
cmd: docker-compose run --rm test-bats
cmd: docker compose run --rm test-bats

test-completions:
ref: test-bats
Expand Down Expand Up @@ -78,7 +79,7 @@ commands:
description: Run golint-ci
depends: [build-lint-image]
cmd:
- docker-compose run --rm lint
- docker compose run --rm lint

fmt:
description: Run sfmt
Expand Down
79 changes: 58 additions & 21 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ import (
"github.com/lets-cli/lets/executor"
"github.com/lets-cli/lets/logging"
"github.com/lets-cli/lets/set"
"github.com/lets-cli/lets/upgrade"
"github.com/lets-cli/lets/upgrade/registry"
"github.com/lets-cli/lets/workdir"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
Expand All @@ -39,13 +42,12 @@ func main() {
os.Exit(1)
}

rootFlags, err := parseRootFlags(rootCmd, args)
rootFlags, err := parseRootFlags(args)
if err != nil {
log.Errorf("lets: parse flags error: %s", err)
os.Exit(1)
}

// TODO add tests
if rootFlags.version {
if err := cmd.PrintVersionMessage(rootCmd); err != nil {
log.Errorf("lets: print version error: %s", err)
Expand Down Expand Up @@ -77,6 +79,34 @@ func main() {
cmd.InitSubCommands(rootCmd, cfg, rootFlags.all, os.Stdout)
}

if rootFlags.init {
wd, err := os.Getwd()
if err == nil {
err = workdir.InitLetsFile(wd, version)
}

if err != nil {
log.Errorf("lets: can not create lets.yaml: %s", err)
os.Exit(1)
}

os.Exit(0)
}

if rootFlags.upgrade {
upgrader, err := upgrade.NewBinaryUpgrader(registry.NewGithubRegistry(ctx), version)
if err == nil {
err = upgrader.Upgrade()
}

if err != nil {
log.Errorf("lets: can not self-upgrade binary: %s", err)
os.Exit(1)
}

os.Exit(0)
}

showUsage := rootFlags.help || (command.Name() == "help" && len(args) == 0)

if showUsage {
Expand Down Expand Up @@ -120,10 +150,10 @@ func getContext() context.Context {
return ctx
}

// do not fail on config error in it is help (-h, --help) or completion command
// do not fail on config error in it is help (-h, --help) or --init or completion command
func failOnConfigError(root *cobra.Command, current *cobra.Command, rootFlags *flags) bool {
rootCommands := set.NewSet("completion", "help")
return (root.Flags().NFlag() == 0 && !rootCommands.Contains(current.Name())) && !rootFlags.help
return (root.Flags().NFlag() == 0 && !rootCommands.Contains(current.Name())) && !rootFlags.help && !rootFlags.init
}

type flags struct {
Expand All @@ -132,6 +162,8 @@ type flags struct {
help bool
version bool
all bool
init bool
upgrade bool
}

// We can not parse --config and --debug flags using cobra.Command.ParseFlags
Expand All @@ -144,19 +176,21 @@ type flags struct {
// cobra will parse all --config flags, but take only latest
//
// --config=myconfig, and this is wrong.
func parseRootFlags(root *cobra.Command, args []string) (*flags, error) {
func parseRootFlags(args []string) (*flags, error) {
f := &flags{}
// if first arg is not a flag, then it is subcommand
if len(args) > 0 && !strings.HasPrefix(args[0], "-") {
return f, nil
}

visited := map[string]bool{
"config": false,
"debug": false,
"help": false,
"version": false,
"all": false,
visited := set.NewSet[string]()

isFlagVisited := func(name string) bool {
if visited.Contains(name) {
return true
}
visited.Add(name)
return false
}

idx := 0
Expand All @@ -170,8 +204,7 @@ func parseRootFlags(root *cobra.Command, args []string) (*flags, error) {
name, value, found := strings.Cut(arg, "=")
switch name {
case "--config", "-c":
if !visited["config"] {
visited["config"] = true
if !isFlagVisited("config") {
if found {
if value == "" {
return nil, errors.New("--config must be set to value")
Expand All @@ -184,27 +217,31 @@ func parseRootFlags(root *cobra.Command, args []string) (*flags, error) {
}
}
case "--debug", "-d", "-dd":
if !visited["debug"] {
if !isFlagVisited("debug") {
f.debug = 1
if arg == "-dd" {
f.debug = 2
}
visited["debug"] = true
}
case "--help", "-h":
if !visited["help"] {
if !isFlagVisited("help") {
f.help = true
visited["help"] = true
}
case "--version", "-v":
if !visited["version"] {
if !isFlagVisited("version") {
f.version = true
visited["version"] = true
}
case "--all":
if !visited["all"] {
if !isFlagVisited("all") {
f.all = true
visited["all"] = true
}
case "--init":
if !isFlagVisited("init") {
f.init = true
}
case "--upgrade":
if !isFlagVisited("upgrade") {
f.upgrade = true
}
}

Expand Down
4 changes: 3 additions & 1 deletion workdir/workdir.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"fmt"
"os"
"path/filepath"
"strings"

"github.com/lithammer/dedent"
log "github.com/sirupsen/logrus"
Expand All @@ -12,7 +13,7 @@ import (
const dotLetsDir = ".lets"

func getDefaltLetsConfig(version string) string {
return dedent.Dedent(fmt.Sprintf(`
template := dedent.Dedent(fmt.Sprintf(`
version: "%s"
shell: bash
commands:
Expand All @@ -25,6 +26,7 @@ func getDefaltLetsConfig(version string) string {
lets hello Friend
cmd: echo Hello, "${LETSOPT_NAME:-world}"!
`, version))
return strings.TrimLeft(template, "\n")
}

func GetDotLetsDir(workDir string) (string, error) {
Expand Down
Loading