From 25c59677e7a9861565a66c1d2a674ea7c365c8c7 Mon Sep 17 00:00:00 2001 From: Yule Date: Thu, 10 Sep 2026 04:12:28 +0800 Subject: [PATCH] =?UTF-8?q?feat(go):=20=E5=88=9D=E5=A7=8B=E5=8C=96=20Go=20?= =?UTF-8?q?=E6=A8=A1=E5=9D=97=EF=BC=8C=E6=96=B0=E5=A2=9E=20config=20?= =?UTF-8?q?=E4=B8=8E=20logging=20=E5=8C=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - config: 强类型配置读写,缺失字段补默认值、单字段损坏回退默认 (对齐旧 shell get_cfg 语义),未知字段原样保留;Set 按字段类型编码, 避免 inotify_events=0 被写成数字;旧 txt/JSON 配置 inspect/migrate - logging: service.log 写入,格式与 WebUI 过滤兼容,等级过滤 + 大小上限重置 - 两包均带 host 单测 --- go/go.mod | 3 + go/internal/config/config.go | 305 ++++++++++++++++++++++++++++ go/internal/config/config_test.go | 266 ++++++++++++++++++++++++ go/internal/config/migrate.go | 185 +++++++++++++++++ go/internal/logging/logging.go | 157 ++++++++++++++ go/internal/logging/logging_test.go | 145 +++++++++++++ 6 files changed, 1061 insertions(+) create mode 100644 go/go.mod create mode 100644 go/internal/config/config.go create mode 100644 go/internal/config/config_test.go create mode 100644 go/internal/config/migrate.go create mode 100644 go/internal/logging/logging.go create mode 100644 go/internal/logging/logging_test.go diff --git a/go/go.mod b/go/go.mod new file mode 100644 index 0000000..6cd2566 --- /dev/null +++ b/go/go.mod @@ -0,0 +1,3 @@ +module github.com/YuleBest/LuminPro/go + +go 1.24 diff --git a/go/internal/config/config.go b/go/internal/config/config.go new file mode 100644 index 0000000..8eaa7f0 --- /dev/null +++ b/go/internal/config/config.go @@ -0,0 +1,305 @@ +// Package config 负责读写模块的 config.json。 +// +// 字段与 WebUI、安装脚本共享,是三方之间的稳定契约:新增字段必须给默认值, +// 缺失字段按默认值补齐(等价于旧 shell 版 get_cfg 的 fallback 行为)。 +package config + +import ( + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "strconv" + "strings" +) + +// 默认值,与 config/config.json 模板及 customize.sh 保持一致。 +const ( + DefaultUIMaxBri = 0 + DefaultMaxBri = 0 + DefaultStepsNum = 50 + DefaultLogMaxSize = 512 + DefaultAutoBriSleep = 1 + DefaultDisplayHdrSleep = 0 + DefaultHdrEnterRatio = 1.15 + DefaultHdrExitRatio = 1.05 + DefaultCompatibilityMode = 0 + DefaultSleepTime = "" + DefaultInotifyEvents = "c" + DefaultNowBriFile = "/sys/class/backlight/panel0-backlight/brightness" + DefaultMaxBriFile = "/sys/class/backlight/panel0-backlight/max_brightness" + DefaultLogLevel = "info" + DefaultDebugMode = 0 +) + +// Config 是模块配置的强类型表示。 +type Config struct { + UIMaxBri int `json:"ui_max_bri"` + MaxBri int `json:"max_bri"` + StepsNum int `json:"steps_num"` + LogMaxSize int `json:"log_max_size"` + AutoBriSleep int `json:"auto_bri_sleep"` + DisplayHdrSleep int `json:"display_hdr_sleep"` + HdrEnterRatio float64 `json:"hdr_enter_ratio"` + HdrExitRatio float64 `json:"hdr_exit_ratio"` + CompatibilityMode int `json:"compatibility_mode"` + SleepTime string `json:"sleep_time"` + InotifyEvents string `json:"inotify_events"` + NowBriFile string `json:"now_bri_file"` + MaxBriFile string `json:"max_bri_file"` + LogLevel string `json:"log_level"` + DebugMode int `json:"debug_mode"` + BlacklistApps []string `json:"blacklist_apps"` + + // extra 保存本程序不认识的键,读写时原样保留,避免与 WebUI 抢字段。 + extra map[string]json.RawMessage +} + +// Default 返回带完整默认值的配置。 +func Default() Config { + return Config{ + UIMaxBri: DefaultUIMaxBri, + MaxBri: DefaultMaxBri, + StepsNum: DefaultStepsNum, + LogMaxSize: DefaultLogMaxSize, + AutoBriSleep: DefaultAutoBriSleep, + DisplayHdrSleep: DefaultDisplayHdrSleep, + HdrEnterRatio: DefaultHdrEnterRatio, + HdrExitRatio: DefaultHdrExitRatio, + CompatibilityMode: DefaultCompatibilityMode, + SleepTime: DefaultSleepTime, + InotifyEvents: DefaultInotifyEvents, + NowBriFile: DefaultNowBriFile, + MaxBriFile: DefaultMaxBriFile, + LogLevel: DefaultLogLevel, + DebugMode: DefaultDebugMode, + BlacklistApps: []string{}, + } +} + +// Load 读取配置。文件不存在或为空时返回默认配置; +// 单个字段损坏时保留该字段的默认值(与旧 shell 版 get_cfg 的降级一致)。 +func Load(path string) (Config, error) { + c := Default() + data, err := os.ReadFile(path) + if errors.Is(err, os.ErrNotExist) { + return c, nil + } + if err != nil { + return c, err + } + if len(strings.TrimSpace(string(data))) == 0 { + return c, nil + } + + var raw map[string]json.RawMessage + if err := json.Unmarshal(data, &raw); err != nil { + return c, fmt.Errorf("解析配置失败: %w", err) + } + c.applyRaw(raw) + return c, nil +} + +// Save 原子写回配置(临时文件 + rename),保证 WebUI 读到的是完整 JSON。 +func (c Config) Save(path string) error { + raw := c.toRawMap() + data, err := json.Marshal(raw) + if err != nil { + return err + } + if dir := filepath.Dir(path); dir != "" { + if err := os.MkdirAll(dir, 0o755); err != nil { + return err + } + } + tmp := path + ".tmp" + if err := os.WriteFile(tmp, data, 0o644); err != nil { + return err + } + return os.Rename(tmp, path) +} + +// Ensure 补齐缺失字段并落盘。 +func Ensure(path string) error { + c, err := Load(path) + if err != nil { + return err + } + return c.Save(path) +} + +// Init 在文件不存在时写入默认配置。 +func Init(path string) error { + if _, err := os.Stat(path); err == nil { + return Ensure(path) + } + return Default().Save(path) +} + +// Set 按 key=value 写入字段。值按字段的既有类型编码(与旧脚本里 jq 的 +// `--arg x | tonumber` / 字符串赋值保持一致),避免 "0" 这类事件字母被写成数字。 +func Set(path string, pairs []string) error { + c, err := Load(path) + if err != nil { + return err + } + raw := c.toRawMap() + for _, p := range pairs { + key, value, ok := strings.Cut(p, "=") + if !ok || key == "" { + return fmt.Errorf("参数格式应为 key=value: %q", p) + } + b, err := encodeValue(key, value) + if err != nil { + return err + } + raw[key] = b + } + + updated := Default() + updated.applyRaw(raw) + return updated.Save(path) +} + +var intFields = map[string]bool{ + "ui_max_bri": true, + "max_bri": true, + "steps_num": true, + "log_max_size": true, + "auto_bri_sleep": true, + "display_hdr_sleep": true, + "compatibility_mode": true, + "debug_mode": true, +} + +var floatFields = map[string]bool{ + "hdr_enter_ratio": true, + "hdr_exit_ratio": true, +} + +var stringFields = map[string]bool{ + "sleep_time": true, + "inotify_events": true, + "now_bri_file": true, + "max_bri_file": true, + "log_level": true, +} + +// encodeValue 按已知字段类型把字符串编码为 JSON 值;未知字段按 JSON 字面量解析。 +func encodeValue(key, value string) (json.RawMessage, error) { + switch { + case intFields[key]: + n, err := strconv.Atoi(strings.TrimSpace(value)) + if err != nil { + return nil, fmt.Errorf("%s 需要整数: %q", key, value) + } + return json.Marshal(n) + case floatFields[key]: + f, err := strconv.ParseFloat(strings.TrimSpace(value), 64) + if err != nil { + return nil, fmt.Errorf("%s 需要数值: %q", key, value) + } + return json.Marshal(f) + case stringFields[key]: + return json.Marshal(value) + case key == "blacklist_apps": + var arr []string + if err := json.Unmarshal([]byte(value), &arr); err != nil { + return nil, fmt.Errorf("blacklist_apps 需要 JSON 数组: %q", value) + } + if arr == nil { + arr = []string{} + } + return json.Marshal(arr) + default: + return json.Marshal(parseValue(value)) + } +} + +// parseValue 把字符串解析为 JSON 值;不是合法 JSON 字面量时按字符串处理。 +func parseValue(s string) any { + var v any + if err := json.Unmarshal([]byte(s), &v); err == nil { + return v + } + return s +} + +// applyRaw 用原始键值填充强类型字段,未识别的键留在 extra。 +func (c *Config) applyRaw(raw map[string]json.RawMessage) { + known := map[string]any{ + "ui_max_bri": &c.UIMaxBri, + "max_bri": &c.MaxBri, + "steps_num": &c.StepsNum, + "log_max_size": &c.LogMaxSize, + "auto_bri_sleep": &c.AutoBriSleep, + "display_hdr_sleep": &c.DisplayHdrSleep, + "hdr_enter_ratio": &c.HdrEnterRatio, + "hdr_exit_ratio": &c.HdrExitRatio, + "compatibility_mode": &c.CompatibilityMode, + "sleep_time": &c.SleepTime, + "inotify_events": &c.InotifyEvents, + "now_bri_file": &c.NowBriFile, + "max_bri_file": &c.MaxBriFile, + "log_level": &c.LogLevel, + "debug_mode": &c.DebugMode, + "blacklist_apps": &c.BlacklistApps, + } + + c.extra = nil + for key, value := range raw { + if dst, ok := known[key]; ok { + // 单个字段损坏时保留默认值,不阻断整体加载。 + _ = json.Unmarshal(value, dst) + continue + } + if c.extra == nil { + c.extra = map[string]json.RawMessage{} + } + c.extra[key] = value + } + if c.BlacklistApps == nil { + c.BlacklistApps = []string{} + } +} + +// toRawMap 导出为原始键值表(含未知键)。 +func (c Config) toRawMap() map[string]json.RawMessage { + out := map[string]json.RawMessage{} + for key, value := range map[string]any{ + "ui_max_bri": c.UIMaxBri, + "max_bri": c.MaxBri, + "steps_num": c.StepsNum, + "log_max_size": c.LogMaxSize, + "auto_bri_sleep": c.AutoBriSleep, + "display_hdr_sleep": c.DisplayHdrSleep, + "hdr_enter_ratio": c.HdrEnterRatio, + "hdr_exit_ratio": c.HdrExitRatio, + "compatibility_mode": c.CompatibilityMode, + "sleep_time": c.SleepTime, + "inotify_events": c.InotifyEvents, + "now_bri_file": c.NowBriFile, + "max_bri_file": c.MaxBriFile, + "log_level": c.LogLevel, + "debug_mode": c.DebugMode, + "blacklist_apps": c.BlacklistApps, + } { + b, err := json.Marshal(value) + if err != nil { + continue + } + out[key] = b + } + for key, value := range c.extra { + if _, ok := out[key]; !ok { + out[key] = value + } + } + return out +} + +// Blacklist 返回黑名单副本,避免调用方误改内部切片。 +func (c Config) Blacklist() []string { + return append([]string(nil), c.BlacklistApps...) +} diff --git a/go/internal/config/config_test.go b/go/internal/config/config_test.go new file mode 100644 index 0000000..db53128 --- /dev/null +++ b/go/internal/config/config_test.go @@ -0,0 +1,266 @@ +package config + +import ( + "encoding/json" + "os" + "path/filepath" + "testing" +) + +func TestLoadMissingFileReturnsDefaults(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.json") + c, err := Load(path) + if err != nil { + t.Fatalf("Load 出错: %v", err) + } + if c.StepsNum != DefaultStepsNum || c.HdrEnterRatio != DefaultHdrEnterRatio || c.LogLevel != DefaultLogLevel { + t.Fatalf("默认值不正确: %+v", c) + } + if c.BlacklistApps == nil { + t.Fatal("BlacklistApps 不应为 nil") + } +} + +func TestLoadPartialFileFillsDefaults(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.json") + if err := os.WriteFile(path, []byte(`{"ui_max_bri":123,"max_bri":4095}`), 0o644); err != nil { + t.Fatal(err) + } + c, err := Load(path) + if err != nil { + t.Fatal(err) + } + if c.UIMaxBri != 123 || c.MaxBri != 4095 { + t.Fatalf("已存在的字段未生效: %+v", c) + } + if c.StepsNum != DefaultStepsNum { + t.Fatalf("缺失字段未补默认值: steps_num=%d", c.StepsNum) + } + if c.NowBriFile != DefaultNowBriFile { + t.Fatalf("缺失字段未补默认值: now_bri_file=%q", c.NowBriFile) + } +} + +func TestLoadMalformedFieldKeepsDefault(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.json") + // steps_num 类型错误,ui_max_bri 正常 + if err := os.WriteFile(path, []byte(`{"ui_max_bri":200,"steps_num":"abc"}`), 0o644); err != nil { + t.Fatal(err) + } + c, err := Load(path) + if err != nil { + t.Fatal(err) + } + if c.UIMaxBri != 200 { + t.Fatalf("正常字段应生效: %d", c.UIMaxBri) + } + if c.StepsNum != DefaultStepsNum { + t.Fatalf("损坏字段应回退默认值: %d", c.StepsNum) + } +} + +func TestUnknownKeysPreservedOnSave(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.json") + if err := os.WriteFile(path, []byte(`{"ui_max_bri":100,"future_field":"keep-me"}`), 0o644); err != nil { + t.Fatal(err) + } + c, err := Load(path) + if err != nil { + t.Fatal(err) + } + c.MaxBri = 999 + if err := c.Save(path); err != nil { + t.Fatal(err) + } + + var raw map[string]json.RawMessage + data, _ := os.ReadFile(path) + if err := json.Unmarshal(data, &raw); err != nil { + t.Fatal(err) + } + var kept string + if err := json.Unmarshal(raw["future_field"], &kept); err != nil || kept != "keep-me" { + t.Fatalf("未知字段未保留: %v %q", err, kept) + } + if _, ok := raw["steps_num"]; !ok { + t.Fatal("保存后应包含全部已知字段") + } +} + +func TestSetParsesTypes(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.json") + err := Set(path, []string{ + "ui_max_bri=1500", + "hdr_enter_ratio=1.25", + "inotify_events=0", + "blacklist_apps=[\"com.a\",\"com.b\"]", + "sleep_time=2200-0700", + }) + if err != nil { + t.Fatal(err) + } + c, err := Load(path) + if err != nil { + t.Fatal(err) + } + if c.UIMaxBri != 1500 { + t.Fatalf("int 未写入: %d", c.UIMaxBri) + } + if c.HdrEnterRatio != 1.25 { + t.Fatalf("float 未写入: %v", c.HdrEnterRatio) + } + if c.InotifyEvents != "0" { + t.Fatalf("字符串未写入: %q", c.InotifyEvents) + } + if len(c.BlacklistApps) != 2 || c.BlacklistApps[0] != "com.a" { + t.Fatalf("数组未写入: %v", c.BlacklistApps) + } + if c.SleepTime != "2200-0700" { + t.Fatalf("时间串未写入: %q", c.SleepTime) + } +} + +func TestSetRejectsBadPair(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.json") + if err := Set(path, []string{"novalue"}); err == nil { + t.Fatal("缺少 = 应报错") + } +} + +func TestSetRejectsBadType(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.json") + if err := Set(path, []string{"ui_max_bri=1500"}); err != nil { + t.Fatal(err) + } + if err := Set(path, []string{"ui_max_bri=abc"}); err == nil { + t.Fatal("整数字段给非数字应报错") + } + // 失败时不应破坏已有配置 + c, err := Load(path) + if err != nil { + t.Fatal(err) + } + if c.UIMaxBri != 1500 { + t.Fatalf("写入失败不应改动原值: %d", c.UIMaxBri) + } +} + +func TestInitCreatesAndEnsureFills(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.json") + if err := Init(path); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(path); err != nil { + t.Fatalf("Init 未创建文件: %v", err) + } + // 删掉一个字段后 Ensure 应补回 + if err := os.WriteFile(path, []byte(`{"ui_max_bri":50}`), 0o644); err != nil { + t.Fatal(err) + } + if err := Ensure(path); err != nil { + t.Fatal(err) + } + c, _ := Load(path) + if c.UIMaxBri != 50 || c.LogMaxSize != DefaultLogMaxSize { + t.Fatalf("Ensure 结果不正确: %+v", c) + } +} + +func TestInspectAndMigrateOldTxt(t *testing.T) { + oldDir := t.TempDir() + write := func(name, content string) { + p := filepath.Join(oldDir, name) + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, []byte(content), 0o644); err != nil { + t.Fatal(err) + } + } + write("ui_max_bri.txt", "1200\n") + write("max_bri.txt", "4095\n") + write("sleep_time.txt", "2200-0700\n") + write("steps_num.txt", "80\n") + write("path/now_bri_file.txt", "/sys/custom/brightness\n") + write("blacklist_apps.txt", "com.a\ncom.b\n\n") + + old, ok := InspectOld(oldDir) + if !ok || old.Format != "txt" { + t.Fatalf("未识别旧 txt 配置: %+v ok=%v", old, ok) + } + if old.Values["ui_max_bri"] != "1200" || old.Values["blacklist_count"] != "2" { + t.Fatalf("inspect 值不正确: %+v", old.Values) + } + + target := filepath.Join(t.TempDir(), "config.json") + if _, err := MigrateOld(oldDir, target); err != nil { + t.Fatal(err) + } + c, err := Load(target) + if err != nil { + t.Fatal(err) + } + if c.UIMaxBri != 1200 || c.MaxBri != 4095 || c.StepsNum != 80 { + t.Fatalf("迁移数值不正确: %+v", c) + } + if c.SleepTime != "2200-0700" || c.NowBriFile != "/sys/custom/brightness" { + t.Fatalf("迁移字符串不正确: %+v", c) + } + if len(c.BlacklistApps) != 2 { + t.Fatalf("迁移黑名单不正确: %v", c.BlacklistApps) + } + if c.LogLevel != DefaultLogLevel { + t.Fatalf("未迁移字段应取默认值: %q", c.LogLevel) + } + + if err := RemoveOldTxt(oldDir); err != nil { + t.Fatalf("删除旧 txt 失败: %v", err) + } + if fileExists(filepath.Join(oldDir, "ui_max_bri.txt")) { + t.Fatal("旧 txt 未删除") + } +} + +func TestMigrateOldJSON(t *testing.T) { + oldDir := t.TempDir() + oldJSON := `{"ui_max_bri":900,"max_bri":3000,"sleep_time":"0100-0600","blacklist_apps":["com.x"]}` + if err := os.WriteFile(filepath.Join(oldDir, "config.json"), []byte(oldJSON), 0o644); err != nil { + t.Fatal(err) + } + + old, ok := InspectOld(oldDir) + if !ok || old.Format != "json" { + t.Fatalf("未识别旧 JSON 配置: %+v ok=%v", old, ok) + } + + target := filepath.Join(t.TempDir(), "config.json") + if _, err := MigrateOld(oldDir, target); err != nil { + t.Fatal(err) + } + c, err := Load(target) + if err != nil { + t.Fatal(err) + } + if c.UIMaxBri != 900 || c.MaxBri != 3000 || c.SleepTime != "0100-0600" { + t.Fatalf("JSON 迁移值不正确: %+v", c) + } + if len(c.BlacklistApps) != 1 || c.BlacklistApps[0] != "com.x" { + t.Fatalf("黑名单未保留: %v", c.BlacklistApps) + } + if c.HdrEnterRatio != DefaultHdrEnterRatio { + t.Fatalf("新字段未补默认值: %v", c.HdrEnterRatio) + } +} + +func TestInspectOldRejectsEmptyConfig(t *testing.T) { + oldDir := t.TempDir() + if err := os.WriteFile(filepath.Join(oldDir, "config.json"), []byte(`{"ui_max_bri":0}`), 0o644); err != nil { + t.Fatal(err) + } + if _, ok := InspectOld(oldDir); ok { + t.Fatal("ui_max_bri 为 0 的旧配置不应被视为可用") + } + if _, ok := InspectOld(t.TempDir()); ok { + t.Fatal("空目录不应被视为可用旧配置") + } +} diff --git a/go/internal/config/migrate.go b/go/internal/config/migrate.go new file mode 100644 index 0000000..755c28b --- /dev/null +++ b/go/internal/config/migrate.go @@ -0,0 +1,185 @@ +package config + +import ( + "encoding/json" + "errors" + "os" + "path/filepath" + "strconv" + "strings" +) + +// OldConfig 描述一份可迁移的旧配置。 +type OldConfig struct { + Format string // "json" 或 "txt" + Values map[string]string + Blacklist []string +} + +// 旧版 txt 配置的字段文件名(相对旧配置目录)。 +var oldTxtFields = map[string]string{ + "ui_max_bri": "ui_max_bri.txt", + "max_bri": "max_bri.txt", + "steps_num": "steps_num.txt", + "log_max_size": "log_max_size.txt", + "auto_bri_sleep": "auto_bri_sleep.txt", + "display_hdr_sleep": "display_hdr_sleep.txt", + "compatibility_mode": "compatibility_mode.txt", + "sleep_time": "sleep_time.txt", + "inotify_events": "inotify_events.txt", +} + +// InspectOld 检查旧配置目录,返回可展示的字段值。ok 为 false 表示没有可用旧配置。 +func InspectOld(dir string) (OldConfig, bool) { + values := map[string]string{} + + // 1. 已有 JSON 配置(要求 ui_max_bri > 0 才算有效,与旧脚本判断一致) + if jsonPath := filepath.Join(dir, "config.json"); fileExists(jsonPath) { + var raw map[string]json.RawMessage + if data, err := os.ReadFile(jsonPath); err == nil && json.Unmarshal(data, &raw) == nil { + var ui int + _ = json.Unmarshal(raw["ui_max_bri"], &ui) + if ui > 0 { + values["ui_max_bri"] = strconv.Itoa(ui) + var maxBri int + _ = json.Unmarshal(raw["max_bri"], &maxBri) + values["max_bri"] = strconv.Itoa(maxBri) + var sleepTime string + _ = json.Unmarshal(raw["sleep_time"], &sleepTime) + values["sleep_time"] = sleepTime + return OldConfig{Format: "json", Values: values}, true + } + } + return OldConfig{}, false + } + + // 2. 旧 txt 配置(ui_max_bri / max_bri 都非空才算有效) + uiTxt := filepath.Join(dir, oldTxtFields["ui_max_bri"]) + maxTxt := filepath.Join(dir, oldTxtFields["max_bri"]) + if !fileExists(uiTxt) || !fileExists(maxTxt) || readTrim(uiTxt) == "" || readTrim(maxTxt) == "" { + return OldConfig{}, false + } + + for key, name := range oldTxtFields { + values[key] = readTrim(filepath.Join(dir, name)) + } + values["now_bri_file"] = readTrim(filepath.Join(dir, "path", "now_bri_file.txt")) + values["max_bri_file"] = readTrim(filepath.Join(dir, "path", "max_bri_file.txt")) + + bl := readBlacklistTxt(dir) + values["blacklist_count"] = strconv.Itoa(len(bl)) + + return OldConfig{Format: "txt", Values: values, Blacklist: bl}, true +} + +// MigrateOld 把旧配置迁移到 target,返回迁移内容用于安装界面展示。 +func MigrateOld(dir, target string) (OldConfig, error) { + old, ok := InspectOld(dir) + if !ok { + return old, errors.New("未找到可迁移的旧配置") + } + + if old.Format == "json" { + data, err := os.ReadFile(filepath.Join(dir, "config.json")) + if err != nil { + return old, err + } + if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil { + return old, err + } + if err := os.WriteFile(target, data, 0o644); err != nil { + return old, err + } + // 补齐新版本新增字段 + c, err := Load(target) + if err != nil { + return old, err + } + // 旧 JSON 缺少 blacklist_apps 时,从 blacklist_apps.txt 补入 + var raw map[string]json.RawMessage + if rawData, err := os.ReadFile(target); err == nil && json.Unmarshal(rawData, &raw) == nil { + if _, has := raw["blacklist_apps"]; !has { + bl := readBlacklistTxt(dir) + c.BlacklistApps = bl + } + } + if err := c.Save(target); err != nil { + return old, err + } + return old, nil + } + + // txt -> JSON + c := Default() + setInt := func(key string, dst *int) { + if v := old.Values[key]; v != "" { + if n, err := strconv.Atoi(v); err == nil { + *dst = n + } + } + } + setInt("ui_max_bri", &c.UIMaxBri) + setInt("max_bri", &c.MaxBri) + setInt("steps_num", &c.StepsNum) + setInt("log_max_size", &c.LogMaxSize) + setInt("auto_bri_sleep", &c.AutoBriSleep) + setInt("display_hdr_sleep", &c.DisplayHdrSleep) + setInt("compatibility_mode", &c.CompatibilityMode) + if v := old.Values["sleep_time"]; v != "" { + c.SleepTime = v + } + if v := old.Values["inotify_events"]; v != "" { + c.InotifyEvents = v + } + if v := old.Values["now_bri_file"]; v != "" { + c.NowBriFile = v + } + if v := old.Values["max_bri_file"]; v != "" { + c.MaxBriFile = v + } + c.BlacklistApps = old.Blacklist + + if err := c.Save(target); err != nil { + return old, err + } + return old, nil +} + +// RemoveOldTxt 删除旧 txt 配置(迁移成功后由安装脚本调用)。 +func RemoveOldTxt(dir string) error { + for _, name := range oldTxtFields { + _ = os.Remove(filepath.Join(dir, name)) + } + if err := os.RemoveAll(filepath.Join(dir, "path")); err != nil { + return err + } + return os.Remove(filepath.Join(dir, "blacklist_apps.txt")) +} + +func fileExists(path string) bool { + info, err := os.Stat(path) + return err == nil && !info.IsDir() +} + +func readTrim(path string) string { + data, err := os.ReadFile(path) + if err != nil { + return "" + } + return strings.TrimSpace(string(data)) +} + +// readBlacklistTxt 读取旧版黑名单文本(每行一条,忽略空行)。 +func readBlacklistTxt(dir string) []string { + data, err := os.ReadFile(filepath.Join(dir, "blacklist_apps.txt")) + if err != nil { + return []string{} + } + out := []string{} + for _, line := range strings.Split(string(data), "\n") { + if line = strings.TrimSpace(line); line != "" { + out = append(out, line) + } + } + return out +} diff --git a/go/internal/logging/logging.go b/go/internal/logging/logging.go new file mode 100644 index 0000000..048b40f --- /dev/null +++ b/go/internal/logging/logging.go @@ -0,0 +1,157 @@ +// Package logging 写模块的 service.log。 +// +// 格式与旧 shell 版一致:`[MM-DD HH:SS] [luminpro] [LEVEL] msg`。 +// WebUI 的日志过滤只做 `includes("[LEVEL]")` 子串匹配,因此格式必须保持。 +package logging + +import ( + "fmt" + "os" + "sync" + "time" +) + +// 日志等级。 +const ( + LevelInfo = "INFO" + LevelWarn = "WARN" + LevelError = "ERROR" + LevelSuccess = "SUCCESS" +) + +// 配置里的 log_level 取值。 +const ( + FilterOff = "off" + FilterError = "error" + FilterWarn = "warn" + FilterInfo = "info" +) + +// Tag 是所有日志行的来源标记(旧版为 service/daemon/up,Go 版统一)。 +const Tag = "luminpro" + +// Logger 是并发安全的追加式日志器。 +type Logger struct { + path string + level string + maxSizeKB int + debug bool + + mu sync.Mutex +} + +// New 创建日志器。maxSizeKB 为 0 时使用默认值 512。 +func New(path, level string, maxSizeKB int) *Logger { + if level == "" { + level = FilterInfo + } + if maxSizeKB <= 0 { + maxSizeKB = 512 + } + return &Logger{path: path, level: level, maxSizeKB: maxSizeKB} +} + +// SetLevel 更新等级过滤(配置热重载时调用)。 +func (l *Logger) SetLevel(level string) { + if l == nil { + return + } + l.mu.Lock() + defer l.mu.Unlock() + if level == "" { + level = FilterInfo + } + l.level = level +} + +// SetMaxSizeKB 更新日志大小上限。 +func (l *Logger) SetMaxSizeKB(kb int) { + if l == nil { + return + } + l.mu.Lock() + defer l.mu.Unlock() + if kb <= 0 { + kb = 512 + } + l.maxSizeKB = kb +} + +// SetDebug 开启/关闭调试日志(对应配置 debug_mode)。 +func (l *Logger) SetDebug(on bool) { + if l == nil { + return + } + l.mu.Lock() + defer l.mu.Unlock() + l.debug = on +} + +// Info / Warn / Error / Success 写一条对应等级的日志。 +func (l *Logger) Info(msg string) { l.write(LevelInfo, msg) } +func (l *Logger) Warn(msg string) { l.write(LevelWarn, msg) } +func (l *Logger) Error(msg string) { l.write(LevelError, msg) } +func (l *Logger) Success(msg string) { l.write(LevelSuccess, msg) } + +// Debug 仅在 debug_mode 开启时写 INFO 日志。 +func (l *Logger) Debug(format string, args ...any) { + if l == nil { + return + } + l.mu.Lock() + on := l.debug + l.mu.Unlock() + if !on { + return + } + l.write(LevelInfo, fmt.Sprintf(format, args...)) +} + +// allowed 判断某等级是否应写入。 +func (l *Logger) allowed(level string) bool { + switch l.level { + case FilterOff: + return false + case FilterError: + return level == LevelError + case FilterWarn: + return level == LevelError || level == LevelWarn + default: + return true + } +} + +func (l *Logger) write(level, msg string) { + if l == nil || l.path == "" { + return + } + l.mu.Lock() + defer l.mu.Unlock() + + if !l.allowed(level) { + return + } + l.rotateLocked() + + f, err := os.OpenFile(l.path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644) + if err != nil { + return + } + defer f.Close() + fmt.Fprintf(f, "[%s] [%s] [%s] %s\n", time.Now().Format("01-02 15:04:05"), Tag, level, msg) +} + +// rotateLocked 超过大小上限时重置日志文件(与旧 up.sh 行为一致)。 +func (l *Logger) rotateLocked() { + info, err := os.Stat(l.path) + if err != nil { + return + } + curKB := int(info.Size() / 1024) + if curKB < l.maxSizeKB { + return + } + reset := fmt.Sprintf("[%s] [%s] [%s] 日志超限 (%dKB / %dKB),已自动重置\n", + time.Now().Format("01-02 15:04:05"), Tag, LevelWarn, curKB, l.maxSizeKB) + _ = os.WriteFile(l.path, []byte(reset), 0o644) +} diff --git a/go/internal/logging/logging_test.go b/go/internal/logging/logging_test.go new file mode 100644 index 0000000..539193d --- /dev/null +++ b/go/internal/logging/logging_test.go @@ -0,0 +1,145 @@ +package logging + +import ( + "os" + "path/filepath" + "regexp" + "strings" + "sync" + "testing" +) + +func readLog(t *testing.T, path string) string { + t.Helper() + data, err := os.ReadFile(path) + if err != nil { + t.Fatalf("读取日志失败: %v", err) + } + return string(data) +} + +func TestFormatMatchesWebUIFilter(t *testing.T) { + path := filepath.Join(t.TempDir(), "service.log") + New(path, FilterInfo, 512).Info("触发提升") + + got := readLog(t, path) + // WebUI 用 includes("[INFO]") 过滤,格式必须保持 + if !strings.Contains(got, "[INFO]") || !strings.Contains(got, "[luminpro]") { + t.Fatalf("日志格式不符合 WebUI 过滤预期: %q", got) + } + re := regexp.MustCompile(`^\[\d{2}-\d{2} \d{2}:\d{2}:\d{2}\] \[luminpro\] \[INFO\] 触发提升\n$`) + if !re.MatchString(got) { + t.Fatalf("日志格式不匹配: %q", got) + } +} + +func TestLevelFiltering(t *testing.T) { + cases := []struct { + filter string + want []string + }{ + {FilterOff, nil}, + {FilterError, []string{"[ERROR]"}}, + {FilterWarn, []string{"[ERROR]", "[WARN]"}}, + {FilterInfo, []string{"[ERROR]", "[WARN]", "[INFO]", "[SUCCESS]"}}, + } + for _, tc := range cases { + t.Run(tc.filter, func(t *testing.T) { + path := filepath.Join(t.TempDir(), "service.log") + l := New(path, tc.filter, 512) + l.Error("e") + l.Warn("w") + l.Info("i") + l.Success("s") + + data, err := os.ReadFile(path) + if tc.want == nil { + if err == nil { + t.Fatalf("off 模式不应写日志: %q", string(data)) + } + return + } + if err != nil { + t.Fatalf("读取失败: %v", err) + } + got := string(data) + for _, level := range []string{"[ERROR]", "[WARN]", "[INFO]", "[SUCCESS]"} { + shouldContain := false + for _, w := range tc.want { + if w == level { + shouldContain = true + } + } + if strings.Contains(got, level) != shouldContain { + t.Fatalf("filter=%s level=%s 不符合预期: %q", tc.filter, level, got) + } + } + }) + } +} + +func TestRotationResetsOversizedLog(t *testing.T) { + path := filepath.Join(t.TempDir(), "service.log") + l := New(path, FilterInfo, 1) // 上限 1KB + for i := 0; i < 200; i++ { + l.Info("填充日志内容填充日志内容填充日志内容填充日志内容") + } + got := readLog(t, path) + if !strings.Contains(got, "日志超限") { + t.Fatalf("超限后未重置: %q", got[:min(len(got), 200)]) + } + if len(got) > 2048 { + t.Fatalf("重置后文件仍然过大: %d 字节", len(got)) + } +} + +func TestDebugOnlyWhenEnabled(t *testing.T) { + path := filepath.Join(t.TempDir(), "service.log") + l := New(path, FilterInfo, 512) + l.Debug("事件: %s", "c") + if _, err := os.Stat(path); err == nil { + t.Fatal("debug 关闭时不应写日志") + } + l.SetDebug(true) + l.Debug("事件: %s", "c") + if got := readLog(t, path); !strings.Contains(got, "事件: c") { + t.Fatalf("debug 开启后应写日志: %q", got) + } +} + +func TestConcurrentWritesKeepLinesIntact(t *testing.T) { + path := filepath.Join(t.TempDir(), "service.log") + l := New(path, FilterInfo, 512) + + var wg sync.WaitGroup + for i := 0; i < 8; i++ { + wg.Add(1) + go func() { + defer wg.Done() + for j := 0; j < 50; j++ { + l.Info("并发写入测试内容") + } + }() + } + wg.Wait() + + for _, line := range strings.Split(strings.TrimSpace(readLog(t, path)), "\n") { + if !strings.HasPrefix(line, "[") || !strings.HasSuffix(line, "并发写入测试内容") { + t.Fatalf("出现被截断/交错的日志行: %q", line) + } + } +} + +func TestSetLevelAndMaxSize(t *testing.T) { + path := filepath.Join(t.TempDir(), "service.log") + l := New(path, FilterInfo, 512) + l.SetLevel(FilterError) + l.Info("不该出现") + l.Error("该出现") + got := readLog(t, path) + if strings.Contains(got, "不该出现") || !strings.Contains(got, "该出现") { + t.Fatalf("SetLevel 未生效: %q", got) + } + l.SetMaxSizeKB(0) // 应回退默认值,不 panic + l.Info("ok") +}