refactor: simplify homeDir and appConfig usage

This commit is contained in:
Mathis Maquenne
2025-06-23 20:58:08 -04:00
parent a619b37922
commit 33e774d078
7 changed files with 46 additions and 31 deletions
+15 -2
View File
@@ -6,11 +6,15 @@ import (
"fmt" "fmt"
"time" "time"
"github.com/mathismqn/godeez/internal/config"
"github.com/mathismqn/godeez/internal/downloader" "github.com/mathismqn/godeez/internal/downloader"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
var opts downloader.Options var (
opts downloader.Options
cfgPath string
)
var downloadCmd = &cobra.Command{ var downloadCmd = &cobra.Command{
Use: "download", Use: "download",
@@ -20,6 +24,7 @@ var downloadCmd = &cobra.Command{
func init() { func init() {
RootCmd.AddCommand(downloadCmd) RootCmd.AddCommand(downloadCmd)
downloadCmd.PersistentFlags().StringVar(&cfgPath, "config", "", "config file (default ~/.godeez/config.toml)")
downloadCmd.PersistentFlags().StringVarP(&opts.Quality, "quality", "q", "best", "download quality [mp3_128, mp3_320, flac, best]") downloadCmd.PersistentFlags().StringVarP(&opts.Quality, "quality", "q", "best", "download quality [mp3_128, mp3_320, flac, best]")
downloadCmd.PersistentFlags().DurationVarP(&opts.Timeout, "timeout", "t", 2*time.Minute, "timeout for each download (e.g. 10s, 1m, 2m30s)") downloadCmd.PersistentFlags().DurationVarP(&opts.Timeout, "timeout", "t", 2*time.Minute, "timeout for each download (e.g. 10s, 1m, 2m30s)")
downloadCmd.PersistentFlags().BoolVar(&opts.BPM, "bpm", false, "fetch BPM/key and add to file tags") downloadCmd.PersistentFlags().BoolVar(&opts.BPM, "bpm", false, "fetch BPM/key and add to file tags")
@@ -42,12 +47,20 @@ func newDownloadCmd(resourceType string) *cobra.Command {
Short: fmt.Sprintf("Download songs from %s %s", article, resourceType), Short: fmt.Sprintf("Download songs from %s %s", article, resourceType),
Args: cobra.ExactArgs(1), Args: cobra.ExactArgs(1),
PreRunE: func(cmd *cobra.Command, args []string) error { PreRunE: func(cmd *cobra.Command, args []string) error {
appConfig, err := config.New(cfgPath)
if err != nil {
return err
}
cmd.SetContext(context.WithValue(cmd.Context(), "appConfig", appConfig))
return opts.Validate() return opts.Validate()
}, },
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
ctx := cmd.Context() ctx := cmd.Context()
dl := downloader.New(appConfig, resourceType) appConfigVal := ctx.Value("appConfig")
appConfig, _ := appConfigVal.(*config.Config)
dl := downloader.New(appConfig, resourceType)
if err := dl.Run(ctx, opts, args[0]); err != nil { if err := dl.Run(ctx, opts, args[0]); err != nil {
if errors.Is(err, context.Canceled) { if errors.Is(err, context.Canceled) {
return nil return nil
+3 -14
View File
@@ -4,35 +4,24 @@ import (
"fmt" "fmt"
"os" "os"
"github.com/mathismqn/godeez/internal/config"
"github.com/mathismqn/godeez/internal/watcher" "github.com/mathismqn/godeez/internal/watcher"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
var (
cfgPath string
appConfig *config.Config
)
var RootCmd = &cobra.Command{ var RootCmd = &cobra.Command{
Use: "godeez", Use: "godeez",
Short: "GoDeez is a tool to download music from Deezer", Short: "GoDeez is a tool to download music from Deezer",
SilenceUsage: true, SilenceUsage: true,
PersistentPreRunE: func(cmd *cobra.Command, args []string) error { PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
var err error homeDir, err := os.UserHomeDir()
appConfig, err = config.New(cfgPath)
if err != nil { if err != nil {
return err return fmt.Errorf("failed to get home directory: %w", err)
} }
if err := watcher.EnsureAutostart(); err != nil { if err := watcher.EnsureAutostart(homeDir); err != nil {
fmt.Fprintf(os.Stderr, "Warning: failed to install autostart for watcher: %v\n", err) fmt.Fprintf(os.Stderr, "Warning: failed to install autostart for watcher: %v\n", err)
} }
return nil return nil
}, },
} }
func init() {
RootCmd.PersistentFlags().StringVar(&cfgPath, "config", "", "config file (default ~/.godeez/config.toml)")
}
+13
View File
@@ -1,6 +1,9 @@
package cmd package cmd
import ( import (
"context"
"github.com/mathismqn/godeez/internal/config"
"github.com/mathismqn/godeez/internal/watcher" "github.com/mathismqn/godeez/internal/watcher"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
@@ -9,8 +12,18 @@ var watchRunCmd = &cobra.Command{
Use: "run", Use: "run",
Short: "Start the background playlist watcher", Short: "Start the background playlist watcher",
Hidden: true, Hidden: true,
PreRun: func(cmd *cobra.Command, args []string) {
appConfig, err := config.New("")
if err != nil {
return
}
cmd.SetContext(context.WithValue(cmd.Context(), "appConfig", appConfig))
},
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
ctx := cmd.Context() ctx := cmd.Context()
appConfigVal := ctx.Value("appConfig")
appConfig, _ := appConfigVal.(*config.Config)
w := watcher.New(appConfig) w := watcher.New(appConfig)
w.Run(ctx, opts) w.Run(ctx, opts)
}, },
+7 -6
View File
@@ -15,6 +15,7 @@ type Config struct {
ArlCookie string `mapstructure:"arl_cookie"` ArlCookie string `mapstructure:"arl_cookie"`
SecretKey string `mapstructure:"secret_key"` SecretKey string `mapstructure:"secret_key"`
OutputDir string `mapstructure:"output_dir"` OutputDir string `mapstructure:"output_dir"`
HomeDir string
} }
func New(cfgPath string) (*Config, error) { func New(cfgPath string) (*Config, error) {
@@ -49,11 +50,11 @@ func New(cfgPath string) (*Config, error) {
return nil, fmt.Errorf("failed to read config file: %w", err) return nil, fmt.Errorf("failed to read config file: %w", err)
} }
var cfg Config cfg := &Config{HomeDir: homeDir}
if err := viper.Unmarshal(&cfg); err != nil { if err := viper.Unmarshal(cfg); err != nil {
return nil, fmt.Errorf("failed to parse config: %w", err) return nil, fmt.Errorf("failed to parse config: %w", err)
} }
if err := cfg.Validate(homeDir); err != nil { if err := cfg.Validate(); err != nil {
return nil, fmt.Errorf("invalid config: %w", err) return nil, fmt.Errorf("invalid config: %w", err)
} }
@@ -61,10 +62,10 @@ func New(cfgPath string) (*Config, error) {
return nil, err return nil, err
} }
return &cfg, nil return cfg, nil
} }
func (c *Config) Validate(homeDir string) error { func (c *Config) Validate() error {
if c.ArlCookie == "" { if c.ArlCookie == "" {
return fmt.Errorf("arl_cookie is not set") return fmt.Errorf("arl_cookie is not set")
} }
@@ -75,7 +76,7 @@ func (c *Config) Validate(homeDir string) error {
return fmt.Errorf("secret_key must be 16 bytes long") return fmt.Errorf("secret_key must be 16 bytes long")
} }
if c.OutputDir == "" { if c.OutputDir == "" {
c.OutputDir = filepath.Join(homeDir, "Music", "GoDeez") c.OutputDir = filepath.Join(c.HomeDir, "Music", "GoDeez")
} }
return nil return nil
+5 -5
View File
@@ -7,18 +7,18 @@ import (
"strings" "strings"
) )
func EnsureAutostart() error { func EnsureAutostart(homeDir string) error {
if isAutostartInstalled() || isTemporaryExecutable() { if isAutostartInstalled(homeDir) || isTemporaryExecutable() {
return nil return nil
} }
return installAutostart() return installAutostart(homeDir)
} }
func isAutostartInstalled() bool { func isAutostartInstalled(homeDir string) bool {
switch runtime.GOOS { switch runtime.GOOS {
case "darwin": case "darwin":
path := filepath.Join(os.Getenv("HOME"), "Library", "LaunchAgents", "com.godeez.watch.plist") path := filepath.Join(homeDir, "Library", "LaunchAgents", "com.godeez.watch.plist")
_, err := os.Stat(path) _, err := os.Stat(path)
return err == nil return err == nil
+2 -2
View File
@@ -9,7 +9,7 @@ import (
"path/filepath" "path/filepath"
) )
func installAutostart() error { func installAutostart(homeDir string) error {
exe, err := os.Executable() exe, err := os.Executable()
if err != nil { if err != nil {
return err return err
@@ -39,7 +39,7 @@ func installAutostart() error {
</dict> </dict>
</plist>`, exe) </plist>`, exe)
path := filepath.Join(os.Getenv("HOME"), "Library", "LaunchAgents", "com.godeez.watch.plist") path := filepath.Join(homeDir, "Library", "LaunchAgents", "com.godeez.watch.plist")
if err := os.WriteFile(path, []byte(plist), 0644); err != nil { if err := os.WriteFile(path, []byte(plist), 0644); err != nil {
return err return err
} }
+1 -2
View File
@@ -20,8 +20,7 @@ type Watcher struct {
} }
func New(appConfig *config.Config) *Watcher { func New(appConfig *config.Config) *Watcher {
homeDir, _ := os.UserHomeDir() logFile := filepath.Join(appConfig.HomeDir, ".godeez", "watcher.log")
logFile := filepath.Join(homeDir, ".godeez", "watcher.log")
file, err := os.OpenFile(logFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644) file, err := os.OpenFile(logFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
if err != nil { if err != nil {
log.Fatalf("Failed to open log file: %v\n", err) log.Fatalf("Failed to open log file: %v\n", err)