From 6e874119c5f858c0efbf0b4cb95c200d030922c9 Mon Sep 17 00:00:00 2001 From: Zino Kader Date: Thu, 23 Feb 2023 16:23:02 +0100 Subject: [PATCH 1/2] feat: refactor config for more extensibility --- cmd/portal/config.go | 33 ++++++++++++-------------- cmd/portal/main.go | 7 ++---- cmd/portal/send.go | 7 ++---- go.mod | 1 + go.sum | 2 ++ internal/config/config.go | 50 +++++++++++++++++++++++++++++++++++++++ ui/sender/sender.go | 18 +++++++------- 7 files changed, 80 insertions(+), 38 deletions(-) create mode 100644 internal/config/config.go diff --git a/cmd/portal/config.go b/cmd/portal/config.go index 27f239a..e26339d 100644 --- a/cmd/portal/config.go +++ b/cmd/portal/config.go @@ -7,24 +7,14 @@ import ( "path/filepath" "strings" + "github.com/SpatiumPortae/portal/internal/config" "github.com/alecthomas/chroma/quick" homedir "github.com/mitchellh/go-homedir" "github.com/spf13/cobra" "github.com/spf13/viper" + "honnef.co/go/tools/config" ) -const CONFIGS_DIR_NAME = ".config" -const PORTAL_CONFIG_DIR_NAME = "portal" -const CONFIG_FILE_NAME = "config" -const CONFIG_FILE_EXT = "yml" - -const DEFAULT_RELAY = "167.71.65.96:80" -const DEFAULT_CONFIG = "relay: " + DEFAULT_RELAY - -type Config struct { - Relay string `mapstructure:"relay"` -} - func init() { configCmd.AddCommand(configPathCmd) configCmd.AddCommand(configViewCmd) @@ -94,7 +84,7 @@ var configResetCmd = &cobra.Command{ Short: "Reset to the default configuration", RunE: func(cmd *cobra.Command, args []string) error { configPath := viper.ConfigFileUsed() - err := os.WriteFile(configPath, []byte(DEFAULT_CONFIG), 0) + err := os.WriteFile(configPath, config.ToYaml(config.GetDefault()), 0) if err != nil { return fmt.Errorf("config file (%s) could not be read/written to: %w", configPath, err) } @@ -114,10 +104,10 @@ func initConfig() { os.Exit(1) } - configPath := filepath.Join(home, CONFIGS_DIR_NAME, PORTAL_CONFIG_DIR_NAME) + configPath := filepath.Join(home, config.CONFIGS_DIR_NAME, config.PORTAL_CONFIG_DIR_NAME) viper.AddConfigPath(configPath) - viper.SetConfigName(CONFIG_FILE_NAME) - viper.SetConfigType(CONFIG_FILE_EXT) + viper.SetConfigName(config.CONFIG_FILE_NAME) + viper.SetConfigType(config.CONFIG_FILE_EXT) if err := viper.ReadInConfig(); err != nil { // Create config file if not found. @@ -128,14 +118,14 @@ func initConfig() { os.Exit(1) } - configFile, err := os.Create(filepath.Join(configPath, fmt.Sprintf("%s.%s", CONFIG_FILE_NAME, CONFIG_FILE_EXT))) + configFile, err := os.Create(filepath.Join(configPath, fmt.Sprintf("%s.%s", config.CONFIG_FILE_NAME, config.CONFIG_FILE_EXT))) if err != nil { fmt.Println("Could not create config file:", err) os.Exit(1) } defer configFile.Close() - _, err = configFile.Write([]byte(DEFAULT_CONFIG)) + _, err = configFile.Write(config.ToYaml(config.GetDefault())) if err != nil { fmt.Println("Could not write defaults to config file:", err) os.Exit(1) @@ -146,3 +136,10 @@ func initConfig() { } } } + +// Sets default viper values. +func setDefaults() { + for k, v := range config.ToMap(config.GetDefault()) { + viper.SetDefault(k, v) + } +} diff --git a/cmd/portal/main.go b/cmd/portal/main.go index 654928f..fc5c411 100644 --- a/cmd/portal/main.go +++ b/cmd/portal/main.go @@ -18,10 +18,7 @@ var version string // Initialization of cobra and viper. func init() { initConfig() - - // Set default values - viper.SetDefault("verbose", false) - viper.SetDefault("relay", DEFAULT_RELAY) + setDefaults() rootCmd.PersistentFlags().BoolP("verbose", "v", false, "Log debug information to a file on the format `.portal-[command].log` in the current directory") // Add cobra subcommands. @@ -66,7 +63,7 @@ func setupLoggingFromViper(cmd string) (*os.File, error) { if viper.GetBool("verbose") { f, err := tea.LogToFile(fmt.Sprintf(".portal-%s.log", cmd), fmt.Sprintf("portal-%s: \n", cmd)) if err != nil { - return nil, fmt.Errorf("could not log to the provided file") + return nil, fmt.Errorf("could not log to the provided file: %w", err) } return f, nil } diff --git a/cmd/portal/send.go b/cmd/portal/send.go index efde435..ae48295 100644 --- a/cmd/portal/send.go +++ b/cmd/portal/send.go @@ -55,7 +55,7 @@ var sendCmd = &cobra.Command{ } defer logFile.Close() - handleSendCommand(args, cmd.Flag("relay").Changed) + handleSendCommand(args) return nil }, } @@ -63,7 +63,7 @@ var sendCmd = &cobra.Command{ // ------------------------------------------------------ Handler ------------------------------------------------------ // handleSendCommand is the sender application. -func handleSendCommand(fileNames []string, selfHostedRelay bool) { +func handleSendCommand(fileNames []string) { var opts []senderui.Option ver, err := semver.Parse(version) // Conditionally add option to sender ui @@ -71,9 +71,6 @@ func handleSendCommand(fileNames []string, selfHostedRelay bool) { opts = append(opts, senderui.WithVersion(ver)) } relayAddr := viper.GetString("relay") - if selfHostedRelay { - opts = append(opts, senderui.WithCopyFlags(map[string]string{"--relay": relayAddr})) - } sender := senderui.New(fileNames, relayAddr, opts...) if _, err := sender.Run(); err != nil { fmt.Println("Error initializing UI", err) diff --git a/go.mod b/go.mod index 1cba247..b24ef4e 100644 --- a/go.mod +++ b/go.mod @@ -50,6 +50,7 @@ require ( github.com/docker/distribution v2.8.0+incompatible // indirect github.com/docker/docker v20.10.11+incompatible // indirect github.com/docker/go-units v0.4.0 // indirect + github.com/fatih/structs v1.1.0 // indirect github.com/gogo/protobuf v1.3.2 // indirect github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect github.com/golang/protobuf v1.5.2 // indirect diff --git a/go.sum b/go.sum index cbc43ff..bf20cb5 100644 --- a/go.sum +++ b/go.sum @@ -303,6 +303,8 @@ github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7 github.com/evanphx/json-patch v4.9.0+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk= github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= github.com/fatih/color v1.10.0/go.mod h1:ELkj/draVOlAH/xkhN6mQ50Qd0MPOk5AAr3maGEBuJM= +github.com/fatih/structs v1.1.0 h1:Q7juDM0QtcnhCpeyLGQKyg4TOIghuNXrkL32pHAUMxo= +github.com/fatih/structs v1.1.0/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga6PJ7M= github.com/form3tech-oss/jwt-go v3.2.2+incompatible/go.mod h1:pbq4aXjuKjdthFRnoDwaVPLA+WlJuPGy+QneDUgJi2k= github.com/frankban/quicktest v1.11.3/go.mod h1:wRf/ReqHper53s+kmmSZizM8NamnL3IM0I9ntUbOk+k= github.com/frankban/quicktest v1.14.3 h1:FJKSZTDHjyhriyC81FLQ0LY93eSai0ZyR/ZIkd3ZUKE= diff --git a/internal/config/config.go b/internal/config/config.go new file mode 100644 index 0000000..ccfc705 --- /dev/null +++ b/internal/config/config.go @@ -0,0 +1,50 @@ +package config + +import ( + "fmt" + "strings" + + "github.com/fatih/structs" + "github.com/spf13/viper" +) + +const CONFIGS_DIR_NAME = ".config" +const PORTAL_CONFIG_DIR_NAME = "portal" +const CONFIG_FILE_NAME = "config" +const CONFIG_FILE_EXT = "yml" + +type Config struct { + Relay string `mapstructure:"relay"` + Verbose bool `mapstructure:"verbose"` +} + +func GetDefault() Config { + return Config{ + Relay: "167.71.65.96:80", + Verbose: false, + } +} + +func ToMap(config Config) map[string]any { + p := map[string]any{} + for _, field := range structs.Fields(config) { + key := field.Tag("mapstructure") + value := field.Value() + p[key] = value + } + return p +} + +func ToYaml(config Config) []byte { + var builder strings.Builder + for k, v := range ToMap(config) { + builder.WriteString(fmt.Sprintf("%s: %v", k, v)) + builder.WriteRune('\n') + } + return []byte(builder.String()) +} + +func IsDefault(key string) bool { + defaults := ToMap(GetDefault()) + return viper.Get(key) == defaults[key] +} diff --git a/ui/sender/sender.go b/ui/sender/sender.go index 9771d11..2e8dcb7 100644 --- a/ui/sender/sender.go +++ b/ui/sender/sender.go @@ -8,6 +8,7 @@ import ( "strings" "time" + "github.com/SpatiumPortae/portal/internal/config" "github.com/SpatiumPortae/portal/internal/conn" "github.com/SpatiumPortae/portal/internal/file" "github.com/SpatiumPortae/portal/internal/semver" @@ -24,6 +25,7 @@ import ( tea "github.com/charmbracelet/bubbletea" "github.com/charmbracelet/lipgloss" "github.com/pkg/errors" + "github.com/spf13/viper" "golang.org/x/exp/slices" ) @@ -67,12 +69,6 @@ func WithVersion(version semver.Version) Option { } } -func WithCopyFlags(flags map[string]string) Option { - return func(m *model) { - m.copyFlags = flags - } -} - type model struct { state uiState // defaults to 0 (showPassword) transferType transfer.Type // defaults to 0 (Unknown) @@ -97,7 +93,6 @@ type model struct { help help.Model keys ui.KeyMap copyMessageTimer timer.Model - copyFlags map[string]string } // New creates a new sender program. @@ -455,11 +450,14 @@ func (m *model) copyReceiverCommand() string { var builder strings.Builder builder.WriteString("portal receive ") builder.WriteString(m.password) - for flag, value := range m.copyFlags { + + relayAddrKey := "relay" + if !config.IsDefault(relayAddrKey) { builder.WriteRune(' ') - builder.WriteString(flag) + builder.WriteString(fmt.Sprintf("--%s", relayAddrKey)) builder.WriteRune(' ') - builder.WriteString(value) + builder.WriteString(viper.GetString(relayAddrKey)) } + return builder.String() } From 2ed0248b4a23945718eaff4e55f58ac3ae81bb1e Mon Sep 17 00:00:00 2001 From: Zino Kader Date: Thu, 23 Feb 2023 16:24:44 +0100 Subject: [PATCH 2/2] fix: bugs --- cmd/portal/config.go | 1 - go.mod | 6 +++--- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/cmd/portal/config.go b/cmd/portal/config.go index e26339d..2fff22a 100644 --- a/cmd/portal/config.go +++ b/cmd/portal/config.go @@ -12,7 +12,6 @@ import ( homedir "github.com/mitchellh/go-homedir" "github.com/spf13/cobra" "github.com/spf13/viper" - "honnef.co/go/tools/config" ) func init() { diff --git a/go.mod b/go.mod index b24ef4e..04ba7af 100644 --- a/go.mod +++ b/go.mod @@ -3,11 +3,13 @@ module github.com/SpatiumPortae/portal go 1.18 require ( + github.com/alecthomas/chroma v0.10.0 github.com/atotto/clipboard v0.1.4 github.com/charmbracelet/bubbles v0.15.0 github.com/charmbracelet/bubbletea v0.23.2 github.com/charmbracelet/lipgloss v0.6.0 github.com/docker/go-connections v0.4.0 + github.com/fatih/structs v1.1.0 github.com/klauspost/pgzip v1.2.5 github.com/mattn/go-runewidth v0.0.14 github.com/mitchellh/go-homedir v1.1.0 @@ -17,6 +19,7 @@ require ( github.com/stretchr/testify v1.8.1 github.com/testcontainers/testcontainers-go v0.13.0 go.uber.org/zap v1.24.0 + golang.org/x/net v0.7.0 nhooyr.io/websocket v1.8.7 ) @@ -39,7 +42,6 @@ require ( github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 // indirect github.com/Microsoft/go-winio v0.5.2 // indirect github.com/Microsoft/hcsshim v0.8.25 // indirect - github.com/alecthomas/chroma v0.10.0 // indirect github.com/aymanbagabas/go-osc52 v1.2.1 // indirect github.com/cenkalti/backoff/v4 v4.1.2 // indirect github.com/charmbracelet/harmonica v0.2.0 // indirect @@ -50,7 +52,6 @@ require ( github.com/docker/distribution v2.8.0+incompatible // indirect github.com/docker/docker v20.10.11+incompatible // indirect github.com/docker/go-units v0.4.0 // indirect - github.com/fatih/structs v1.1.0 // indirect github.com/gogo/protobuf v1.3.2 // indirect github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect github.com/golang/protobuf v1.5.2 // indirect @@ -73,7 +74,6 @@ require ( go.opencensus.io v0.24.0 // indirect go.uber.org/atomic v1.10.0 // indirect go.uber.org/multierr v1.9.0 // indirect - golang.org/x/net v0.7.0 // indirect golang.org/x/sync v0.1.0 // indirect google.golang.org/genproto v0.0.0-20221227171554-f9683d7f8bef // indirect google.golang.org/grpc v1.52.0 // indirect