Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ Flags:

## Configuration

You can preconfigure rcon-cli to use the arguments you want by default with a config file. rcon-cli uses the first one it finds of:
You can preconfigure rcon-cli to use the arguments you want by default with a config file. The config file is YAML (`.yaml` or `.yml`). rcon-cli uses the first one it finds of:

1. the file given with `--config /path/to/the/config.yaml`
2. `rcon-cli/config.yaml` in your user config directory: `$XDG_CONFIG_HOME` or `~/.config` on Linux, `~/Library/Application Support` on macOS, `%AppData%` on Windows
Expand Down
113 changes: 79 additions & 34 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,23 +15,44 @@
package cmd

import (
"flag"
"fmt"
"log"
"net"
"os"
"path/filepath"
"strconv"
"strings"

"github.com/itzg/go-flagsfiller"
"github.com/itzg/rcon-cli/cli"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"gopkg.in/yaml.v3"
)

// Config holds every rcon-cli setting. Flags, environment variables and
// the config file all feed into this one struct.
type Config struct {
Host string `default:"localhost" usage:"RCON server's hostname"`
Password string `usage:"RCON server's password"`
Port int `default:"25575" usage:"Server's RCON port"`
AbortOnCtrlC bool `default:"true" usage:"Abort on ctrl-c rather than clearing line"`
}

var (
cfgFile string
config Config
)

// fileConfig mirrors Config but with pointer fields, so a config file
// that omits a key can be told apart from one that sets it. A missing
// key must not overwrite the flag, env or default value.
type fileConfig struct {
Host *string `yaml:"host"`
Password *string `yaml:"password"`
Port *int `yaml:"port"`
AbortOnCtrlC *bool `yaml:"abort-on-ctrl-c"`
}

