Skip to content

Commit

Permalink
Support config files
Browse files Browse the repository at this point in the history
  • Loading branch information
ashald committed Jun 14, 2019
1 parent b51c47a commit 76b03f2
Show file tree
Hide file tree
Showing 12 changed files with 132 additions and 147 deletions.
13 changes: 5 additions & 8 deletions app/exec.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"fmt"
"github.com/mitchellh/go-homedir"
"github.com/paraterraform/para/app/index"
"github.com/paraterraform/para/utils"
"io/ioutil"
"os"
"os/exec"
Expand Down Expand Up @@ -33,15 +34,11 @@ func Execute(args []string, primaryIndexCandidates, indexExtensions []string, cu
var stat os.FileInfo
var err error

fmt.Printf("Para is being initialized...\n")

// Plugin Dir
fmt.Printf("- Plugin Dir: ")
for _, pluginDir = range pluginDirCandidates {
expandedPath, err := homedir.Expand(pluginDir)
if err != nil {
continue
}
expandedPath := utils.PathExpand(pluginDir)

if stat, err = os.Stat(expandedPath); !os.IsNotExist(err) {
mountpoint = &expandedPath
break
Expand Down Expand Up @@ -100,7 +97,7 @@ func Execute(args []string, primaryIndexCandidates, indexExtensions []string, cu
)
os.Exit(1)
}
fmt.Println(simplifyPath(cacheDir))
fmt.Println(utils.PathSimplify(cacheDir))

// Primary Index
fmt.Printf("- Primary Index: ")
Expand Down Expand Up @@ -221,7 +218,7 @@ func discoverCacheDir(customPath string) (string, error) {
userCacheDir, err := os.UserCacheDir()
if err != nil {
userCacheDirForPara := filepath.Join(userCacheDir, "para")
if pathExists(userCacheDirForPara) {
if utils.PathExists(userCacheDirForPara) {
return userCacheDirForPara, nil // TODO verify it's writable?
}
}
Expand Down
11 changes: 5 additions & 6 deletions app/index/loading.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@ package index

import (
"fmt"
"github.com/paraterraform/para/app/crypto"
"github.com/paraterraform/para/app/xio"
"github.com/paraterraform/para/utils"
yml "gopkg.in/ashald/yaml.v2"
"io/ioutil"
"os"
Expand Down Expand Up @@ -62,9 +61,9 @@ func DiscoverIndex(candidates []string, cacheDir string, refresh time.Duration)
}

func openIndex(location string, cacheDir string, refresh time.Duration) ([]byte, time.Time, error) {
if xio.IsRemote(location) {
if utils.UrlIsRemote(location) {
indexCacheDir := filepath.Join(cacheDir, "index")
indexCachePath := filepath.Join(indexCacheDir, crypto.DefaultStringHash(location))
indexCachePath := filepath.Join(indexCacheDir, utils.HashString(location))

cacheData, errCacheData := ioutil.ReadFile(indexCachePath)
cacheMeta, errCacheMeta := os.Stat(indexCachePath)
Expand All @@ -77,7 +76,7 @@ func openIndex(location string, cacheDir string, refresh time.Duration) ([]byte,

maxAge := time.Duration(refresh) * time.Minute
if cacheTimestamp.Before(time.Now().Add(-maxAge)) || errCacheData != nil {
freshData, errFreshData := xio.UrlReadAll(location)
freshData, errFreshData := utils.UrlReadAll(location)
if errFreshData != nil {
if errCacheData != nil {
return nil, time.Now(), errFreshData // we're not sure our cache is valid and failed to fetch so just fail
Expand All @@ -93,7 +92,7 @@ func openIndex(location string, cacheDir string, refresh time.Duration) ([]byte,
return cacheData, cacheTimestamp, nil
}
} else {
data, err := xio.UrlReadAll(location)
data, err := utils.UrlReadAll(location)
return data, time.Now(), err
}
}
Expand Down
7 changes: 3 additions & 4 deletions app/index/runtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@ package index

import (
"fmt"
"github.com/paraterraform/para/app/crypto"
"github.com/paraterraform/para/app/xio"
"github.com/paraterraform/para/utils"
"io"
"os"
"path/filepath"
Expand Down Expand Up @@ -118,7 +117,7 @@ func (i *RuntimeIndex) ClosePlugin(plugin *Plugin) error {

func downloadPlugin(url string, saveTo string) error {
// Get the data
pluginData, err := xio.UrlOpen(url)
pluginData, err := utils.UrlOpen(url)
if err != nil {
return err
}
Expand Down Expand Up @@ -152,7 +151,7 @@ func verifyPlugin(path string, size uint64, digest string) error {
}

if len(digest) > 0 {
return crypto.CheckDigest(path, digest)
return utils.DigestVerify(path, digest)
}

return nil
Expand Down
30 changes: 0 additions & 30 deletions app/paths.go

This file was deleted.

124 changes: 70 additions & 54 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bazil.org/fuse"
"fmt"
"github.com/paraterraform/para/app"
"github.com/paraterraform/para/utils"
"github.com/spf13/viper"
"os"
"strings"
Expand All @@ -12,6 +13,16 @@ import (
"github.com/spf13/cobra"
)

const (
flagConfig = "config"
flagUnmount = "unmount"

flagIndex = "index"
flagExtensions = "extensions"
flagCache = "cache"
flagRefresh = "refresh"
)

const usageTemplate = `Flags:
{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}
`
Expand Down Expand Up @@ -43,29 +54,25 @@ Use "para -h/--help" for more information.

var defaultConfigCandidates = []string{
"para.cfg.yaml",
"~/.para.cfg.yaml",
"/etc/para.cfg.yaml",
"~/.para/para.cfg.yaml",
"/etc/para/para.cfg.yaml",
}

var defaultIndexCandidates = []string{
"para.idx.yaml",
"~/.para.idx.yaml",
"/etc/para.idx.yaml",
"~/.para/para.idx.yaml",
"/etc/para/para.idx.yaml",
"https://raw.githubusercontent.com/paraterraform/index/master/para.idx.yaml",
}

var defaultExtensionsCandidates = []string{
"para.d",
"~/.para.d",
"/etc/para.d",
"para.idx.d",
"~/.para/para.idx.d",
"/etc/para/para.idx.d",
}

var optionCachePath string
var optionIndex string
var optionConfig string
var optionExtensions string
var optionUnmount string
var optionRefresh time.Duration

var rootCmd = &cobra.Command{

Expand Down Expand Up @@ -141,20 +148,23 @@ Concepts
}

var indexCandidates []string

if len(optionConfig) > 0 {
indexCandidates = append(indexCandidates, optionConfig)
optionIndex := viper.GetString(flagIndex)
if len(optionIndex) > 0 {
indexCandidates = append(indexCandidates, optionIndex)
} else {
indexCandidates = defaultIndexCandidates
}

var extensionsCandidates []string
optionExtensions := viper.GetString(flagExtensions)
if len(optionExtensions) > 0 {
extensionsCandidates = append(extensionsCandidates, optionExtensions)
} else {
extensionsCandidates = defaultExtensionsCandidates
}

optionCachePath := viper.GetString(flagCache)
optionRefresh := viper.GetDuration(flagRefresh)
app.Execute(args, indexCandidates, extensionsCandidates, optionCachePath, optionRefresh)
},
}
Expand All @@ -167,88 +177,94 @@ func Execute() {
}

func init() {
//cobra.OnInitialize(initConfig) // TODO - reactivate
fmt.Println("Para is being initialized...")

cobra.OnInitialize(initConfig)
rootCmd.Flags().SetInterspersed(false)
rootCmd.Flags().SortFlags = false
rootCmd.SetUsageTemplate(usageTemplate)
rootCmd.Flags().StringVarP(
&optionConfig,
"config",
flagConfig,
"f",
"",
fmt.Sprintf(
"config file (default - first available from: %s)",
strings.Join(defaultConfigCandidates, ", "),
),
)
rootCmd.Flags().StringVarP(
&optionIndex,
"index",
rootCmd.Flags().StringP(
flagIndex,
"i",
"",
fmt.Sprintf(
"index location (default - first available from: %s)",
strings.Join(defaultIndexCandidates, ", "),
),
)
rootCmd.Flags().StringVarP(
&optionExtensions,
"extensions",
rootCmd.Flags().StringP(
flagExtensions,
"x",
"",
fmt.Sprintf(
"index extensions directory (default - union from: %s)",
strings.Join(defaultExtensionsCandidates, ", "),
),
)
rootCmd.Flags().StringVarP(
&optionCachePath,
"cache",
rootCmd.Flags().StringP(
flagCache,
"c",
"",
"cache dir (default - ~/.cache/para if exists or /tmp/para-$UID)",
)
rootCmd.Flags().DurationVarP(
&optionRefresh,
"refresh",
rootCmd.Flags().DurationP(
flagRefresh,
"r",
time.Hour,
"attempt to refresh remote indices every given interval",
)
rootCmd.Flags().StringVarP(
&optionUnmount,
"unmount",
flagUnmount,
"u",
"",
"force unmount dir (just unmount the given dir and exit, all other flags and arguments ignored)",
)

_ = viper.BindPFlag("index", rootCmd.Flags().Lookup("index"))
_ = viper.BindPFlag("extensions", rootCmd.Flags().Lookup("extensions"))
_ = viper.BindPFlag("cache", rootCmd.Flags().Lookup("cache"))
_ = viper.BindPFlag("refresh", rootCmd.Flags().Lookup("refresh"))
_ = viper.BindPFlag(flagIndex, rootCmd.Flags().Lookup(flagIndex))
_ = viper.BindPFlag(flagExtensions, rootCmd.Flags().Lookup(flagExtensions))
_ = viper.BindPFlag(flagCache, rootCmd.Flags().Lookup(flagCache))
_ = viper.BindPFlag(flagRefresh, rootCmd.Flags().Lookup(flagRefresh))
}

func initConfig() {
//// Don't forget to read config either from cfgFile or from home directory!
//if cfgFile != "" {
// // Use config file from the flag.
// viper.SetConfigFile(cfgFile)
//} else {
// // Find home directory.
// home, err := homedir.Dir()
// if err != nil {
// fmt.Println(err)
// os.Exit(1)
// }
//
// // Search config in home directory with name ".cobra" (without extension).
// viper.AddConfigPath(home)
// viper.SetConfigName("para.cfg.yaml")
//}
//
//if err := viper.ReadInConfig(); err != nil {
// fmt.Println("Can't read config:", err)
// os.Exit(1)
//}
var candidates []string
var selected string

// Don't forget to read config either from cfgFile or from home directory!
if optionConfig != "" {
candidates = []string{optionConfig}
// Use config file from the flag.
//
} else {
candidates = defaultConfigCandidates
}

// For now just sticking with YAML
// TODO consider using viper to parse all configs and therefore support more formats
for _, path := range candidates {
expanded := utils.PathExpand(path)
if utils.PathExists(expanded) {
selected = expanded
}
}

if selected != "" {
fmt.Println("- Config File:", utils.PathSimplify(selected))
viper.SetConfigFile(selected)
if err := viper.ReadInConfig(); err != nil {
fmt.Println("* Can't read config:", err)
os.Exit(1)
}
}
}
4 changes: 0 additions & 4 deletions scratch/hello

This file was deleted.

Loading

0 comments on commit 76b03f2

Please sign in to comment.