From ef757104eeb13bab8f1c02430d4d384a3938c8ce Mon Sep 17 00:00:00 2001 From: Sam Boysel Date: Tue, 24 May 2022 02:47:48 -0700 Subject: [PATCH] Use XDG_CONFIG_HOME for config and theme (#34) * default config and theme to XDG_CONFIG_HOME * copy default theme and config to XDG_CONFIG_HOME if they do not exist --- README.md | 6 ++++-- cmd/gorss/main.go | 19 +++++++++++++++++++ internal/util.go | 33 +++++++++++++++++++++++++++++++++ 3 files changed, 56 insertions(+), 2 deletions(-) create mode 100644 internal/util.go diff --git a/README.md b/README.md index 2587f93..3d35d95 100644 --- a/README.md +++ b/README.md @@ -20,8 +20,10 @@ You can also specify theme, configuration and database manually. ./gorss -config gorss.conf -theme default.theme -db mydb.db ``` -Gorss expect to have `gorss.conf` and `default.theme` in the same directory as `gorss` itself if not -starting it with parameters as above. +If either the configuration or theme files are not specified, gorss will attempt +to use`$XDG_CONFIG_HOME/gorss/gorss.conf` and +`$XDG_CONFIG_HOME/gorss/themes/default.theme`, respectively. These files will be +created from the defaults if not present. To build and run use the makefile. ``` diff --git a/cmd/gorss/main.go b/cmd/gorss/main.go index d4e23d8..7b16884 100644 --- a/cmd/gorss/main.go +++ b/cmd/gorss/main.go @@ -1,6 +1,7 @@ package main import ( + "errors" "flag" "fmt" "log" @@ -55,6 +56,13 @@ func main() { s := conf.QueryConfig(defaultConfig) if s != "" { cfg = s + } else { + cfg = fmt.Sprintf("%s/%s", configHome, defaultConfig) + // check if default config exists, copy if not + _, err := os.Stat(cfg) + if errors.Is(err, os.ErrNotExist) { + internal.CopyFile(defaultConfig, cfg) + } } } @@ -63,6 +71,17 @@ func main() { s := conf.QueryConfig(defaultTheme) if s != "" { theme = s + } else { + theme = fmt.Sprintf("%s/%s", configHome, defaultTheme) + // check if default config exists, copy if not + _, err := os.Stat(theme) + if errors.Is(err, os.ErrNotExist) { + themeDir := fmt.Sprintf("%s/%s", configHome, "themes") + if err := os.Mkdir(themeDir, os.ModePerm); err != nil { + log.Printf("Failed to create dir: %s\n", themeDir) + } + internal.CopyFile(defaultTheme, theme) + } } } diff --git a/internal/util.go b/internal/util.go new file mode 100644 index 0000000..5f70df2 --- /dev/null +++ b/internal/util.go @@ -0,0 +1,33 @@ +package internal + +import ( + "fmt" + "io" + "os" +) + +// copy file from src to dst +func CopyFile(src, dst string) (int64, error) { + sourceFileStat, err := os.Stat(src) + if err != nil { + return 0, err + } + + if !sourceFileStat.Mode().IsRegular() { + return 0, fmt.Errorf("%s is not a regular file", src) + } + + source, err := os.Open(src) + if err != nil { + return 0, err + } + defer source.Close() + + destination, err := os.Create(dst) + if err != nil { + return 0, err + } + defer destination.Close() + nBytes, err := io.Copy(destination, source) + return nBytes, err +}