bootstrap: truncate config file when saving

Before this change config files would have remnants of the previous
file's data. When saving, open file using os.Create() to truncate and/or create
the file before writing. In cases when the file is read only, open using
os.Open() which is shorthand for opening with the os.O_RDWR flag.
This commit is contained in:
Sean Callahan 2021-10-19 10:56:43 -07:00
parent 738a7536ff
commit 5cb83c86d0

View File

@ -4,14 +4,15 @@ import (
"encoding/base64" "encoding/base64"
"encoding/json" "encoding/json"
"fmt" "fmt"
"github.com/gorilla/securecookie"
"github.com/jessevdk/go-flags"
"log" "log"
"math/rand" "math/rand"
"os" "os"
"path/filepath" "path/filepath"
"runtime" "runtime"
"time" "time"
"github.com/gorilla/securecookie"
"github.com/jessevdk/go-flags"
) )
type Flags struct { type Flags struct {
@ -59,7 +60,7 @@ type Config struct {
GlibcLibLoc string `json:"-"` GlibcLibLoc string `json:"-"`
Autostart string `json:"-"` Autostart string `json:"-"`
ConsoleCacheSize int `json:"console_cache_size,omitempty"` // the amount of cached lines, inside the factorio output cache ConsoleCacheSize int `json:"console_cache_size,omitempty"` // the amount of cached lines, inside the factorio output cache
Secure bool `json:"secure"` // set to `false` to use this tool without SSL/TLS (Default: `true`) Secure bool `json:"secure"` // set to `false` to use this tool without SSL/TLS (Default: `true`)
} }
// set Configs default values. JSON unmarshal will replace when it found something different // set Configs default values. JSON unmarshal will replace when it found something different
@ -88,7 +89,7 @@ func GetConfig() Config {
} }
func (config *Config) updateConfigFile() { func (config *Config) updateConfigFile() {
file, err := os.OpenFile(config.ConfFile, os.O_RDONLY, 0) file, err := os.Open(config.ConfFile)
failOnError(err, "Error opening file") failOnError(err, "Error opening file")
defer file.Close() defer file.Close()
@ -138,7 +139,7 @@ func (config *Config) updateConfigFile() {
if resave { if resave {
// save json file again // save json file again
file, err = os.OpenFile(config.ConfFile, os.O_WRONLY, 0) file, err = os.Create(config.ConfFile)
failOnError(err, "Error opening file for writing") failOnError(err, "Error opening file for writing")
defer file.Close() defer file.Close()
@ -156,7 +157,7 @@ func (config *Config) loadServerConfig() {
// load and potentially update conf.json // load and potentially update conf.json
config.updateConfigFile() config.updateConfigFile()
file, err := os.OpenFile(config.ConfFile, os.O_RDWR, 0) file, err := os.Open(config.ConfFile)
failOnError(err, "Error loading config file.") failOnError(err, "Error loading config file.")
defer file.Close() defer file.Close()