Просмотр исходного кода

feat: use temp dir instead of current dir for log file and avatar caching

ayn2op 9 месяцев назад
Родитель
Сommit
9f79196893
3 измененных файлов с 24 добавлено и 15 удалено
  1. 22 0
      internal/consts/consts.go
  2. 1 9
      internal/logger/logger.go
  3. 1 6
      internal/notifications/notifications.go

+ 22 - 0
internal/consts/consts.go

@@ -2,7 +2,10 @@ package consts
 
 
 import (
 import (
 	"encoding/json"
 	"encoding/json"
+	"log/slog"
 	"net/http"
 	"net/http"
+	"os"
+	"path/filepath"
 
 
 	"github.com/diamondburned/arikawa/v3/discord"
 	"github.com/diamondburned/arikawa/v3/discord"
 	"github.com/diamondburned/arikawa/v3/gateway"
 	"github.com/diamondburned/arikawa/v3/gateway"
@@ -75,3 +78,22 @@ func GetIdentifyProps() gateway.IdentifyProperties {
 		HasClientMods: false,
 		HasClientMods: false,
 	}
 	}
 }
 }
+
+var cacheDir string
+
+func CacheDir() string {
+	return cacheDir
+}
+
+func init() {
+	userCacheDir, err := os.UserCacheDir()
+	if err != nil {
+		userCacheDir = os.TempDir()
+		slog.Warn("failed to get user cache dir; falling back to temp dir", "err", err, "path", userCacheDir)
+	}
+
+	cacheDir = filepath.Join(userCacheDir, Name)
+	if err := os.MkdirAll(cacheDir, os.ModePerm); err != nil {
+		slog.Error("failed to create cache dir", "err", err, "path", cacheDir)
+	}
+}

+ 1 - 9
internal/logger/logger.go

@@ -13,15 +13,7 @@ import (
 const fileName = "logs.txt"
 const fileName = "logs.txt"
 
 
 func DefaultPath() string {
 func DefaultPath() string {
-	path, err := os.UserCacheDir()
-	if err != nil {
-		slog.Info(
-			"user cache directory path cannot be determined; falling back to the current directory path",
-		)
-		path = "."
-	}
-
-	return filepath.Join(path, consts.Name, fileName)
+	return filepath.Join(consts.CacheDir(), fileName)
 }
 }
 
 
 // Load opens the log file and configures default logger.
 // Load opens the log file and configures default logger.

+ 1 - 6
internal/notifications/notifications.go

@@ -75,12 +75,7 @@ func Notify(state *ningen.State, msg *gateway.MessageCreateEvent, cfg *config.Co
 }
 }
 
 
 func getCachedProfileImage(avatarHash discord.Hash, url string) (string, error) {
 func getCachedProfileImage(avatarHash discord.Hash, url string) (string, error) {
-	path, err := os.UserCacheDir()
-	if err != nil {
-		return "", err
-	}
-
-	path = filepath.Join(path, consts.Name, "assets")
+	path := filepath.Join(consts.CacheDir(), "avatars")
 	if err := os.MkdirAll(path, os.ModePerm); err != nil {
 	if err := os.MkdirAll(path, os.ModePerm); err != nil {
 		return "", err
 		return "", err
 	}
 	}