阶段十:完成 Go Cmd Tools 注释基线清零

This commit is contained in:
Christ committed 2026-08-15 05:40:01 +08:00
1 parent 393c45a1e3
commit ea1f2ec430
25 files changed
+694 -4281

No files matched your search

+96 -23
View File
@@ -33,6 +33,7 @@ import (
appversion "xianyu-go/internal/version"
)
// serverOptions 保存serverOptions,供当前处理流程使用
type serverOptions struct {
dbPath string
dbURL string
@@ -56,43 +57,53 @@ type serverOptions struct {
showVersion bool
}
// defaultDBPath 保存defaultDB路径,供当前处理流程使用
const (
defaultDBPath = "data/xianyu_data.db"
userDataDirName = "YdisksXianyuHelper"
defaultDataKeyName = "data-key"
)
// main 负责main相关处理。
func main() {
// opts 保存opts,供当前处理流程使用
opts := parseOptions()
if opts.showVersion {
fmt.Printf("Ydisks Xianyu Helper %s (commit %s, built %s)\n", appversion.Version, appversion.ShortCommit(), appversion.BuildTime)
return
}
if opts.workDir != "" {
if err := os.Chdir(opts.workDir); err != nil {
if // err 保存err,供当前处理流程使用
err := os.Chdir(opts.workDir); err != nil {
fmt.Fprintf(os.Stderr, "切换工作目录失败: %v\n", err)
os.Exit(2)
}
}
// run 保存运行,供当前处理流程使用
run := func(ctx context.Context) error { return runServer(ctx, opts) }
if opts.service {
if err := runPlatformService("YdisksXianyuHelper", run); err != nil {
if // err 保存err,供当前处理流程使用
err := runPlatformService("YdisksXianyuHelper", run); err != nil {
fmt.Fprintf(os.Stderr, "服务运行失败: %v\n", err)
os.Exit(1)
}
return
}
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer cancel()
if err := run(ctx); err != nil {
if // err 保存err,供当前处理流程使用
err := run(ctx); err != nil {
slog.Error("服务退出", "err", err)
os.Exit(1)
}
}
// parseOptions 负责parseOptions相关处理。
func parseOptions() serverOptions {
// opts 保存opts,供当前处理流程使用
var opts serverOptions
flag.StringVar(&opts.dbPath, "db", defaultDBPath, "SQLite 数据库路径(兼容旧用法)")
flag.StringVar(&opts.dbURL, "db-url", "", "数据库连接 URL(sqlite:// mysql:// postgres://),优先级高于 -db;也可用 DATABASE_URL 环境变量")
@@ -118,18 +129,23 @@ func parseOptions() serverOptions {
return opts
}
// runServer 负责运行Server相关处理。
func runServer(parent context.Context, opts serverOptions) error {
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
ctx, cancel := context.WithCancel(parent)
defer cancel()
// dataDir、err 保存数据Dir、err,供当前处理流程使用
dataDir, err := resolveDataDir(opts.workDir)
if err != nil {
return err
}
// packagedPlaywrightRuntime 保存packagedPlaywrightRuntime,供当前处理流程使用
packagedPlaywrightRuntime := strings.TrimSpace(opts.playwrightRuntimeRoot) != ""
applyPlaywrightRuntimeRoot(&opts)
if dataDir != "" {
if err := os.MkdirAll(dataDir, 0o700); err != nil {
if // err 保存err,供当前处理流程使用
err := os.MkdirAll(dataDir, 0o700); err != nil {
return fmt.Errorf("创建应用数据目录失败: %w", err)
}
if opts.dataKeyFile == "" {
@@ -148,25 +164,30 @@ func runServer(parent context.Context, opts serverOptions) error {
}
if opts.playwrightDriverDir != "" {
if err := os.Setenv("PLAYWRIGHT_DRIVER_PATH", opts.playwrightDriverDir); err != nil {
if // err 保存err,供当前处理流程使用
err := os.Setenv("PLAYWRIGHT_DRIVER_PATH", opts.playwrightDriverDir); err != nil {
return fmt.Errorf("设置 Playwright driver 目录失败: %w", err)
}
}
if opts.playwrightBrowserDir != "" {
if err := os.Setenv("PLAYWRIGHT_BROWSERS_PATH", opts.playwrightBrowserDir); err != nil {
if // err 保存err,供当前处理流程使用
err := os.Setenv("PLAYWRIGHT_BROWSERS_PATH", opts.playwrightBrowserDir); err != nil {
return fmt.Errorf("设置 Playwright 浏览器目录失败: %w", err)
}
}
if strings.TrimSpace(os.Getenv("XIANYU_DATA_KEY")) == "" && opts.dataKeyFile != "" {
// key、err 保存key、err,供当前处理流程使用
key, err := loadOrCreateDataKey(opts.dataKeyFile)
if err != nil {
return err
}
if err := os.Setenv("XIANYU_DATA_KEY", key); err != nil {
if // err 保存err,供当前处理流程使用
err := os.Setenv("XIANYU_DATA_KEY", key); err != nil {
return fmt.Errorf("设置 XIANYU_DATA_KEY 失败: %w", err)
}
}
// resolvedDBURL 保存resolvedDBURL,供当前处理流程使用
resolvedDBURL := strings.TrimSpace(os.Getenv("DATABASE_URL"))
if resolvedDBURL == "" {
resolvedDBURL = strings.TrimSpace(opts.dbURL)
@@ -175,12 +196,15 @@ func runServer(parent context.Context, opts serverOptions) error {
resolvedDBURL = resolveDBPath(dataDir, opts.dbPath)
}
if dataDir != "" && resolvedDBURL == resolveDBPath(dataDir, defaultDBPath) {
if err := os.MkdirAll(filepath.Dir(resolvedDBURL), 0o700); err != nil {
if // err 保存err,供当前处理流程使用
err := os.MkdirAll(filepath.Dir(resolvedDBURL), 0o700); err != nil {
return fmt.Errorf("创建数据库目录失败: %w", err)
}
}
// resolvedLogLevel 保存resolvedLogLevel,供当前处理流程使用
resolvedLogLevel := strings.TrimSpace(os.Getenv("LOG_LEVEL"))
// explicitLogLevel 保存explicitLogLevel,供当前处理流程使用
explicitLogLevel := resolvedLogLevel != ""
if strings.TrimSpace(opts.logLevel) != "" {
resolvedLogLevel = strings.TrimSpace(opts.logLevel)
@@ -190,55 +214,68 @@ func runServer(parent context.Context, opts serverOptions) error {
resolvedLogLevel = "debug"
explicitLogLevel = true
}
if err := logging.SetLevel(resolvedLogLevel); err != nil {
if // err 保存err,供当前处理流程使用
err := logging.SetLevel(resolvedLogLevel); err != nil {
return fmt.Errorf("日志等级无效: %w", err)
}
// resolvedLogFormat 保存resolvedLogFormat,供当前处理流程使用
resolvedLogFormat := strings.TrimSpace(os.Getenv("LOG_FORMAT"))
// explicitLogFormat 保存explicitLogFormat,供当前处理流程使用
explicitLogFormat := resolvedLogFormat != ""
if strings.TrimSpace(opts.logFormat) != "" {
resolvedLogFormat = strings.TrimSpace(opts.logFormat)
explicitLogFormat = true
}
// logWriter、closeLog、err 保存logWriter、closeLog、err,供当前处理流程使用
logWriter, closeLog, err := openServerLogWriter(dataDir)
if err != nil {
return err
}
defer closeLog()
// logger 保存logger,供当前处理流程使用
logger := logging.NewLogger(logWriter, resolvedLogFormat)
slog.SetDefault(logger)
// database、dialect、err 保存database、dialect、err,供当前处理流程使用
database, dialect, err := db.Open(ctx, resolvedDBURL)
if err != nil {
return fmt.Errorf("打开数据库失败: %w", err)
}
defer database.Close()
logger.Info("数据库已就绪", "dialect", dialect)
// store 保存store,供当前处理流程使用
store := db.NewStore(database, dialect)
if err := store.EncryptLegacySecrets(ctx); err != nil {
if // err 保存err,供当前处理流程使用
err := store.EncryptLegacySecrets(ctx); err != nil {
return fmt.Errorf("校验或升级数据库敏感字段失败: %w", err)
}
if !explicitLogLevel {
if lv, err := store.Settings.Get(ctx, "log_level"); err == nil && strings.TrimSpace(lv) != "" {
if err := logging.SetLevel(lv); err != nil {
if // lv、err 保存lv、err,供当前处理流程使用
lv, err := store.Settings.Get(ctx, "log_level"); err == nil && strings.TrimSpace(lv) != "" {
if // err 保存err,供当前处理流程使用
err := logging.SetLevel(lv); err != nil {
logger.Warn("忽略无效的系统日志设置", "value", lv, "err", err)
}
}
}
if !explicitLogFormat {
if format, err := store.Settings.Get(ctx, "log_format"); err == nil && strings.TrimSpace(format) != "" {
if // format、err 保存format、err,供当前处理流程使用
format, err := store.Settings.Get(ctx, "log_format"); err == nil && strings.TrimSpace(format) != "" {
logger = logging.NewLogger(logWriter, format)
slog.SetDefault(logger)
}
}
if opts.initAdmin {
if err := ensureAdmin(ctx, store, opts.adminEmail, opts.adminPassword); err != nil {
if // err 保存err,供当前处理流程使用
err := ensureAdmin(ctx, store, opts.adminEmail, opts.adminPassword); err != nil {
return fmt.Errorf("初始化管理员失败: %w", err)
}
logger.Info("管理员初始化完成", "username", "admin")
return nil
}
if opts.ensureAdmin {
// created、err 保存created、err,供当前处理流程使用
created, err := ensureAdminIfMissing(ctx, store, opts.adminEmail, opts.adminPassword)
if err != nil {
return fmt.Errorf("检查或初始化管理员失败: %w", err)
@@ -248,34 +285,45 @@ func runServer(parent context.Context, opts serverOptions) error {
}
}
if init, _ := store.Users.IsSystemInitialized(ctx); !init {
if // init 保存init,供当前处理流程使用
init, _ := store.Users.IsSystemInitialized(ctx); !init {
logger.Warn("系统尚未初始化,请先运行本二进制的 -init-admin 初始化管理员")
}
// bm 保存bm,供当前处理流程使用
var bm *browser.Manager
if !opts.noBrowser {
bm = browser.NewManager(logger)
if err := bm.Initialize(); err != nil {
if // err 保存err,供当前处理流程使用
err := bm.Initialize(); err != nil {
return fmt.Errorf("初始化 Playwright Chromium 指纹失败: %w", err)
}
}
// ap 保存ap,供当前处理流程使用
ap := adapter.New(store, bm, logger)
// chatService 保存聊天Service,供当前处理流程使用
chatService := chat.New(store)
ap.SetChatService(chatService)
// mgr 保存mgr,供当前处理流程使用
mgr := account.NewManager(store, ap, logger)
// autoCenter 保存autoCenter,供当前处理流程使用
autoCenter := automation.New(store, mgr, logger)
autoCenter.SetOrderDetailFetcher(ap)
// notifier 保存notifier,供当前处理流程使用
notifier := notify.New("", store, logger)
notifier.Start(ctx)
autoCenter.SetNotifier(notifier)
ap.SetAutomation(autoCenter)
ap.SetNotifier(notifier)
if err := mgr.StartAll(ctx); err != nil {
if // err 保存err,供当前处理流程使用
err := mgr.StartAll(ctx); err != nil {
logger.Error("启动账号引擎失败", "err", err)
}
// automationScheduler 保存自动化Scheduler,供当前处理流程使用
automationScheduler := automation.NewScheduler(autoCenter)
go automationScheduler.Run(ctx)
// renewalScheduler 保存renewalScheduler,供当前处理流程使用
renewalScheduler := renewal.NewScheduler(store, mgr, ap, logger, notifier)
go renewalScheduler.Run(ctx)
@@ -297,6 +345,7 @@ func runServer(parent context.Context, opts serverOptions) error {
cancel()
// stopCtx 是关闭 HTTP 服务及其后台 worker 的有限等待上下文。
// stopCancel 释放 stopCtx 的定时器资源。
// stopCtx、stopCancel 保存stopCtx、stop取消,供当前处理流程使用
stopCtx, stopCancel := context.WithTimeout(context.Background(), 10*time.Second)
_ = srv.Stop(stopCtx)
stopCancel()
@@ -314,7 +363,9 @@ func runServer(parent context.Context, opts serverOptions) error {
// desktop/system-service installations persist logs in their platform log
// directory. Windows services do not have a useful console, so they get a
// default log file beside the service data directory.
// openServerLogWriter 负责openServerLogWriter相关处理。
func openServerLogWriter(dataDir string) (io.Writer, func(), error) {
// logDir 保存logDir,供当前处理流程使用
logDir := strings.TrimSpace(os.Getenv("XIANYU_LOG_DIR"))
if logDir == "" && runtime.GOOS == "windows" && dataDir != "" {
logDir = filepath.Join(dataDir, "logs")
@@ -322,10 +373,13 @@ func openServerLogWriter(dataDir string) (io.Writer, func(), error) {
if logDir == "" {
return os.Stdout, func() {}, nil
}
if err := os.MkdirAll(logDir, 0o700); err != nil {
if // err 保存err,供当前处理流程使用
err := os.MkdirAll(logDir, 0o700); err != nil {
return nil, nil, fmt.Errorf("创建日志目录失败: %w", err)
}
// logPath 保存log路径,供当前处理流程使用
logPath := filepath.Join(logDir, "server.log")
// file、err 保存file、err,供当前处理流程使用
file, err := os.OpenFile(logPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o600)
if err != nil {
return nil, nil, fmt.Errorf("打开日志文件失败: %w", err)
@@ -333,14 +387,17 @@ func openServerLogWriter(dataDir string) (io.Writer, func(), error) {
return file, func() { _ = file.Close() }, nil
}
// applyPlaywrightRuntimeRoot 负责applyPlaywrightRuntimeRoot相关处理。
func applyPlaywrightRuntimeRoot(opts *serverOptions) {
if opts == nil {
return
}
// root 保存root,供当前处理流程使用
root := strings.TrimSpace(opts.playwrightRuntimeRoot)
if root == "" {
return
}
// archRoot 保存archRoot,供当前处理流程使用
archRoot := filepath.Join(root, runtime.GOARCH)
if opts.playwrightDriverDir == "" {
opts.playwrightDriverDir = filepath.Join(archRoot, "playwright-driver")
@@ -353,6 +410,7 @@ func applyPlaywrightRuntimeRoot(opts *serverOptions) {
// resolveDataDir 返回桌面端的标准用户数据目录。
// Linux/Docker 保留原有相对路径行为;macOS 和 Windows 在没有显式 -workdir
// 时使用当前用户的系统配置目录,避免把具体用户路径写进安装包或代码。
// resolveDataDir 负责resolve数据Dir相关处理。
func resolveDataDir(workDir string) (string, error) {
if strings.TrimSpace(workDir) != "" {
return filepath.Clean(workDir), nil
@@ -360,6 +418,7 @@ func resolveDataDir(workDir string) (string, error) {
if runtime.GOOS != "darwin" && runtime.GOOS != "windows" {
return "", nil
}
// configDir、err 保存配置Dir、err,供当前处理流程使用
configDir, err := os.UserConfigDir()
if err != nil {
return "", fmt.Errorf("读取用户配置目录失败: %w", err)
@@ -367,6 +426,7 @@ func resolveDataDir(workDir string) (string, error) {
return filepath.Join(configDir, userDataDirName), nil
}
// resolveDBPath 负责resolveDB路径相关处理。
func resolveDBPath(dataDir, configuredPath string) string {
if dataDir != "" && configuredPath == defaultDBPath {
return filepath.Join(dataDir, "data", "xianyu_data.db")
@@ -374,12 +434,15 @@ func resolveDBPath(dataDir, configuredPath string) string {
return configuredPath
}
// loadOrCreateDataKey 负责loadOrCreate数据Key相关处理。
func loadOrCreateDataKey(path string) (string, error) {
path = strings.TrimSpace(path)
if path == "" {
return "", fmt.Errorf("data key 文件路径不能为空")
}
if raw, err := os.ReadFile(path); err == nil {
if // raw、err 保存raw、err,供当前处理流程使用
raw, err := os.ReadFile(path); err == nil {
// key 保存key,供当前处理流程使用
key := strings.TrimSpace(string(raw))
if key == "" {
return "", fmt.Errorf("data key 文件为空: %s", path)
@@ -389,20 +452,26 @@ func loadOrCreateDataKey(path string) (string, error) {
return "", fmt.Errorf("读取 data key 文件失败: %w", err)
}
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
if // err 保存err,供当前处理流程使用
err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
return "", fmt.Errorf("创建 data key 目录失败: %w", err)
}
// raw 保存原始,供当前处理流程使用
raw := make([]byte, 48)
if _, err := rand.Read(raw); err != nil {
if // err 保存err,供当前处理流程使用
_, err := rand.Read(raw); err != nil {
return "", fmt.Errorf("生成 data key 失败: %w", err)
}
// key 保存key,供当前处理流程使用
key := base64.RawStdEncoding.EncodeToString(raw)
if err := os.WriteFile(path, []byte(key+"\n"), 0o600); err != nil {
if // err 保存err,供当前处理流程使用
err := os.WriteFile(path, []byte(key+"\n"), 0o600); err != nil {
return "", fmt.Errorf("写入 data key 文件失败: %w", err)
}
return key, nil
}
// ensureAdmin 负责ensureAdmin相关处理。
func ensureAdmin(ctx context.Context, store *db.Store, email, password string) error {
if password == "" {
password = os.Getenv("XIANYU_ADMIN_PASSWORD")
@@ -410,11 +479,14 @@ func ensureAdmin(ctx context.Context, store *db.Store, email, password string) e
if password == "" {
return fmt.Errorf("admin 密码不能为空,请传 -admin-password 或设置 XIANYU_ADMIN_PASSWORD")
}
// err 保存err,供当前处理流程使用
_, err := auth.InitAdmin(ctx, store, email, password)
return err
}
// ensureAdminIfMissing 负责ensureAdminIfMissing相关处理。
func ensureAdminIfMissing(ctx context.Context, store *db.Store, email, password string) (bool, error) {
// admin、err 保存admin、err,供当前处理流程使用
admin, err := store.Users.GetAdmin(ctx)
if err != nil && !errors.Is(err, db.ErrNotFound) {
return false, fmt.Errorf("查询 admin 失败: %w", err)
@@ -422,7 +494,8 @@ func ensureAdminIfMissing(ctx context.Context, store *db.Store, email, password
if admin != nil {
return false, nil
}
if err := ensureAdmin(ctx, store, email, password); err != nil {
if // err 保存err,供当前处理流程使用
err := ensureAdmin(ctx, store, email, password); err != nil {
return false, err
}
return true, nil
+40 -5
View File
@@ -11,15 +11,20 @@ import (
"xianyu-go/internal/db"
)
// TestEnsureAdminIfMissingCreatesOnlyOnce 负责TestEnsureAdminIfMissingCreatesOnlyOnce相关处理。
func TestEnsureAdminIfMissingCreatesOnlyOnce(t *testing.T) {
// ctx 保存ctx,供当前处理流程使用
ctx := context.Background()
// database、dialect、err 保存database、dialect、err,供当前处理流程使用
database, dialect, err := db.Open(ctx, "sqlite://"+filepath.Join(t.TempDir(), "server.db"))
if err != nil {
t.Fatalf("open database: %v", err)
}
t.Cleanup(func() { _ = database.Close() })
// store 保存store,供当前处理流程使用
store := db.NewStore(database, dialect)
// created、err 保存created、err,供当前处理流程使用
created, err := ensureAdminIfMissing(ctx, store, "admin@example.com", "first-password")
if err != nil || !created {
t.Fatalf("first ensure: created=%v err=%v", created, err)
@@ -28,16 +33,21 @@ func TestEnsureAdminIfMissingCreatesOnlyOnce(t *testing.T) {
if err != nil || created {
t.Fatalf("second ensure: created=%v err=%v", created, err)
}
if _, ok, err := store.Users.VerifyAndUpgrade(ctx, "admin", "first-password"); err != nil || !ok {
if // ok、err 保存ok、err,供当前处理流程使用
_, ok, err := store.Users.VerifyAndUpgrade(ctx, "admin", "first-password"); err != nil || !ok {
t.Fatalf("original password should remain valid: ok=%v err=%v", ok, err)
}
if _, ok, err := store.Users.VerifyAndUpgrade(ctx, "admin", "second-password"); err == nil || ok {
if // ok、err 保存ok、err,供当前处理流程使用
_, ok, err := store.Users.VerifyAndUpgrade(ctx, "admin", "second-password"); err == nil || ok {
t.Fatalf("later password must not reset admin: ok=%v err=%v", ok, err)
}
}
// TestLoadOrCreateDataKeyPersists 负责TestLoadOrCreate数据KeyPersists相关处理。
func TestLoadOrCreateDataKeyPersists(t *testing.T) {
// path 保存路径,供当前处理流程使用
path := filepath.Join(t.TempDir(), "data-key")
// first、err 保存first、err,供当前处理流程使用
first, err := loadOrCreateDataKey(path)
if err != nil {
t.Fatalf("create data key: %v", err)
@@ -45,6 +55,7 @@ func TestLoadOrCreateDataKeyPersists(t *testing.T) {
if first == "" {
t.Fatal("created data key is empty")
}
// second、err 保存second、err,供当前处理流程使用
second, err := loadOrCreateDataKey(path)
if err != nil {
t.Fatalf("load data key: %v", err)
@@ -52,24 +63,30 @@ func TestLoadOrCreateDataKeyPersists(t *testing.T) {
if first != second {
t.Fatalf("data key changed between loads")
}
if raw, err := os.ReadFile(path); err != nil || string(raw) == "" {
if // raw、err 保存raw、err,供当前处理流程使用
raw, err := os.ReadFile(path); err != nil || string(raw) == "" {
t.Fatalf("data key file was not written: err=%v", err)
}
}
// TestOpenServerLogWriterUsesConfiguredDirectory 负责TestOpenServerLogWriterUsesConfiguredDirectory相关处理。
func TestOpenServerLogWriterUsesConfiguredDirectory(t *testing.T) {
// logDir 保存logDir,供当前处理流程使用
logDir := t.TempDir()
t.Setenv("XIANYU_LOG_DIR", logDir)
// writer、closeLog、err 保存writer、closeLog、err,供当前处理流程使用
writer, closeLog, err := openServerLogWriter("")
if err != nil {
t.Fatalf("open log writer: %v", err)
}
if _, err := io.WriteString(writer, "test log\n"); err != nil {
if // err 保存err,供当前处理流程使用
_, err := io.WriteString(writer, "test log\n"); err != nil {
t.Fatalf("write log: %v", err)
}
closeLog()
// content、err 保存content、err,供当前处理流程使用
content, err := os.ReadFile(filepath.Join(logDir, "server.log"))
if err != nil {
t.Fatalf("read log file: %v", err)
@@ -79,8 +96,11 @@ func TestOpenServerLogWriterUsesConfiguredDirectory(t *testing.T) {
}
}
// TestResolveDataDirKeepsExplicitDirectory 负责TestResolve数据DirKeepsExplicitDirectory相关处理。
func TestResolveDataDirKeepsExplicitDirectory(t *testing.T) {
// explicit 保存explicit,供当前处理流程使用
explicit := filepath.Join(t.TempDir(), "ydisks-data")
// got、err 保存got、err,供当前处理流程使用
got, err := resolveDataDir(explicit)
if err != nil {
t.Fatalf("resolve explicit data directory: %v", err)
@@ -90,35 +110,50 @@ func TestResolveDataDirKeepsExplicitDirectory(t *testing.T) {
}
}
// TestUserDataDirName 负责Test用户数据Dir名称相关处理。
func TestUserDataDirName(t *testing.T) {
// base 保存base,供当前处理流程使用
base := filepath.Join(t.TempDir(), "Application Support")
// got 保存got,供当前处理流程使用
got := filepath.Join(base, userDataDirName)
// want 保存want,供当前处理流程使用
want := filepath.Join(base, "YdisksXianyuHelper")
if got != want {
t.Fatalf("unexpected user data directory: got %q want %q", got, want)
}
}
// TestResolveDBPathUsesDataDirectoryForDefault 负责TestResolveDB路径Uses数据DirectoryForDefault相关处理。
func TestResolveDBPathUsesDataDirectoryForDefault(t *testing.T) {
// dataDir 保存数据Dir,供当前处理流程使用
dataDir := filepath.Join(t.TempDir(), "YdisksXianyuHelper")
// got 保存got,供当前处理流程使用
got := resolveDBPath(dataDir, defaultDBPath)
// want 保存want,供当前处理流程使用
want := filepath.Join(dataDir, "data", "xianyu_data.db")
if got != want {
t.Fatalf("unexpected default database path: got %q want %q", got, want)
}
}
// TestResolveDBPathPreservesCustomPath 负责TestResolveDB路径PreservesCustom路径相关处理。
func TestResolveDBPathPreservesCustomPath(t *testing.T) {
// dataDir 保存数据Dir,供当前处理流程使用
dataDir := filepath.Join(t.TempDir(), "YdisksXianyuHelper")
// custom 保存custom,供当前处理流程使用
custom := filepath.Join(t.TempDir(), "custom.db")
if got := resolveDBPath(dataDir, custom); got != custom {
if // got 保存got,供当前处理流程使用
got := resolveDBPath(dataDir, custom); got != custom {
t.Fatalf("custom database path changed: got %q want %q", got, custom)
}
}
// TestPlaywrightRuntimeRootUsesProcessArchitecture 负责TestPlaywrightRuntimeRootUsesProcessArchitecture相关处理。
func TestPlaywrightRuntimeRootUsesProcessArchitecture(t *testing.T) {
// opts 保存opts,供当前处理流程使用
opts := serverOptions{playwrightRuntimeRoot: filepath.Join(t.TempDir(), "playwright-runtime")}
applyPlaywrightRuntimeRoot(&opts)
// wantRoot 保存wantRoot,供当前处理流程使用
wantRoot := filepath.Join(opts.playwrightRuntimeRoot, runtime.GOARCH)
if opts.playwrightDriverDir != filepath.Join(wantRoot, "playwright-driver") {
t.Fatalf("driver 目录=%q", opts.playwrightDriverDir)
+1
View File
@@ -7,6 +7,7 @@ import (
"fmt"
)
// runPlatformService 负责运行PlatformService相关处理。
func runPlatformService(_ string, _ func(context.Context) error) error {
return fmt.Errorf("当前平台不支持 -service;请使用系统服务管理器启动普通进程")
}
+12 -3
View File
@@ -9,35 +9,44 @@ import (
"golang.org/x/sys/windows/svc"
)
// windowsServiceHandler 保存windowsServiceHandler,供当前处理流程使用
type windowsServiceHandler struct {
run func(context.Context) error
}
// runPlatformService 负责运行PlatformService相关处理。
func runPlatformService(name string, run func(context.Context) error) error {
if err := svc.Run(name, windowsServiceHandler{run: run}); err != nil {
if // err 保存err,供当前处理流程使用
err := svc.Run(name, windowsServiceHandler{run: run}); err != nil {
return fmt.Errorf("Windows Service %q: %w", name, err)
}
return nil
}
// Execute 负责Execute相关处理。
func (h windowsServiceHandler) Execute(_ []string, requests <-chan svc.ChangeRequest, status chan<- svc.Status) (bool, uint32) {
// accepted 保存accepted,供当前处理流程使用
const accepted = svc.AcceptStop | svc.AcceptShutdown
status <- svc.Status{State: svc.StartPending}
// ctx、cancel 保存ctx、cancel,供当前处理流程使用
ctx, cancel := context.WithCancel(context.Background())
// done 保存done,供当前处理流程使用
done := make(chan error, 1)
go func() { done <- h.run(ctx) }()
status <- svc.Status{State: svc.Running, Accepts: accepted}
for {
select {
case request := <-requests:
case // request 保存请求,供当前处理流程使用
request := <-requests:
switch request.Cmd {
case svc.Stop, svc.Shutdown:
status <- svc.Status{State: svc.StopPending, Accepts: accepted}
cancel()
}
case err := <-done:
case // err 保存err,供当前处理流程使用
err := <-done:
cancel()
if err != nil {
return true, 1