// RootCmd represents the base command when called without any subcommands
var RootCmd = &cobra.Command{
Use: "rcon-cli [flags] [RCON command ...]",
Expand All @@ -51,15 +72,12 @@ as a single command (joined by spaces), the response is displayed,
and the CLI will exit.
`,
Run: func(cmd *cobra.Command, args []string) {

hostPort := net.JoinHostPort(viper.GetString("host"), strconv.Itoa(viper.GetInt("port")))
password := viper.GetString("password")
abortOnCtrlC := viper.GetBool("abort-on-ctrl-c")
hostPort := net.JoinHostPort(config.Host, strconv.Itoa(config.Port))

if len(args) == 0 {
cli.Start(hostPort, password, os.Stdout, abortOnCtrlC)
cli.Start(hostPort, config.Password, os.Stdout, config.AbortOnCtrlC)
} else {
cli.Execute(hostPort, password, os.Stdout, args...)
cli.Execute(hostPort, config.Password, os.Stdout, args...)
}
},
}
Expand All @@ -77,37 +95,60 @@ func init() {
cobra.OnInitialize(initConfig)

RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $XDG_CONFIG_HOME/rcon-cli/config.yaml or $HOME/.rcon-cli.yaml)")
RootCmd.PersistentFlags().String("host", "localhost", "RCON server's hostname")
RootCmd.PersistentFlags().String("password", "", "RCON server's password")
RootCmd.PersistentFlags().Int("port", 25575, "Server's RCON port")
RootCmd.PersistentFlags().Bool("abort-on-ctrl-c", true, "Abort on ctrl-c rather than clearing line")
err := viper.BindPFlags(RootCmd.PersistentFlags())
if err != nil {

filler := flagsfiller.New(flagsfiller.WithEnv("RCON"))
var fs flag.FlagSet
if err := filler.Fill(&fs, &config); err != nil {
log.Fatal(err)
}
RootCmd.PersistentFlags().AddGoFlagSet(&fs)
}

// initConfig reads in config file and ENV variables if set.
func initConfig() {
if cfgFile != "" { // enable ability to specify config file via flag
viper.SetConfigFile(cfgFile)
} else if userConfigFile := findUserConfigFile(); userConfigFile != "" {
viper.SetConfigFile(userConfigFile)
} else {
viper.SetConfigName(".rcon-cli") // name of config file (without extension)
viper.AddConfigPath("$HOME")
viper.AddConfigPath("/data")
viper.AddConfigPath("/server")
path := cfgFile
if path == "" {
path = findUserConfigFile()
}
if path == "" {
for _, dir := range []string{"$HOME", "/data", "/server"} {
if p := findConfigFileIn(dir); p != "" {
path = p
break
}
}
}
if path == "" {
return
}
data, err := os.ReadFile(path)
if err != nil {
log.Fatalf("reading config file %s: %v", path, err)
}
var fc fileConfig
if err := yaml.Unmarshal(data, &fc); err != nil {
log.Fatalf("parsing config file %s: %v", path, err)
}
applyConfigFile(&fc)
}

// This will allow for env vars like RCON_PORT
viper.SetEnvPrefix("rcon")
viper.SetEnvKeyReplacer(strings.NewReplacer("-", "_"))
viper.AutomaticEnv() // read in environment variables that match

// If a config file is found, read it in.
// Indicates viper.ConfigFileNotFoundError if no config file is provided, which is fine
_ = viper.ReadInConfig()
// applyConfigFile copies a config file value into config only where the
// user did not set the value by flag or by env, so the precedence stays
// flags > env > config file > defaults.
func applyConfigFile(fc *fileConfig) {
flags := RootCmd.PersistentFlags()
if fc.Host != nil && !flags.Changed("host") && os.Getenv("RCON_HOST") == "" {
config.Host = *fc.Host
}
if fc.Password != nil && !flags.Changed("password") && os.Getenv("RCON_PASSWORD") == "" {
config.Password = *fc.Password
}
if fc.Port != nil && !flags.Changed("port") && os.Getenv("RCON_PORT") == "" {
config.Port = *fc.Port
}
if fc.AbortOnCtrlC != nil && !flags.Changed("abort-on-ctrl-c") && os.Getenv("RCON_ABORT_ON_CTRL_C") == "" {
config.AbortOnCtrlC = *fc.AbortOnCtrlC
}
}

// findUserConfigFile looks for a config file in the user's config directory, such as
Expand All @@ -120,10 +161,14 @@ func findUserConfigFile() string {
return findConfigFileIn(filepath.Join(dir, "rcon-cli"))
}

// findConfigFileIn returns the path of the first config.<ext> file in dir, where ext is
// one of the extensions supported by viper, or an empty string if there is none.
// configFileExtensions are the config file formats rcon-cli reads.
// YAML is the only format the README documents.
var configFileExtensions = []string{"yaml", "yml"}

// findConfigFileIn returns the path of the first config.<ext> file in dir,
// or an empty string if there is none.
func findConfigFileIn(dir string) string {
for _, ext := range viper.SupportedExts {
for _, ext := range configFileExtensions {
candidate := filepath.Join(dir, "config."+ext)
if info, err := os.Stat(candidate); err == nil && !info.IsDir() {
return candidate
Expand Down
98 changes: 96 additions & 2 deletions cmd/root_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,17 @@ func TestFindConfigFileIn(t *testing.T) {
}
})

t.Run("other extension", func(t *testing.T) {
t.Run("other extension ignored", func(t *testing.T) {
dir := t.TempDir()
want := filepath.Join(dir, "config.toml")
writeFile(t, filepath.Join(dir, "config.toml"))
if got := findConfigFileIn(dir); got != "" {
t.Errorf("findConfigFileIn() = %q, want empty (only yaml is read)", got)
}
})

t.Run("yml", func(t *testing.T) {
dir := t.TempDir()
want := filepath.Join(dir, "config.yml")
writeFile(t, want)
if got := findConfigFileIn(dir); got != want {
t.Errorf("findConfigFileIn() = %q, want %q", got, want)
Expand All @@ -56,3 +64,89 @@ func writeFile(t *testing.T, path string) {
t.Fatal(err)
}
}

func TestInitConfigLoadsFile(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "config.yaml")
if err := os.WriteFile(path, []byte("host: mc1\nport: 25576\npassword: secret\n"), 0o600); err != nil {
t.Fatal(err)
}

oldCfgFile := cfgFile
oldConfig := config
t.Cleanup(func() {
cfgFile = oldCfgFile
config = oldConfig
})

cfgFile = path
config = Config{Host: "localhost", Port: 25575, AbortOnCtrlC: true}
initConfig()

if config.Host != "mc1" || config.Port != 25576 || config.Password != "secret" {
t.Errorf("config after initConfig() = %+v, want host mc1, port 25576, password secret", config)
}
}

func TestApplyConfigFilePrecedence(t *testing.T) {
str := func(s string) *string { return &s }
num := func(n int) *int { return &n }
boolean := func(b bool) *bool { return &b }

t.Run("file beats defaults", func(t *testing.T) {
old := config
t.Cleanup(func() { config = old })
config = Config{Host: "localhost", Port: 25575, AbortOnCtrlC: true}
applyConfigFile(&fileConfig{Host: str("mc1"), Port: num(25576)})
if config.Host != "mc1" || config.Port != 25576 {
t.Errorf("config = %+v, want host mc1, port 25576", config)
}
})

t.Run("omitted keys keep their values", func(t *testing.T) {
old := config
t.Cleanup(func() { config = old })
config = Config{Host: "localhost", Port: 25575, Password: "keep", AbortOnCtrlC: true}
applyConfigFile(&fileConfig{Host: str("mc1")})
if config.Port != 25575 || config.Password != "keep" || !config.AbortOnCtrlC {
t.Errorf("config = %+v, want port 25575, password keep, abort true", config)
}
})

t.Run("env beats file", func(t *testing.T) {
old := config
t.Cleanup(func() { config = old })
t.Setenv("RCON_PORT", "25577")
config = Config{Host: "localhost", Port: 25575, AbortOnCtrlC: true}
applyConfigFile(&fileConfig{Port: num(25576)})
if config.Port != 25575 {
t.Errorf("config.Port = %d, want 25575 (env set, file must not win)", config.Port)
}
})

t.Run("flag beats file", func(t *testing.T) {
old := config
t.Cleanup(func() {
config = old
RootCmd.PersistentFlags().Lookup("port").Changed = false
})
config = Config{Host: "localhost", Port: 25575, AbortOnCtrlC: true}
if err := RootCmd.PersistentFlags().Set("port", "25578"); err != nil {
t.Fatal(err)
}
applyConfigFile(&fileConfig{Port: num(25576)})
if config.Port != 25578 {
t.Errorf("config.Port = %d, want 25578 (flag set, file must not win)", config.Port)
}
})

t.Run("bool from file", func(t *testing.T) {
old := config
t.Cleanup(func() { config = old })
config = Config{Host: "localhost", Port: 25575, AbortOnCtrlC: true}
applyConfigFile(&fileConfig{AbortOnCtrlC: boolean(false)})
if config.AbortOnCtrlC {
t.Errorf("config.AbortOnCtrlC = true, want false from file")
}
})
}
16 changes: 5 additions & 11 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,25 +3,19 @@ module github.com/itzg/rcon-cli
go 1.27.4

require (
github.com/itzg/go-flagsfiller v1.19.0
github.com/peterh/liner v1.2.3
github.com/spf13/cobra v1.10.2
github.com/spf13/viper v1.21.0
gopkg.in/yaml.v3 v3.0.1
)

require (
github.com/clipperhouse/uax29/v2 v2.7.0 // indirect
github.com/fsnotify/fsnotify v1.9.0 // indirect
github.com/go-viper/mapstructure/v2 v2.4.0 // indirect
github.com/iancoleman/strcase v0.3.0 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/kr/pretty v0.3.1 // indirect
github.com/mattn/go-runewidth v0.0.31 // indirect
github.com/pelletier/go-toml/v2 v2.4.3-0.20260718010011-08b09f19fe93 // indirect
github.com/sagikazarmark/locafero v0.11.0 // indirect
github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 // indirect
github.com/spf13/afero v1.15.0 // indirect
github.com/spf13/cast v1.10.0 // indirect
github.com/spf13/pflag v1.0.10 // indirect
github.com/subosito/gotenv v1.6.0 // indirect
go.yaml.in/yaml/v3 v3.0.4 // indirect
golang.org/x/sys v0.48.0 // indirect
golang.org/x/text v0.40.1-0.20260805201538-02aa981a75cb // indirect
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 // indirect
)
31 changes: 6 additions & 25 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,58 +1,39 @@
github.com/clipperhouse/uax29/v2 v2.7.0 h1:+gs4oBZ2gPfVrKPthwbMzWZDaAFPGYK72F0NJv2v7Vk=
github.com/clipperhouse/uax29/v2 v2.7.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJSwu5BF98AuoVM=
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs=
github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/iancoleman/strcase v0.3.0 h1:nTXanmYxhfFAMjZL34Ov6gkzEsSJZ5DbhxWjvSASxEI=
github.com/iancoleman/strcase v0.3.0/go.mod h1:iwCmte+B7n89clKwxIoIXy/HfoL7AsD47ZCWhYzw7ho=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/itzg/go-flagsfiller v1.19.0 h1:CiT97rDZJrRvWoiVzbx/mRM+/fn+GQ6cRMMa/x3psBs=
github.com/itzg/go-flagsfiller v1.19.0/go.mod h1:Zq4PnNALfrY73hVPlg7GExLxm3lVRu90895WVe8NQVg=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/mattn/go-runewidth v0.0.31 h1:1oCV4ReTlosDBc6rYRw5cL8S/4y8iv5oRl4SJ5IBgwo=
github.com/mattn/go-runewidth v0.0.31/go.mod h1:3qAiGCV4Koz/yuveO58qUefmUTRm8r0IGEXZ9jeHp/8=
github.com/pelletier/go-toml/v2 v2.4.3-0.20260718010011-08b09f19fe93 h1:6jzgmmynqlN23AlQKv8m/bsS9N1eaecVjm1Brl516aU=
github.com/pelletier/go-toml/v2 v2.4.3-0.20260718010011-08b09f19fe93/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
github.com/peterh/liner v1.2.3 h1:JF4G03iaZjtPyJE7gdOk76/fvs4OObMJWQHwR3wphxE=
github.com/peterh/liner v1.2.3/go.mod h1:IC6gIBWLzuPGXmiX/86/ieO9K+9ITsaE6SKm1XkU9uw=
github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/sagikazarmark/locafero v0.11.0 h1:1iurJgmM9G3PA/I+wWYIOw/5SyBtxapeHDcg+AAIFXc=
github.com/sagikazarmark/locafero v0.11.0/go.mod h1:nVIGvgyzw595SUSUE6tvCp3YYTeHs15MvlmU87WwIik=
github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 h1:+jumHNA0Wrelhe64i8F6HNlS8pkoyMv5sreGx2Ry5Rw=
github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8/go.mod h1:3n1Cwaq1E1/1lhQhtRK2ts/ZwZEhjcQeJQ1RuC6Q/8U=
github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I=
github.com/spf13/afero v1.15.0/go.mod h1:NC2ByUVxtQs4b3sIUphxK0NioZnmxgyCrfzeuq8lxMg=
github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY=
github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo=
github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=
github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk=
github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU=
github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/text v0.40.1-0.20260805201538-02aa981a75cb h1:wlz5NIk+KNUnq1TOsByeB/mAy0IL5LDBr9OeCg1BdUs=
golang.org/x/text v0.40.1-0.20260805201538-02aa981a75cb/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
Expand Down