Skip to content

Commit

Permalink
add configuration file via viper
Browse files Browse the repository at this point in the history
  • Loading branch information
lylex committed Dec 4, 2018
1 parent dce6aad commit ff44a2e
Show file tree
Hide file tree
Showing 4 changed files with 73 additions and 7 deletions.
48 changes: 42 additions & 6 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,33 +2,46 @@ package cmd

import (
"fmt"
"os"
"path/filepath"
"time"

"github.com/lylex/drm/pkg/files"
"github.com/lylex/drm/pkg/utils"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)

const (
// RootCmdName represents the cobra root command name.
RootCmdName = "drm"

// TODO replate it
// DefaultConfigPath represents the default path for config.
DefaultConfigPath = "/etc/drm/drm.cfg"

// TempFileStorePath TODO replate it
TempFileStorePath = "/Users/xuq3/workspace/drm/tem"
)

var (
isForce bool
isRecursive bool
version string
cfgFile = DefaultConfigPath
)

func init() {
RootCmd.Flags().BoolVarP(&isRecursive, "recursive", "r", false, `ignore
nonexistent files and arguments, never prompt`)
RootCmd.PersistentFlags().BoolVarP(&isForce, "force", "f", false, `remove directories
and their contents recursively or not`)
cobra.OnInitialize(initConfig)

// determin whether to remove recursively.
RootCmd.Flags().BoolVarP(&isRecursive, "recursive", "r", false, "remove directories and their contents recursively or not")

// determine whether to remove objects by force.
RootCmd.Flags().BoolVarP(&isForce, "force", "f", false, "ignore nonexistent files and arguments, never prompt")

// pass configuration file from options.
RootCmd.PersistentFlags().StringVar(&cfgFile, "config", DefaultConfigPath,
fmt.Sprintf("config file (default is %s)", DefaultConfigPath))
}

// RootCmd represents the base command.
Expand All @@ -45,6 +58,13 @@ var RootCmd = &cobra.Command{
Version: fmt.Sprintf("%s", version),
Args: cobra.ArbitraryArgs,
Run: func(cmd *cobra.Command, args []string) {
if len(args) == 0 {
msg := "no operation concluded"
fmt.Fprintf(os.Stderr, fmt.Sprintf("Error: %s\n", msg))
cmd.Usage()
utils.ErrExit(fmt.Sprintf("\nFailed to execute command: %s\n", msg), nil)
}

for _, path := range args {
if !files.IsAbsolutePath(path) {
path = filepath.Join(files.GetWd(), path)
Expand All @@ -60,7 +80,7 @@ var RootCmd = &cobra.Command{
if files.IsDir(path) && !isRecursive {
utils.ErrExit(fmt.Sprintf("%s: %s: is a directory\n", RootCmdName, path), nil)
}
files.Move(path, filepath.Join(TempFileStorePath,
files.Move(path, filepath.Join(string(viper.GetString("dataPath")),
fmt.Sprintf("%d_%s", time.Now().UnixNano(), files.Name(path))))
}
},
Expand All @@ -73,3 +93,19 @@ func Execute() {
utils.ErrExit("Failed to execute command: %+v\n", err)
}
}

// initConfig reads in config file and ENV variables if set.
func initConfig() {
if cfgFile == "" {
cfgFile = DefaultConfigPath
}
viper.SetConfigFile(cfgFile)
viper.SetConfigType("json")

if err := viper.ReadInConfig(); err != nil {
utils.ErrExit("Failed to read configuration file: %+v\n", err)
}

// read config from enviroment virable.
viper.AutomaticEnv()
}
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ require (
github.com/inconshreveable/mousetrap v1.0.0 // indirect
github.com/spf13/cobra v0.0.3
github.com/spf13/pflag v1.0.3 // indirect
github.com/spf13/viper v1.2.1
)

replace github.com/lylex/drm/pkg/utils => ./pkg/utils
Expand Down
27 changes: 27 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,6 +1,33 @@
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I=
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4=
github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ=
github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM=
github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
github.com/magiconair/properties v1.8.0 h1:LLgXmsheXeRoUOBOjtwPQCWIYqM/LU1ayDtDePerRcY=
github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ=
github.com/mitchellh/mapstructure v1.0.0 h1:vVpGvMXJPqSDh2VYHF7gsfQj8Ncx+Xw5Y1KHeTRY+7I=
github.com/mitchellh/mapstructure v1.0.0/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
github.com/pelletier/go-toml v1.2.0 h1:T5zMGML61Wp+FlcbWjRDT7yAxhJNAiPPLOFECq181zc=
github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic=
github.com/spf13/afero v1.1.2 h1:m8/z1t7/fwjysjQRYbP0RD+bUIF/8tJwPdEZsI83ACI=
github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ=
github.com/spf13/cast v1.2.0 h1:HHl1DSRbEQN2i8tJmtS6ViPyHx35+p51amrdsiTCrkg=
github.com/spf13/cast v1.2.0/go.mod h1:r2rcYCSwa1IExKTDiTfzaxqT2FNHs8hODu4LnUfgKEg=
github.com/spf13/cobra v0.0.3 h1:ZlrZ4XsMRm04Fr5pSFxBgfND2EBVa1nLpiy1stUsX/8=
github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ=
github.com/spf13/jwalterweatherman v1.0.0 h1:XHEdyB+EcvlqZamSM4ZOMGlc93t6AcsBEu9Gc1vn7yk=
github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo=
github.com/spf13/pflag v1.0.2/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=
github.com/spf13/pflag v1.0.3 h1:zPAT6CGy6wXeQ7NtTnaTerfKOsV6V6F8agHXFiazDkg=
github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=
github.com/spf13/viper v1.2.1 h1:bIcUwXqLseLF3BDAZduuNfekWG87ibtFxi59Bq+oI9M=
github.com/spf13/viper v1.2.1/go.mod h1:P4AexN0a+C9tGAnUFNwDMYYZv3pjFuvmeiMyKRaNVlI=
golang.org/x/sys v0.0.0-20180906133057-8cf3aee42992 h1:BH3eQWeGbwRU2+wxxuuPOdFBmaiBH81O8BugSjHeTFg=
golang.org/x/sys v0.0.0-20180906133057-8cf3aee42992/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.1 h1:mUhvW9EsL+naU5Q3cakzfE91YhliOondGd6ZrsDBHQE=
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
4 changes: 3 additions & 1 deletion scripts/drm.conf
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
key: value
{
"dataPath": "/usr/lib/drm/"
}

0 comments on commit ff44a2e

Please sign in to comment.