From 21c0f126ddda3448f3a2c63874c96c9080ea779a Mon Sep 17 00:00:00 2001 From: = Date: Sat, 4 Dec 2021 03:56:57 +0100 Subject: [PATCH] Add command to initialize client-config --- cmd/ezshare.go | 10 ++++++++++ config/config.go | 41 ++++++++++++++++++++++++++++++++++++++++- 2 files changed, 50 insertions(+), 1 deletion(-) diff --git a/cmd/ezshare.go b/cmd/ezshare.go index f561e3d..65c3614 100644 --- a/cmd/ezshare.go +++ b/cmd/ezshare.go @@ -83,6 +83,11 @@ func main() { ArgsUsage: "PATH [PATH]..", Action: ActionClientUpload, }, + { + Name: "config-init", + Usage: "Initialize default config", + Action: ActionInitConfig, + }, }, }, { @@ -326,6 +331,11 @@ func ActionGencerts(c *cli.Context) error { return certs.GenAllCerts(outDir) } +func ActionInitConfig(c *cli.Context) error { + defaultCfg := config.FromDefault() + return defaultCfg.ToDefaultFile() +} + func getConfig(c *cli.Context) (*config.Config, error) { if c.IsSet("config") { cfgPath := c.String("config") diff --git a/config/config.go b/config/config.go index 7ccac2f..c8d89a9 100644 --- a/config/config.go +++ b/config/config.go @@ -3,8 +3,10 @@ package config import ( "crypto/tls" "crypto/x509" + "errors" "fmt" "io" + "io/fs" "io/ioutil" "os" "path/filepath" @@ -171,5 +173,42 @@ func (cc *ClientConfig) Creds() (credentials.TransportCredentials, error) { RootCAs: certPool, } return credentials.NewTLS(config), nil - +} + +func (c *Config) ToDefaultFile() error { + userConfigDir, err := os.UserConfigDir() + if err != nil { + return err + } + configDirPath := filepath.Join(userConfigDir, "ezshare") + info, err := os.Stat(configDirPath) + if err != nil { + if !errors.Is(err, fs.ErrNotExist) { + return err + } + if err := os.Mkdir(configDirPath, 0755); err != nil { + return fmt.Errorf("unable to create config-dir: %w", err) + } + } else { + if !info.IsDir() { + return fmt.Errorf("config-directory is not a directory") + } + } + + configFilePath := filepath.Join(configDirPath, "ezshare.toml") + _, err = os.Stat(configFilePath) + if err != nil { + if !errors.Is(err, fs.ErrNotExist) { + return fmt.Errorf("error stating config-file: %w", err) + } + + f, err := os.Create(configFilePath) + if err != nil { + return fmt.Errorf("unable to create config-file: %w", err) + } + encoder := toml.NewEncoder(f) + fmt.Printf("Writing config to '%s'", configFilePath) + return encoder.Encode(c) + } + return fmt.Errorf("config-file already exists") }