All checks were successful
ci/woodpecker/tag/woodpecker Pipeline was successful
- 移除 cobra 依赖,使用更轻量的 urfave/cli v3 - 删除 cmd/root.go,将 CLI 逻辑整合到 main.go - 添加编译时版本号注入(Version 和 Commit) - 适配 .woodpecker.yml 以支持新的版本号路径 - 代码从 147 行减少到 135 行(净减少 12 行) 版本号现在通过 ldflags 在编译时注入,不再硬编码。 CI 构建时会自动从 Git tag 和 commit SHA 注入版本信息。
102 lines
2.2 KiB
Go
102 lines
2.2 KiB
Go
/*
|
|
Copyright © 2024 慕枫Go <mapleafgo@163.com>
|
|
*/
|
|
package main
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"game-driver/config"
|
|
"game-driver/config/game"
|
|
"game-driver/config/wait"
|
|
"game-driver/internal"
|
|
"io/fs"
|
|
"log"
|
|
"os"
|
|
|
|
"github.com/spf13/viper"
|
|
"github.com/urfave/cli/v3"
|
|
)
|
|
|
|
// 版本信息,编译时通过 ldflags 注入
|
|
var (
|
|
Version = "dev"
|
|
Commit = "unknown"
|
|
)
|
|
|
|
// formatVersion 格式化版本信息
|
|
func formatVersion() string {
|
|
if Commit == "unknown" {
|
|
return Version
|
|
}
|
|
if len(Commit) > 7 {
|
|
return Version + " (" + Commit[:7] + ")"
|
|
}
|
|
return Version + " (" + Commit + ")"
|
|
}
|
|
|
|
// initConfig 读取配置文件和环境变量
|
|
func initConfig(cfgFile string) error {
|
|
viper.SetConfigFile(cfgFile)
|
|
viper.AutomaticEnv()
|
|
|
|
// 读取配置文件
|
|
if err := viper.ReadInConfig(); err == nil {
|
|
log.Printf("使用配置文件: %s", viper.ConfigFileUsed())
|
|
} else if errors.Is(err, fs.ErrNotExist) {
|
|
return fmt.Errorf("配置文件不存在: %s", cfgFile)
|
|
} else {
|
|
return fmt.Errorf("读取配置文件错误: %w", err)
|
|
}
|
|
|
|
// 解析主配置
|
|
if err := viper.Unmarshal(&config.C); err != nil {
|
|
return fmt.Errorf("解析主配置失败: %w", err)
|
|
}
|
|
|
|
// 解析游戏配置
|
|
if game.C = game.NewConfig(config.C.Point); game.C != nil {
|
|
if err := viper.UnmarshalKey("game", &game.C); err != nil {
|
|
return fmt.Errorf("解析游戏配置失败: %w", err)
|
|
}
|
|
}
|
|
|
|
// 解析待机配置
|
|
if wait.C = wait.NewConfig(config.C.Point); wait.C != nil {
|
|
if err := viper.UnmarshalKey("wait", &wait.C); err != nil {
|
|
return fmt.Errorf("解析待机配置失败: %w", err)
|
|
}
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func main() {
|
|
app := &cli.Command{
|
|
Name: "game-driver",
|
|
Usage: "游戏驱动程序",
|
|
Version: formatVersion(),
|
|
Flags: []cli.Flag{
|
|
&cli.StringFlag{
|
|
Name: "config",
|
|
Aliases: []string{"c"},
|
|
Value: "config.yml",
|
|
Usage: "配置文件路径",
|
|
Sources: cli.EnvVars("CONFIG_FILE"),
|
|
},
|
|
},
|
|
Before: func(ctx context.Context, cmd *cli.Command) (context.Context, error) {
|
|
return ctx, initConfig(cmd.String("config"))
|
|
},
|
|
Action: func(ctx context.Context, cmd *cli.Command) error {
|
|
internal.Run()
|
|
return nil
|
|
},
|
|
}
|
|
|
|
if err := app.Run(context.Background(), os.Args); err != nil {
|
|
os.Exit(1)
|
|
}
|
|
}
|