Skip to content

Commit

Permalink
Integrate viper with cobra flags.
Browse files Browse the repository at this point in the history
Signed-off-by: Vaibhav <[email protected]>
  • Loading branch information
vrongmeal committed Feb 26, 2020
1 parent c4c0022 commit 3169aaa
Show file tree
Hide file tree
Showing 249 changed files with 54,445 additions and 3,687 deletions.
65 changes: 45 additions & 20 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,12 @@
## Contents

1. [Installation](#installation)
1. [Using `go get`](#using-go-get)
1. [Manual](#manual)
1. [Using `go get`](#using-go-get)
1. [Manual](#manual)
1. [Usage](#usage)
1. [Command line help](#command-line-help)
1. [Configuration file](#configuration-file)
1. [Command line help](#command-line-help)
1. [Configuration file](#configuration-file)
1. [Configuring using cmd](#configuring-using-cmd)

## Installation

Expand Down Expand Up @@ -45,8 +46,13 @@ Available Commands:
version Leaf version

Flags:
-c, --config string Config path for leaf configuration file (default "<CWD>/.leaf.yml")
-h, --help help for leaf
-c, --config string Config path for leaf configuration file (default "<CWD>/.leaf.yml")
-d, --delay duration Delay after which commands are run on file change (default 500ms)
-e, --exclude DEFAULTS Paths to exclude. You can append default paths by adding DEFAULTS in your list (default [.git/,node_modules/,vendor/,venv/])
-x, --exec strings Exec commands on file change
-f, --filters strings Filters to apply to watch
-h, --help help for leaf
-r, --root string Root directory to watch (default "<CWD>")

Use "leaf [command] --help" for more information about a command.
```
Expand All @@ -60,38 +66,57 @@ This project doesn't really require a hot-reload but a sample hot-reload for thi

# Root directory to watch.
# Defaults to current working directory.
root: "."
root: .

# Exclude directories while watching.
# If certain directories are not excluded, it might reach a limitation where watcher doesn't start.
exclude:
- ".git/"
- "vendor/"
- "build/"
- DEFAULTS # This includes the default ignored directories
- build/

# Filters to apply on the watch.
# Filters starting with '+' are includent and then with '-' are excluded.
# This is not like exclude, these are still being watched yet can be excluded from the execution.
# These can include any filepath regex supported by "filepath".Match method or even a directory.
filters:
- "- .git*"
- "- .go*"
- "- .golangci.yml"
- "- go.*"
- "- Makefile"
- "- LICENSE"
- "- README.md"
# The following can be simplified by also doing an include filter:
# ['+cmd/', '+pkg/', '+scripts/']
# This example is just to show that expressions are supported.
- -.git*
- -.go*
- -.golangci.yml
- -go.*
- -Makefile
- -LICENSE
- -README.md

# Commands to be executed.
# These are run in the provided order.
exec:
- ["make", "build"]
- make build

# Delay after which commands are executed.
delay: '1s'
delay: 1s
```
By default the config path is taken as `<current working directory>/.leaf.yml` which you can change using the `--config` or `-c` flag. You can also use a JSON or TOML file. Just remember to use "delay" in nanoseconds (seconds * 10^9).
By default the config path is taken as `<current working directory>/.leaf.yml` which you can change using the `--config` or `-c` flag. You can also use a JSON or TOML file.

## Configuring using cmd

You can also configure using command line. The above config can be run as follows:

```console
> leaf -d=1s -e=DEFAULTS -e='build/' -f='+cmd/' -f='+pkg/' -f='+scripts/' -x='make build'
[0000] WARN Continuing without config...
[0000] INFO Starting to watch: /Users/vrongmeal/Projects/vrongmeal/leaf
[0000] INFO Excluded paths:
[0000] INFO .git/
[0000] INFO node_modules/
[0000] INFO vendor/
[0000] INFO venv/
[0000] INFO build/
...
```

---

Expand Down
28 changes: 15 additions & 13 deletions _examples/sample.leaf.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,32 +2,34 @@

# Root directory to watch.
# Defaults to current working directory.
root: "."
root: .

# Exclude directories while watching.
# If certain directories are not excluded, it might reach a limitation where watcher doesn't start.
exclude:
- ".git/"
- "vendor/"
- "build/"
- DEFAULTS # This includes the default ignored directories
- build/

# Filters to apply on the watch.
# Filters starting with '+' are includent and then with '-' are excluded.
# This is not like exclude, these are still being watched yet can be excluded from the execution.
# These can include any filepath regex supported by "filepath".Match method or even a directory.
filters:
- "- .git*"
- "- .go*"
- "- .golangci.yml"
- "- go.*"
- "- Makefile"
- "- LICENSE"
- "- README.md"
# The following can be simplified by also doing an include filter:
# ['+cmd/', '+pkg/', '+scripts/']
# This example is just to show that expressions are supported.
- -.git*
- -.go*
- -.golangci.yml
- -go.*
- -Makefile
- -LICENSE
- -README.md

# Commands to be executed.
# These are run in the provided order.
exec:
- ["make", "build"]
- make build

# Delay after which commands are executed.
delay: '1s'
delay: 1s
73 changes: 63 additions & 10 deletions cmd/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,14 @@ package cmd

import (
"fmt"
"time"

"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/viper"

"github.com/vrongmeal/leaf/pkg/engine"
"github.com/vrongmeal/leaf/pkg/types"
"github.com/vrongmeal/leaf/pkg/utils"
"github.com/vrongmeal/leaf/version"

Expand All @@ -16,28 +19,54 @@ import (

var (
confPath string
conf types.Config

rootCmd = &cobra.Command{
Use: "leaf",
Short: "General purpose hot-reloader for all projects",
Long: `Given a set of commands, leaf watches the filtered paths in the project directory for any changes and runs the commands in
order so you don't have to yourself`,

Run: func(*cobra.Command, []string) {
conf, err := utils.GetConfig(confPath)
if err != nil {
logrus.Fatalf("Error getting config: %s", err.Error())
PreRun: func(*cobra.Command, []string) {
if confPath != "" {
viper.SetConfigFile(confPath)
} else {
viper.SetConfigFile(utils.DefaultConfPath)
}

viper.AutomaticEnv()

if err := viper.ReadInConfig(); err != nil {
logrus.Warnln("Continuing without config...")
}

isdir, err := utils.IsDir(conf.Root)
if err != nil || !isdir {
conf.Root = utils.CWD
if err := viper.Unmarshal(&conf); err != nil {
logrus.Fatalf("Cannot unmarshal config: %s", err.Error())
}

// Check and include defaults if required
if len(conf.Exclude) == 0 {
conf.Exclude = utils.DefaultExcludePaths
} else {
finalExcludes := []string{}
for _, e := range conf.Exclude {
if e == utils.DefaultExcludePathsKeyword {
finalExcludes = append(finalExcludes, utils.DefaultExcludePaths...)
continue
}

finalExcludes = append(finalExcludes, e)
}

conf.Exclude = finalExcludes
}
},

Run: func(*cobra.Command, []string) {
logrus.Infof("Starting to watch: %s", conf.Root)
logrus.Infoln("Excluded paths:")
for i, e := range conf.Exclude {
logrus.Infof("%d. %s", i, e)
for _, e := range conf.Exclude {
logrus.Infof("\t%s", e)
}

if err := engine.Start(&conf); err != nil {
Expand All @@ -60,11 +89,35 @@ Version [%s]
)

func init() {
logrus.SetLevel(logrus.TraceLevel)
logrus.SetLevel(logrus.DebugLevel)
logrus.SetFormatter(new(prefixed.TextFormatter))

rootCmd.PersistentFlags().StringVarP(&confPath, "config", "c", utils.DefaultConfPath, "Config path for leaf configuration file")

rootCmd.Flags().StringP("root", "r", utils.CWD, "Root directory to watch")
rootCmd.Flags().StringSliceP(
"exclude", "e", utils.DefaultExcludePaths,
fmt.Sprintf("Paths to exclude. You can append default paths by adding `%s` in your list", utils.DefaultExcludePathsKeyword))
rootCmd.Flags().StringSliceP("filters", "f", []string{}, "Filters to apply to watch")
rootCmd.Flags().StringSliceP("exec", "x", []string{}, "Exec commands on file change")
rootCmd.Flags().DurationP("delay", "d", 500*time.Millisecond, "Delay after which commands are run on file change")

if err := viper.BindPFlag("root", rootCmd.Flags().Lookup("root")); err != nil {
logrus.Fatalf("Error binding flag to viper: %s", err.Error())
}
if err := viper.BindPFlag("exclude", rootCmd.Flags().Lookup("exclude")); err != nil {
logrus.Fatalf("Error binding flag to viper: %s", err.Error())
}
if err := viper.BindPFlag("filters", rootCmd.Flags().Lookup("filters")); err != nil {
logrus.Fatalf("Error binding flag to viper: %s", err.Error())
}
if err := viper.BindPFlag("exec", rootCmd.Flags().Lookup("exec")); err != nil {
logrus.Fatalf("Error binding flag to viper: %s", err.Error())
}
if err := viper.BindPFlag("delay", rootCmd.Flags().Lookup("delay")); err != nil {
logrus.Fatalf("Error binding flag to viper: %s", err.Error())
}

rootCmd.AddCommand(versionCmd)
}

Expand Down
22 changes: 18 additions & 4 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,31 @@ module github.com/vrongmeal/leaf
go 1.13

require (
github.com/BurntSushi/toml v0.3.1
github.com/fsnotify/fsnotify v1.4.7
github.com/golangci/golangci-lint v1.23.6 // indirect
github.com/golang/protobuf v1.3.2 // indirect
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51
github.com/konsorten/go-windows-terminal-sequences v1.0.2 // indirect
github.com/kr/pretty v0.2.0 // indirect
github.com/mattn/go-colorable v0.1.4 // indirect
github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b // indirect
github.com/onsi/ginkgo v1.12.0 // indirect
github.com/onsi/gomega v1.9.0 // indirect
github.com/pelletier/go-toml v1.6.0 // indirect
github.com/sirupsen/logrus v1.4.2
github.com/spf13/afero v1.2.2 // indirect
github.com/spf13/cast v1.3.1 // indirect
github.com/spf13/cobra v0.0.6
github.com/spf13/jwalterweatherman v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/spf13/viper v1.6.2
github.com/stretchr/testify v1.4.0 // indirect
github.com/x-cray/logrus-prefixed-formatter v0.5.2
golang.org/x/sys v0.0.0-20200212091648-12a6c2dcc1e4 // indirect
gopkg.in/yaml.v2 v2.2.8
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550 // indirect
golang.org/x/net v0.0.0-20190923162816-aa69164e4478 // indirect
golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae // indirect
golang.org/x/text v0.3.2 // indirect
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898 // indirect
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 // indirect
gopkg.in/ini.v1 v1.52.0 // indirect
gopkg.in/yaml.v2 v2.2.8 // indirect
)
Loading

0 comments on commit 3169aaa

Please sign in to comment.