Skip to content

Commit

Permalink
Merge pull request #51 from SpatiumPortae/f/refactor-config
Browse files Browse the repository at this point in the history
feat: refactor config for more extensibility
  • Loading branch information
mellonnen committed Feb 23, 2023
2 parents 11a72a8 + 2ed0248 commit 88805c3
Show file tree
Hide file tree
Showing 7 changed files with 81 additions and 40 deletions.
32 changes: 14 additions & 18 deletions cmd/portal/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,24 +7,13 @@ 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"
)

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)
Expand Down Expand Up @@ -94,7 +83,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)
}
Expand All @@ -114,10 +103,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.
Expand All @@ -128,14 +117,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)
Expand All @@ -146,3 +135,10 @@ func initConfig() {
}
}
}

// Sets default viper values.
func setDefaults() {
for k, v := range config.ToMap(config.GetDefault()) {
viper.SetDefault(k, v)
}
}
7 changes: 2 additions & 5 deletions cmd/portal/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
}
Expand Down
7 changes: 2 additions & 5 deletions cmd/portal/send.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,25 +55,22 @@ var sendCmd = &cobra.Command{
}
defer logFile.Close()

handleSendCommand(args, cmd.Flag("relay").Changed)
handleSendCommand(args)
return nil
},
}

// ------------------------------------------------------ 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
if err == nil {
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)
Expand Down
5 changes: 3 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
)

Expand All @@ -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
Expand Down Expand Up @@ -72,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
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -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=
Expand Down
50 changes: 50 additions & 0 deletions internal/config/config.go
Original file line number Diff line number Diff line change
@@ -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]
}
18 changes: 8 additions & 10 deletions ui/sender/sender.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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"
)

Expand Down Expand Up @@ -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)
Expand All @@ -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.
Expand Down Expand Up @@ -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()
}

0 comments on commit 88805c3

Please sign in to comment.