Line data Source code
1 : package config
2 :
3 : import (
4 : "fmt"
5 : "math/rand/v2"
6 : "os"
7 :
8 : "github.com/caarlos0/env/v11"
9 : "github.com/kijimaD/ruins/internal/logger"
10 : )
11 :
12 : // Load は環境変数から設定を読み込み、新しいConfigインスタンスを返す
13 : // Seedが環境変数で指定されていない場合は、ランダム値を生成する
14 : func Load() (*Config, error) {
15 1 : cfg := &Config{}
16 1 :
17 : // プロファイルを最初に決定(デフォルトはproduction)
18 1 : profile := os.Getenv("RUINS_PROFILE")
19 1 : if profile == "" {
20 1 : cfg.Profile = ProfileProduction
21 1 : } else {
22 1 : cfg.Profile = Profile(profile)
23 1 : }
24 :
25 : // プロファイルに基づくデフォルト値を設定
26 1 : cfg.ApplyProfileDefaults()
27 1 :
28 : // 永続化されたユーザー設定をファイルから読み込んで上書きする。
29 : // 失敗してもデフォルト値で起動を継続する。ファイルの生成は EnsureUserConfigFile が担う
30 1 : if err := cfg.loadUserConfig(); err != nil {
31 1 : logger.New(logger.CategoryLoad).Warn("failed to load user config; continuing with defaults", "error", err)
32 1 : }
33 :
34 : // 環境変数で明示的に設定された値で上書きする。優先順位はデフォルト < ファイル < 環境変数
35 1 : if err := env.Parse(cfg); err != nil {
36 1 : return nil, fmt.Errorf("failed to load config: %w", err)
37 1 : }
38 :
39 : // Seedが未設定の場合はランダム値を生成
40 1 : if os.Getenv("RUINS_SEED") == "" {
41 1 : cfg.Seed = rand.Uint64()
42 1 : }
43 : // SeedからRNGを生成
44 1 : cfg.RNG = rand.New(rand.NewPCG(cfg.Seed, 0))
45 1 :
46 1 : if err := cfg.Validate(); err != nil {
47 1 : return nil, fmt.Errorf("failed to validate config: %w", err)
48 1 : }
49 :
50 1 : return cfg, nil
51 : }
52 :
53 : // String は設定の文字列表現を返す(デバッグ用)
54 : func (c *Config) String() string {
55 1 : return fmt.Sprintf(`Config{
56 1 : Profile: %s,
57 1 : WindowWidth: %d, WindowHeight: %d,
58 1 : Debug: %t, LogLevel: %s, LogCategories: %s, DebugPProf: %t, PProfPort: %d,
59 1 : Seed: %d,
60 1 : TargetFPS: %d,
61 1 : ProfileMemory: %t, ProfileCPU: %t, ProfileMutex: %t, ProfileTrace: %t,
62 1 : ProfilePath: %s
63 1 : }`,
64 1 : c.Profile,
65 1 : c.User.WindowWidth, c.User.WindowHeight,
66 1 : c.Debug, c.LogLevel, c.LogCategories, c.DebugPProf, c.PProfPort,
67 1 : c.Seed,
68 1 : c.TargetFPS,
69 1 : c.ProfileMemory, c.ProfileCPU, c.ProfileMutex, c.ProfileTrace,
70 1 : c.ProfilePath)
71 1 : }
|