This repository was archived by the owner on May 29, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuserdata_helpers.go
More file actions
66 lines (59 loc) · 1.67 KB
/
userdata_helpers.go
File metadata and controls
66 lines (59 loc) · 1.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package main
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
)
func getUserDataDir(userId UserId) string {
return filepath.Join(USERDATA_PATH, string(userId))
}
func getUserDataFile(userId UserId, filename string) string {
return filepath.Join(getUserDataDir(userId), filename)
}
func LoadUserJSON[T any](userId UserId, filename string) (T, error) {
var result T
path := getUserDataFile(userId, filename)
data, err := os.ReadFile(path)
if err != nil {
return result, err
}
if err := json.Unmarshal(data, &result); err != nil {
return result, fmt.Errorf("unmarshaling %s: %w", path, err)
}
return result, nil
}
func SaveUserJSON[T any](userId UserId, filename string, v T) error {
path := getUserDataFile(userId, filename)
dir := filepath.Dir(path)
if err := os.MkdirAll(dir, 0755); err != nil {
return fmt.Errorf("creating user data directory %s: %w", dir, err)
}
data, err := json.MarshalIndent(v, "", " ")
if err != nil {
return fmt.Errorf("marshaling %s: %w", path, err)
}
return atomicWrite(path, data, 0644)
}
func LoadUserCosmetics(userId UserId) (*UserCosmetics, error) {
uc, err := LoadUserJSON[UserCosmetics](userId, "cosmetics.json")
if err != nil {
if os.IsNotExist(err) {
return &UserCosmetics{ActiveCosmetics: map[CosmeticType]string{}, OwnedCosmetics: []string{}}, nil
}
return nil, err
}
if uc.ActiveCosmetics == nil {
uc.ActiveCosmetics = map[CosmeticType]string{}
}
if uc.OwnedCosmetics == nil {
uc.OwnedCosmetics = []string{}
}
return &uc, nil
}
func SaveUserCosmetics(userId UserId, uc *UserCosmetics) error {
if uc == nil {
return fmt.Errorf("nil UserCosmetics provided")
}
return SaveUserJSON(userId, "cosmetics.json", *uc)
}