Add command to initialize client-config

This commit is contained in:
Torjus Håkestad 2021-12-04 03:56:57 +01:00
parent 7920fc9a19
commit 21c0f126dd
2 changed files with 50 additions and 1 deletions

View File

@ -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")

View File

@ -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")
}