refactor(all): share core services and streamline launcher workflows
Centralize configuration, logging, database decryption and resource metadata. Use task dependencies for development, SDK and release builds; move source tools and game downloads to Go with ordered client preparation. Rename the client to BD2 Launcher, add native icons, and update packaging and SDK checks.
This commit is contained in:
1 parent
3e7aa33cf4
commit
fe67072b7d
123 files changed
+6380
-1624
No files matched your search
@@ -22,6 +22,7 @@ dist/
|
||||
**/dist-newstyle/
|
||||
go/.cache/
|
||||
go/coverage.out
|
||||
go/cmd/bd2client/icon_windows_*.syso
|
||||
*.prof
|
||||
*.pprof
|
||||
plugins/**/bin/
|
||||
|
||||
@@ -42,6 +42,10 @@
|
||||
.\bd2w sdk pack --game-dir '<客户端目录>'
|
||||
.\bd2w sdk verify --game-dir '<客户端目录>'
|
||||
.\bd2w sdk update-names --game-dir '<客户端目录>' --game-mapping '<映射文件>'
|
||||
.\bd2w deobfuscate --source '<Assembly-CSharp目录>' --mapping '<映射文件>' --output '<源码镜像目录>'
|
||||
.\bd2w diff --a '<旧源码目录>' --b '<新源码目录>' --out '<报告目录>/report.txt'
|
||||
.\bd2w download-client --package-dir '<客户端发布包目录>'
|
||||
.\bd2w download-resources --output '<资源目录>' --bundle-version '<资源版本>' --game-data-version '<GameData版本>'
|
||||
```
|
||||
|
||||
## 客户端插件项目
|
||||
@@ -54,7 +58,7 @@
|
||||
|
||||
## 可视化客户端工具
|
||||
|
||||
BD2 Client Studio 是使用 Wails 的独立桌面客户端设置工具。Windows 使用系统 WebView2 Runtime,macOS 使用系统 WKWebView。它提供以下操作:
|
||||
BD2 Launcher 是使用 Wails 的独立桌面游戏启动器。Windows 使用系统 WebView2 Runtime,macOS 使用系统 WKWebView。它提供以下操作:
|
||||
|
||||
- 选择并验证 Brown Dust II 安装目录。
|
||||
- 填写服务器 origin 和端口,自动写入游戏目录下的 `BepInEx/config/bd2.client.json`。
|
||||
|
||||
@@ -2,44 +2,12 @@
|
||||
set -eu
|
||||
root=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd -P)
|
||||
|
||||
if [ "${1-}" = check-csharp ]; then
|
||||
shift
|
||||
(
|
||||
cd "$root"
|
||||
if [ "$#" -eq 0 ]; then
|
||||
set -- GameSdk GameNames LocalIdentity LoginUI CashShop FChat CaptureEnvironment
|
||||
fi
|
||||
for project do
|
||||
case "$project" in
|
||||
GameSdk|GameNames|LocalIdentity|LoginUI|CashShop|FChat|CaptureEnvironment) ;;
|
||||
*) printf 'bd2w: unknown C# project: %s\n' "$project" >&2; exit 1 ;;
|
||||
esac
|
||||
done
|
||||
Configuration=Release
|
||||
export Configuration
|
||||
failed=0
|
||||
for project do
|
||||
printf 'Checking %s\n' "$project"
|
||||
project_file="$root/plugins/$project/$project.csproj"
|
||||
if ! dotnet build "$project_file" -c Release -t:Rebuild --nologo -warnaserror; then
|
||||
failed=1
|
||||
continue
|
||||
fi
|
||||
if ! dotnet format style "$project_file" --verify-no-changes --severity info --no-restore; then
|
||||
failed=1
|
||||
fi
|
||||
done
|
||||
exit "$failed"
|
||||
)
|
||||
exit $?
|
||||
fi
|
||||
|
||||
tool_dir="$root/.build/tools"
|
||||
tool="$tool_dir/bd2w"
|
||||
|
||||
tool_is_current() {
|
||||
[ -f "$tool" ] || return 1
|
||||
newer_sources=$(find "$root/go/build" "$root/go/go.mod" "$root/go/go.sum" -type f -newer "$tool" -print) || {
|
||||
newer_sources=$(find "$root/go/build" "$root/go/internal/common" "$root/go/internal/client" "$root/go/go.mod" "$root/go/go.sum" -type f -newer "$tool" -print) || {
|
||||
printf 'bd2w: cannot check build tool source timestamps.\n' >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
@echo off
|
||||
setlocal DisableDelayedExpansion
|
||||
set "BD2W_ROOT=%~dp0"
|
||||
if /I "%~1"=="check-csharp" goto check_csharp
|
||||
set "BD2W_TOOL_DIR=%BD2W_ROOT%.build\tools"
|
||||
set "BD2W_TOOL=%BD2W_TOOL_DIR%\bd2w.exe"
|
||||
set "BD2W_RUN_TOOL=%BD2W_TOOL%"
|
||||
@@ -71,38 +70,3 @@ exit /b 0
|
||||
:compile_failed
|
||||
popd
|
||||
exit /b 1
|
||||
|
||||
:check_csharp
|
||||
shift
|
||||
set "BD2W_PROJECTS="
|
||||
:check_arguments
|
||||
if "%~1"=="" goto check_start
|
||||
set "BD2W_PROJECT="
|
||||
for %%P in (GameSdk GameNames LocalIdentity LoginUI CashShop FChat CaptureEnvironment) do if "%~1"=="%%P" set "BD2W_PROJECT=%%P"
|
||||
if not defined BD2W_PROJECT (
|
||||
echo bd2w: Unknown C# project: "%~1" 1>&2
|
||||
exit /b 1
|
||||
)
|
||||
set "BD2W_PROJECTS=%BD2W_PROJECTS% %BD2W_PROJECT%"
|
||||
shift
|
||||
goto check_arguments
|
||||
:check_start
|
||||
if not defined BD2W_PROJECTS set "BD2W_PROJECTS=GameSdk GameNames LocalIdentity LoginUI CashShop FChat CaptureEnvironment"
|
||||
pushd "%BD2W_ROOT%"
|
||||
if errorlevel 1 exit /b 1
|
||||
set "Configuration=Release"
|
||||
set "BD2W_FAILED=0"
|
||||
for %%P in (%BD2W_PROJECTS%) do call :check_project %%P
|
||||
popd
|
||||
exit /b %BD2W_FAILED%
|
||||
|
||||
:check_project
|
||||
echo Checking %~1
|
||||
call dotnet build "%BD2W_ROOT%plugins\%~1\%~1.csproj" -c Release -t:Rebuild --nologo -warnaserror
|
||||
if errorlevel 1 (
|
||||
set "BD2W_FAILED=1"
|
||||
exit /b 0
|
||||
)
|
||||
call dotnet format style "%BD2W_ROOT%plugins\%~1\%~1.csproj" --verify-no-changes --severity info --no-restore
|
||||
if errorlevel 1 set "BD2W_FAILED=1"
|
||||
exit /b 0
|
||||
+48
-18
@@ -1,13 +1,16 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"os/signal"
|
||||
"strings"
|
||||
|
||||
clientplugin "bd2server/internal/client/plugin"
|
||||
"bd2server/build/sourcetools"
|
||||
"bd2server/internal/common/taskgraph"
|
||||
)
|
||||
|
||||
func main() {
|
||||
@@ -33,6 +36,11 @@ func usage() {
|
||||
bd2w sdk verify [--game-dir directory] [--package-version version] [--package-directory directory]
|
||||
bd2w sdk update-names --game-mapping file [--game-dir directory] [--version-config file]
|
||||
bd2w version-source --config file --output file --plugin name
|
||||
bd2w deobfuscate --source directory --mapping file --output directory
|
||||
bd2w diff --a directory --b directory --out report.txt [diff options]
|
||||
bd2w download-client [--package-dir directory] [--manifest file] [--download | --base]
|
||||
bd2w download-resources --output directory --bundle-version version --game-data-version version
|
||||
Add --plan to show task dependencies without running them.
|
||||
|
||||
Windows: .\bd2w build
|
||||
Linux/macOS: ./bd2w build
|
||||
@@ -41,11 +49,30 @@ The wrappers cache the build tool and refresh it when its sources change.`)
|
||||
}
|
||||
|
||||
func run(args []string) error {
|
||||
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt)
|
||||
defer cancel()
|
||||
var planOnly bool
|
||||
filtered := make([]string, 0, len(args))
|
||||
for _, arg := range args {
|
||||
if arg == "--plan" {
|
||||
planOnly = true
|
||||
} else {
|
||||
filtered = append(filtered, arg)
|
||||
}
|
||||
}
|
||||
args = filtered
|
||||
t := task{ctx: ctx, planOnly: planOnly}
|
||||
if len(args) == 0 || isHelp(args[0]) {
|
||||
usage()
|
||||
return nil
|
||||
}
|
||||
if args[0] != "build" && args[0] != "runClient" && args[0] != "runClient2" && args[0] != "runServer" && args[0] != "sdk" && args[0] != "version-source" && args[0] != "plugins" {
|
||||
switch args[0] {
|
||||
case "deobfuscate":
|
||||
return t.execute("deobfuscate", taskgraph.Task{Name: "deobfuscate", Run: func(context.Context) error { return sourcetools.RunDeobfuscate(args[1:], os.Stdout) }})
|
||||
case "diff":
|
||||
return t.execute("diff", taskgraph.Task{Name: "diff", Run: func(context.Context) error { return sourcetools.RunDiff(args[1:], os.Stdout) }})
|
||||
}
|
||||
if args[0] != "build" && args[0] != "runClient" && args[0] != "runClient2" && args[0] != "runServer" && args[0] != "sdk" && args[0] != "version-source" && args[0] != "plugins" && args[0] != "check-csharp" && args[0] != "download-client" && args[0] != "download-resources" {
|
||||
return fmt.Errorf("unknown task %q; use --help for available commands", args[0])
|
||||
}
|
||||
if len(args) == 2 && isHelp(args[1]) {
|
||||
@@ -60,29 +87,32 @@ func run(args []string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
t := task{root, native}
|
||||
t.root, t.target = root, native
|
||||
switch args[0] {
|
||||
case "plugins":
|
||||
opts, err := parseOptions(args[1:])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if opts.skipTests || opts.schedulesOnly {
|
||||
return errors.New("plugins accepts only --game-dir")
|
||||
}
|
||||
game, _, _, err := t.gameDirectory(opts.gameDir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return clientplugin.BuildDevelopment(t.root, game, os.Stdout)
|
||||
return t.plugins(args[1:])
|
||||
case "runClient2":
|
||||
return t.runClient2(args[1:])
|
||||
case "runClient":
|
||||
return t.command("go", append([]string{"run", "-tags", "production", "./cmd/bd2client", "--dev", "run"}, args[1:]...)...)
|
||||
if t.planOnly {
|
||||
return t.command("go", append([]string{"run", "-tags", "production", "./cmd/bd2client", "--dev", "run", "--plan"}, args[1:]...)...)
|
||||
}
|
||||
return t.execute("runClient", t.clientIcon(), taskgraph.Task{Name: "runClient", DependsOn: []string{"client:icon"}, Run: func(context.Context) error {
|
||||
return t.command("go", append([]string{"run", "-tags", "production", "./cmd/bd2client", "--dev", "run"}, args[1:]...)...)
|
||||
}})
|
||||
case "runServer":
|
||||
return t.command("go", append([]string{"run", "./cmd/bd2server", "--dev", "run"}, args[1:]...)...)
|
||||
if t.planOnly {
|
||||
return t.command("go", append([]string{"run", "./cmd/bd2server", "--dev", "run", "--plan"}, args[1:]...)...)
|
||||
}
|
||||
return t.execute("runServer", taskgraph.Task{Name: "runServer", Run: func(context.Context) error {
|
||||
return t.command("go", append([]string{"run", "./cmd/bd2server", "--dev", "run"}, args[1:]...)...)
|
||||
}})
|
||||
case "version-source":
|
||||
return t.generateVersionSource(args[1:])
|
||||
return t.execute("version-source", taskgraph.Task{Name: "version-source", Run: func(context.Context) error { return t.generateVersionSource(args[1:]) }})
|
||||
case "check-csharp":
|
||||
return t.checkCSharp(args[1:])
|
||||
case "download-client", "download-resources":
|
||||
return t.runDownload(args[0], args[1:])
|
||||
case "sdk":
|
||||
if len(args) < 2 || isHelp(args[1]) || (len(args) == 3 && isHelp(args[2])) {
|
||||
usage()
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
|
||||
"bd2server/internal/common/taskgraph"
|
||||
)
|
||||
|
||||
func (t task) checkCSharp(projects []string) error {
|
||||
allowed := []string{"GameSdk", "GameNames", "LocalIdentity", "LoginUI", "CashShop", "FChat", "CaptureEnvironment"}
|
||||
if len(projects) == 0 {
|
||||
projects = allowed
|
||||
}
|
||||
var tasks []taskgraph.Task
|
||||
var targets []string
|
||||
seen := map[string]bool{}
|
||||
for _, project := range projects {
|
||||
if !slices.Contains(allowed, project) {
|
||||
return fmt.Errorf("unknown C# project %q", project)
|
||||
}
|
||||
if seen[project] {
|
||||
continue
|
||||
}
|
||||
seen[project] = true
|
||||
file := filepath.Join(t.root, "plugins", project, project+".csproj")
|
||||
build, format := "csharp:build:"+project, "csharp:style:"+project
|
||||
tasks = append(tasks,
|
||||
taskgraph.Task{Name: build, Run: func(context.Context) error {
|
||||
_, err := t.sdkCommand(t.root, nil, false, "build", file, "-c", "Release", "-t:Rebuild", "--nologo", "-warnaserror")
|
||||
return err
|
||||
}},
|
||||
taskgraph.Task{Name: format, DependsOn: []string{build}, Run: func(context.Context) error {
|
||||
_, err := t.sdkCommand(t.root, map[string]string{"Configuration": "Release"}, false, "format", "style", file, "--verify-no-changes", "--severity", "info", "--no-restore")
|
||||
return err
|
||||
}})
|
||||
targets = append(targets, format)
|
||||
}
|
||||
tasks = append(tasks, taskgraph.Task{Name: "check-csharp", DependsOn: targets})
|
||||
return t.execute("check-csharp", tasks...)
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"errors"
|
||||
"io"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
func (t task) packageBepInEx(game, bepinex, client string) error {
|
||||
file, err := os.Create(filepath.Join(client, "bepinex.zip"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
archive := zip.NewWriter(file)
|
||||
add := func(source, name string) error {
|
||||
in, err := os.Open(source)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = in.Close() }()
|
||||
info, err := in.Stat()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !info.Mode().IsRegular() {
|
||||
return errors.New("BepInEx package entries must be regular files")
|
||||
}
|
||||
header, err := zip.FileInfoHeader(info)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
header.Name = filepath.ToSlash(name)
|
||||
header.Method = zip.Deflate
|
||||
out, err := archive.CreateHeader(header)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = io.Copy(out, in)
|
||||
return err
|
||||
}
|
||||
var result error
|
||||
for _, name := range []string{"winhttp.dll", "doorstop_config.ini"} {
|
||||
if result = add(filepath.Join(game, name), name); result != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
if result == nil {
|
||||
core := filepath.Join(bepinex, "core")
|
||||
result = filepath.WalkDir(core, func(path string, entry fs.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if entry.IsDir() {
|
||||
return nil
|
||||
}
|
||||
if entry.Type()&os.ModeSymlink != 0 {
|
||||
return errors.New("BepInEx core must not contain symlinks")
|
||||
}
|
||||
relative, err := filepath.Rel(core, path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return add(path, filepath.Join("BepInEx", "core", relative))
|
||||
})
|
||||
}
|
||||
return errors.Join(result, archive.Close(), file.Close())
|
||||
}
|
||||
+79
-55
@@ -1,6 +1,7 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
@@ -11,6 +12,8 @@ import (
|
||||
clientinstance "bd2server/internal/client/instance"
|
||||
clientplugin "bd2server/internal/client/plugin"
|
||||
clientsetup "bd2server/internal/client/setup"
|
||||
"bd2server/internal/common/taskgraph"
|
||||
"bd2server/internal/common/versionconfig"
|
||||
)
|
||||
|
||||
func (t task) runClient2(args []string) error {
|
||||
@@ -23,60 +26,81 @@ func (t task) runClient2(args []string) error {
|
||||
if fs.NArg() != 0 {
|
||||
return fmt.Errorf("unexpected argument %q", fs.Arg(0))
|
||||
}
|
||||
game, _, _, err := t.gameDirectory(*gameDir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
versions, err := clientconfig.LoadReleaseVersions(filepath.Join(t.root, "versions.json"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := clientsetup.Inspect(game, versions); err != nil {
|
||||
return err
|
||||
}
|
||||
settings, err := clientconfig.Load(game)
|
||||
if err != nil {
|
||||
return fmt.Errorf("save the original client's connection settings first: %w", err)
|
||||
}
|
||||
settings.ProxyURL = ""
|
||||
|
||||
instance, err := clientinstance.Prepare(*name, game, versions.GameVersion)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !instance.Created {
|
||||
settings, err = clientconfig.Load(instance.GameDirectory)
|
||||
if err != nil {
|
||||
return fmt.Errorf("load second client's connection settings: %w", err)
|
||||
}
|
||||
}
|
||||
if _, err := clientsetup.SaveSettings(instance.GameDirectory, settings, versions); err != nil {
|
||||
return fmt.Errorf("prepare second client's resources: %w", err)
|
||||
}
|
||||
if instance.Created {
|
||||
if err := clientplugin.BuildDevelopment(t.root, game, os.Stdout); err != nil {
|
||||
var game, launcher string
|
||||
var versions versionconfig.Config
|
||||
var settings clientconfig.Settings
|
||||
var instance clientinstance.Instance
|
||||
return t.execute("runClient2",
|
||||
taskgraph.Task{Name: "instance:configuration", Run: func(context.Context) error {
|
||||
var err error
|
||||
game, _, _, err = t.gameDirectory(*gameDir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
versions, err = versionconfig.Load(filepath.Join(t.root, "versions.json"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := clientsetup.Inspect(game, versions); err != nil {
|
||||
return err
|
||||
}
|
||||
settings, err = clientconfig.Load(game)
|
||||
if err != nil {
|
||||
return fmt.Errorf("save the original client's connection settings first: %w", err)
|
||||
}
|
||||
settings.ProxyURL = ""
|
||||
return nil
|
||||
}},
|
||||
taskgraph.Task{Name: "instance:prepare", DependsOn: []string{"instance:configuration"}, Run: func(context.Context) error {
|
||||
var err error
|
||||
instance, err = clientinstance.Prepare(*name, game, versions.GameVersion)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !instance.Created {
|
||||
settings, err = clientconfig.Load(instance.GameDirectory)
|
||||
if err != nil {
|
||||
return fmt.Errorf("load second client's connection settings: %w", err)
|
||||
}
|
||||
}
|
||||
if _, err := clientsetup.SaveSettings(instance.GameDirectory, settings, versions); err != nil {
|
||||
return fmt.Errorf("prepare second client's resources: %w", err)
|
||||
}
|
||||
return nil
|
||||
}},
|
||||
taskgraph.Task{Name: "instance:plugins", DependsOn: []string{"instance:prepare"}, Run: func(ctx context.Context) error {
|
||||
if !instance.Created {
|
||||
return nil
|
||||
}
|
||||
if err := clientplugin.BuildDevelopment(ctx, t.root, game, os.Stdout); err != nil {
|
||||
return err
|
||||
}
|
||||
plugins := func(name string) string {
|
||||
return filepath.Join(t.root, "plugins", name, "bin", "Release", "netstandard2.1", "BD2"+name+".dll")
|
||||
}
|
||||
_, err := clientsetup.InstallPlugins(instance.GameDirectory, settings, versions, plugins("LocalIdentity"), plugins("LoginUI"), plugins("CashShop"), plugins("FChat"))
|
||||
return err
|
||||
}
|
||||
plugins := func(name string) string {
|
||||
return filepath.Join(t.root, "plugins", name, "bin", "Release", "netstandard2.1", "BD2"+name+".dll")
|
||||
}
|
||||
if _, err := clientsetup.InstallPlugins(instance.GameDirectory, settings, versions, plugins("LocalIdentity"), plugins("LoginUI"), plugins("CashShop"), plugins("FChat")); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
launcher, err := instance.WriteLauncher()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Println("Second client ready:", launcher)
|
||||
fmt.Println("Unity log:", filepath.Join(instance.Root, "logs", "Player.log"))
|
||||
fmt.Println("BepInEx log:", filepath.Join(instance.GameDirectory, "BepInEx", "LogOutput.log"))
|
||||
if t.target.goos == "windows" {
|
||||
return exec.Command("wscript.exe", "//nologo", launcher).Run()
|
||||
}
|
||||
command := exec.Command("/bin/sh", launcher)
|
||||
if err := command.Start(); err != nil {
|
||||
return err
|
||||
}
|
||||
return command.Process.Release()
|
||||
}},
|
||||
taskgraph.Task{Name: "instance:launcher", DependsOn: []string{"instance:plugins"}, Run: func(context.Context) error {
|
||||
var err error
|
||||
launcher, err = instance.WriteLauncher()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Println("Second client ready:", launcher)
|
||||
fmt.Println("Unity log:", filepath.Join(instance.Root, "logs", "Player.log"))
|
||||
fmt.Println("BepInEx log:", filepath.Join(instance.GameDirectory, "BepInEx", "LogOutput.log"))
|
||||
return nil
|
||||
}},
|
||||
taskgraph.Task{Name: "runClient2", DependsOn: []string{"instance:launcher"}, Run: func(context.Context) error {
|
||||
if t.target.goos == "windows" {
|
||||
return exec.CommandContext(t.ctx, "wscript.exe", "//nologo", launcher).Run()
|
||||
}
|
||||
command := exec.Command("/bin/sh", launcher)
|
||||
if err := command.Start(); err != nil {
|
||||
return err
|
||||
}
|
||||
return command.Process.Release()
|
||||
}},
|
||||
)
|
||||
}
|
||||
+5
-24
@@ -1,40 +1,21 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
commonconfig "bd2server/internal/common/config"
|
||||
)
|
||||
|
||||
func readJSON(path string, v any, strict bool) error {
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d := json.NewDecoder(bytes.NewReader(bytes.TrimPrefix(raw, []byte{0xef, 0xbb, 0xbf})))
|
||||
if strict {
|
||||
d.DisallowUnknownFields()
|
||||
}
|
||||
if err = d.Decode(v); err != nil {
|
||||
return fmt.Errorf("%s: %w", path, err)
|
||||
}
|
||||
if err = d.Decode(new(any)); err != io.EOF {
|
||||
return fmt.Errorf("%s must contain one JSON object", path)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (t task) gameDirectory(explicit string) (string, string, string, error) {
|
||||
if explicit == "" {
|
||||
var c struct {
|
||||
c, err := commonconfig.Load(filepath.Join(t.root, "go", "config.json"), struct {
|
||||
SchemaVersion int `json:"schema_version"`
|
||||
GameDirectory string `json:"game_directory"`
|
||||
}
|
||||
if err := readJSON(filepath.Join(t.root, "go", "config.json"), &c, true); err != nil {
|
||||
}{}, commonconfig.DecodeOptions{DisallowUnknownFields: true, RejectTrailing: true, AllowBOM: true})
|
||||
if err != nil {
|
||||
return "", "", "", fmt.Errorf("read go/config.json or pass -GameDir: %w", err)
|
||||
}
|
||||
if c.SchemaVersion != 1 || strings.TrimSpace(c.GameDirectory) == "" {
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"bd2server/internal/common/taskgraph"
|
||||
)
|
||||
|
||||
func (t task) runDownload(name string, args []string) error {
|
||||
if name == "download-resources" {
|
||||
forwarded, _, err := absoluteDownloadPaths(args, "output")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return t.execute(name, taskgraph.Task{Name: name, Run: func(context.Context) error {
|
||||
return t.command("go", append([]string{"run", "-tags", "production", "./cmd/bd2client", name}, forwarded...)...)
|
||||
}})
|
||||
}
|
||||
forwarded, err := downloadClientArguments(t.root, args)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if t.planOnly {
|
||||
return t.command("go", append([]string{"run", "-tags", "production", "./cmd/bd2client", "prepare", "--plan"}, forwarded...)...)
|
||||
}
|
||||
return t.execute(name, taskgraph.Task{Name: name, Run: func(context.Context) error {
|
||||
return t.command("go", append([]string{"run", "-tags", "production", "./cmd/bd2client", "prepare"}, forwarded...)...)
|
||||
}})
|
||||
}
|
||||
|
||||
func downloadClientArguments(root string, args []string) ([]string, error) {
|
||||
forwarded, paths, err := absoluteDownloadPaths(args, "package-dir", "manifest", "version-config", "game-dir", "resource-dir")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if paths["package-dir"] == "" {
|
||||
forwarded = append(forwarded, "--package-dir", root)
|
||||
if paths["manifest"] == "" {
|
||||
forwarded = append(forwarded, "--manifest", filepath.Join(root, "tools", "client", "client-download.json"))
|
||||
}
|
||||
} else if paths["manifest"] == "" {
|
||||
forwarded = append(forwarded, "--manifest", filepath.Join(paths["package-dir"], "client-download.json"))
|
||||
}
|
||||
return forwarded, nil
|
||||
}
|
||||
|
||||
func absoluteDownloadPaths(args []string, names ...string) ([]string, map[string]string, error) {
|
||||
forwarded := append([]string{}, args...)
|
||||
paths := map[string]string{}
|
||||
for i := 0; i < len(forwarded); i++ {
|
||||
if !strings.HasPrefix(forwarded[i], "-") {
|
||||
continue
|
||||
}
|
||||
name, value, assigned := strings.Cut(forwarded[i], "=")
|
||||
name = strings.TrimLeft(name, "-")
|
||||
pathOption := false
|
||||
for _, candidate := range names {
|
||||
pathOption = pathOption || name == candidate
|
||||
}
|
||||
if !pathOption {
|
||||
continue
|
||||
}
|
||||
if !assigned {
|
||||
i++
|
||||
if i >= len(forwarded) {
|
||||
return nil, nil, fmt.Errorf("--%s requires a path", name)
|
||||
}
|
||||
value = forwarded[i]
|
||||
}
|
||||
if value == "" {
|
||||
return nil, nil, fmt.Errorf("--%s requires a path", name)
|
||||
}
|
||||
absolute, err := filepath.Abs(value)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
paths[name] = absolute
|
||||
if assigned {
|
||||
forwarded[i] = "--" + name + "=" + absolute
|
||||
} else {
|
||||
forwarded[i] = absolute
|
||||
}
|
||||
}
|
||||
return forwarded, paths, nil
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDownloadForwardingPreservesCallerPathsAndRepoDefaults(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
args, err := downloadClientArguments(root, []string{"--game-dir=game-output", "--probe-only"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
wantGame, err := filepath.Abs("game-output")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if args[0] != "--game-dir="+wantGame {
|
||||
t.Fatalf("game path would change after child changes directory: %v", args)
|
||||
}
|
||||
_, paths, err := absoluteDownloadPaths(args, "package-dir", "manifest")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if paths["package-dir"] != root || paths["manifest"] != filepath.Join(root, "tools", "client", "client-download.json") {
|
||||
t.Fatalf("development defaults do not point to the repository: %v", paths)
|
||||
}
|
||||
packageDir := filepath.Join(root, "release")
|
||||
args, err = downloadClientArguments(root, []string{"--package-dir", packageDir})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, paths, err = absoluteDownloadPaths(args, "package-dir", "manifest")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if paths["manifest"] != filepath.Join(packageDir, "client-download.json") {
|
||||
t.Fatalf("explicit release package used repository manifest: %v", paths)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"bd2server/internal/client/iconresource"
|
||||
"bd2server/internal/common/taskgraph"
|
||||
)
|
||||
|
||||
func (t task) clientIcon() taskgraph.Task {
|
||||
return taskgraph.Task{Name: "client:icon", Run: func(context.Context) error {
|
||||
_, err := iconresource.Generate(t.root, t.target.goos, t.target.goarch)
|
||||
return err
|
||||
}}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
|
||||
clientplugin "bd2server/internal/client/plugin"
|
||||
"bd2server/internal/common/taskgraph"
|
||||
)
|
||||
|
||||
func (t task) plugins(args []string) error {
|
||||
opts, err := parseOptions(args)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if opts.skipTests || opts.schedulesOnly {
|
||||
return errors.New("plugins accepts only --game-dir")
|
||||
}
|
||||
var game string
|
||||
return t.execute("plugins",
|
||||
taskgraph.Task{Name: "game:locate", Run: func(context.Context) error {
|
||||
var err error
|
||||
game, _, _, err = t.gameDirectory(opts.gameDir)
|
||||
return err
|
||||
}},
|
||||
taskgraph.Task{Name: "plugins", DependsOn: []string{"game:locate"}, Run: func(context.Context) error { return clientplugin.BuildDevelopment(t.ctx, t.root, game, os.Stdout) }})
|
||||
}
|
||||
+24
-3
@@ -1,17 +1,38 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"bd2server/internal/common/taskgraph"
|
||||
)
|
||||
|
||||
type task struct {
|
||||
root string
|
||||
target target
|
||||
root string
|
||||
target target
|
||||
ctx context.Context
|
||||
planOnly bool
|
||||
}
|
||||
|
||||
func (t task) execute(target string, tasks ...taskgraph.Task) error {
|
||||
graph, err := taskgraph.New(tasks...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if t.planOnly {
|
||||
plan, err := graph.Plan(target)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = fmt.Fprintln(os.Stdout, strings.Join(plan, "\n"))
|
||||
return err
|
||||
}
|
||||
return graph.Run(t.ctx, target)
|
||||
}
|
||||
|
||||
func repositoryRoot() (string, error) {
|
||||
@@ -32,7 +53,7 @@ func repositoryRoot() (string, error) {
|
||||
|
||||
// Every child receives a process-local native target and repository-local cache.
|
||||
func (t task) command(program string, args ...string) error {
|
||||
cmd := exec.Command(program, args...)
|
||||
cmd := exec.CommandContext(t.ctx, program, args...)
|
||||
cmd.Dir = filepath.Join(t.root, "go")
|
||||
cmd.Stdin = os.Stdin
|
||||
cmd.Stdout = os.Stdout
|
||||
|
||||
+3
-119
@@ -1,7 +1,6 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -11,7 +10,7 @@ import (
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
clientplugin "bd2server/internal/client/plugin"
|
||||
commonconfig "bd2server/internal/common/config"
|
||||
)
|
||||
|
||||
type buildOptions struct {
|
||||
@@ -59,8 +58,8 @@ func parseOptions(args []string) (buildOptions, error) {
|
||||
return opts, nil
|
||||
}
|
||||
func (t task) versions() (releaseVersions, error) {
|
||||
var v releaseVersions
|
||||
if err := readJSON(filepath.Join(t.root, "versions.json"), &v, false); err != nil {
|
||||
v, err := commonconfig.Load(filepath.Join(t.root, "versions.json"), releaseVersions{}, commonconfig.DecodeOptions{RejectTrailing: true, AllowBOM: true})
|
||||
if err != nil {
|
||||
return v, err
|
||||
}
|
||||
valid := regexp.MustCompile(`^[A-Za-z0-9.+_-]+$`)
|
||||
@@ -94,118 +93,3 @@ func (t task) schedules(gameVersion string) ([]string, string, error) {
|
||||
hash := fmt.Sprintf("%x", sha256.Sum256([]byte(strings.Join(lines, "\n"))))[:12]
|
||||
return files, "bd2schedules-" + gameVersion + "-" + hash, nil
|
||||
}
|
||||
func (t task) build(opts buildOptions) error {
|
||||
v, err := t.versions()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
schedules, scheduleName, err := t.schedules(v.Game)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
buildRoot := filepath.Join(t.root, ".build")
|
||||
if opts.schedulesOnly {
|
||||
out := filepath.Join(buildRoot, scheduleName)
|
||||
if err := os.MkdirAll(out, 0755); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, file := range schedules {
|
||||
if err := copyFile(file, filepath.Join(out, filepath.Base(file))); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
fmt.Println("Built schedule release:", out)
|
||||
return nil
|
||||
}
|
||||
game, _, _, err := t.gameDirectory(opts.gameDir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
packageRoot := filepath.Join(buildRoot, "package")
|
||||
server := filepath.Join(packageRoot, "bd2server")
|
||||
client := filepath.Join(packageRoot, "bd2client")
|
||||
suffix := "-" + t.target.platform + "-" + t.target.architecture + ".zip"
|
||||
serverZip := filepath.Join(buildRoot, "bd2server-"+v.Server+suffix)
|
||||
clientZip := filepath.Join(buildRoot, "bd2client-"+v.Client+suffix)
|
||||
if err := os.MkdirAll(buildRoot, 0755); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, path := range []string{packageRoot, serverZip, clientZip} {
|
||||
if err := removeBuildOutput(buildRoot, path); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for _, path := range []string{filepath.Join(server, "go"), filepath.Join(server, "data", "state"), filepath.Join(server, "schedules"), filepath.Join(client, "plugins")} {
|
||||
if err := os.MkdirAll(path, 0755); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if !opts.skipTests {
|
||||
for _, args := range [][]string{{"test", "./..."}, {"vet", "./..."}, {"test", "-tags", "release,production", "./..."}, {"vet", "-tags", "release,production", "./..."}} {
|
||||
if err := t.command("go", args...); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
ext := ""
|
||||
clientFlags := "-s -w"
|
||||
if t.target.goos == "windows" {
|
||||
ext = ".exe"
|
||||
clientFlags = "-H windowsgui -s -w"
|
||||
}
|
||||
if err := t.command("go", "build", "-tags", "release", "-trimpath", "-ldflags", "-s -w", "-o", filepath.Join(server, "bd2server"+ext), "./cmd/bd2server"); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := t.command("go", "build", "-tags", "release,production", "-trimpath", "-ldflags", clientFlags, "-o", filepath.Join(client, "bd2client"+ext), "./cmd/bd2client"); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := clientplugin.BuildDevelopment(t.root, game, os.Stdout); err != nil {
|
||||
return err
|
||||
}
|
||||
var shared []byte
|
||||
for _, plugin := range []string{"LocalIdentity", "LoginUI", "CashShop", "FChat"} {
|
||||
out := filepath.Join(t.root, "plugins", plugin, "bin", "Release", "netstandard2.1")
|
||||
raw, err := os.ReadFile(filepath.Join(out, "BD2.GameNames.dll"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if shared != nil && !bytes.Equal(shared, raw) {
|
||||
return errors.New("plugins were built with different BD2.GameNames libraries")
|
||||
}
|
||||
shared = raw
|
||||
for _, name := range []string{"BD2" + plugin + ".dll", "BD2.GameNames.dll"} {
|
||||
if err := copyFile(filepath.Join(out, name), filepath.Join(client, "plugins", name)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := copyTree(filepath.Join(t.root, "go", "seed"), filepath.Join(server, "go", "seed")); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, file := range schedules {
|
||||
if err := copyFile(file, filepath.Join(server, "schedules", filepath.Base(file))); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for _, name := range []string{"versions.json", "README.md", "LICENSE"} {
|
||||
for _, out := range []string{server, client} {
|
||||
if err := copyFile(filepath.Join(t.root, name), filepath.Join(out, name)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, name := range []string{"AUTHENTICATION.md", "RESOURCES.md", "GAME_CONFIGURATION.md"} {
|
||||
if err := copyFile(filepath.Join(t.root, name), filepath.Join(server, name)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err := archiveDirectory(server, serverZip); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := archiveDirectory(client, clientZip); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Println("Built server archive:", serverZip)
|
||||
fmt.Println("Built client archive:", clientZip)
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
clientplugin "bd2server/internal/client/plugin"
|
||||
"bd2server/internal/common/taskgraph"
|
||||
)
|
||||
|
||||
type release struct {
|
||||
task task
|
||||
options buildOptions
|
||||
versions releaseVersions
|
||||
schedules []string
|
||||
scheduleName, game, bepinex string
|
||||
buildRoot, packageRoot, server, client, serverZip, clientZip string
|
||||
}
|
||||
|
||||
func (t task) build(opts buildOptions) error {
|
||||
r := &release{task: t, options: opts, buildRoot: filepath.Join(t.root, ".build")}
|
||||
nodes := []taskgraph.Task{
|
||||
{Name: "release:metadata", Run: func(context.Context) error { return r.loadMetadata() }},
|
||||
{Name: "release:schedules", DependsOn: []string{"release:metadata"}, Run: func(context.Context) error { return r.exportSchedules() }},
|
||||
}
|
||||
if opts.schedulesOnly {
|
||||
return t.execute("release:schedules", nodes...)
|
||||
}
|
||||
checks := []string{"release:metadata"}
|
||||
if !opts.skipTests {
|
||||
var prior string
|
||||
for _, check := range []struct {
|
||||
name string
|
||||
args []string
|
||||
}{
|
||||
{"go:test", []string{"test", "./..."}}, {"go:vet", []string{"vet", "./..."}},
|
||||
{"go:test-release", []string{"test", "-tags", "release,production", "./..."}}, {"go:vet-release", []string{"vet", "-tags", "release,production", "./..."}},
|
||||
} {
|
||||
dependencies := []string{"release:metadata"}
|
||||
if prior != "" {
|
||||
dependencies = []string{prior}
|
||||
}
|
||||
nodes = append(nodes, taskgraph.Task{Name: check.name, DependsOn: dependencies, Run: func(context.Context) error { return t.command("go", check.args...) }})
|
||||
prior = check.name
|
||||
}
|
||||
checks = append(checks, prior)
|
||||
}
|
||||
nodes = append(nodes,
|
||||
t.clientIcon(),
|
||||
taskgraph.Task{Name: "release:stage", DependsOn: checks, Run: func(context.Context) error { return r.prepareStage() }},
|
||||
taskgraph.Task{Name: "release:server", DependsOn: []string{"release:stage"}, Run: func(context.Context) error { return r.compileServer() }},
|
||||
taskgraph.Task{Name: "release:client", DependsOn: []string{"release:stage", "client:icon"}, Run: func(context.Context) error { return r.compileClient() }},
|
||||
taskgraph.Task{Name: "release:plugins", DependsOn: []string{"release:stage"}, Run: func(context.Context) error { return clientplugin.BuildDevelopment(t.ctx, t.root, r.game, os.Stdout) }},
|
||||
taskgraph.Task{Name: "release:assets", DependsOn: []string{"release:stage", "release:plugins"}, Run: func(context.Context) error { return r.stageAssets() }},
|
||||
taskgraph.Task{Name: "build", DependsOn: []string{"release:server", "release:client", "release:assets"}, Run: func(context.Context) error { return r.archive() }},
|
||||
)
|
||||
return t.execute("build", nodes...)
|
||||
}
|
||||
|
||||
func (r *release) loadMetadata() error {
|
||||
var err error
|
||||
r.versions, err = r.task.versions()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
r.schedules, r.scheduleName, err = r.task.schedules(r.versions.Game)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if r.options.schedulesOnly {
|
||||
return nil
|
||||
}
|
||||
r.game, _, r.bepinex, err = r.task.gameDirectory(r.options.gameDir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
r.packageRoot = filepath.Join(r.buildRoot, "package")
|
||||
r.server, r.client = filepath.Join(r.packageRoot, "bd2server"), filepath.Join(r.packageRoot, "bd2client")
|
||||
suffix := "-" + r.task.target.platform + "-" + r.task.target.architecture + ".zip"
|
||||
r.serverZip = filepath.Join(r.buildRoot, "bd2server-"+r.versions.Server+suffix)
|
||||
r.clientZip = filepath.Join(r.buildRoot, "bd2client-"+r.versions.Client+suffix)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *release) exportSchedules() error {
|
||||
out := filepath.Join(r.buildRoot, r.scheduleName)
|
||||
if err := os.MkdirAll(out, 0755); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, file := range r.schedules {
|
||||
if err := copyFile(file, filepath.Join(out, filepath.Base(file))); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
fmt.Println("Built schedule release:", out)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *release) prepareStage() error {
|
||||
if err := os.MkdirAll(r.buildRoot, 0755); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, path := range []string{r.packageRoot, r.serverZip, r.clientZip} {
|
||||
if err := removeBuildOutput(r.buildRoot, path); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for _, path := range []string{filepath.Join(r.server, "go"), filepath.Join(r.server, "data", "state"), filepath.Join(r.server, "schedules"), filepath.Join(r.client, "plugins")} {
|
||||
if err := os.MkdirAll(path, 0755); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *release) executable(name string) string {
|
||||
if r.task.target.goos == "windows" {
|
||||
return name + ".exe"
|
||||
}
|
||||
return name
|
||||
}
|
||||
|
||||
func (r *release) compileServer() error {
|
||||
return r.task.command("go", "build", "-tags", "release", "-trimpath", "-ldflags", "-s -w", "-o", filepath.Join(r.server, r.executable("bd2server")), "./cmd/bd2server")
|
||||
}
|
||||
|
||||
func (r *release) compileClient() error {
|
||||
flags := "-s -w"
|
||||
if r.task.target.goos == "windows" {
|
||||
flags = "-H windowsgui -s -w"
|
||||
}
|
||||
return r.task.command("go", "build", "-tags", "release,production", "-trimpath", "-ldflags", flags, "-o", filepath.Join(r.client, r.executable("bd2client")), "./cmd/bd2client")
|
||||
}
|
||||
|
||||
func (r *release) stageAssets() error {
|
||||
root := r.task.root
|
||||
if err := copyFile(filepath.Join(root, "tools", "client", "client-download.json"), filepath.Join(r.client, "client-download.json")); err != nil {
|
||||
return err
|
||||
}
|
||||
if r.task.target.goos == "windows" {
|
||||
if err := r.task.packageBepInEx(r.game, r.bepinex, r.client); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
var shared []byte
|
||||
for _, plugin := range []string{"LocalIdentity", "LoginUI", "CashShop", "FChat"} {
|
||||
out := filepath.Join(root, "plugins", plugin, "bin", "Release", "netstandard2.1")
|
||||
raw, err := os.ReadFile(filepath.Join(out, "BD2.GameNames.dll"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if shared != nil && !bytes.Equal(shared, raw) {
|
||||
return errors.New("plugins were built with different BD2.GameNames libraries")
|
||||
}
|
||||
shared = raw
|
||||
for _, name := range []string{"BD2" + plugin + ".dll", "BD2.GameNames.dll"} {
|
||||
if err := copyFile(filepath.Join(out, name), filepath.Join(r.client, "plugins", name)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := copyTree(filepath.Join(root, "go", "seed"), filepath.Join(r.server, "go", "seed")); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, file := range r.schedules {
|
||||
if err := copyFile(file, filepath.Join(r.server, "schedules", filepath.Base(file))); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for _, name := range []string{"versions.json", "README.md", "LICENSE"} {
|
||||
for _, out := range []string{r.server, r.client} {
|
||||
if err := copyFile(filepath.Join(root, name), filepath.Join(out, name)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, name := range []string{"AUTHENTICATION.md", "RESOURCES.md", "GAME_CONFIGURATION.md"} {
|
||||
if err := copyFile(filepath.Join(root, name), filepath.Join(r.server, name)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *release) archive() error {
|
||||
if err := archiveDirectory(r.server, r.serverZip); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := archiveDirectory(r.client, r.clientZip); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Println("Built server archive:", r.serverZip)
|
||||
fmt.Println("Built client archive:", r.clientZip)
|
||||
return nil
|
||||
}
|
||||
+5
-3
@@ -12,6 +12,8 @@ import (
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
commonconfig "bd2server/internal/common/config"
|
||||
)
|
||||
|
||||
type sdkOptions struct{ gameDir, versionConfig, packageVersion, outputDirectory, packageDirectory, gameMapping string }
|
||||
@@ -53,8 +55,8 @@ func (t task) sdkOptions(args []string, mode string) (sdkOptions, error) {
|
||||
}
|
||||
|
||||
func (t task) sdkPackageVersion(o sdkOptions) (string, string, error) {
|
||||
var versions releaseVersions
|
||||
if err := readJSON(o.versionConfig, &versions, false); err != nil {
|
||||
versions, err := commonconfig.Load(o.versionConfig, releaseVersions{}, commonconfig.DecodeOptions{RejectTrailing: true, AllowBOM: true})
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
if !regexp.MustCompile(`^\d+\.\d+\.\d+$`).MatchString(versions.Game) {
|
||||
@@ -97,7 +99,7 @@ func (t task) sdkPackageVersion(o sdkOptions) (string, string, error) {
|
||||
}
|
||||
|
||||
func (t task) sdkCommand(workdir string, env map[string]string, capture bool, args ...string) (string, error) {
|
||||
cmd := exec.Command("dotnet", args...)
|
||||
cmd := exec.CommandContext(t.ctx, "dotnet", args...)
|
||||
cmd.Dir = workdir
|
||||
cmd.Stdin = os.Stdin
|
||||
cmd.Env = replaceEnvironment(os.Environ(), env)
|
||||
|
||||
+131
-91
@@ -1,72 +1,101 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bd2server/internal/common/taskgraph"
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type sdkPackage struct {
|
||||
task task
|
||||
options sdkOptions
|
||||
version, gameVersion, managed, workspace, tool, sdk, shared, table, config string
|
||||
}
|
||||
|
||||
func (t task) sdkPack(args []string) (result error) {
|
||||
o, err := t.sdkOptions(args, "pack")
|
||||
options, err := t.sdkOptions(args, "pack")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
version, gameVersion, err := t.sdkPackageVersion(o)
|
||||
if err != nil {
|
||||
return err
|
||||
p := &sdkPackage{task: t, options: options}
|
||||
defer func() {
|
||||
if p.workspace != "" {
|
||||
t.sdkCleanup(p.workspace, &result)
|
||||
}
|
||||
}()
|
||||
return t.execute("sdk:pack", p.tasks()...)
|
||||
}
|
||||
|
||||
func (p *sdkPackage) tasks() []taskgraph.Task {
|
||||
t := p.task
|
||||
return []taskgraph.Task{
|
||||
{Name: "sdk:configuration", Run: func(context.Context) error {
|
||||
var err error
|
||||
p.version, p.gameVersion, err = t.sdkPackageVersion(p.options)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, p.managed, _, err = t.gameDirectory(p.options.gameDir)
|
||||
return err
|
||||
}},
|
||||
{Name: "sdk:workspace", DependsOn: []string{"sdk:configuration"}, Run: func(context.Context) error {
|
||||
var err error
|
||||
p.workspace, err = t.sdkWorkspace("sdk-pack-")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
p.tool = filepath.Join(p.workspace, "tool")
|
||||
p.sdk = filepath.Join(p.workspace, "sdk")
|
||||
p.config = filepath.Join(p.workspace, "NuGet.Config")
|
||||
return os.MkdirAll(p.options.outputDirectory, 0755)
|
||||
}},
|
||||
{Name: "sdk:tool", DependsOn: []string{"sdk:workspace"}, Run: func(context.Context) error {
|
||||
_, err := t.sdkCommand(t.root, nil, false, "publish", filepath.Join(t.root, "plugins", "GameSdk", "GameSdk.csproj"), "-c", "Release", "--nologo", "-o", p.tool, "-p:Version="+strings.SplitN(p.version, "-", 2)[0], "-p:UseAppHost=false")
|
||||
return err
|
||||
}},
|
||||
{Name: "sdk:prepare", DependsOn: []string{"sdk:tool"}, Run: func(context.Context) error {
|
||||
cache := os.Getenv("BD2_GAME_SDK_CACHE")
|
||||
if cache == "" {
|
||||
cache = filepath.Join(t.root, ".build", "game-sdk")
|
||||
}
|
||||
if _, err := t.sdkCommand(t.root, map[string]string{"BD2_GAME_SDK_CACHE": cache}, false, filepath.Join(p.tool, "GameSdk.dll"), "prepare-embedded", filepath.Join(p.managed, "Assembly-CSharp.dll"), p.sdk, "--game-version", p.gameVersion); err != nil {
|
||||
return err
|
||||
}
|
||||
var err error
|
||||
p.shared, err = sdkReadTrimmed(filepath.Join(p.sdk, "shared-sdk.txt"))
|
||||
p.table = filepath.Join(p.shared, "names.json")
|
||||
return err
|
||||
}},
|
||||
{Name: "sdk:names-package", DependsOn: []string{"sdk:prepare"}, Run: func(context.Context) error {
|
||||
_, err := t.sdkCommand(t.root, nil, false, "pack", filepath.Join(t.root, "plugins", "GameNames", "GameNames.csproj"), "-c", "Release", "--nologo", "-o", p.options.outputDirectory, "-p:Version="+p.version, "-p:GameNamesTable="+p.table, "-p:BaseIntermediateOutputPath="+filepath.Join(p.workspace, "runtime-obj")+string(filepath.Separator), "-p:OutputPath="+filepath.Join(p.workspace, "runtime-bin")+string(filepath.Separator))
|
||||
return err
|
||||
}},
|
||||
{Name: "sdk:package-restore", DependsOn: []string{"sdk:names-package"}, Run: func(context.Context) error {
|
||||
if err := sdkNugetConfig(p.config, p.options.outputDirectory, ""); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := t.sdkCommand(t.root, nil, false, append([]string{"restore", p.project(), "--configfile", p.config}, p.properties()...)...)
|
||||
return err
|
||||
}},
|
||||
{Name: "sdk:pack", DependsOn: []string{"sdk:package-restore"}, Run: func(context.Context) error {
|
||||
args := []string{"pack", p.project(), "-c", "Release", "--no-restore", "--nologo", "-o", p.options.outputDirectory, "-p:BD2ToolPublishDir=" + p.tool}
|
||||
if _, err := t.sdkCommand(t.root, nil, false, append(args, p.properties()...)...); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Printf("Created BD2.GameNames and BD2.GameSdk %s in %s\n", p.version, p.options.outputDirectory)
|
||||
return nil
|
||||
}},
|
||||
}
|
||||
_, managed, _, err := t.gameDirectory(o.gameDir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
workspace, err := t.sdkWorkspace("sdk-pack-")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer t.sdkCleanup(workspace, &result)
|
||||
if err = os.MkdirAll(o.outputDirectory, 0755); err != nil {
|
||||
return err
|
||||
}
|
||||
tool := filepath.Join(workspace, "tool")
|
||||
sdk := filepath.Join(workspace, "sdk")
|
||||
command := func(args ...string) error { _, err := t.sdkCommand(t.root, nil, false, args...); return err }
|
||||
if err = command("publish", filepath.Join(t.root, "plugins", "GameSdk", "GameSdk.csproj"), "-c", "Release", "--nologo", "-o", tool, "-p:Version="+strings.SplitN(version, "-", 2)[0], "-p:UseAppHost=false"); err != nil {
|
||||
return err
|
||||
}
|
||||
toolDLL := filepath.Join(tool, "GameSdk.dll")
|
||||
cache := os.Getenv("BD2_GAME_SDK_CACHE")
|
||||
if cache == "" {
|
||||
cache = filepath.Join(t.root, ".build", "game-sdk")
|
||||
}
|
||||
if _, err = t.sdkCommand(t.root, map[string]string{"BD2_GAME_SDK_CACHE": cache}, false, toolDLL, "prepare-embedded", filepath.Join(managed, "Assembly-CSharp.dll"), sdk, "--game-version", gameVersion); err != nil {
|
||||
return err
|
||||
}
|
||||
shared, err := sdkReadTrimmed(filepath.Join(sdk, "shared-sdk.txt"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
table := filepath.Join(shared, "names.json")
|
||||
runtimeObj := filepath.Join(workspace, "runtime-obj") + string(filepath.Separator)
|
||||
runtimeBin := filepath.Join(workspace, "runtime-bin") + string(filepath.Separator)
|
||||
if err = command("pack", filepath.Join(t.root, "plugins", "GameNames", "GameNames.csproj"), "-c", "Release", "--nologo", "-o", o.outputDirectory, "-p:Version="+version, "-p:GameNamesTable="+table, "-p:BaseIntermediateOutputPath="+runtimeObj, "-p:OutputPath="+runtimeBin); err != nil {
|
||||
return err
|
||||
}
|
||||
project := filepath.Join(t.root, "plugins", "GameSdk", "Package", "BD2.GameSdk.Package.csproj")
|
||||
config := filepath.Join(workspace, "NuGet.Config")
|
||||
if err = sdkNugetConfig(config, o.outputDirectory, ""); err != nil {
|
||||
return err
|
||||
}
|
||||
packageProps := []string{"-p:Version=" + version, "-p:BD2Packaging=true", "-p:BaseIntermediateOutputPath=" + filepath.Join(workspace, "package-obj") + string(filepath.Separator), "-p:OutputPath=" + filepath.Join(workspace, "package-bin") + string(filepath.Separator)}
|
||||
if err = command(append([]string{"restore", project, "--configfile", config}, packageProps...)...); err != nil {
|
||||
return err
|
||||
}
|
||||
packArgs := []string{"pack", project, "-c", "Release", "--no-restore", "--nologo", "-o", o.outputDirectory, "-p:BD2ToolPublishDir=" + tool}
|
||||
if err = command(append(packArgs, packageProps...)...); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Printf("Created BD2.GameNames and BD2.GameSdk %s in %s\n", version, o.outputDirectory)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *sdkPackage) project() string {
|
||||
return filepath.Join(p.task.root, "plugins", "GameSdk", "Package", "BD2.GameSdk.Package.csproj")
|
||||
}
|
||||
func (p *sdkPackage) properties() []string {
|
||||
return []string{"-p:Version=" + p.version, "-p:BD2Packaging=true", "-p:BaseIntermediateOutputPath=" + filepath.Join(p.workspace, "package-obj") + string(filepath.Separator), "-p:OutputPath=" + filepath.Join(p.workspace, "package-bin") + string(filepath.Separator)}
|
||||
}
|
||||
|
||||
func (t task) sdkUpdateNames(args []string) (result error) {
|
||||
@@ -77,40 +106,51 @@ func (t task) sdkUpdateNames(args []string) (result error) {
|
||||
if strings.TrimSpace(o.gameMapping) == "" {
|
||||
return fmt.Errorf("sdk update-names requires --game-mapping")
|
||||
}
|
||||
mapping, err := filepath.Abs(o.gameMapping)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !regular(mapping) {
|
||||
return fmt.Errorf("mapping file missing: %s", mapping)
|
||||
}
|
||||
_, managed, _, err := t.gameDirectory(o.gameDir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
workspace, err := t.sdkWorkspace("sdk-names-")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer t.sdkCleanup(workspace, &result)
|
||||
toolDir := filepath.Join(workspace, "tool")
|
||||
command := func(args ...string) error { _, err := t.sdkCommand(t.root, nil, false, args...); return err }
|
||||
if err = command("publish", filepath.Join(t.root, "plugins", "GameSdk", "GameSdk.csproj"), "-c", "Release", "--nologo", "-o", toolDir, "-p:UseAppHost=false"); err != nil {
|
||||
return err
|
||||
}
|
||||
tool := filepath.Join(toolDir, "GameSdk.dll")
|
||||
assembly := filepath.Join(managed, "Assembly-CSharp.dll")
|
||||
table := filepath.Join(workspace, "names.json")
|
||||
if err = command(tool, "names", assembly, mapping, o.versionConfig, table); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = command(tool, "shell", table, assembly, filepath.Join(workspace, "Assembly-CSharp.Readable.dll")); err != nil {
|
||||
return err
|
||||
}
|
||||
destination := filepath.Join(t.root, "plugins", "GameNames", "Mappings", "names.json.gz")
|
||||
if err = sdkAtomicCopy(table+".gz", destination); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Printf("Updated SDK/runtime shared table: %s. Rebuild SDK and plugins, then pack a new version.\n", destination)
|
||||
return nil
|
||||
var mapping, managed, workspace, tool, table string
|
||||
defer func() {
|
||||
if workspace != "" {
|
||||
t.sdkCleanup(workspace, &result)
|
||||
}
|
||||
}()
|
||||
return t.execute("sdk:update-names",
|
||||
taskgraph.Task{Name: "names:configuration", Run: func(context.Context) error {
|
||||
var err error
|
||||
mapping, err = filepath.Abs(o.gameMapping)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !regular(mapping) {
|
||||
return fmt.Errorf("mapping file missing: %s", mapping)
|
||||
}
|
||||
_, managed, _, err = t.gameDirectory(o.gameDir)
|
||||
return err
|
||||
}},
|
||||
taskgraph.Task{Name: "names:workspace", DependsOn: []string{"names:configuration"}, Run: func(context.Context) error {
|
||||
var err error
|
||||
workspace, err = t.sdkWorkspace("sdk-names-")
|
||||
tool = filepath.Join(workspace, "tool", "GameSdk.dll")
|
||||
table = filepath.Join(workspace, "names.json")
|
||||
return err
|
||||
}},
|
||||
taskgraph.Task{Name: "names:tool", DependsOn: []string{"names:workspace"}, Run: func(context.Context) error {
|
||||
_, err := t.sdkCommand(t.root, nil, false, "publish", filepath.Join(t.root, "plugins", "GameSdk", "GameSdk.csproj"), "-c", "Release", "--nologo", "-o", filepath.Dir(tool), "-p:UseAppHost=false")
|
||||
return err
|
||||
}},
|
||||
taskgraph.Task{Name: "names:generate", DependsOn: []string{"names:tool"}, Run: func(context.Context) error {
|
||||
_, err := t.sdkCommand(t.root, nil, false, tool, "names", filepath.Join(managed, "Assembly-CSharp.dll"), mapping, o.versionConfig, table)
|
||||
return err
|
||||
}},
|
||||
taskgraph.Task{Name: "names:validate", DependsOn: []string{"names:generate"}, Run: func(context.Context) error {
|
||||
_, err := t.sdkCommand(t.root, nil, false, tool, "shell", table, filepath.Join(managed, "Assembly-CSharp.dll"), filepath.Join(workspace, "Assembly-CSharp.Readable.dll"))
|
||||
return err
|
||||
}},
|
||||
taskgraph.Task{Name: "sdk:update-names", DependsOn: []string{"names:validate"}, Run: func(context.Context) error {
|
||||
destination := filepath.Join(t.root, "plugins", "GameNames", "Mappings", "names.json.gz")
|
||||
if err := sdkAtomicCopy(table+".gz", destination); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Printf("Updated SDK/runtime shared table: %s. Rebuild SDK and plugins, then pack a new version.\n", destination)
|
||||
return nil
|
||||
}},
|
||||
)
|
||||
}
|
||||
+110
-84
@@ -1,93 +1,126 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/xml"
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"bd2server/internal/common/taskgraph"
|
||||
)
|
||||
|
||||
type sdkVerification struct {
|
||||
packages *sdkPackage
|
||||
workspace, managed, project, output, tool, table, readyPath, navigationPath string
|
||||
properties []string
|
||||
readyTime, navigationTime time.Time
|
||||
}
|
||||
|
||||
func (t task) sdkVerify(args []string) (result error) {
|
||||
o, err := t.sdkOptions(args, "verify")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
version, gameVersion, err := t.sdkPackageVersion(o)
|
||||
options, err := t.sdkOptions(args, "verify")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
options.outputDirectory = options.packageDirectory
|
||||
v := &sdkVerification{packages: &sdkPackage{task: t, options: options}}
|
||||
defer func() {
|
||||
for _, workspace := range []string{v.workspace, v.packages.workspace} {
|
||||
if workspace != "" {
|
||||
t.sdkCleanup(workspace, &result)
|
||||
}
|
||||
}
|
||||
}()
|
||||
nodes := append(v.packages.tasks(),
|
||||
taskgraph.Task{Name: "verify:workspace", DependsOn: []string{"sdk:pack"}, Run: func(context.Context) error { return v.prepareWorkspace() }},
|
||||
taskgraph.Task{Name: "verify:compile", DependsOn: []string{"verify:workspace"}, Run: func(context.Context) error { return v.build(false) }},
|
||||
taskgraph.Task{Name: "verify:outputs", DependsOn: []string{"verify:compile"}, Run: func(context.Context) error { return v.checkOutputs() }},
|
||||
taskgraph.Task{Name: "verify:navigation", DependsOn: []string{"verify:outputs"}, Run: func(context.Context) error { return v.checkNavigation() }},
|
||||
taskgraph.Task{Name: "verify:incremental", DependsOn: []string{"verify:navigation"}, Run: func(context.Context) error { return v.checkIncremental() }},
|
||||
taskgraph.Task{Name: "sdk:verify", DependsOn: []string{"verify:incremental"}, Run: func(context.Context) error { return v.checkVersionRejection() }},
|
||||
)
|
||||
return t.execute("sdk:verify", nodes...)
|
||||
}
|
||||
|
||||
func (v *sdkVerification) prepareWorkspace() error {
|
||||
t, o := v.packages.task, v.packages.options
|
||||
game, managed, bep, err := t.gameDirectory(o.gameDir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
workspace, err := t.sdkWorkspace("sdk-verify-")
|
||||
v.managed = managed
|
||||
v.workspace, err = t.sdkWorkspace("sdk-verify-")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer t.sdkCleanup(workspace, &result)
|
||||
consumer := filepath.Join(v.workspace, "consumer")
|
||||
for _, name := range []string{"ExamplePlugin.csproj", "Plugin.cs"} {
|
||||
if err = copyFile(filepath.Join(t.root, "plugins", "GameSdk", "samples", "ExamplePlugin", name), filepath.Join(workspace, name)); err != nil {
|
||||
if err := copyFile(filepath.Join(t.root, "plugins", "GameSdk", "samples", "ExamplePlugin", name), filepath.Join(consumer, name)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
project := filepath.Join(workspace, "ExamplePlugin.csproj")
|
||||
raw, err := os.ReadFile(project)
|
||||
v.project = filepath.Join(consumer, "ExamplePlugin.csproj")
|
||||
raw, err := os.ReadFile(v.project)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
packageReference := regexp.MustCompile(`(<PackageReference\s+Include="BD2\.GameSdk"\s+Version=")[^"]+("[^>]*>)`)
|
||||
if !packageReference.Match(raw) {
|
||||
reference := regexp.MustCompile(`(<PackageReference\s+Include="BD2\.GameSdk"\s+Version=")[^"]+("[^>]*>)`)
|
||||
if !reference.Match(raw) {
|
||||
return fmt.Errorf("sample has no BD2.GameSdk PackageReference")
|
||||
}
|
||||
text := packageReference.ReplaceAllString(string(raw), `${1}`+version+`${2}`)
|
||||
text = regexp.MustCompile(`<BD2GameVersion>[^<]*</BD2GameVersion>`).ReplaceAllString(text, "<BD2GameVersion>"+gameVersion+"</BD2GameVersion>")
|
||||
if err = os.WriteFile(project, []byte(text), 0644); err != nil {
|
||||
text := reference.ReplaceAllString(string(raw), `${1}`+v.packages.version+`${2}`)
|
||||
text = regexp.MustCompile(`<BD2GameVersion>[^<]*</BD2GameVersion>`).ReplaceAllString(text, "<BD2GameVersion>"+v.packages.gameVersion+"</BD2GameVersion>")
|
||||
if err := os.WriteFile(v.project, []byte(text), 0644); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, name := range []string{"Directory.Build.props", "Directory.Build.targets"} {
|
||||
if err = os.WriteFile(filepath.Join(workspace, name), []byte("<Project />\n"), 0644); err != nil {
|
||||
if err := os.WriteFile(filepath.Join(v.workspace, name), []byte("<Project />\n"), 0644); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err = sdkNugetConfig(filepath.Join(workspace, "NuGet.Config"), o.packageDirectory, filepath.Join(workspace, "packages")); err != nil {
|
||||
if err := sdkNugetConfig(filepath.Join(v.workspace, "NuGet.Config"), o.packageDirectory, filepath.Join(v.workspace, "packages")); err != nil {
|
||||
return err
|
||||
}
|
||||
sharedCache := filepath.Join(t.root, ".build", "game-sdk")
|
||||
properties := []string{"-p:GameDir=" + game, "-p:BD2ManagedDir=" + managed, "-p:BD2BepInExDir=" + bep, "-p:BD2GameSdkCache=" + sharedCache}
|
||||
build := func(noRestore bool) error {
|
||||
args := []string{"build", project, "-c", "Release", "--nologo"}
|
||||
if noRestore {
|
||||
args = append(args, "--no-restore")
|
||||
}
|
||||
_, err := t.sdkCommand(workspace, nil, false, append(args, properties...)...)
|
||||
return err
|
||||
v.properties = []string{"-p:GameDir=" + game, "-p:BD2ManagedDir=" + managed, "-p:BD2BepInExDir=" + bep, "-p:BD2GameSdkCache=" + filepath.Join(t.root, ".build", "game-sdk")}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (v *sdkVerification) command(args ...string) error {
|
||||
_, err := v.packages.task.sdkCommand(v.workspace, nil, false, args...)
|
||||
return err
|
||||
}
|
||||
|
||||
func (v *sdkVerification) build(noRestore bool) error {
|
||||
args := []string{"build", v.project, "-c", "Release", "--nologo"}
|
||||
if noRestore {
|
||||
args = append(args, "--no-restore")
|
||||
}
|
||||
if err = build(false); err != nil {
|
||||
return err
|
||||
}
|
||||
output := filepath.Join(workspace, "bin", "Release", "netstandard2.1")
|
||||
return v.command(append(args, v.properties...)...)
|
||||
}
|
||||
|
||||
func (v *sdkVerification) checkOutputs() error {
|
||||
v.output = filepath.Join(filepath.Dir(v.project), "bin", "Release", "netstandard2.1")
|
||||
for _, name := range []string{"BD2.GameNames.dll", "ExamplePlugin.dll"} {
|
||||
if !regular(filepath.Join(output, name)) {
|
||||
if !regular(filepath.Join(v.output, name)) {
|
||||
return fmt.Errorf("missing output: %s", name)
|
||||
}
|
||||
}
|
||||
for _, name := range []string{"Assembly-CSharp.Readable.dll", "Assembly-CSharp.Readable.pdb", "Assembly-CSharp.dll", "GameSdk.dll", "Mono.Cecil.dll", "ICSharpCode.Decompiler.dll", "BepInEx.dll", "0Harmony.dll", "UnityEngine.dll", "ExamplePlugin.pdb", "navigation.json", "sources", "ref", "lib"} {
|
||||
if _, err = os.Lstat(filepath.Join(output, name)); err == nil {
|
||||
if _, err := os.Lstat(filepath.Join(v.output, name)); err == nil {
|
||||
return fmt.Errorf("unexpected deployment artifact: %s", name)
|
||||
} else if !os.IsNotExist(err) {
|
||||
return err
|
||||
}
|
||||
}
|
||||
tool := filepath.Join(workspace, "packages", "bd2.gamesdk", strings.ToLower(version), "tools", "net8.0", "GameSdk.dll")
|
||||
sdk := filepath.Join(workspace, "obj", "Release", "netstandard2.1", "bd2-game-sdk")
|
||||
v.tool = filepath.Join(v.workspace, "packages", "bd2.gamesdk", strings.ToLower(v.packages.version), "tools", "net8.0", "GameSdk.dll")
|
||||
sdk := filepath.Join(filepath.Dir(v.project), "obj", "Release", "netstandard2.1", "bd2-game-sdk")
|
||||
shared, err := sdkReadTrimmed(filepath.Join(sdk, "shared-sdk.txt"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
table := filepath.Join(shared, "names.json")
|
||||
v.table = filepath.Join(shared, "names.json")
|
||||
size, err := sdkDirectorySize(sdk)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -95,67 +128,60 @@ func (t task) sdkVerify(args []string) (result error) {
|
||||
if size > 65536 {
|
||||
return fmt.Errorf("SDK obj contains %d bytes instead of shared references", size)
|
||||
}
|
||||
var example struct {
|
||||
Group struct {
|
||||
Version string `xml:"BD2GameVersion"`
|
||||
} `xml:"PropertyGroup"`
|
||||
}
|
||||
if err = xml.Unmarshal([]byte(text), &example); err != nil {
|
||||
return err
|
||||
}
|
||||
if filepath.Base(filepath.Dir(shared)) != example.Group.Version {
|
||||
if filepath.Base(filepath.Dir(shared)) != v.packages.gameVersion {
|
||||
return fmt.Errorf("shared SDK directory is not grouped by plugin-declared game version")
|
||||
}
|
||||
readyPath := filepath.Join(shared, "ready.txt")
|
||||
navigationPath := filepath.Join(sdk, "GameSourceNavigation.props")
|
||||
stamp := func(path string) (time.Time, error) {
|
||||
v.readyPath = filepath.Join(shared, "ready.txt")
|
||||
v.navigationPath = filepath.Join(sdk, "GameSourceNavigation.props")
|
||||
for path, stamp := range map[string]*time.Time{v.readyPath: &v.readyTime, v.navigationPath: &v.navigationTime} {
|
||||
info, err := os.Stat(path)
|
||||
if err != nil {
|
||||
return time.Time{}, err
|
||||
return err
|
||||
}
|
||||
return info.ModTime(), nil
|
||||
*stamp = info.ModTime()
|
||||
}
|
||||
readyTime, err := stamp(readyPath)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (v *sdkVerification) checkNavigation() error {
|
||||
if err := v.command(v.tool, "verify-navigation", filepath.Dir(v.navigationPath)); err != nil {
|
||||
return err
|
||||
}
|
||||
navigationTime, err := stamp(navigationPath)
|
||||
if err != nil {
|
||||
return v.verifyPlugin()
|
||||
}
|
||||
|
||||
func (v *sdkVerification) verifyPlugin() error {
|
||||
return v.command(v.tool, "verify", v.table, filepath.Join(v.output, "ExamplePlugin.dll"), filepath.Join(v.managed, "Assembly-CSharp.dll"))
|
||||
}
|
||||
|
||||
func (v *sdkVerification) checkIncremental() error {
|
||||
if err := v.build(true); err != nil {
|
||||
return err
|
||||
}
|
||||
command := func(args ...string) error { _, err := t.sdkCommand(workspace, nil, false, args...); return err }
|
||||
plugin := filepath.Join(output, "ExamplePlugin.dll")
|
||||
assembly := filepath.Join(managed, "Assembly-CSharp.dll")
|
||||
if err = command(tool, "verify-navigation", sdk); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = command(tool, "verify", table, plugin, assembly); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = build(true); err != nil {
|
||||
return err
|
||||
}
|
||||
after, err := stamp(navigationPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !after.Equal(navigationTime) {
|
||||
return fmt.Errorf("unchanged navigation props were rewritten")
|
||||
}
|
||||
after, err = stamp(readyPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !after.Equal(readyTime) {
|
||||
return fmt.Errorf("repeated build unexpectedly regenerated shared SDK")
|
||||
}
|
||||
if err = command(tool, "verify", table, plugin, assembly); err != nil {
|
||||
return err
|
||||
for _, check := range []struct {
|
||||
path string
|
||||
stamp time.Time
|
||||
error string
|
||||
}{
|
||||
{v.navigationPath, v.navigationTime, "unchanged navigation props were rewritten"},
|
||||
{v.readyPath, v.readyTime, "repeated build unexpectedly regenerated shared SDK"},
|
||||
} {
|
||||
info, err := os.Stat(check.path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !info.ModTime().Equal(check.stamp) {
|
||||
return fmt.Errorf("%s", check.error)
|
||||
}
|
||||
}
|
||||
return v.verifyPlugin()
|
||||
}
|
||||
|
||||
func (v *sdkVerification) checkVersionRejection() error {
|
||||
for _, invalid := range []string{"", "0.0.0"} {
|
||||
args := append([]string{"build", project, "-c", "Release", "--no-restore", "--nologo"}, properties...)
|
||||
args := append([]string{"build", v.project, "-c", "Release", "--no-restore", "--nologo"}, v.properties...)
|
||||
args = append(args, "-p:BD2GameVersion="+invalid)
|
||||
rejected, err := t.sdkCommand(workspace, nil, true, args...)
|
||||
rejected, err := v.packages.task.sdkCommand(v.workspace, nil, true, args...)
|
||||
if err == nil || (invalid == "" && !strings.Contains(rejected, "BD2GameVersion")) || (invalid != "" && !strings.Contains(rejected, "Plugin requires game 0.0.0")) {
|
||||
return fmt.Errorf("missing/mismatched game version was not rejected: %q\n%s", invalid, rejected)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,346 @@
|
||||
package sourcetools
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"slices"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type diffEntry struct {
|
||||
Name string `json:"name"`
|
||||
Kind string `json:"kind"`
|
||||
Diff string `json:"diff"`
|
||||
SourceDiff string `json:"source_diff,omitempty"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
}
|
||||
type fileResult struct {
|
||||
Path string `json:"path"`
|
||||
OldPath *string `json:"old_path"`
|
||||
NewPath *string `json:"new_path"`
|
||||
Status string `json:"status"`
|
||||
Members []diffEntry `json:"members"`
|
||||
Noise []diffEntry `json:"noise"`
|
||||
Review []diffEntry `json:"review,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
func formatTokens(s []string) string {
|
||||
var b strings.Builder
|
||||
previous := ""
|
||||
for _, t := range s {
|
||||
compact := contains([]string{".", "?.", "::", ",", ";", ")", "]"}, t) || contains([]string{".", "?.", "::", "(", "["}, previous) || t == previous && (t == "<" || t == ">")
|
||||
if t == "(" && previous != "" && (identifier(previous) || contains([]string{")", "]", ">"}, previous)) && !contains([]string{"if", "while", "switch", "for", "foreach", "using", "catch", "lock"}, previous) {
|
||||
compact = true
|
||||
}
|
||||
if b.Len() > 0 && !compact {
|
||||
b.WriteByte(' ')
|
||||
}
|
||||
b.WriteString(t)
|
||||
previous = t
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
func render(seq []string) []string {
|
||||
lines := []string{}
|
||||
current := []string{}
|
||||
parens, indent := 0, 0
|
||||
flush := func() {
|
||||
if len(current) > 0 {
|
||||
lines = append(lines, strings.Repeat(" ", max(0, indent))+formatTokens(current))
|
||||
current = nil
|
||||
}
|
||||
}
|
||||
for _, t := range seq {
|
||||
if t == "}" {
|
||||
flush()
|
||||
indent--
|
||||
}
|
||||
current = append(current, t)
|
||||
switch t {
|
||||
case "(":
|
||||
parens++
|
||||
case ")":
|
||||
parens--
|
||||
}
|
||||
if t == "{" {
|
||||
flush()
|
||||
indent++
|
||||
} else if t == "}" || t == ";" && parens == 0 {
|
||||
flush()
|
||||
}
|
||||
}
|
||||
flush()
|
||||
return lines
|
||||
}
|
||||
|
||||
type editLine struct {
|
||||
kind byte
|
||||
line string
|
||||
}
|
||||
|
||||
func lineEdits(a, b []string) []editLine {
|
||||
prefix := 0
|
||||
for prefix < len(a) && prefix < len(b) && a[prefix] == b[prefix] {
|
||||
prefix++
|
||||
}
|
||||
suffix := 0
|
||||
for suffix < len(a)-prefix && suffix < len(b)-prefix && a[len(a)-1-suffix] == b[len(b)-1-suffix] {
|
||||
suffix++
|
||||
}
|
||||
result := []editLine{}
|
||||
for _, l := range a[:prefix] {
|
||||
result = append(result, editLine{' ', l})
|
||||
}
|
||||
left, right := a[prefix:len(a)-suffix], b[prefix:len(b)-suffix]
|
||||
if len(left)*len(right) <= 4_000_000 {
|
||||
width := len(right) + 1
|
||||
dp := make([]int, (len(left)+1)*width)
|
||||
for i := range slices.Backward(left) {
|
||||
for j := range slices.Backward(right) {
|
||||
if left[i] == right[j] {
|
||||
dp[i*width+j] = 1 + dp[(i+1)*width+j+1]
|
||||
} else {
|
||||
dp[i*width+j] = max(dp[(i+1)*width+j], dp[i*width+j+1])
|
||||
}
|
||||
}
|
||||
}
|
||||
i, j := 0, 0
|
||||
for i < len(left) || j < len(right) {
|
||||
if i < len(left) && j < len(right) && left[i] == right[j] {
|
||||
result = append(result, editLine{' ', left[i]})
|
||||
i++
|
||||
j++
|
||||
} else if i < len(left) && (j == len(right) || dp[(i+1)*width+j] >= dp[i*width+j+1]) {
|
||||
result = append(result, editLine{'-', left[i]})
|
||||
i++
|
||||
} else {
|
||||
result = append(result, editLine{'+', right[j]})
|
||||
j++
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for _, l := range left {
|
||||
result = append(result, editLine{'-', l})
|
||||
}
|
||||
for _, l := range right {
|
||||
result = append(result, editLine{'+', l})
|
||||
}
|
||||
}
|
||||
for _, l := range a[len(a)-suffix:] {
|
||||
result = append(result, editLine{' ', l})
|
||||
}
|
||||
return result
|
||||
}
|
||||
func unified(a, b []string, old, new string, context int) string {
|
||||
if slices.Equal(a, b) {
|
||||
return "\n"
|
||||
}
|
||||
edits := lineEdits(a, b)
|
||||
type hunk struct{ start, end int }
|
||||
hunks := []hunk{}
|
||||
for i, e := range edits {
|
||||
if e.kind == ' ' {
|
||||
continue
|
||||
}
|
||||
start, end := max(0, i-context), min(len(edits), i+context+1)
|
||||
if len(hunks) > 0 && start <= hunks[len(hunks)-1].end {
|
||||
hunks[len(hunks)-1].end = end
|
||||
} else {
|
||||
hunks = append(hunks, hunk{start, end})
|
||||
}
|
||||
}
|
||||
var out strings.Builder
|
||||
fmt.Fprintf(&out, "--- %s\n+++ %s\n", old, new)
|
||||
oldLine, newLine := 1, 1
|
||||
position := 0
|
||||
rangeText := func(start, count int) string {
|
||||
if count == 0 {
|
||||
start--
|
||||
}
|
||||
if count == 1 {
|
||||
return fmt.Sprint(start)
|
||||
}
|
||||
return fmt.Sprintf("%d,%d", start, count)
|
||||
}
|
||||
for _, h := range hunks {
|
||||
for position < h.start {
|
||||
if edits[position].kind != '+' {
|
||||
oldLine++
|
||||
}
|
||||
if edits[position].kind != '-' {
|
||||
newLine++
|
||||
}
|
||||
position++
|
||||
}
|
||||
oldCount, newCount := 0, 0
|
||||
for _, e := range edits[h.start:h.end] {
|
||||
if e.kind != '+' {
|
||||
oldCount++
|
||||
}
|
||||
if e.kind != '-' {
|
||||
newCount++
|
||||
}
|
||||
}
|
||||
fmt.Fprintf(&out, "@@ -%s +%s @@\n", rangeText(oldLine, oldCount), rangeText(newLine, newCount))
|
||||
for position < h.end {
|
||||
e := edits[position]
|
||||
out.WriteByte(e.kind)
|
||||
out.WriteString(e.line)
|
||||
out.WriteByte('\n')
|
||||
if e.kind != '+' {
|
||||
oldLine++
|
||||
}
|
||||
if e.kind != '-' {
|
||||
newLine++
|
||||
}
|
||||
position++
|
||||
}
|
||||
}
|
||||
return out.String()
|
||||
}
|
||||
|
||||
type indexedMembers struct {
|
||||
order []string
|
||||
members map[string]*member
|
||||
}
|
||||
|
||||
func indexMembers(s []*member) indexedMembers {
|
||||
r := indexedMembers{[]string{}, map[string]*member{}}
|
||||
counts := map[string]int{}
|
||||
for _, m := range s {
|
||||
base := m.key
|
||||
if i := strings.LastIndex(base, " #"); i >= 0 {
|
||||
base = base[:i]
|
||||
}
|
||||
base = generated(base)
|
||||
counts[base]++
|
||||
key := fmt.Sprintf("%s #%d", base, counts[base])
|
||||
r.order = append(r.order, key)
|
||||
r.members[key] = m
|
||||
}
|
||||
return r
|
||||
}
|
||||
func memberTokens(m *member) []string {
|
||||
if m == nil {
|
||||
return nil
|
||||
}
|
||||
return m.tokens
|
||||
}
|
||||
func compareText(old, new string, context int, strict bool, oldSymbols, newSymbols map[string]string) fileResult {
|
||||
result := fileResult{Status: "unchanged", Members: []diffEntry{}, Noise: []diffEntry{}}
|
||||
a, b := tokenize(old, oldSymbols), tokenize(new, newSymbols)
|
||||
if slices.Equal(a, b) {
|
||||
return result
|
||||
}
|
||||
da, db := indexMembers(splitMembers(a)), indexMembers(splitMembers(b))
|
||||
keys := []string{}
|
||||
all := map[string]bool{}
|
||||
for k := range da.members {
|
||||
all[k] = true
|
||||
}
|
||||
for k := range db.members {
|
||||
all[k] = true
|
||||
}
|
||||
for k := range all {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
asyncNew, builderOld := false, false
|
||||
for _, m := range db.members {
|
||||
asyncNew = asyncNew || contains(m.tokens, "async")
|
||||
}
|
||||
for _, m := range da.members {
|
||||
builderOld = builderOld || contains(m.tokens, "t__builder")
|
||||
}
|
||||
for _, key := range keys {
|
||||
left, right := da.members[key], db.members[key]
|
||||
if left != nil && right != nil && slices.Equal(left.tokens, right.tokens) {
|
||||
continue
|
||||
}
|
||||
ca, cb := normalizePair(left, right)
|
||||
rawA, rawB := render(memberTokens(left)), render(memberTokens(right))
|
||||
entry := diffEntry{Name: key, Kind: "modified"}
|
||||
if left == nil {
|
||||
entry.Kind = "added"
|
||||
} else if right == nil {
|
||||
entry.Kind = "removed"
|
||||
}
|
||||
simpleUsing := true
|
||||
ambiguous := false
|
||||
for _, m := range []*member{left, right} {
|
||||
if m != nil {
|
||||
simpleUsing = simpleUsing && m.kind == "using" && !contains(m.tokens, "=") && !contains(m.tokens, "static")
|
||||
ambiguous = ambiguous || m.ambiguous
|
||||
}
|
||||
}
|
||||
if !strict && !ambiguous && (left != nil && right != nil && slices.Equal(ca, cb) || simpleUsing) {
|
||||
entry.Reason = "局部名 / 冗余括号 / 推断泛型 / 生成编号 / 标签 / 属性顺序(启发式,需审阅)"
|
||||
entry.Diff = unified(rawA, rawB, "old", "new", context)
|
||||
if simpleUsing {
|
||||
entry.Reason = "using 声明变化,未做名称绑定证明,保留复核"
|
||||
result.Review = append(result.Review, entry)
|
||||
} else {
|
||||
result.Noise = append(result.Noise, entry)
|
||||
}
|
||||
} else {
|
||||
if strict {
|
||||
entry.Diff = unified(rawA, rawB, "old", "new", context)
|
||||
} else {
|
||||
entry.Diff = unified(render(ca), render(cb), "old", "new", context)
|
||||
}
|
||||
entry.SourceDiff = unified(rawA, rawB, "old", "new", context)
|
||||
structural := false
|
||||
if asyncNew && builderOld {
|
||||
structural = strings.Contains(key, "_d__") || strings.Contains(key, "_d /")
|
||||
for _, m := range []*member{left, right} {
|
||||
if m != nil {
|
||||
structural = structural || contains(m.tokens, "t__builder") || contains(m.tokens, "async")
|
||||
}
|
||||
}
|
||||
}
|
||||
if structural || ambiguous {
|
||||
entry.Reason = "async / 状态机导出结构不同,需复核正文"
|
||||
if ambiguous {
|
||||
entry.Reason = "导出代码含同一作用域重名局部,绑定无法可靠恢复"
|
||||
}
|
||||
result.Review = append(result.Review, entry)
|
||||
} else {
|
||||
result.Members = append(result.Members, entry)
|
||||
}
|
||||
}
|
||||
}
|
||||
order := func(from, to indexedMembers, methods bool) []string {
|
||||
r := []string{}
|
||||
for _, key := range from.order {
|
||||
m := from.members[key]
|
||||
if to.members[key] == nil {
|
||||
continue
|
||||
}
|
||||
include := m.kind == "method" || m.kind == "using"
|
||||
if !methods {
|
||||
include = !include && m.kind != "type"
|
||||
}
|
||||
if include {
|
||||
r = append(r, key)
|
||||
}
|
||||
}
|
||||
return r
|
||||
}
|
||||
orderA, orderB := order(da, db, false), order(db, da, false)
|
||||
if !slices.Equal(orderA, orderB) {
|
||||
result.Members = append(result.Members, diffEntry{Name: "声明 / 初始化顺序", Kind: "order", Diff: unified(orderA, orderB, "old order", "new order", context)})
|
||||
}
|
||||
methodA, methodB := order(da, db, true), order(db, da, true)
|
||||
if !slices.Equal(methodA, methodB) {
|
||||
result.Noise = append(result.Noise, diffEntry{Name: "方法 / using 排列顺序", Kind: "order", Reason: "同名成员分别比较,声明顺序单独记录", Diff: unified(methodA, methodB, "old order", "new order", context)})
|
||||
}
|
||||
if len(result.Members) > 0 {
|
||||
result.Status = "modified"
|
||||
} else if len(result.Review) > 0 {
|
||||
result.Status = "review"
|
||||
} else if len(result.Noise) > 0 {
|
||||
result.Status = "noise"
|
||||
}
|
||||
return result
|
||||
}
|
||||
@@ -0,0 +1,412 @@
|
||||
package sourcetools
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
const mirrorTool = "bd2.deobfuscate_client_source"
|
||||
const mirrorManifest = ".bd2-deobfuscate-manifest.json"
|
||||
|
||||
var keywords = wordSet("abstract as base bool break byte case catch char checked class const continue decimal default delegate do double else enum event explicit extern false finally fixed float for foreach goto if implicit in int interface internal is lock long namespace new null object operator out override params private protected public readonly ref return sbyte sealed short sizeof stackalloc static string struct switch this throw true try typeof uint ulong unchecked unsafe ushort using virtual void volatile while")
|
||||
|
||||
func wordSet(s string) map[string]bool {
|
||||
m := map[string]bool{}
|
||||
for w := range strings.FieldsSeq(s) {
|
||||
m[w] = true
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
type mapEntry struct {
|
||||
Line int `json:"line"`
|
||||
Source string `json:"source"`
|
||||
Meaning string `json:"meaning"`
|
||||
Replacement string `json:"replacement,omitempty"`
|
||||
Sanitized bool `json:"sanitized"`
|
||||
Collision bool `json:"name_collision"`
|
||||
}
|
||||
|
||||
func parseMapping(path string) ([]mapEntry, []string, error) {
|
||||
text, _, e := readSource(path)
|
||||
if e != nil {
|
||||
return nil, nil, e
|
||||
}
|
||||
entries := []mapEntry{}
|
||||
warnings := []string{}
|
||||
for i, line := range strings.Split(strings.ReplaceAll(text, "\r\n", "\n"), "\n") {
|
||||
line = strings.TrimSpace(line)
|
||||
if line == "" || strings.HasPrefix(line, "//") || strings.EqualFold(line, "#ReverseOrder") {
|
||||
continue
|
||||
}
|
||||
a, b, ok := strings.Cut(line, "⇨")
|
||||
if !ok {
|
||||
if !strings.HasPrefix(line, "#") {
|
||||
warnings = append(warnings, fmt.Sprintf("line %d: ignored (no '⇨')", i+1))
|
||||
}
|
||||
continue
|
||||
}
|
||||
a, b = strings.TrimSpace(a), strings.TrimSpace(b)
|
||||
if a == "" || b == "" {
|
||||
warnings = append(warnings, fmt.Sprintf("line %d: ignored (empty mapping side)", i+1))
|
||||
continue
|
||||
}
|
||||
if !identifier(a) || strings.HasPrefix(a, "@") {
|
||||
warnings = append(warnings, fmt.Sprintf("line %d: ignored (non-identifier source %q)", i+1, a))
|
||||
continue
|
||||
}
|
||||
entries = append(entries, mapEntry{Line: i + 1, Source: a, Meaning: b})
|
||||
}
|
||||
return entries, warnings, nil
|
||||
}
|
||||
|
||||
var meaningParts = regexp.MustCompile(`(?:\.|::|/|\\)+`)
|
||||
var asciiSuffix = regexp.MustCompile(`[^A-Za-z0-9_]`)
|
||||
|
||||
func readableIdentifier(meaning string) string {
|
||||
parts := meaningParts.Split(strings.TrimSpace(meaning), -1)
|
||||
raw := ""
|
||||
for _, p := range parts {
|
||||
if p != "" {
|
||||
raw = p
|
||||
}
|
||||
}
|
||||
var b strings.Builder
|
||||
for i, c := range raw {
|
||||
if c == '_' || c < 128 && unicode.IsLetter(c) || i > 0 && c >= '0' && c <= '9' {
|
||||
b.WriteRune(c)
|
||||
} else if i == 0 && c >= '0' && c <= '9' {
|
||||
b.WriteByte('_')
|
||||
b.WriteRune(c)
|
||||
} else {
|
||||
b.WriteByte('_')
|
||||
}
|
||||
}
|
||||
name := strings.Trim(b.String(), "_")
|
||||
if name == "" {
|
||||
name = "unnamed"
|
||||
}
|
||||
if name[0] >= '0' && name[0] <= '9' || keywords[name] {
|
||||
name = "_" + name
|
||||
}
|
||||
return name
|
||||
}
|
||||
func buildReplacements(entries []mapEntry) (map[string]string, []mapEntry, []string) {
|
||||
groups := map[string][]mapEntry{}
|
||||
order := []string{}
|
||||
for _, e := range entries {
|
||||
if _, ok := groups[e.Source]; !ok {
|
||||
order = append(order, e.Source)
|
||||
}
|
||||
groups[e.Source] = append(groups[e.Source], e)
|
||||
}
|
||||
replacements := map[string]string{}
|
||||
report := []mapEntry{}
|
||||
warnings := []string{}
|
||||
used := map[string]bool{}
|
||||
for _, source := range order {
|
||||
group := groups[source]
|
||||
meanings := map[string]bool{}
|
||||
for _, e := range group {
|
||||
meanings[e.Meaning] = true
|
||||
}
|
||||
if len(meanings) != 1 {
|
||||
warnings = append(warnings, fmt.Sprintf("source %q: ignored ambiguous scoped mappings (%d meanings)", source, len(meanings)))
|
||||
continue
|
||||
}
|
||||
e := group[0]
|
||||
base := readableIdentifier(e.Meaning)
|
||||
replacement := base
|
||||
e.Collision = used[replacement]
|
||||
if e.Collision {
|
||||
suffix := asciiSuffix.ReplaceAllString(source, "_")
|
||||
if strings.Trim(suffix, "_") == "" {
|
||||
parts := []string{}
|
||||
for _, c := range source {
|
||||
parts = append(parts, fmt.Sprintf("u%04X", c))
|
||||
}
|
||||
suffix = strings.Join(parts, "_")
|
||||
}
|
||||
replacement = base + "__from_" + suffix
|
||||
for n := 2; used[replacement]; n++ {
|
||||
replacement = fmt.Sprintf("%s__from_%s_%d", base, suffix, n)
|
||||
}
|
||||
}
|
||||
used[replacement] = true
|
||||
replacements[source] = replacement
|
||||
e.Replacement = replacement
|
||||
e.Sanitized = replacement != e.Meaning
|
||||
report = append(report, e)
|
||||
}
|
||||
return replacements, report, warnings
|
||||
}
|
||||
func camel(s string) string {
|
||||
r := []rune(s)
|
||||
i := 0
|
||||
for i < len(r) && unicode.IsUpper(r[i]) {
|
||||
r[i] = unicode.ToLower(r[i])
|
||||
i++
|
||||
}
|
||||
return string(r)
|
||||
}
|
||||
|
||||
type replacementIndex struct {
|
||||
exact map[string]string
|
||||
derived map[string][]string
|
||||
}
|
||||
|
||||
func newReplacementIndex(m map[string]string) *replacementIndex {
|
||||
idx := &replacementIndex{m, map[string][]string{}}
|
||||
for s := range m {
|
||||
if c := camel(s); c != s {
|
||||
idx.derived[c] = append(idx.derived[c], s)
|
||||
}
|
||||
}
|
||||
return idx
|
||||
}
|
||||
func (idx *replacementIndex) base(t string) (string, bool) {
|
||||
if r, ok := idx.exact[t]; ok {
|
||||
return r, false
|
||||
}
|
||||
if s := idx.derived[t]; len(s) == 1 {
|
||||
return camel(idx.exact[s[0]]), true
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
func (idx *replacementIndex) resolve(t string) (string, bool) {
|
||||
if r, d := idx.base(t); r != "" {
|
||||
return r, d
|
||||
}
|
||||
if len(t) == utf8.RuneCountInString(t) {
|
||||
return t, false
|
||||
}
|
||||
r := []rune(t)
|
||||
for cut := len(r) - 1; cut > 0; cut-- {
|
||||
digits := true
|
||||
for _, c := range r[cut:] {
|
||||
if !unicode.IsDigit(c) {
|
||||
digits = false
|
||||
break
|
||||
}
|
||||
}
|
||||
if digits {
|
||||
if base, _ := idx.base(string(r[:cut])); base != "" {
|
||||
return base + string(r[cut:]), true
|
||||
}
|
||||
}
|
||||
}
|
||||
return t, false
|
||||
}
|
||||
func replaceIdentifiers(text string, index *replacementIndex) (string, int, int) {
|
||||
var b strings.Builder
|
||||
changed, derived := 0, 0
|
||||
for _, t := range lex(text) {
|
||||
v := t.text
|
||||
if t.kind == "identifier" {
|
||||
bare := strings.TrimPrefix(v, "@")
|
||||
r, d := index.resolve(bare)
|
||||
if r != bare {
|
||||
if strings.HasPrefix(v, "@") {
|
||||
r = "@" + r
|
||||
}
|
||||
v = r
|
||||
changed++
|
||||
if d {
|
||||
derived++
|
||||
}
|
||||
}
|
||||
}
|
||||
b.WriteString(v)
|
||||
}
|
||||
return b.String(), changed, derived
|
||||
}
|
||||
func managedMirror(output string) bool {
|
||||
b, e := os.ReadFile(filepath.Join(output, mirrorManifest))
|
||||
if e != nil {
|
||||
return false
|
||||
}
|
||||
var m struct {
|
||||
Tool string `json:"tool"`
|
||||
}
|
||||
return json.Unmarshal(b, &m) == nil && m.Tool == mirrorTool
|
||||
}
|
||||
|
||||
// RunDeobfuscate parses the source mirror command's standalone arguments.
|
||||
func RunDeobfuscate(args []string, out io.Writer) error {
|
||||
f := flag.NewFlagSet("deobfuscate", flag.ContinueOnError)
|
||||
f.SetOutput(out)
|
||||
source := f.String("source", "", "client Assembly-CSharp directory")
|
||||
mapping := f.String("mapping", "", "ObfuscationTranslation file")
|
||||
output := f.String("output", "", "mirror directory outside --source")
|
||||
if e := f.Parse(args); e != nil {
|
||||
if errors.Is(e, flag.ErrHelp) {
|
||||
return nil
|
||||
}
|
||||
return e
|
||||
}
|
||||
if f.NArg() != 0 {
|
||||
return errors.New("deobfuscate does not accept positional arguments")
|
||||
}
|
||||
if *source == "" || *mapping == "" || *output == "" {
|
||||
return errors.New("--source, --mapping and --output are required")
|
||||
}
|
||||
m, e := deobfuscate(*source, *mapping, *output)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
stats := m["statistics"].(map[string]int)
|
||||
_, e = fmt.Fprintf(out, "wrote %s (%d files, %d replacements)\n", m["output"], stats["files"], stats["identifier_replacements"])
|
||||
return e
|
||||
}
|
||||
func deobfuscate(source, mapping, output string) (_ map[string]any, retErr error) {
|
||||
source, output, e := safeTrees(source, output)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
mapping, e = canonicalPath(mapping)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
if within(mapping, output) {
|
||||
return nil, errors.New("mapping must be outside output")
|
||||
}
|
||||
entries, warnings, e := parseMapping(mapping)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
replacements, report, notes := buildReplacements(entries)
|
||||
warnings = append(warnings, notes...)
|
||||
index := newReplacementIndex(replacements)
|
||||
for k, s := range index.derived {
|
||||
if len(s) > 1 {
|
||||
warnings = append(warnings, fmt.Sprintf("derived name %q: ignored ambiguous camel-case sources (%d candidates)", k, len(s)))
|
||||
}
|
||||
}
|
||||
if _, e = os.Lstat(output); e == nil && !managedMirror(output) {
|
||||
return nil, fmt.Errorf("refusing to overwrite non-managed output directory: %s", output)
|
||||
} else if e != nil && !os.IsNotExist(e) {
|
||||
return nil, e
|
||||
}
|
||||
if e = os.MkdirAll(filepath.Dir(output), 0755); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
stage, e := os.MkdirTemp(filepath.Dir(output), ".bd2-deobfuscate-stage-")
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
defer func() { retErr = errors.Join(retErr, os.RemoveAll(stage)) }()
|
||||
paths := []string{}
|
||||
e = filepath.WalkDir(source, func(p string, d os.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if d.Type()&os.ModeSymlink != 0 {
|
||||
return fmt.Errorf("source contains symbolic link: %s", p)
|
||||
}
|
||||
if !d.IsDir() {
|
||||
paths = append(paths, p)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
sort.Strings(paths)
|
||||
files := []map[string]any{}
|
||||
occupied := map[string]bool{}
|
||||
stats := map[string]int{"mapping_entries": len(report), "files": len(paths), "csharp_files": 0, "identifier_replacements": 0, "derived_identifier_replacements": 0}
|
||||
for _, p := range paths {
|
||||
rel, _ := filepath.Rel(source, p)
|
||||
dest := rel
|
||||
ext := filepath.Ext(rel)
|
||||
if strings.EqualFold(ext, ".cs") {
|
||||
stem := strings.TrimSuffix(filepath.Base(rel), ext)
|
||||
if r, ok := replacements[stem]; ok {
|
||||
stem = r
|
||||
}
|
||||
dest = filepath.Join(filepath.Dir(rel), stem+ext)
|
||||
for n := 2; occupied[strings.ToLower(dest)]; n++ {
|
||||
dest = filepath.Join(filepath.Dir(rel), fmt.Sprintf("%s__file_%d%s", stem, n, ext))
|
||||
}
|
||||
}
|
||||
occupied[strings.ToLower(dest)] = true
|
||||
target := filepath.Join(stage, dest)
|
||||
if e = os.MkdirAll(filepath.Dir(target), 0755); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
record := map[string]any{"source": filepath.ToSlash(rel), "output": filepath.ToSlash(dest), "action": "copied"}
|
||||
if strings.EqualFold(ext, ".cs") {
|
||||
stats["csharp_files"]++
|
||||
text, enc, err := readSource(p)
|
||||
if err != nil {
|
||||
if _, err = os.Stat(p); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
e = copyFile(p, target)
|
||||
record["reason"] = "unsupported text encoding"
|
||||
warnings = append(warnings, rel+": copied without replacement (unsupported encoding)")
|
||||
} else {
|
||||
translated, changed, derived := replaceIdentifiers(text, index)
|
||||
e = writeSource(target, translated, enc)
|
||||
record["action"] = "translated"
|
||||
record["identifier_replacements"] = changed
|
||||
record["derived_identifier_replacements"] = derived
|
||||
stats["identifier_replacements"] += changed
|
||||
stats["derived_identifier_replacements"] += derived
|
||||
}
|
||||
} else {
|
||||
e = copyFile(p, target)
|
||||
}
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
files = append(files, record)
|
||||
}
|
||||
manifest := map[string]any{"tool": mirrorTool, "source": source, "output": output, "mapping": mapping, "mapping_entries": report, "files": files, "warnings": warnings, "statistics": stats, "limitations": []string{"Only C# identifier tokens are changed; comments and literal contents are preserved.", "Qualified mapping values become their terminal identifier component.", "Decompiler-derived suffix and camel-case locals are resolved only when unambiguous.", "This is a searchable mirror, not a promise that the transformed source compiles."}}
|
||||
b, e := json.MarshalIndent(manifest, "", " ")
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
if e = os.WriteFile(filepath.Join(stage, mirrorManifest), append(b, '\n'), 0644); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
if _, e = os.Stat(output); e == nil {
|
||||
if !managedMirror(output) {
|
||||
return nil, errors.New("output ownership changed during generation")
|
||||
}
|
||||
backup, err := os.MkdirTemp(filepath.Dir(output), ".bd2-deobfuscate-backup-")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = os.Remove(backup); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = os.Rename(output, backup); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = os.Rename(stage, output); err != nil {
|
||||
restore := os.Rename(backup, output)
|
||||
return nil, errors.Join(err, restore)
|
||||
}
|
||||
if err = os.RemoveAll(backup); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else if os.IsNotExist(e) {
|
||||
if e = os.Rename(stage, output); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
} else {
|
||||
return nil, e
|
||||
}
|
||||
return manifest, nil
|
||||
}
|
||||
@@ -0,0 +1,286 @@
|
||||
package sourcetools
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type repeatedFlag []string
|
||||
|
||||
func (s *repeatedFlag) String() string { return strings.Join(*s, ",") }
|
||||
func (s *repeatedFlag) Set(v string) error { *s = append(*s, v); return nil }
|
||||
|
||||
type diffReport struct {
|
||||
Tool string `json:"tool"`
|
||||
Output string `json:"output"`
|
||||
Schema int `json:"schema"`
|
||||
OldRoot string `json:"old_root"`
|
||||
NewRoot string `json:"new_root"`
|
||||
Workers int `json:"workers"`
|
||||
Strict bool `json:"strict"`
|
||||
ElapsedSeconds float64 `json:"elapsed_seconds"`
|
||||
Counts map[string]int `json:"counts"`
|
||||
Warnings []string `json:"warnings"`
|
||||
RenamedPaths int `json:"renamed_paths"`
|
||||
Files []fileResult `json:"files"`
|
||||
}
|
||||
|
||||
const diffTool = "bd2.cleandiff_client_source"
|
||||
|
||||
// RunDiff parses source comparison arguments and writes a six-file report bundle.
|
||||
func RunDiff(args []string, out io.Writer) error {
|
||||
f := flag.NewFlagSet("diff", flag.ContinueOnError)
|
||||
f.SetOutput(out)
|
||||
aFlag := f.String("a", "", "old C# source tree")
|
||||
bFlag := f.String("b", "", "new C# source tree")
|
||||
outputFlag := f.String("out", "cleandiff-report.txt", "summary path; also writes .html/.json/.diff/.noise.diff/.review.diff")
|
||||
workersFlag := f.Int("workers", 0, "workers, 0=automatic; 1=serial")
|
||||
contextFlag := f.Int("context", 3, "diff context lines")
|
||||
strictFlag := f.Bool("strict", false, "include local names, parentheses, inferred generics and generated numbering in main differences")
|
||||
var includes, excludes repeatedFlag
|
||||
f.Var(&includes, "include", "logical relative path glob, repeatable (e.g. Proto/Net/*)")
|
||||
f.Var(&excludes, "exclude", "exclude path glob, repeatable")
|
||||
if e := f.Parse(args); e != nil {
|
||||
if errors.Is(e, flag.ErrHelp) {
|
||||
return nil
|
||||
}
|
||||
return e
|
||||
}
|
||||
if f.NArg() != 0 {
|
||||
return errors.New("diff does not accept positional arguments")
|
||||
}
|
||||
if *aFlag == "" || *bFlag == "" {
|
||||
return errors.New("--a and --b are required")
|
||||
}
|
||||
if *workersFlag < 0 || *contextFlag < 0 {
|
||||
return errors.New("--workers and --context must not be negative")
|
||||
}
|
||||
if !strings.EqualFold(filepath.Ext(*outputFlag), ".txt") {
|
||||
return errors.New("--out must end in .txt to avoid overlapping report files")
|
||||
}
|
||||
a, e := sourceRoot(*aFlag)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
b, e := sourceRoot(*bFlag)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
output, e := canonicalPath(*outputFlag)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if within(output, a) || within(output, b) {
|
||||
return errors.New("reports must be outside both input source directories")
|
||||
}
|
||||
for _, path := range reportPaths(output) {
|
||||
resolved, e := canonicalPath(path)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if resolved != path {
|
||||
return fmt.Errorf("report path resolves through a symbolic link: %s", path)
|
||||
}
|
||||
if within(resolved, a) || within(resolved, b) {
|
||||
return errors.New("reports must be outside both input source directories")
|
||||
}
|
||||
}
|
||||
if e = checkReportOutput(output); e != nil {
|
||||
return e
|
||||
}
|
||||
start := time.Now()
|
||||
ia, e := inventory(a, includes, excludes)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
ib, e := inventory(b, includes, excludes)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
tasks, symbolsA, symbolsB, warnings := pairTrees(a, b, ia, ib)
|
||||
workers := *workersFlag
|
||||
if workers == 0 {
|
||||
workers = min(8, runtime.NumCPU())
|
||||
}
|
||||
if _, e = fmt.Fprintf(out, "旧版 %d / 新版 %d C# 文件;%d workers\n", len(ia), len(ib), workers); e != nil {
|
||||
return e
|
||||
}
|
||||
results := make([]fileResult, len(tasks))
|
||||
jobs := make(chan int)
|
||||
var wg sync.WaitGroup
|
||||
for w := 0; w < min(workers, max(1, len(tasks))); w++ {
|
||||
wg.Go(func() {
|
||||
for i := range jobs {
|
||||
results[i] = compareFile(a, b, tasks[i], *contextFlag, *strictFlag, symbolsA, symbolsB)
|
||||
}
|
||||
})
|
||||
}
|
||||
for i := range tasks {
|
||||
jobs <- i
|
||||
}
|
||||
close(jobs)
|
||||
wg.Wait()
|
||||
counts := map[string]int{}
|
||||
for _, status := range []string{"modified", "added", "removed", "review", "noise", "unchanged", "error"} {
|
||||
counts[status] = 0
|
||||
}
|
||||
renamed := 0
|
||||
for _, r := range results {
|
||||
counts[r.Status]++
|
||||
if r.OldPath != nil && r.NewPath != nil && *r.OldPath != *r.NewPath {
|
||||
renamed++
|
||||
}
|
||||
}
|
||||
report := diffReport{Tool: diffTool, Output: output, Schema: 1, OldRoot: a, NewRoot: b, Workers: workers, Strict: *strictFlag, ElapsedSeconds: time.Since(start).Seconds(), Counts: counts, Warnings: warnings, RenamedPaths: renamed, Files: results}
|
||||
if e = writeReports(output, report); e != nil {
|
||||
return e
|
||||
}
|
||||
countJSON, _ := json.Marshal(counts)
|
||||
if _, e = fmt.Fprintf(out, "%s\n匹配混淆后缀路径 %d;比较 %.2fs;总计 %.2fs\n摘要: %s\n可视化: %s\n", countJSON, renamed, report.ElapsedSeconds, time.Since(start).Seconds(), output, strings.TrimSuffix(output, filepath.Ext(output))+".html"); e != nil {
|
||||
return e
|
||||
}
|
||||
if counts["error"] > 0 {
|
||||
return fmt.Errorf("source comparison reported %d file errors; see %s", counts["error"], output)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func reportPaths(output string) []string {
|
||||
stem := strings.TrimSuffix(output, filepath.Ext(output))
|
||||
return []string{output, stem + ".json", stem + ".html", stem + ".diff", stem + ".noise.diff", stem + ".review.diff"}
|
||||
}
|
||||
func checkReportOutput(output string) error {
|
||||
paths := reportPaths(output)
|
||||
managed := false
|
||||
b, e := os.ReadFile(paths[1])
|
||||
if e == nil {
|
||||
var owner struct {
|
||||
Tool string `json:"tool"`
|
||||
Output string `json:"output"`
|
||||
}
|
||||
managed = json.Unmarshal(b, &owner) == nil && owner.Tool == diffTool && owner.Output == output
|
||||
} else if !os.IsNotExist(e) {
|
||||
return e
|
||||
}
|
||||
for _, p := range paths {
|
||||
stat, e := os.Lstat(p)
|
||||
if e == nil {
|
||||
if !managed || !stat.Mode().IsRegular() {
|
||||
return fmt.Errorf("refusing to overwrite non-managed report: %s", p)
|
||||
}
|
||||
} else if !os.IsNotExist(e) {
|
||||
return e
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func writeReports(output string, report diffReport) (retErr error) {
|
||||
if e := checkReportOutput(output); e != nil {
|
||||
return e
|
||||
}
|
||||
if e := os.MkdirAll(filepath.Dir(output), 0755); e != nil {
|
||||
return e
|
||||
}
|
||||
stage, e := os.MkdirTemp(filepath.Dir(output), ".bd2-diff-stage-")
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
cleanup := true
|
||||
defer func() {
|
||||
if cleanup {
|
||||
retErr = errors.Join(retErr, os.RemoveAll(stage))
|
||||
}
|
||||
}()
|
||||
paths := reportPaths(output)
|
||||
summary, patch, noise, review := strings.Builder{}, strings.Builder{}, strings.Builder{}, strings.Builder{}
|
||||
fmt.Fprintf(&summary, "# %s\n# → %s\n\n", report.OldRoot, report.NewRoot)
|
||||
counts, _ := json.Marshal(report.Counts)
|
||||
fmt.Fprintf(&summary, "%s\n耗时 %.2fs / %d workers\n行号为归一化成员行号;疑似噪声不等于已证明语义相同。\n\n", counts, report.ElapsedSeconds, report.Workers)
|
||||
for _, w := range report.Warnings {
|
||||
fmt.Fprintf(&summary, "警告: %s\n", w)
|
||||
}
|
||||
for _, r := range report.Files {
|
||||
if r.Status == "unchanged" {
|
||||
continue
|
||||
}
|
||||
fmt.Fprintf(&summary, "[%s] %s\n", r.Status, r.Path)
|
||||
if r.Error != "" {
|
||||
fmt.Fprintf(&summary, " %s\n", r.Error)
|
||||
}
|
||||
for i, group := range [][]diffEntry{r.Members, r.Noise, r.Review} {
|
||||
dest := &patch
|
||||
switch i {
|
||||
case 1:
|
||||
dest = &noise
|
||||
case 2:
|
||||
dest = &review
|
||||
}
|
||||
for _, m := range group {
|
||||
if i != 1 {
|
||||
fmt.Fprintf(&summary, " %s: %s\n", m.Kind, m.Name)
|
||||
}
|
||||
fmt.Fprintf(dest, "\n# %s :: %s\n%s", r.Path, m.Name, m.Diff)
|
||||
}
|
||||
}
|
||||
}
|
||||
fmt.Fprintf(&summary, "\n主差异: %s\n需复核结构: %s\n疑似噪声: %s\n可视化: %s\n结构化报告: %s\n", paths[3], paths[5], paths[4], paths[2], paths[1])
|
||||
jsonData, e := json.MarshalIndent(report, "", " ")
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
htmlData, e := renderHTML(report)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
data := [][]byte{[]byte(summary.String()), append(jsonData, '\n'), htmlData, []byte(patch.String()), []byte(noise.String()), []byte(review.String())}
|
||||
for i, p := range paths {
|
||||
if e = os.WriteFile(filepath.Join(stage, filepath.Base(p)), data[i], 0644); e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
// Back up the complete existing bundle before replacing any of its files.
|
||||
// On a publication error, restore all previous reports.
|
||||
if e = checkReportOutput(output); e != nil {
|
||||
return e
|
||||
}
|
||||
backups := map[string]string{}
|
||||
published := []string{}
|
||||
rollback := func(cause error) error {
|
||||
for _, p := range published {
|
||||
cause = errors.Join(cause, os.Remove(p))
|
||||
}
|
||||
for p, backup := range backups {
|
||||
if e := os.Rename(backup, p); e != nil {
|
||||
cleanup = false
|
||||
cause = errors.Join(cause, fmt.Errorf("restore %s failed; backup retained at %s: %w", p, backup, e))
|
||||
}
|
||||
}
|
||||
return cause
|
||||
}
|
||||
for _, p := range paths {
|
||||
if _, err := os.Stat(p); err == nil {
|
||||
backup := filepath.Join(stage, filepath.Base(p)+".backup")
|
||||
if err = os.Rename(p, backup); err != nil {
|
||||
return rollback(err)
|
||||
}
|
||||
backups[p] = backup
|
||||
} else if !os.IsNotExist(err) {
|
||||
return rollback(err)
|
||||
}
|
||||
}
|
||||
for _, p := range paths {
|
||||
if e = os.Rename(filepath.Join(stage, filepath.Base(p)), p); e != nil {
|
||||
return rollback(e)
|
||||
}
|
||||
published = append(published, p)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package sourcetools
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"html/template"
|
||||
)
|
||||
|
||||
func renderHTML(report diffReport) ([]byte, error) {
|
||||
files := []fileResult{}
|
||||
for _, f := range report.Files {
|
||||
if f.Status != "unchanged" {
|
||||
files = append(files, f)
|
||||
}
|
||||
}
|
||||
payload, e := json.Marshal(files)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
data := struct {
|
||||
Report diffReport
|
||||
Payload template.JS
|
||||
}{report, template.JS(payload)}
|
||||
t, e := template.New("report").Parse(reportHTML)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
var out bytes.Buffer
|
||||
e = t.Execute(&out, data)
|
||||
return out.Bytes(), e
|
||||
}
|
||||
|
||||
const reportHTML = `<!doctype html><html lang="zh-CN"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>客户端源码 Clean Diff</title>
|
||||
<style>body{font:15px system-ui;margin:0;background:#10151d;color:#e0e6ed}header{padding:20px 24px;position:sticky;top:0;background:#17202df5;z-index:1}h1{font-size:24px;margin:0 0 12px}input,select,button{padding:9px;background:#10151d;color:#e0e6ed;border:1px solid #506079;border-radius:5px}button{cursor:pointer}button:disabled{opacity:.4}input{width:min(45vw,600px)}main{padding:10px 24px}details.file{border:1px solid #344256;border-radius:7px;margin:12px 0}summary{cursor:pointer;padding:12px;overflow-wrap:anywhere}details.member{margin:8px 16px;border-left:2px solid #526581}pre{font:13px/1.6 Consolas,monospace;overflow:auto;margin:0;padding:12px;background:#0c1118}.add{display:block;background:#163d2b;color:#b9f3c7}.del{display:block;background:#48212a;color:#ffc3c9}.hunk{display:block;color:#8bc4ff}.line{display:block}.muted{color:#9eafc2}.raw{margin:10px 14px}#count{margin-left:12px}nav{padding-top:12px}.reason{margin:10px 16px;color:#e8c079}</style>
|
||||
<header><h1>客户端源码 Clean Diff</h1><p>{{range $k,$v := .Report.Counts}}{{$k}}: {{$v}} / {{end}}</p><p class="muted">{{.Report.OldRoot}} → {{.Report.NewRoot}}</p><p class="muted">按文件 → 成员展开。行号为归一化成员行号;局部变量显示为 localN,可展开保留原名称的 diff。复核区保留 async / 状态机与无法确定的结构变化。</p>
|
||||
<input id="q" placeholder="搜索路径、成员、差异文本"><select id="filter"><option value="changes">主差异</option><option value="review">需复核结构</option><option value="noise">疑似写法噪声</option><option value="all">全部</option></select><span id="count"></span><nav><button id="prev">上一页</button> <span id="page"></span> <button id="next">下一页</button></nav></header><main id="files"></main>{{range .Report.Warnings}}<p class="reason">{{.}}</p>{{end}}
|
||||
<script type="application/json" id="data">{{.Payload}}</script><script>
|
||||
const data=JSON.parse(document.querySelector('#data').textContent);document.querySelector('#data').remove();
|
||||
const q=document.querySelector('#q'),filter=document.querySelector('#filter'),list=document.querySelector('#files');
|
||||
const labels={modified:'变化',added:'新增',removed:'删除',noise:'疑似噪声',review:'需复核',error:'读取失败'};
|
||||
let matches=[],page=0,timer;const size=100;
|
||||
function node(tag,text,cls){const el=document.createElement(tag);if(text!==undefined)el.textContent=text;if(cls)el.className=cls;return el}
|
||||
function showDiff(diff){const pre=node('pre');for(const line of diff.split('\n')){const cls=line.startsWith('+')?'add':line.startsWith('-')?'del':line.startsWith('@@')?'hunk':'line';pre.append(node('span',line||' ',cls))}return pre}
|
||||
function member(entry,title){const el=node('details',undefined,'member');el.append(node('summary',title+' · '+entry.name));el.addEventListener('toggle',()=>{if(!el.open||el.dataset.loaded)return;el.dataset.loaded='1';if(entry.reason)el.append(node('p',entry.reason,'reason'));el.append(showDiff(entry.diff));if(entry.source_diff&&entry.source_diff!==entry.diff){const raw=node('details',undefined,'raw');raw.append(node('summary','查看保留局部名 / 括号 / 泛型的差异'));raw.addEventListener('toggle',()=>{if(raw.open&&!raw.dataset.loaded){raw.dataset.loaded='1';raw.append(showDiff(entry.source_diff))}});el.append(raw)}});return el}
|
||||
function draw(){list.replaceChildren();const mode=filter.value;for(const item of matches.slice(page*size,(page+1)*size)){const el=node('details',undefined,'file');el.append(node('summary',labels[item.status]+' · '+item.path+' ('+item.members.length+' 变化 / '+(item.review||[]).length+' 复核 / '+item.noise.length+' 噪声)'));el.addEventListener('toggle',()=>{if(!el.open||el.dataset.loaded)return;el.dataset.loaded='1';el.append(node('p','旧: '+(item.old_path||'∅')+' → 新: '+(item.new_path||'∅'),'muted raw'));if(item.error)el.append(node('pre',item.error));for(const [key,title] of [['members','变化'],['review','需复核'],['noise','疑似噪声']]){if(mode==='review'&&key!=='review'||mode==='noise'&&key!=='noise')continue;for(const entry of item[key]||[])el.append(member(entry,title))}});list.append(el)}document.querySelector('#count').textContent=matches.length+' 文件';document.querySelector('#page').textContent=(matches.length?page+1:0)+' / '+Math.ceil(matches.length/size);document.querySelector('#prev').disabled=page===0;document.querySelector('#next').disabled=(page+1)*size>=matches.length}
|
||||
function search(){page=0;const s=q.value.toLowerCase(),mode=filter.value;matches=data.filter(item=>{if(mode==='changes'&&!['modified','added','removed','error'].includes(item.status))return false;if(mode==='noise'&&!item.noise.length)return false;if(mode==='review'&&!(item.review||[]).length)return false;if(!s||item.path.toLowerCase().includes(s))return true;return ['members','review','noise'].some(key=>(item[key]||[]).some(m=>(m.name+' '+m.diff+' '+(m.source_diff||'')).toLowerCase().includes(s)))});draw()}
|
||||
q.addEventListener('input',()=>{clearTimeout(timer);timer=setTimeout(search,150)});filter.addEventListener('change',search);document.querySelector('#prev').onclick=()=>{page--;draw()};document.querySelector('#next').onclick=()=>{page++;draw()};search();
|
||||
</script></html>`
|
||||
@@ -0,0 +1,641 @@
|
||||
package sourcetools
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"regexp"
|
||||
"slices"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var suffixPattern = regexp.MustCompile(`__from_u[0-9a-fA-F]{4}(?:_u[0-9a-fA-F]{4})*`)
|
||||
var nonType = wordSet("return throw new yield case goto break continue else if while switch lock nameof typeof sizeof default await this base true false null in is as do try finally checked unchecked")
|
||||
var modifiers = wordSet("public private protected internal static virtual override sealed abstract partial readonly volatile const async unsafe extern new ref out in params event")
|
||||
|
||||
func contains(s []string, t string) bool { return slices.Contains(s, t) }
|
||||
func tokenize(text string, symbols map[string]string) []string {
|
||||
r := []string{}
|
||||
for _, t := range lex(text) {
|
||||
if t.kind == "comment" || t.kind == "space" {
|
||||
continue
|
||||
}
|
||||
v := t.text
|
||||
if t.kind == "identifier" {
|
||||
if mapped, ok := symbols[v]; ok {
|
||||
v = mapped
|
||||
} else {
|
||||
v = suffixPattern.ReplaceAllString(v, "")
|
||||
}
|
||||
}
|
||||
r = append(r, v)
|
||||
}
|
||||
out := []string{}
|
||||
for i, t := range r {
|
||||
if t == "global" && i+1 < len(r) && r[i+1] == "::" || t == "::" && i > 0 && r[i-1] == "global" {
|
||||
continue
|
||||
}
|
||||
out = append(out, t)
|
||||
}
|
||||
return out
|
||||
}
|
||||
func pairs(s []string) map[int]int {
|
||||
stacks := map[string][]int{"(": {}, "[": {}, "{": {}}
|
||||
closing := map[string]string{")": "(", "]": "[", "}": "{"}
|
||||
r := map[int]int{}
|
||||
for i, t := range s {
|
||||
if stack, ok := stacks[t]; ok {
|
||||
stacks[t] = append(stack, i)
|
||||
} else if open, ok := closing[t]; ok {
|
||||
stack := stacks[open]
|
||||
if len(stack) > 0 {
|
||||
r[stack[len(stack)-1]] = i
|
||||
stacks[open] = stack[:len(stack)-1]
|
||||
}
|
||||
}
|
||||
}
|
||||
return r
|
||||
}
|
||||
func withoutAttributes(s []string) []string {
|
||||
ends := pairs(s)
|
||||
i := 0
|
||||
for i < len(s) && s[i] == "[" {
|
||||
j, ok := ends[i]
|
||||
if !ok {
|
||||
break
|
||||
}
|
||||
i = j + 1
|
||||
}
|
||||
return s[i:]
|
||||
}
|
||||
func assignmentAt(s []string) int {
|
||||
ends := pairs(s)
|
||||
for i := 0; i < len(s); {
|
||||
if j, ok := ends[i]; ok && (s[i] == "(" || s[i] == "[") {
|
||||
i = j + 1
|
||||
} else if s[i] == "=" || s[i] == "=>" {
|
||||
return i
|
||||
} else {
|
||||
i++
|
||||
}
|
||||
}
|
||||
return len(s)
|
||||
}
|
||||
func memberKey(s []string) string {
|
||||
s = withoutAttributes(s)
|
||||
s = s[:assignmentAt(s)]
|
||||
paren := slices.Index(s, "(")
|
||||
if paren >= 0 {
|
||||
begin := paren - 1
|
||||
if begin >= 0 && s[begin] == ">" {
|
||||
depth := 1
|
||||
begin--
|
||||
for begin >= 0 && depth > 0 {
|
||||
if s[begin] == ">" {
|
||||
depth++
|
||||
}
|
||||
if s[begin] == "<" {
|
||||
depth--
|
||||
}
|
||||
begin--
|
||||
}
|
||||
}
|
||||
end, ok := pairs(s)[paren]
|
||||
if !ok {
|
||||
end = len(s) - 1
|
||||
}
|
||||
parameters := []string{}
|
||||
current := []string{}
|
||||
depth := 0
|
||||
for _, t := range append(slices.Clone(s[paren+1:end]), ",") {
|
||||
if t == "," && depth == 0 {
|
||||
part := current
|
||||
if eq := slices.Index(part, "="); eq >= 0 {
|
||||
part = part[:eq]
|
||||
}
|
||||
if len(part) > 1 && identifier(part[len(part)-1]) {
|
||||
part = part[:len(part)-1]
|
||||
}
|
||||
parameters = append(parameters, strings.Join(part, " "))
|
||||
current = nil
|
||||
} else {
|
||||
current = append(current, t)
|
||||
if contains([]string{"<", "[", "("}, t) {
|
||||
depth++
|
||||
}
|
||||
if contains([]string{">", "]", ")"}, t) {
|
||||
depth--
|
||||
}
|
||||
}
|
||||
}
|
||||
name := strings.Join(s[max(0, begin):paren], " ")
|
||||
if begin > 0 && s[begin-1] == "~" {
|
||||
name = "~" + name
|
||||
}
|
||||
return name + "(" + strings.Join(parameters, ", ") + ")"
|
||||
}
|
||||
r := []string{}
|
||||
for _, t := range s {
|
||||
if !modifiers[t] {
|
||||
r = append(r, t)
|
||||
}
|
||||
}
|
||||
return strings.Join(r, " ")
|
||||
}
|
||||
|
||||
type member struct {
|
||||
key string
|
||||
tokens []string
|
||||
body int
|
||||
kind string
|
||||
ambiguous bool
|
||||
}
|
||||
|
||||
func splitMembers(tokens []string) []*member {
|
||||
ends := pairs(tokens)
|
||||
result := []*member{}
|
||||
counts := map[string]int{}
|
||||
emit := func(key string, seq []string, body int, kind string) {
|
||||
counts[key]++
|
||||
result = append(result, &member{key: fmt.Sprintf("%s #%d", key, counts[key]), tokens: seq, body: body, kind: kind})
|
||||
}
|
||||
var scope func(int, int, string)
|
||||
scope = func(start, stop int, prefix string) {
|
||||
for i := start; i < stop; {
|
||||
begin := i
|
||||
for i < stop {
|
||||
t := tokens[i]
|
||||
if j, ok := ends[i]; ok && (t == "[" || t == "(") {
|
||||
i = j + 1
|
||||
} else if t == ";" || t == "{" {
|
||||
break
|
||||
} else {
|
||||
i++
|
||||
}
|
||||
}
|
||||
if i == stop {
|
||||
if begin < stop {
|
||||
emit(prefix+" / trailing", tokens[begin:stop], -1, "member")
|
||||
}
|
||||
return
|
||||
}
|
||||
header := tokens[begin:i]
|
||||
plain := withoutAttributes(header)
|
||||
first := 0
|
||||
for first < len(plain) && modifiers[plain[first]] {
|
||||
first++
|
||||
}
|
||||
typeAt := -1
|
||||
if first < len(plain) && contains([]string{"namespace", "class", "struct", "interface", "enum"}, plain[first]) {
|
||||
typeAt = first
|
||||
}
|
||||
end, hasEnd := ends[i]
|
||||
if tokens[i] == "{" && hasEnd && typeAt >= 0 {
|
||||
tail := plain[typeAt+1:]
|
||||
if colon := slices.Index(tail, ":"); colon >= 0 {
|
||||
tail = tail[:colon]
|
||||
}
|
||||
path := prefix + " / " + strings.Join(tail, " ")
|
||||
if plain[typeAt] == "enum" {
|
||||
emit(path, tokens[begin:end+1], -1, "enum")
|
||||
} else {
|
||||
emit(path+" / declaration", header, -1, "type")
|
||||
scope(i+1, end, path)
|
||||
}
|
||||
i = end + 1
|
||||
continue
|
||||
}
|
||||
body := -1
|
||||
if tokens[i] == "{" {
|
||||
if !hasEnd {
|
||||
emit(prefix+" / unparsed", tokens[begin:stop], -1, "member")
|
||||
return
|
||||
}
|
||||
body = i - begin
|
||||
i = end + 1
|
||||
if assignmentAt(header) < len(header) {
|
||||
for i < stop && tokens[i] != ";" {
|
||||
if j, ok := ends[i]; ok && contains([]string{"{", "[", "("}, tokens[i]) {
|
||||
i = j + 1
|
||||
} else {
|
||||
i++
|
||||
}
|
||||
}
|
||||
if i < stop {
|
||||
i++
|
||||
}
|
||||
body = -1
|
||||
} else if i < stop && tokens[i] == ";" {
|
||||
i++
|
||||
}
|
||||
} else {
|
||||
i++
|
||||
}
|
||||
kind := "member"
|
||||
if body >= 0 && contains(plain[:assignmentAt(plain)], "(") {
|
||||
kind = "method"
|
||||
}
|
||||
if prefix == "file" && len(plain) > 0 && plain[0] == "using" {
|
||||
kind = "using"
|
||||
}
|
||||
emit(prefix+" / "+memberKey(header), tokens[begin:i], body, kind)
|
||||
}
|
||||
}
|
||||
scope(0, len(tokens), "file")
|
||||
return result
|
||||
}
|
||||
func typeEnd(s []string, i int) int {
|
||||
if i >= len(s) || !identifier(s[i]) || nonType[s[i]] {
|
||||
return i
|
||||
}
|
||||
j := i + 1
|
||||
for j < len(s) {
|
||||
if (s[j] == "." || s[j] == "::") && j+1 < len(s) && identifier(s[j+1]) {
|
||||
j += 2
|
||||
} else if s[j] == "<" {
|
||||
depth, k := 1, j+1
|
||||
for k < len(s) && depth > 0 {
|
||||
if s[k] == "<" {
|
||||
depth++
|
||||
} else if s[k] == ">" {
|
||||
depth--
|
||||
} else if !identifier(s[k]) && !contains([]string{",", ".", "[", "]", "?", "::"}, s[k]) {
|
||||
return i
|
||||
}
|
||||
k++
|
||||
}
|
||||
if depth > 0 {
|
||||
return i
|
||||
}
|
||||
j = k
|
||||
} else if s[j] == "[" {
|
||||
k := j + 1
|
||||
for k < len(s) && s[k] == "," {
|
||||
k++
|
||||
}
|
||||
if k >= len(s) || s[k] != "]" {
|
||||
break
|
||||
}
|
||||
j = k + 1
|
||||
} else if s[j] == "?" {
|
||||
j++
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
return j
|
||||
}
|
||||
func alphaLocals(m *member) []string {
|
||||
seq := slices.Clone(m.tokens)
|
||||
if m.body < 0 || m.kind != "method" || contains(seq, "nameof") {
|
||||
return seq
|
||||
}
|
||||
scopes := []map[string]string{{}}
|
||||
scopeEnds := []int{len(seq)}
|
||||
ends := pairs(seq)
|
||||
declarations := map[int]string{}
|
||||
typePositions := map[int]bool{}
|
||||
parameters := map[string]bool{}
|
||||
header := withoutAttributes(seq[:m.body])
|
||||
if begin := slices.Index(header, "("); begin >= 0 {
|
||||
end := pairs(header)[begin]
|
||||
part := []string{}
|
||||
depth := 0
|
||||
for _, t := range append(slices.Clone(header[begin+1:end]), ",") {
|
||||
if t == "," && depth == 0 {
|
||||
p := part
|
||||
if eq := slices.Index(p, "="); eq >= 0 {
|
||||
p = p[:eq]
|
||||
}
|
||||
if len(p) > 0 && identifier(p[len(p)-1]) {
|
||||
parameters[p[len(p)-1]] = true
|
||||
}
|
||||
part = nil
|
||||
} else {
|
||||
part = append(part, t)
|
||||
if contains([]string{"<", "[", "("}, t) {
|
||||
depth++
|
||||
}
|
||||
if contains([]string{">", "]", ")"}, t) {
|
||||
depth--
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
mark := func(start, end int) {
|
||||
for p := start; p < end; p++ {
|
||||
typePositions[p] = true
|
||||
}
|
||||
}
|
||||
for i := 0; i+1 < len(seq); i++ {
|
||||
if contains([]string{"new", "as", "is"}, seq[i]) {
|
||||
mark(i+1, typeEnd(seq, i+1))
|
||||
} else if contains([]string{"typeof", "sizeof", "default"}, seq[i]) && seq[i+1] == "(" {
|
||||
mark(i+2, typeEnd(seq, i+2))
|
||||
} else if seq[i] == "<" && i > 0 {
|
||||
if end := typeEnd(seq, i-1); end > i+1 {
|
||||
mark(i+1, end)
|
||||
}
|
||||
}
|
||||
}
|
||||
serial := 0
|
||||
for i := m.body + 1; i < len(seq); i++ {
|
||||
for len(scopes) > 1 && i > scopeEnds[len(scopeEnds)-1] {
|
||||
scopes = scopes[:len(scopes)-1]
|
||||
scopeEnds = scopeEnds[:len(scopeEnds)-1]
|
||||
}
|
||||
if seq[i] == "{" {
|
||||
scopes = append(scopes, map[string]string{})
|
||||
scopeEnds = append(scopeEnds, ends[i])
|
||||
} else if contains([]string{"for", "foreach", "using", "catch"}, seq[i]) && i+1 < len(seq) && seq[i+1] == "(" {
|
||||
if headerEnd, ok := ends[i+1]; ok && headerEnd+1 < len(seq) {
|
||||
end := headerEnd + 1
|
||||
if blockEnd, ok := ends[end]; ok && seq[end] == "{" {
|
||||
end = blockEnd
|
||||
} else {
|
||||
for end < len(seq)-1 && seq[end] != ";" {
|
||||
end++
|
||||
}
|
||||
}
|
||||
scopes = append(scopes, map[string]string{})
|
||||
scopeEnds = append(scopeEnds, end)
|
||||
}
|
||||
}
|
||||
prev := m.tokens[i-1]
|
||||
boundary := contains([]string{";", "{", "}"}, prev) || prev == "(" && i > 1 && contains([]string{"for", "foreach", "using", "catch"}, seq[i-2]) || prev == "out"
|
||||
if boundary {
|
||||
j := typeEnd(m.tokens, i)
|
||||
if j > i && j+1 < len(seq) && identifier(seq[j]) && contains([]string{"=", ";", ",", "in", ")"}, seq[j+1]) {
|
||||
serial++
|
||||
name := m.tokens[j]
|
||||
binding := fmt.Sprintf("local%d", serial)
|
||||
if parameters[name] || scopes[len(scopes)-1][name] != "" && contains([]string{";", "{", "}"}, prev) {
|
||||
m.ambiguous = true
|
||||
}
|
||||
scopes[len(scopes)-1][name] = binding
|
||||
declarations[j] = binding
|
||||
mark(i, j)
|
||||
}
|
||||
}
|
||||
if binding, ok := declarations[i]; ok {
|
||||
seq[i] = binding
|
||||
} else if !typePositions[i] && identifier(seq[i]) && !contains([]string{".", "?.", "::"}, prev) {
|
||||
for j := range slices.Backward(scopes) {
|
||||
if binding, ok := scopes[j][seq[i]]; ok {
|
||||
seq[i] = binding
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return seq
|
||||
}
|
||||
|
||||
var generatedPatterns = []*regexp.Regexp{regexp.MustCompile(`c__DisplayClass[0-9]+_[0-9]+`), regexp.MustCompile(`b__[0-9]+_`), regexp.MustCompile(`d__[0-9]+`), regexp.MustCompile(`9__[0-9]+_`), regexp.MustCompile(`g__\w+?_[0-9]+_[0-9]+`)}
|
||||
|
||||
func generated(s string) string {
|
||||
for n, r := range generatedPatterns {
|
||||
s = r.ReplaceAllStringFunc(s, func(t string) string {
|
||||
switch n {
|
||||
case 0:
|
||||
i := strings.LastIndex(t, "_")
|
||||
return "c__DisplayClassN" + t[i:]
|
||||
case 1:
|
||||
return "b__N_"
|
||||
case 2:
|
||||
return "d__N"
|
||||
case 3:
|
||||
return "9__N_"
|
||||
default:
|
||||
i := strings.LastIndex(t, "_")
|
||||
j := strings.LastIndex(t[:i], "_")
|
||||
return t[:j+1] + "N" + t[i:]
|
||||
}
|
||||
})
|
||||
}
|
||||
return s
|
||||
}
|
||||
func outerParentheses(seq []string) []string {
|
||||
ends := pairs(seq)
|
||||
drop := map[int]bool{}
|
||||
precedence := map[string]int{"??": 1, "||": 2, "&&": 3, "|": 4, "^": 5, "&": 6, "==": 7, "!=": 7, "<": 8, ">": 8, "<=": 8, ">=": 8, "is": 8, "as": 8, "+": 10, "-": 10, "*": 11, "/": 11, "%": 11}
|
||||
for i, j := range ends {
|
||||
if seq[i] != "(" || i == 0 {
|
||||
continue
|
||||
}
|
||||
prev := seq[i-1]
|
||||
following := ""
|
||||
if j+1 < len(seq) {
|
||||
following = seq[j+1]
|
||||
}
|
||||
doubled := i+1 < j && seq[i+1] == "(" && ends[i+1] == j-1
|
||||
whole := contains([]string{"return", "=", "+=", "-=", "*=", "/="}, prev) && following == ";"
|
||||
if whole {
|
||||
for k := i + 1; k < j; {
|
||||
if end, ok := ends[k]; ok && contains([]string{"(", "[", "{"}, seq[k]) {
|
||||
k = end + 1
|
||||
} else if seq[k] == "," {
|
||||
whole = false
|
||||
break
|
||||
} else {
|
||||
k++
|
||||
}
|
||||
}
|
||||
}
|
||||
redundant := false
|
||||
_, prevOp := precedence[prev]
|
||||
_, nextOp := precedence[following]
|
||||
if i+1 < j && prev != "<" && prev != ">" && (prevOp || contains([]string{"(", "[", ",", "=", "return", "?", ":", "!", "~"}, prev)) && (nextOp || contains([]string{";", ",", ")", "]", "?", ":", "}"}, following)) {
|
||||
minimum := 17
|
||||
for k := i + 1; k < j; {
|
||||
t := seq[k]
|
||||
if end, ok := ends[k]; ok && (t == "(" || t == "[") {
|
||||
k = end + 1
|
||||
continue
|
||||
}
|
||||
if contains([]string{"=", "=>", "?", ":", ";", ",", "++", "--"}, t) {
|
||||
minimum = 0
|
||||
break
|
||||
}
|
||||
if (t == "<" || t == ">") && k+1 < j && seq[k+1] == t {
|
||||
minimum = min(minimum, 9)
|
||||
k += 2
|
||||
continue
|
||||
}
|
||||
if p, ok := precedence[t]; ok {
|
||||
_, priorOp := precedence[seq[k-1]]
|
||||
if !contains([]string{"+", "-"}, t) || k != i+1 && !priorOp {
|
||||
minimum = min(minimum, p)
|
||||
}
|
||||
}
|
||||
k++
|
||||
}
|
||||
redundant = minimum > max(precedence[prev], precedence[following])
|
||||
}
|
||||
if doubled || whole || redundant {
|
||||
drop[i], drop[j] = true, true
|
||||
}
|
||||
}
|
||||
result := []string{}
|
||||
for i, t := range seq {
|
||||
if !drop[i] {
|
||||
result = append(result, t)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
type typeargs struct {
|
||||
start, end int
|
||||
name string
|
||||
}
|
||||
|
||||
func callTypeargs(seq []string, start int) []typeargs {
|
||||
r := []typeargs{}
|
||||
for i := start; i < len(seq); i++ {
|
||||
if seq[i] != "<" || i == 0 || !identifier(seq[i-1]) {
|
||||
continue
|
||||
}
|
||||
depth, j := 1, i+1
|
||||
for j < len(seq) && depth > 0 {
|
||||
t := seq[j]
|
||||
if t == "<" {
|
||||
depth++
|
||||
} else if t == ">" {
|
||||
depth--
|
||||
} else if !identifier(t) && !contains([]string{",", ".", "[", "]", "?", "::"}, t) {
|
||||
break
|
||||
}
|
||||
j++
|
||||
}
|
||||
k := i - 2
|
||||
for k >= 1 && (seq[k] == "." || seq[k] == "::") {
|
||||
k -= 2
|
||||
}
|
||||
constructor := k >= 0 && seq[k] == "new"
|
||||
if depth == 0 && j < len(seq) && seq[j] == "(" && !constructor {
|
||||
r = append(r, typeargs{i, j, seq[i-1]})
|
||||
i = j
|
||||
}
|
||||
}
|
||||
return r
|
||||
}
|
||||
func inferredGenerics(seq []string, start int, allowed map[string]bool) []string {
|
||||
drop := map[int]bool{}
|
||||
for _, c := range callTypeargs(seq, start) {
|
||||
if allowed[c.name] {
|
||||
for i := c.start; i < c.end; i++ {
|
||||
drop[i] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
r := []string{}
|
||||
for i, t := range seq {
|
||||
if !drop[i] {
|
||||
r = append(r, t)
|
||||
}
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
var labelPattern = regexp.MustCompile(`^IL_[0-9A-Fa-f]+$`)
|
||||
|
||||
func heuristic(m *member) []string {
|
||||
seq := alphaLocals(m)
|
||||
for i, t := range seq {
|
||||
if identifier(t) {
|
||||
seq[i] = generated(t)
|
||||
}
|
||||
}
|
||||
for i := 0; i < len(seq); i++ {
|
||||
if seq[i] != "<" || i == 0 || !identifier(seq[i-1]) {
|
||||
continue
|
||||
}
|
||||
depth, j := 1, i+1
|
||||
for j < len(seq) && depth > 0 {
|
||||
if seq[j] == "<" {
|
||||
depth++
|
||||
}
|
||||
if seq[j] == ">" {
|
||||
depth--
|
||||
}
|
||||
j++
|
||||
}
|
||||
if depth == 0 && j+1 < len(seq) && seq[j] == "." && strings.HasPrefix(seq[j+1], "c__DisplayClass") {
|
||||
chunk := append([]string{".", seq[j+1]}, seq[i:j]...)
|
||||
copy(seq[i:j+2], chunk)
|
||||
i = j + 1
|
||||
}
|
||||
}
|
||||
labels := map[string]string{}
|
||||
for i, t := range seq {
|
||||
if i+1 < len(seq) && labelPattern.MatchString(t) && seq[i+1] == ":" {
|
||||
if _, ok := labels[t]; !ok {
|
||||
labels[t] = fmt.Sprintf("label%d", len(labels)+1)
|
||||
}
|
||||
}
|
||||
}
|
||||
for i, t := range seq {
|
||||
if label, ok := labels[t]; ok {
|
||||
seq[i] = label
|
||||
}
|
||||
}
|
||||
ends := pairs(seq)
|
||||
attrs := [][]string{}
|
||||
i := 0
|
||||
for i < len(seq) && seq[i] == "[" {
|
||||
end, ok := ends[i]
|
||||
if !ok {
|
||||
break
|
||||
}
|
||||
attrs = append(attrs, seq[i:end+1])
|
||||
i = end + 1
|
||||
}
|
||||
if len(attrs) > 1 {
|
||||
sort.Slice(attrs, func(i, j int) bool { return strings.Join(attrs[i], "\x00") < strings.Join(attrs[j], "\x00") })
|
||||
r := []string{}
|
||||
for _, a := range attrs {
|
||||
r = append(r, a...)
|
||||
}
|
||||
seq = append(r, seq[i:]...)
|
||||
}
|
||||
return outerParentheses(seq)
|
||||
}
|
||||
func normalizePair(a, b *member) ([]string, []string) {
|
||||
ca, cb := []string{}, []string{}
|
||||
if a != nil {
|
||||
ca = heuristic(a)
|
||||
}
|
||||
if b != nil {
|
||||
cb = heuristic(b)
|
||||
}
|
||||
if a != nil && b != nil && a.kind == "method" && b.kind == "method" {
|
||||
startA, startB := a.body+1, b.body+1
|
||||
namesA, namesB := map[string]bool{}, map[string]bool{}
|
||||
for _, c := range callTypeargs(ca, startA) {
|
||||
namesA[c.name] = true
|
||||
}
|
||||
for _, c := range callTypeargs(cb, startB) {
|
||||
namesB[c.name] = true
|
||||
}
|
||||
bare := func(s []string, start int) map[string]bool {
|
||||
r := map[string]bool{}
|
||||
for i := start; i < len(s); i++ {
|
||||
if s[i] == "(" && i > 0 && identifier(s[i-1]) {
|
||||
r[s[i-1]] = true
|
||||
}
|
||||
}
|
||||
return r
|
||||
}
|
||||
bareA, bareB := bare(ca, startA), bare(cb, startB)
|
||||
allowedA, allowedB := map[string]bool{}, map[string]bool{}
|
||||
for n := range namesA {
|
||||
allowedA[n] = !namesB[n] && bareB[n]
|
||||
}
|
||||
for n := range namesB {
|
||||
allowedB[n] = !namesA[n] && bareA[n]
|
||||
}
|
||||
ca = inferredGenerics(ca, startA, allowedA)
|
||||
cb = inferredGenerics(cb, startB, allowedB)
|
||||
}
|
||||
return ca, cb
|
||||
}
|
||||
@@ -0,0 +1,294 @@
|
||||
// Package sourcetools creates readable mirrors and member-level reports for
|
||||
// decompiled C# source. It never writes into an input source tree.
|
||||
package sourcetools
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"unicode"
|
||||
"unicode/utf16"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
func identifierStart(r rune) bool {
|
||||
return r == '_' || unicode.IsLetter(r) || unicode.In(r, unicode.Nl)
|
||||
}
|
||||
func identifierContinue(r rune) bool {
|
||||
return identifierStart(r) || unicode.In(r, unicode.Mn, unicode.Mc, unicode.Nd, unicode.Pc, unicode.Cf)
|
||||
}
|
||||
func identifier(s string) bool {
|
||||
s = strings.TrimPrefix(s, "@")
|
||||
r := []rune(s)
|
||||
if len(r) == 0 || !identifierStart(r[0]) {
|
||||
return false
|
||||
}
|
||||
for _, c := range r[1:] {
|
||||
if !identifierContinue(c) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// Lexing keeps comments and all literal payloads opaque, including raw strings.
|
||||
type token struct{ text, kind string }
|
||||
|
||||
func lex(s string) []token {
|
||||
s = strings.TrimPrefix(s, "\ufeff")
|
||||
var result []token
|
||||
for i := 0; i < len(s); {
|
||||
start := i
|
||||
if strings.HasPrefix(s[i:], "//") {
|
||||
if j := strings.IndexByte(s[i:], '\n'); j >= 0 {
|
||||
i += j
|
||||
} else {
|
||||
i = len(s)
|
||||
}
|
||||
result = append(result, token{s[start:i], "comment"})
|
||||
continue
|
||||
}
|
||||
if strings.HasPrefix(s[i:], "/*") {
|
||||
if j := strings.Index(s[i+2:], "*/"); j >= 0 {
|
||||
i += j + 4
|
||||
} else {
|
||||
i = len(s)
|
||||
}
|
||||
result = append(result, token{s[start:i], "comment"})
|
||||
continue
|
||||
}
|
||||
q := i
|
||||
for q < len(s) && (s[q] == '$' || s[q] == '@') {
|
||||
q++
|
||||
}
|
||||
if q < len(s) && (s[q] == '"' || s[q] == '\'') && (q == i || s[q] == '"') {
|
||||
quote := s[q]
|
||||
count := 1
|
||||
for q+count < len(s) && s[q+count] == quote {
|
||||
count++
|
||||
}
|
||||
if quote == '"' && count >= 3 {
|
||||
marker := strings.Repeat("\"", count)
|
||||
if j := strings.Index(s[q+count:], marker); j >= 0 {
|
||||
i = q + count + j + count
|
||||
} else {
|
||||
i = len(s)
|
||||
}
|
||||
} else {
|
||||
verbatim := strings.Contains(s[start:q], "@")
|
||||
i = q + 1
|
||||
for i < len(s) {
|
||||
if verbatim && quote == '"' && strings.HasPrefix(s[i:], "\"\"") {
|
||||
i += 2
|
||||
continue
|
||||
}
|
||||
if s[i] == quote {
|
||||
i++
|
||||
break
|
||||
}
|
||||
if !verbatim && s[i] == '\\' {
|
||||
i += 2
|
||||
} else {
|
||||
i++
|
||||
}
|
||||
}
|
||||
if i > len(s) {
|
||||
i = len(s)
|
||||
}
|
||||
}
|
||||
result = append(result, token{s[start:i], "literal"})
|
||||
continue
|
||||
}
|
||||
r, size := utf8.DecodeRuneInString(s[i:])
|
||||
if unicode.IsSpace(r) {
|
||||
i += size
|
||||
result = append(result, token{s[start:i], "space"})
|
||||
continue
|
||||
}
|
||||
at := r == '@'
|
||||
if at && i+size < len(s) {
|
||||
r, _ = utf8.DecodeRuneInString(s[i+size:])
|
||||
}
|
||||
if identifierStart(r) {
|
||||
i += size
|
||||
if at {
|
||||
_, n := utf8.DecodeRuneInString(s[i:])
|
||||
i += n
|
||||
}
|
||||
for i < len(s) {
|
||||
c, n := utf8.DecodeRuneInString(s[i:])
|
||||
if !identifierContinue(c) {
|
||||
break
|
||||
}
|
||||
i += n
|
||||
}
|
||||
result = append(result, token{s[start:i], "identifier"})
|
||||
continue
|
||||
}
|
||||
if s[i] >= '0' && s[i] <= '9' || s[i] == '.' && i+1 < len(s) && s[i+1] >= '0' && s[i+1] <= '9' {
|
||||
i++
|
||||
for i < len(s) {
|
||||
c := s[i]
|
||||
if c >= '0' && c <= '9' || c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c == '_' || c == '.' && i+1 < len(s) && s[i+1] >= '0' && s[i+1] <= '9' {
|
||||
i++
|
||||
continue
|
||||
}
|
||||
if (c == '+' || c == '-') && (s[i-1] == 'e' || s[i-1] == 'E') {
|
||||
i++
|
||||
continue
|
||||
}
|
||||
break
|
||||
}
|
||||
result = append(result, token{s[start:i], "number"})
|
||||
continue
|
||||
}
|
||||
op := ""
|
||||
for _, v := range []string{"??=", "<<=", ">>=", "=>", "==", "!=", "<=", ">=", "&&", "||", "++", "--", "+=", "-=", "*=", "/=", "%=", "&=", "|=", "^=", "??", "?.", "::", "->"} {
|
||||
if strings.HasPrefix(s[i:], v) {
|
||||
op = v
|
||||
break
|
||||
}
|
||||
}
|
||||
if op != "" {
|
||||
i += len(op)
|
||||
} else {
|
||||
i += size
|
||||
}
|
||||
result = append(result, token{s[start:i], "operator"})
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func readSource(path string) (string, string, error) {
|
||||
b, e := os.ReadFile(path)
|
||||
if e != nil {
|
||||
return "", "", e
|
||||
}
|
||||
if len(b) >= 2 && (b[0] == 0xff && b[1] == 0xfe || b[0] == 0xfe && b[1] == 0xff) {
|
||||
if len(b)%2 != 0 {
|
||||
return "", "", errors.New("invalid UTF-16 length")
|
||||
}
|
||||
enc := "utf-16-le"
|
||||
var order binary.ByteOrder = binary.LittleEndian
|
||||
if b[0] == 0xfe {
|
||||
enc = "utf-16-be"
|
||||
order = binary.BigEndian
|
||||
}
|
||||
words := make([]uint16, (len(b)-2)/2)
|
||||
for i := range words {
|
||||
words[i] = order.Uint16(b[2+i*2:])
|
||||
}
|
||||
for i := 0; i < len(words); i++ {
|
||||
if words[i] >= 0xd800 && words[i] <= 0xdbff {
|
||||
if i+1 == len(words) || words[i+1] < 0xdc00 || words[i+1] > 0xdfff {
|
||||
return "", "", errors.New("invalid UTF-16 surrogate")
|
||||
}
|
||||
i++
|
||||
} else if words[i] >= 0xdc00 && words[i] <= 0xdfff {
|
||||
return "", "", errors.New("invalid UTF-16 surrogate")
|
||||
}
|
||||
}
|
||||
return string(utf16.Decode(words)), enc, nil
|
||||
}
|
||||
enc := "utf-8"
|
||||
if len(b) >= 3 && string(b[:3]) == "\xef\xbb\xbf" {
|
||||
enc = "utf-8-sig"
|
||||
b = b[3:]
|
||||
}
|
||||
if !utf8.Valid(b) {
|
||||
return "", "", errors.New("unsupported text encoding")
|
||||
}
|
||||
return string(b), enc, nil
|
||||
}
|
||||
func writeSource(path, text, enc string) error {
|
||||
var b []byte
|
||||
switch enc {
|
||||
case "utf-16-le", "utf-16-be":
|
||||
words := utf16.Encode([]rune(text))
|
||||
b = make([]byte, 2+len(words)*2)
|
||||
var order binary.ByteOrder = binary.LittleEndian
|
||||
b[0], b[1] = 0xff, 0xfe
|
||||
if enc == "utf-16-be" {
|
||||
order = binary.BigEndian
|
||||
b[0], b[1] = 0xfe, 0xff
|
||||
}
|
||||
for i, w := range words {
|
||||
order.PutUint16(b[2+i*2:], w)
|
||||
}
|
||||
case "utf-8-sig":
|
||||
b = append([]byte{0xef, 0xbb, 0xbf}, []byte(text)...)
|
||||
default:
|
||||
b = []byte(text)
|
||||
}
|
||||
return os.WriteFile(path, b, 0644)
|
||||
}
|
||||
|
||||
func canonicalPath(path string) (string, error) {
|
||||
absolute, e := filepath.Abs(path)
|
||||
if e != nil {
|
||||
return "", e
|
||||
}
|
||||
p := absolute
|
||||
var suffix []string
|
||||
for {
|
||||
resolved, e := filepath.EvalSymlinks(p)
|
||||
if e == nil {
|
||||
for _, name := range slices.Backward(suffix) {
|
||||
resolved = filepath.Join(resolved, name)
|
||||
}
|
||||
return filepath.Clean(resolved), nil
|
||||
}
|
||||
if !os.IsNotExist(e) {
|
||||
return "", e
|
||||
}
|
||||
parent := filepath.Dir(p)
|
||||
if parent == p {
|
||||
return "", e
|
||||
}
|
||||
suffix = append(suffix, filepath.Base(p))
|
||||
p = parent
|
||||
}
|
||||
}
|
||||
func within(child, parent string) bool {
|
||||
r, e := filepath.Rel(parent, child)
|
||||
return e == nil && r != ".." && !strings.HasPrefix(r, ".."+string(filepath.Separator)) && !filepath.IsAbs(r)
|
||||
}
|
||||
func sourceRoot(path string) (string, error) {
|
||||
p, e := canonicalPath(path)
|
||||
if e != nil {
|
||||
return "", e
|
||||
}
|
||||
s, e := os.Stat(p)
|
||||
if e != nil {
|
||||
return "", e
|
||||
}
|
||||
if !s.IsDir() {
|
||||
return "", fmt.Errorf("source is not a directory: %s", p)
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
func safeTrees(source, output string) (string, string, error) {
|
||||
s, e := sourceRoot(source)
|
||||
if e != nil {
|
||||
return "", "", e
|
||||
}
|
||||
o, e := canonicalPath(output)
|
||||
if e != nil {
|
||||
return "", "", e
|
||||
}
|
||||
if within(s, o) || within(o, s) {
|
||||
return "", "", errors.New("output must be outside, and not contain, source")
|
||||
}
|
||||
return s, o, nil
|
||||
}
|
||||
func copyFile(source, target string) error {
|
||||
b, e := os.ReadFile(source)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
return os.WriteFile(target, b, 0644)
|
||||
}
|
||||
@@ -0,0 +1,395 @@
|
||||
package sourcetools_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
"unicode/utf16"
|
||||
|
||||
"bd2server/build/sourcetools"
|
||||
)
|
||||
|
||||
type entry struct{ Name, Kind, Diff, SourceDiff, Reason string }
|
||||
|
||||
func (e *entry) UnmarshalJSON(b []byte) error {
|
||||
type wire struct {
|
||||
Name, Kind, Diff, Reason string
|
||||
SourceDiff string `json:"source_diff"`
|
||||
}
|
||||
var w wire
|
||||
if err := json.Unmarshal(b, &w); err != nil {
|
||||
return err
|
||||
}
|
||||
*e = entry{w.Name, w.Kind, w.Diff, w.SourceDiff, w.Reason}
|
||||
return nil
|
||||
}
|
||||
|
||||
type result struct {
|
||||
Path, Status, Error string
|
||||
OldPath *string `json:"old_path"`
|
||||
NewPath *string `json:"new_path"`
|
||||
Members, Noise, Review []entry
|
||||
}
|
||||
type report struct {
|
||||
Counts map[string]int
|
||||
Files []result
|
||||
Warnings []string
|
||||
RenamedPaths int `json:"renamed_paths"`
|
||||
}
|
||||
|
||||
func write(t *testing.T, path, text string) {
|
||||
t.Helper()
|
||||
if e := os.MkdirAll(filepath.Dir(path), 0755); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e := os.WriteFile(path, []byte(text), 0644); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
}
|
||||
func read(t *testing.T, path string) string {
|
||||
t.Helper()
|
||||
b, e := os.ReadFile(path)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
func loadReport(t *testing.T, output string) report {
|
||||
t.Helper()
|
||||
var r report
|
||||
if e := json.Unmarshal([]byte(read(t, strings.TrimSuffix(output, ".txt")+".json")), &r); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
return r
|
||||
}
|
||||
func compare(t *testing.T, old, new string, extra ...string) result {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
a, b := filepath.Join(dir, "a"), filepath.Join(dir, "b")
|
||||
write(t, filepath.Join(a, "Game.cs"), old)
|
||||
write(t, filepath.Join(b, "Game.cs"), new)
|
||||
output := filepath.Join(dir, "report.txt")
|
||||
args := append([]string{"--a", a, "--b", b, "--out", output, "--context", "50", "--workers", "1"}, extra...)
|
||||
if e := sourcetools.RunDiff(args, io.Discard); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
r := loadReport(t, output)
|
||||
if len(r.Files) != 1 {
|
||||
t.Fatalf("expected one file: %+v", r)
|
||||
}
|
||||
return r.Files[0]
|
||||
}
|
||||
func entryDiff(entries []entry) string {
|
||||
var out strings.Builder
|
||||
for _, e := range entries {
|
||||
out.WriteString(e.Diff)
|
||||
out.WriteString(e.SourceDiff)
|
||||
}
|
||||
return out.String()
|
||||
}
|
||||
|
||||
func TestLocalRenamesRemainReviewableAndStrictDiffKeepsNames(t *testing.T) {
|
||||
old := `class Inventory { int Count(int limit = 3) { int count = Read(); { int subtotal = Read(); Use(subtotal); } return count + 1; } int Price() { int amount = Read(); return amount; } }`
|
||||
new := `class Inventory { int Count(int limit = 3) { int value = Read(); { int part = Read(); Use(part); } return value + 1; } int Price() { int sum = Read(); return sum; } }`
|
||||
r := compare(t, old, new)
|
||||
if r.Status != "noise" || len(r.Noise) != 2 || len(r.Members) != 0 {
|
||||
t.Fatalf("renames should retain both method diffs as noise: %+v", r)
|
||||
}
|
||||
diff := entryDiff(r.Noise)
|
||||
if !strings.Contains(diff, "count") || !strings.Contains(diff, "subtotal") || !strings.Contains(diff, "part") || !strings.Contains(diff, "sum") {
|
||||
t.Fatal("review diff lost original names: " + diff)
|
||||
}
|
||||
strict := compare(t, old, new, "--strict")
|
||||
if strict.Status != "modified" || len(strict.Members) != 2 || len(strict.Noise) != 0 {
|
||||
t.Fatalf("strict report should expose both renames: %+v", strict)
|
||||
}
|
||||
}
|
||||
func TestLoopBindingExpiresBeforeFollowingFieldRead(t *testing.T) {
|
||||
old := `class C { int count; void Run() { for (int count = 0; count < 2; count++) { Use(count); } Use(count); } }`
|
||||
equivalent := `class C { int count; void Run() { for (int index = 0; index < 2; index++) { Use(index); } Use(count); } }`
|
||||
r := compare(t, old, equivalent)
|
||||
if r.Status != "noise" {
|
||||
t.Fatalf("loop-local rename should not rewrite the later field read: %+v", r)
|
||||
}
|
||||
changed := `class C { int count; void Run() { for (int index = 0; index < 2; index++) { Use(index); } Use(index); } }`
|
||||
r = compare(t, old, changed)
|
||||
if r.Status != "modified" || !strings.Contains(entryDiff(r.Members), "Use(count)") || !strings.Contains(entryDiff(r.Members), "Use(index)") {
|
||||
t.Fatalf("out-of-scope references must stay visible: %+v", r)
|
||||
}
|
||||
}
|
||||
func TestBusinessValuesTargetsAndStatementOrderRemainVisible(t *testing.T) {
|
||||
old := `class Checkout { static int first = Next(); static int second = Next(); int Run() { int total = Price(); Charge(total); Audit(total); return (a + b) * c; } }`
|
||||
new := `class Checkout { static int second = Next(); static int first = Next(); int Run() { int value = Price(); Log(value); Refund(value); return a + b * c; } }`
|
||||
r := compare(t, old, new)
|
||||
diff := entryDiff(r.Members)
|
||||
if r.Status != "modified" || !strings.Contains(diff, "Charge(local1)") || !strings.Contains(diff, "Refund(local1)") || !strings.Contains(diff, "(a + b) * c") || !strings.Contains(diff, "a + b * c") {
|
||||
t.Fatalf("business changes were hidden: %+v", r)
|
||||
}
|
||||
foundOrder := false
|
||||
for _, e := range r.Members {
|
||||
foundOrder = foundOrder || e.Kind == "order"
|
||||
}
|
||||
if !foundOrder {
|
||||
t.Fatal("field initialization order must be a main difference")
|
||||
}
|
||||
// The statements alone still differ when their order changes.
|
||||
r = compare(t, `class C { void Run() { Charge(); Audit(); } }`, `class C { void Run() { Audit(); Charge(); } }`)
|
||||
if r.Status != "modified" {
|
||||
t.Fatalf("statement order was normalized away: %+v", r)
|
||||
}
|
||||
}
|
||||
func TestGenericArgumentsAndLiteralPayloadSurviveNormalization(t *testing.T) {
|
||||
old := `class C { Dictionary<int,string> data; void Run() { var items = new NS.List<int>(); Foo<int>(items); Save(@"//keep ""global::__from_u0041"" /*old*/"); } }`
|
||||
new := `class C { Dictionary<int,int> data; void Run() { var list = new NS.List<string>(); Foo<string>(list); Save(@"//keep ""global::__from_u0042"" /*new*/"); } }`
|
||||
r := compare(t, old, new)
|
||||
diff := entryDiff(r.Members)
|
||||
if r.Status != "modified" || !strings.Contains(diff, "Dictionary < int, string >") || !strings.Contains(diff, "new NS.List < int >()") || !strings.Contains(diff, "new NS.List < string >()") || !strings.Contains(diff, "Foo < int >") || !strings.Contains(diff, "Foo < string >") || !strings.Contains(diff, `global::__from_u0041"" /*old*/`) || !strings.Contains(diff, `global::__from_u0042"" /*new*/`) {
|
||||
t.Fatalf("type/literal changes should remain in main diff: %+v", r)
|
||||
}
|
||||
inferred := compare(t, `class C { void Run() { Foo(x); } }`, `class C { void Run() { Foo<int>(x); } }`)
|
||||
if inferred.Status != "noise" || !strings.Contains(entryDiff(inferred.Noise), "int") {
|
||||
t.Fatalf("inference difference should remain reviewable: %+v", inferred)
|
||||
}
|
||||
}
|
||||
func TestObservableNamesAndAmbiguousBindingsAreNeverDiscarded(t *testing.T) {
|
||||
r := compare(t, `class C { string Run() { int count = 0; return nameof(count); } }`, `class C { string Run() { int value = 0; return nameof(value); } }`)
|
||||
if r.Status != "modified" || !strings.Contains(entryDiff(r.Members), "nameof(count)") || !strings.Contains(entryDiff(r.Members), "nameof(value)") {
|
||||
t.Fatalf("nameof changes observable strings: %+v", r)
|
||||
}
|
||||
r = compare(t, `class C { void Run() { int num = 1; double num = 2; Use(num); } }`, `class C { void Run() { int first = 1; double second = 2; Use(second); } }`)
|
||||
if r.Status != "review" || len(r.Review) != 1 || r.Review[0].Reason == "" || !strings.Contains(r.Review[0].SourceDiff, "num") || !strings.Contains(r.Review[0].SourceDiff, "second") {
|
||||
t.Fatalf("ambiguous binding needs the source diff: %+v", r)
|
||||
}
|
||||
}
|
||||
func TestAsyncStructureKeepsBusinessBodiesInReview(t *testing.T) {
|
||||
old := `class C { Task Run() { Run_d__1 state; state.t__builder = Create(); return state.t__builder.Task; } struct Run_d__1 { AsyncTaskMethodBuilder t__builder; void MoveNext() { ChargeAccount(10); AuditTransaction(10); } } int Price() { return 100; } }`
|
||||
new := `class C { async Task Run() { await ChargeAccount(20); AuditTransaction(20); } int Price() { return 200; } }`
|
||||
r := compare(t, old, new)
|
||||
diff := entryDiff(r.Review)
|
||||
if r.Status != "modified" || len(r.Review) == 0 || len(r.Members) != 1 || !strings.Contains(r.Members[0].Name, "Price") || !strings.Contains(diff, "ChargeAccount(10)") || !strings.Contains(diff, "ChargeAccount(20)") || !strings.Contains(diff, "AuditTransaction(10)") || !strings.Contains(diff, "AuditTransaction(20)") {
|
||||
t.Fatalf("async body or independent business change lost: %+v", r)
|
||||
}
|
||||
}
|
||||
func TestCommentsAreIgnoredWhileStringsAndLambdaTargetsArePreserved(t *testing.T) {
|
||||
r := compare(t, "class C { global::System.Int32 value__from_u0041; // old\n }", "/* new */ class C\n { System.Int32 value; }")
|
||||
if r.Status != "unchanged" {
|
||||
t.Fatalf("format/suffix cleanup should be exact: %+v", r)
|
||||
}
|
||||
r = compare(t, `class C { void Run() { callbacks.b__12_0(); Save("name__from_u0041"); } }`, `class C { void Run() { callbacks.b__13_1(); Save("name__from_u0042"); } }`)
|
||||
diff := entryDiff(r.Members)
|
||||
if r.Status != "modified" || !strings.Contains(diff, "b__N_0") || !strings.Contains(diff, "b__N_1") || !strings.Contains(diff, `"name__from_u0041"`) || !strings.Contains(diff, `"name__from_u0042"`) {
|
||||
t.Fatalf("lambda target/literal changes must remain visible: %+v", r)
|
||||
}
|
||||
}
|
||||
func TestCollisionPairingPreservesDistinctTypesAndCallTargets(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
a, b := filepath.Join(dir, "a"), filepath.Join(dir, "b")
|
||||
write(t, filepath.Join(a, "Message__from_u0041.cs"), `class Message__from_u0041 { int Count = 1; static void Build() {} }`)
|
||||
write(t, filepath.Join(a, "Message__from_u0042.cs"), `class Message__from_u0042 { string Label; static void Build() {} }`)
|
||||
write(t, filepath.Join(b, "Message__from_u0043.cs"), `class Message__from_u0043 { string Label; static void Build() {} }`)
|
||||
write(t, filepath.Join(b, "Message__from_u0044.cs"), `class Message__from_u0044 { int Count = 2; static void Build() {} }`)
|
||||
write(t, filepath.Join(a, "Use.cs"), `class Use { void Run() { Message__from_u0041.Build(); } }`)
|
||||
write(t, filepath.Join(b, "Use.cs"), `class Use { void Run() { Message__from_u0044.Build(); } }`)
|
||||
output := filepath.Join(dir, "report.txt")
|
||||
args := []string{"--a", a, "--b", b, "--out", output, "--workers", "1"}
|
||||
if e := sourcetools.RunDiff(args, io.Discard); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
r := loadReport(t, output)
|
||||
pairs := map[string]string{}
|
||||
for _, f := range r.Files {
|
||||
if f.OldPath == nil || f.NewPath == nil {
|
||||
t.Fatalf("unique types should pair: %+v", f)
|
||||
}
|
||||
pairs[*f.OldPath] = *f.NewPath
|
||||
if *f.OldPath == "Use.cs" && f.Status != "unchanged" {
|
||||
t.Fatalf("reference to the same type should be unchanged: %+v", f)
|
||||
}
|
||||
}
|
||||
if pairs["Message__from_u0041.cs"] != "Message__from_u0044.cs" || pairs["Message__from_u0042.cs"] != "Message__from_u0043.cs" || r.Counts["modified"] != 1 {
|
||||
t.Fatalf("pairing changed type identity: %+v", r)
|
||||
}
|
||||
write(t, filepath.Join(b, "Use.cs"), `class Use { void Run() { Message__from_u0043.Build(); } }`)
|
||||
if e := sourcetools.RunDiff(args, io.Discard); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
r = loadReport(t, output)
|
||||
if r.Counts["modified"] != 2 {
|
||||
t.Fatalf("change to a distinct same-named type was hidden: %+v", r)
|
||||
}
|
||||
}
|
||||
func TestAmbiguousCollisionReportsEveryFileSeparately(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
a, b := filepath.Join(dir, "a"), filepath.Join(dir, "b")
|
||||
write(t, filepath.Join(a, "Message__from_u0041.cs"), `class Message__from_u0041 { int value; }`)
|
||||
write(t, filepath.Join(a, "Message__from_u0042.cs"), `class Message__from_u0042 { int value; }`)
|
||||
write(t, filepath.Join(b, "Message__from_u0043.cs"), `class Message__from_u0043 { int value; }`)
|
||||
write(t, filepath.Join(b, "Message__from_u0044.cs"), `class Message__from_u0044 { int value; }`)
|
||||
output := filepath.Join(dir, "report.txt")
|
||||
if e := sourcetools.RunDiff([]string{"--a", a, "--b", b, "--out", output}, io.Discard); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
r := loadReport(t, output)
|
||||
if len(r.Files) != 4 || r.Counts["added"] != 2 || r.Counts["removed"] != 2 || len(r.Warnings) == 0 {
|
||||
t.Fatalf("ambiguous collision discarded files: %+v", r)
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, f := range r.Files {
|
||||
if seen[f.Path] || f.OldPath != nil && f.NewPath != nil {
|
||||
t.Fatalf("files must retain distinct unpaired identities: %+v", f)
|
||||
}
|
||||
seen[f.Path] = true
|
||||
}
|
||||
}
|
||||
func TestWorkersReportsFilteringErrorsAndHTMLPayload(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
a, b := filepath.Join(dir, "a"), filepath.Join(dir, "b")
|
||||
write(t, filepath.Join(a, "Proto/Net/Changed.cs"), `class C { string x = "</script><script>alert(1)</script>"; }`)
|
||||
write(t, filepath.Join(b, "Proto/Net/Changed.cs"), `class C { string x = "safe"; }`)
|
||||
write(t, filepath.Join(a, "Proto/Net/Bad.cs"), string([]byte{0xff}))
|
||||
write(t, filepath.Join(b, "Proto/Net/Bad.cs"), string([]byte{0xff}))
|
||||
write(t, filepath.Join(a, "Skip.cs"), `class A {}`)
|
||||
write(t, filepath.Join(b, "Skip.cs"), `class B {}`)
|
||||
write(t, filepath.Join(b, "Proto/Net/Empty.cs"), "")
|
||||
output := filepath.Join(dir, "report.txt")
|
||||
args := []string{"--a", a, "--b", b, "--out", output, "--include", "Proto/Net/*", "--exclude", "*Ignore*", "--workers", "1"}
|
||||
if e := sourcetools.RunDiff(args, io.Discard); e == nil {
|
||||
t.Fatal("invalid UTF-8 must fail even when bytes match")
|
||||
}
|
||||
serial := loadReport(t, output)
|
||||
if serial.Counts["modified"] != 1 || serial.Counts["error"] != 1 || serial.Counts["added"] != 1 || len(serial.Files) != 3 {
|
||||
t.Fatalf("filter/error contract failed: %+v", serial)
|
||||
}
|
||||
args[len(args)-1] = "2"
|
||||
if e := sourcetools.RunDiff(args, io.Discard); e == nil {
|
||||
t.Fatal("parallel run must report the same decoding failure")
|
||||
}
|
||||
parallel := loadReport(t, output)
|
||||
if !reflect.DeepEqual(serial, parallel) {
|
||||
t.Fatalf("worker count changed report content: serial=%+v parallel=%+v", serial, parallel)
|
||||
}
|
||||
stem := strings.TrimSuffix(output, ".txt")
|
||||
for _, suffix := range []string{".txt", ".json", ".html", ".diff", ".noise.diff", ".review.diff"} {
|
||||
if _, e := os.Stat(stem + suffix); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
}
|
||||
html := read(t, stem+".html")
|
||||
if strings.Contains(html, "</script><script>alert(1)</script>") || !strings.Contains(html, `\u003c/script\u003e`) || !strings.Contains(html, "source_diff") {
|
||||
t.Fatal("HTML must safely retain the actual source diffs")
|
||||
}
|
||||
}
|
||||
func TestReportOutputRefusesSourceAndUnownedFiles(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
a, b := filepath.Join(dir, "a"), filepath.Join(dir, "b")
|
||||
write(t, filepath.Join(a, "C.cs"), `class C {}`)
|
||||
write(t, filepath.Join(b, "C.cs"), `class C {}`)
|
||||
protected := filepath.Join(dir, "report.diff")
|
||||
write(t, protected, "do not overwrite")
|
||||
if e := sourcetools.RunDiff([]string{"--a", a, "--b", b, "--out", filepath.Join(dir, "report.txt")}, io.Discard); e == nil {
|
||||
t.Fatal("non-managed companion report must not be overwritten")
|
||||
}
|
||||
if read(t, protected) != "do not overwrite" {
|
||||
t.Fatal("protected file was modified")
|
||||
}
|
||||
if e := sourcetools.RunDiff([]string{"--a", a, "--b", b, "--out", filepath.Join(a, "report.txt")}, io.Discard); e == nil {
|
||||
t.Fatal("report inside source must be rejected")
|
||||
}
|
||||
var help bytes.Buffer
|
||||
if e := sourcetools.RunDiff([]string{"--help"}, &help); e != nil || !strings.Contains(help.String(), "include") {
|
||||
t.Fatalf("--help should work without input/config: %v %s", e, help.String())
|
||||
}
|
||||
}
|
||||
func TestDeobfuscationPreservesPayloadEncodingSourcesAndMappingAmbiguity(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
source, output, mapping := filepath.Join(dir, "source"), filepath.Join(dir, "mirror"), filepath.Join(dir, "map.obfuscate")
|
||||
original := `class Ω { Ω Ω2; Π Π3; Ж unresolved; string value = "Ω Π Ж"; string raw = """Ω // Π"""; // Ω Π Ж
|
||||
/* Ω Π Ж */ }`
|
||||
write(t, filepath.Join(source, "Ω.cs"), original)
|
||||
write(t, filepath.Join(source, "Π.cs"), `class Π {}`)
|
||||
write(t, filepath.Join(source, "Player.cs"), `class Existing {}`)
|
||||
write(t, filepath.Join(source, "bytes.bin"), string([]byte{1, 2, 3}))
|
||||
write(t, mapping, "\ufeff#ReverseOrder\nΩ⇨Net.Player\nΠ⇨Player\nЖ⇨One\nЖ⇨Two\ninvalid line\n")
|
||||
// A UTF-16 input retains its byte order marker after translating tokens.
|
||||
words := utf16.Encode([]rune(`class Ψ { Ω value; }`))
|
||||
encoded := make([]byte, 2+len(words)*2)
|
||||
encoded[0], encoded[1] = 0xfe, 0xff
|
||||
for i, w := range words {
|
||||
binary.BigEndian.PutUint16(encoded[2+i*2:], w)
|
||||
}
|
||||
if e := os.WriteFile(filepath.Join(source, "Utf16.cs"), encoded, 0644); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
args := []string{"--source", source, "--mapping", mapping, "--output", output}
|
||||
if e := sourcetools.RunDeobfuscate(args, io.Discard); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
translated := read(t, filepath.Join(output, "Player__file_2.cs"))
|
||||
if !strings.Contains(translated, "class Player") || !strings.Contains(translated, "Player Player2") || !strings.Contains(translated, "Player__from_u03A0 Player__from_u03A03") || !strings.Contains(translated, "Ж unresolved") || !strings.Contains(translated, `"Ω Π Ж"`) || !strings.Contains(translated, `"""Ω // Π"""`) || !strings.Contains(translated, "// Ω Π Ж") {
|
||||
t.Fatal("mapping or literal semantics lost: " + translated)
|
||||
}
|
||||
if read(t, filepath.Join(source, "Ω.cs")) != original {
|
||||
t.Fatal("source modified")
|
||||
}
|
||||
if read(t, filepath.Join(output, "bytes.bin")) != string([]byte{1, 2, 3}) {
|
||||
t.Fatal("non-code copy changed")
|
||||
}
|
||||
actual, e := os.ReadFile(filepath.Join(output, "Utf16.cs"))
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if len(actual) < 2 || actual[0] != 0xfe || actual[1] != 0xff {
|
||||
t.Fatal("UTF-16 BOM lost")
|
||||
}
|
||||
var manifest struct {
|
||||
Warnings []string
|
||||
Files []struct{ Source, Output string }
|
||||
Statistics map[string]int
|
||||
}
|
||||
if e = json.Unmarshal([]byte(read(t, filepath.Join(output, ".bd2-deobfuscate-manifest.json"))), &manifest); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if len(manifest.Files) != 5 || len(manifest.Warnings) < 2 || manifest.Statistics["derived_identifier_replacements"] != 2 {
|
||||
t.Fatalf("manifest must expose ambiguity and derived token replacements: %+v", manifest)
|
||||
}
|
||||
write(t, filepath.Join(source, "Ω.cs"), `class Ω { int newField; }`)
|
||||
if e = sourcetools.RunDeobfuscate(args, io.Discard); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if !strings.Contains(read(t, filepath.Join(output, "Player__file_2.cs")), "newField") {
|
||||
t.Fatal("managed mirror was not republished")
|
||||
}
|
||||
}
|
||||
func TestDeobfuscationRefusesOverlappingAndUnownedOutput(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
source, mapping := filepath.Join(dir, "source"), filepath.Join(dir, "map.obfuscate")
|
||||
write(t, filepath.Join(source, "Ω.cs"), `class Ω {}`)
|
||||
write(t, mapping, "Ω⇨Player\n")
|
||||
unowned := filepath.Join(dir, "output")
|
||||
write(t, filepath.Join(unowned, "keep.txt"), "owned by user")
|
||||
args := []string{"--source", source, "--mapping", mapping, "--output", unowned}
|
||||
if e := sourcetools.RunDeobfuscate(args, io.Discard); e == nil {
|
||||
t.Fatal("unowned directory must be protected")
|
||||
}
|
||||
if read(t, filepath.Join(unowned, "keep.txt")) != "owned by user" {
|
||||
t.Fatal("unowned output changed")
|
||||
}
|
||||
args[len(args)-1] = filepath.Join(source, "mirror")
|
||||
if e := sourcetools.RunDeobfuscate(args, io.Discard); e == nil {
|
||||
t.Fatal("output nested in input must be rejected")
|
||||
}
|
||||
args[len(args)-1] = dir
|
||||
if e := sourcetools.RunDeobfuscate(args, io.Discard); e == nil {
|
||||
t.Fatal("output containing source must be rejected")
|
||||
}
|
||||
var help bytes.Buffer
|
||||
if e := sourcetools.RunDeobfuscate([]string{"--help"}, &help); e != nil || !strings.Contains(help.String(), "mapping") {
|
||||
t.Fatalf("standalone help failed: %v %s", e, help.String())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,347 @@
|
||||
package sourcetools
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Python-style globs match slashes as ordinary characters.
|
||||
func glob(pattern, value string) bool {
|
||||
var b strings.Builder
|
||||
b.WriteByte('^')
|
||||
for i := 0; i < len(pattern); i++ {
|
||||
c := pattern[i]
|
||||
switch c {
|
||||
case '*':
|
||||
b.WriteString(".*")
|
||||
case '?':
|
||||
b.WriteByte('.')
|
||||
case '[':
|
||||
j := i + 1
|
||||
for j < len(pattern) && pattern[j] != ']' {
|
||||
j++
|
||||
}
|
||||
if j < len(pattern) {
|
||||
class := pattern[i+1 : j]
|
||||
if strings.HasPrefix(class, "!") {
|
||||
class = "^" + class[1:]
|
||||
}
|
||||
b.WriteByte('[')
|
||||
b.WriteString(class)
|
||||
b.WriteByte(']')
|
||||
i = j
|
||||
} else {
|
||||
b.WriteString(`\[`)
|
||||
}
|
||||
default:
|
||||
b.WriteString(regexp.QuoteMeta(string(c)))
|
||||
}
|
||||
}
|
||||
b.WriteByte('$')
|
||||
r, e := regexp.Compile(b.String())
|
||||
return e == nil && r.MatchString(value)
|
||||
}
|
||||
func inventory(root string, includes, excludes []string) ([]string, error) {
|
||||
found := []string{}
|
||||
skip := wordSet("bin obj .git .vs __pycache__")
|
||||
e := filepath.WalkDir(root, func(p string, d os.DirEntry, e error) error {
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if d.Type()&os.ModeSymlink != 0 {
|
||||
return fmt.Errorf("source contains symbolic link: %s", p)
|
||||
}
|
||||
if d.IsDir() {
|
||||
if skip[d.Name()] {
|
||||
return filepath.SkipDir
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if !strings.EqualFold(filepath.Ext(p), ".cs") {
|
||||
return nil
|
||||
}
|
||||
rel, e := filepath.Rel(root, p)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
rel = filepath.ToSlash(rel)
|
||||
logical := suffixPattern.ReplaceAllString(rel, "")
|
||||
included := len(includes) == 0
|
||||
for _, pat := range includes {
|
||||
included = included || glob(pat, logical)
|
||||
}
|
||||
if !included {
|
||||
return nil
|
||||
}
|
||||
for _, pat := range excludes {
|
||||
if glob(pat, logical) {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
found = append(found, rel)
|
||||
return nil
|
||||
})
|
||||
sort.Strings(found)
|
||||
return found, e
|
||||
}
|
||||
|
||||
type fileTask struct{ logical, old, new string }
|
||||
|
||||
func pairTrees(a, b string, ia, ib []string) ([]fileTask, map[string]string, map[string]string, []string) {
|
||||
ga, gb := map[string][]string{}, map[string][]string{}
|
||||
for _, p := range ia {
|
||||
logical := suffixPattern.ReplaceAllString(p, "")
|
||||
ga[logical] = append(ga[logical], p)
|
||||
}
|
||||
for _, p := range ib {
|
||||
logical := suffixPattern.ReplaceAllString(p, "")
|
||||
gb[logical] = append(gb[logical], p)
|
||||
}
|
||||
tasks := []fileTask{}
|
||||
symbolsA, symbolsB := map[string]string{}, map[string]string{}
|
||||
warnings := []string{}
|
||||
appendTask := func(logical, old, new string) {
|
||||
tasks = append(tasks, fileTask{logical, old, new})
|
||||
name := strings.TrimSuffix(filepath.Base(logical), filepath.Ext(logical))
|
||||
for i, p := range []string{old, new} {
|
||||
stem := strings.TrimSuffix(filepath.Base(p), filepath.Ext(p))
|
||||
if p != "" && suffixPattern.MatchString(stem) {
|
||||
symbols := symbolsA
|
||||
if i == 1 {
|
||||
symbols = symbolsB
|
||||
}
|
||||
symbols[stem] = name
|
||||
}
|
||||
}
|
||||
}
|
||||
shapeCache := map[string]map[string]bool{}
|
||||
shape := func(root, rel string) map[string]bool {
|
||||
cacheKey := filepath.Join(root, rel)
|
||||
if s, ok := shapeCache[cacheKey]; ok {
|
||||
return s
|
||||
}
|
||||
text, _, e := readSource(cacheKey)
|
||||
if e != nil {
|
||||
shapeCache[cacheKey] = nil
|
||||
return nil
|
||||
}
|
||||
s := map[string]bool{}
|
||||
for _, m := range splitMembers(tokenize(text, nil)) {
|
||||
s[generated(m.key)] = true
|
||||
}
|
||||
shapeCache[cacheKey] = s
|
||||
return s
|
||||
}
|
||||
fingerprint := func(s map[string]bool) string {
|
||||
if s == nil {
|
||||
return ""
|
||||
}
|
||||
keys := []string{}
|
||||
for k := range s {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
return strings.Join(keys, "\x00")
|
||||
}
|
||||
logicals := map[string]bool{}
|
||||
for k := range ga {
|
||||
logicals[k] = true
|
||||
}
|
||||
for k := range gb {
|
||||
logicals[k] = true
|
||||
}
|
||||
ordered := []string{}
|
||||
for k := range logicals {
|
||||
ordered = append(ordered, k)
|
||||
}
|
||||
sort.Strings(ordered)
|
||||
sortedSet := func(s map[string]bool) []string {
|
||||
r := []string{}
|
||||
for k := range s {
|
||||
r = append(r, k)
|
||||
}
|
||||
sort.Strings(r)
|
||||
return r
|
||||
}
|
||||
for _, logical := range ordered {
|
||||
left, right := map[string]bool{}, map[string]bool{}
|
||||
for _, p := range ga[logical] {
|
||||
left[p] = true
|
||||
}
|
||||
for _, p := range gb[logical] {
|
||||
right[p] = true
|
||||
}
|
||||
collision := len(left) > 1 || len(right) > 1
|
||||
for _, p := range sortedSet(left) {
|
||||
if right[p] {
|
||||
key := logical
|
||||
if collision {
|
||||
key = p
|
||||
}
|
||||
appendTask(key, p, p)
|
||||
delete(left, p)
|
||||
delete(right, p)
|
||||
}
|
||||
}
|
||||
if !collision {
|
||||
if len(left)+len(right) > 0 {
|
||||
old, new := "", ""
|
||||
for p := range left {
|
||||
old = p
|
||||
}
|
||||
for p := range right {
|
||||
new = p
|
||||
}
|
||||
appendTask(logical, old, new)
|
||||
}
|
||||
continue
|
||||
}
|
||||
sa, sb := map[string][]string{}, map[string][]string{}
|
||||
for _, p := range sortedSet(left) {
|
||||
key := fingerprint(shape(a, p))
|
||||
sa[key] = append(sa[key], p)
|
||||
}
|
||||
for _, p := range sortedSet(right) {
|
||||
key := fingerprint(shape(b, p))
|
||||
sb[key] = append(sb[key], p)
|
||||
}
|
||||
variant := 0
|
||||
variantKey := func() string {
|
||||
variant++
|
||||
ext := filepath.Ext(logical)
|
||||
return strings.TrimSuffix(logical, ext) + fmt.Sprintf("__variant_%d", variant) + ext
|
||||
}
|
||||
fps := []string{}
|
||||
for key := range sa {
|
||||
if key != "" && len(sa[key]) == 1 && len(sb[key]) == 1 {
|
||||
fps = append(fps, key)
|
||||
}
|
||||
}
|
||||
sort.Strings(fps)
|
||||
for _, key := range fps {
|
||||
old, new := sa[key][0], sb[key][0]
|
||||
appendTask(variantKey(), old, new)
|
||||
delete(left, old)
|
||||
delete(right, new)
|
||||
}
|
||||
type candidate struct {
|
||||
score float64
|
||||
old, new string
|
||||
}
|
||||
candidates := []candidate{}
|
||||
for _, old := range sortedSet(left) {
|
||||
fa := shape(a, old)
|
||||
for _, new := range sortedSet(right) {
|
||||
fb := shape(b, new)
|
||||
if len(fa) == 0 || len(fb) == 0 {
|
||||
continue
|
||||
}
|
||||
inter := 0
|
||||
for k := range fa {
|
||||
if fb[k] {
|
||||
inter++
|
||||
}
|
||||
}
|
||||
score := float64(inter) / float64(len(fa)+len(fb)-inter)
|
||||
if score >= .85 {
|
||||
candidates = append(candidates, candidate{score, old, new})
|
||||
}
|
||||
}
|
||||
}
|
||||
sort.Slice(candidates, func(i, j int) bool {
|
||||
if candidates[i].score != candidates[j].score {
|
||||
return candidates[i].score > candidates[j].score
|
||||
}
|
||||
if candidates[i].old != candidates[j].old {
|
||||
return candidates[i].old > candidates[j].old
|
||||
}
|
||||
return candidates[i].new > candidates[j].new
|
||||
})
|
||||
for _, c := range candidates {
|
||||
if !left[c.old] || !right[c.new] {
|
||||
continue
|
||||
}
|
||||
rival := float64(-1)
|
||||
for _, other := range candidates {
|
||||
if (other.old == c.old || other.new == c.new) && (other.old != c.old || other.new != c.new) {
|
||||
rival = max(rival, other.score)
|
||||
}
|
||||
}
|
||||
if rival >= 0 && c.score-rival < .15 {
|
||||
continue
|
||||
}
|
||||
appendTask(variantKey(), c.old, c.new)
|
||||
delete(left, c.old)
|
||||
delete(right, c.new)
|
||||
}
|
||||
if len(left) == 1 && len(right) == 1 {
|
||||
old, new := sortedSet(left)[0], sortedSet(right)[0]
|
||||
appendTask(variantKey(), old, new)
|
||||
delete(left, old)
|
||||
delete(right, new)
|
||||
}
|
||||
for i, remainder := range []map[string]bool{left, right} {
|
||||
side := "old"
|
||||
if i == 1 {
|
||||
side = "new"
|
||||
}
|
||||
for _, p := range sortedSet(remainder) {
|
||||
warnings = append(warnings, fmt.Sprintf("同名类型未能唯一配对,保留为%s独立文件: %s", side, p))
|
||||
tag := sha256.Sum256([]byte(p))
|
||||
ext := filepath.Ext(logical)
|
||||
key := strings.TrimSuffix(logical, ext) + fmt.Sprintf("__unpaired_%s_%x", side, tag[:6]) + ext
|
||||
old, new := p, ""
|
||||
if i == 1 {
|
||||
old, new = "", p
|
||||
}
|
||||
appendTask(key, old, new)
|
||||
}
|
||||
}
|
||||
}
|
||||
sort.Slice(tasks, func(i, j int) bool { return tasks[i].logical < tasks[j].logical })
|
||||
return tasks, symbolsA, symbolsB, warnings
|
||||
}
|
||||
func compareFile(a, b string, t fileTask, context int, strict bool, symbolsA, symbolsB map[string]string) fileResult {
|
||||
result := fileResult{Path: t.logical, Status: "unchanged", Members: []diffEntry{}, Noise: []diffEntry{}}
|
||||
if t.old != "" {
|
||||
p := t.old
|
||||
result.OldPath = &p
|
||||
}
|
||||
if t.new != "" {
|
||||
p := t.new
|
||||
result.NewPath = &p
|
||||
}
|
||||
old, new := "", ""
|
||||
var err error
|
||||
if t.old != "" {
|
||||
old, _, err = readSource(filepath.Join(a, t.old))
|
||||
}
|
||||
if err == nil && t.new != "" {
|
||||
new, _, err = readSource(filepath.Join(b, t.new))
|
||||
}
|
||||
if err != nil {
|
||||
result.Status = "error"
|
||||
result.Error = err.Error()
|
||||
return result
|
||||
}
|
||||
if t.old == "" || t.new == "" {
|
||||
result.Status = "added"
|
||||
oldName, newName := t.old, t.new
|
||||
if t.new == "" {
|
||||
result.Status = "removed"
|
||||
newName = "/dev/null"
|
||||
} else {
|
||||
oldName = "/dev/null"
|
||||
}
|
||||
result.Members = append(result.Members, diffEntry{Name: "整个文件", Kind: result.Status, Diff: unified(render(tokenize(old, symbolsA)), render(tokenize(new, symbolsB)), oldName, newName, context)})
|
||||
return result
|
||||
}
|
||||
compared := compareText(old, new, context, strict, symbolsA, symbolsB)
|
||||
compared.Path, compared.OldPath, compared.NewPath = result.Path, result.OldPath, result.NewPath
|
||||
return compared
|
||||
}
|
||||
@@ -3,17 +3,23 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"bd2server/internal/client/iconresource"
|
||||
clientlayout "bd2server/internal/client/layout"
|
||||
clientplugin "bd2server/internal/client/plugin"
|
||||
"bd2server/internal/common/taskgraph"
|
||||
)
|
||||
|
||||
type clientDevelopmentConfig struct {
|
||||
@@ -37,7 +43,7 @@ var runDevelopmentChild = func(root string, args []string) error {
|
||||
// `production`, retaining the embedded frontend and normal native host while
|
||||
// the project-level --dev option supplies development paths and plugin builds.
|
||||
func relaunchDevelopmentIfNeeded(args []string) (bool, error) {
|
||||
if len(args) == 0 || args[0] != "--dev" || wailsDevelopmentBuild {
|
||||
if len(args) == 0 || args[0] != "--dev" || slices.Contains(args, "--plan") {
|
||||
return false, nil
|
||||
}
|
||||
if len(args) < 2 || args[1] != "run" {
|
||||
@@ -47,50 +53,104 @@ func relaunchDevelopmentIfNeeded(args []string) (bool, error) {
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
childArgs := []string{"run", "-tags", "production", "./cmd/bd2client", "--dev", "run"}
|
||||
childArgs = append(childArgs, args[2:]...)
|
||||
if err := runDevelopmentChild(root, childArgs); err != nil {
|
||||
return false, fmt.Errorf("run Wails development client: %w", err)
|
||||
var changed, relaunched bool
|
||||
graph, err := taskgraph.New(
|
||||
taskgraph.Task{Name: "client:icon", Run: func(context.Context) error {
|
||||
var err error
|
||||
changed, err = iconresource.Generate(root, runtime.GOOS, runtime.GOARCH)
|
||||
return err
|
||||
}},
|
||||
taskgraph.Task{Name: "client:backend", DependsOn: []string{"client:icon"}, Run: func(context.Context) error {
|
||||
if wailsDevelopmentBuild && !changed {
|
||||
return nil
|
||||
}
|
||||
childArgs := []string{"run", "-tags", "production", "./cmd/bd2client", "--dev", "run"}
|
||||
childArgs = append(childArgs, args[2:]...)
|
||||
if err := runDevelopmentChild(root, childArgs); err != nil {
|
||||
return fmt.Errorf("run Wails development client: %w", err)
|
||||
}
|
||||
relaunched = true
|
||||
return nil
|
||||
}},
|
||||
)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return true, nil
|
||||
err = graph.Run(context.Background(), "client:backend")
|
||||
return relaunched, err
|
||||
}
|
||||
|
||||
func developmentRunOptions(args []string) ([]string, clientRunOptions, error) {
|
||||
func runClientDevelopmentCommand(args []string) (bool, error) {
|
||||
if len(args) == 0 || args[0] != "--dev" {
|
||||
return args, clientRunOptions{}, nil
|
||||
return false, nil
|
||||
}
|
||||
if len(args) < 2 || args[1] != "run" {
|
||||
return nil, clientRunOptions{}, errors.New("usage: bd2client --dev run [client options]")
|
||||
return true, errors.New("usage: bd2client --dev run [--plan] [client options]")
|
||||
}
|
||||
root, err := findClientDevelopmentRoot()
|
||||
if err != nil {
|
||||
return nil, clientRunOptions{}, err
|
||||
}
|
||||
clientArgs := append([]string(nil), args[2:]...)
|
||||
gameDir, err := clientDevelopmentGameDirectory(clientArgs)
|
||||
if err != nil {
|
||||
return nil, clientRunOptions{}, err
|
||||
}
|
||||
if gameDir == "" {
|
||||
config, configErr := loadClientDevelopmentConfig(filepath.Join(root, "go", "config.json"))
|
||||
if configErr != nil {
|
||||
return nil, clientRunOptions{}, configErr
|
||||
}
|
||||
gameDir = config.GameDirectory
|
||||
}
|
||||
if gameDir != "" {
|
||||
if err := buildDevelopmentPlugins(root, gameDir); err != nil {
|
||||
return nil, clientRunOptions{}, err
|
||||
planOnly := false
|
||||
clientArgs := make([]string, 0, len(args)-2)
|
||||
for _, arg := range args[2:] {
|
||||
if arg == "--plan" {
|
||||
planOnly = true
|
||||
} else {
|
||||
clientArgs = append(clientArgs, arg)
|
||||
}
|
||||
}
|
||||
return clientArgs, clientRunOptions{
|
||||
versionConfigPath: filepath.Join(root, "versions.json"),
|
||||
logExecutablePath: filepath.Join(root, "data", "bd2client-dev"),
|
||||
localIdentityPlugin: filepath.Join(root, "plugins", "LocalIdentity", "bin", "Release", "netstandard2.1", "BD2LocalIdentity.dll"),
|
||||
loginUIPlugin: filepath.Join(root, "plugins", "LoginUI", "bin", "Release", "netstandard2.1", "BD2LoginUI.dll"),
|
||||
cashShopPlugin: filepath.Join(root, "plugins", "CashShop", "bin", "Release", "netstandard2.1", "BD2CashShop.dll"),
|
||||
fChatPlugin: filepath.Join(root, "plugins", "FChat", "bin", "Release", "netstandard2.1", "BD2FChat.dll"),
|
||||
}, nil
|
||||
var root, gameDir string
|
||||
var options clientRunOptions
|
||||
graph, err := taskgraph.New(
|
||||
taskgraph.Task{Name: "client:configuration", Run: func(context.Context) error {
|
||||
var err error
|
||||
root, err = findClientDevelopmentRoot()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
gameDir, err = clientDevelopmentGameDirectory(clientArgs)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if gameDir == "" {
|
||||
config, err := loadClientDevelopmentConfig(filepath.Join(root, "go", "config.json"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
gameDir = config.GameDirectory
|
||||
}
|
||||
return nil
|
||||
}},
|
||||
taskgraph.Task{Name: "client:plugins", DependsOn: []string{"client:configuration"}, Run: func(ctx context.Context) error {
|
||||
if gameDir == "" {
|
||||
return nil
|
||||
}
|
||||
return buildDevelopmentPlugins(ctx, root, gameDir)
|
||||
}},
|
||||
taskgraph.Task{Name: "client:options", DependsOn: []string{"client:plugins"}, Run: func(context.Context) error {
|
||||
options = clientRunOptions{
|
||||
versionConfigPath: filepath.Join(root, "versions.json"),
|
||||
logExecutablePath: filepath.Join(root, "data", "bd2client-dev"),
|
||||
localIdentityPlugin: filepath.Join(root, "plugins", "LocalIdentity", "bin", "Release", "netstandard2.1", "BD2LocalIdentity.dll"),
|
||||
loginUIPlugin: filepath.Join(root, "plugins", "LoginUI", "bin", "Release", "netstandard2.1", "BD2LoginUI.dll"),
|
||||
cashShopPlugin: filepath.Join(root, "plugins", "CashShop", "bin", "Release", "netstandard2.1", "BD2CashShop.dll"),
|
||||
fChatPlugin: filepath.Join(root, "plugins", "FChat", "bin", "Release", "netstandard2.1", "BD2FChat.dll"),
|
||||
}
|
||||
return nil
|
||||
}},
|
||||
taskgraph.Task{Name: "runClient", DependsOn: []string{"client:options"}, Run: func(context.Context) error { return runClient(clientArgs, options) }},
|
||||
)
|
||||
if err != nil {
|
||||
return true, err
|
||||
}
|
||||
if planOnly {
|
||||
plan, err := graph.Plan("runClient")
|
||||
if err != nil {
|
||||
return true, err
|
||||
}
|
||||
fmt.Println(strings.Join(plan, " -> "))
|
||||
return true, nil
|
||||
}
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
|
||||
defer stop()
|
||||
return true, graph.Run(ctx, "runClient")
|
||||
}
|
||||
|
||||
func loadClientDevelopmentConfig(path string) (clientDevelopmentConfig, error) {
|
||||
@@ -166,7 +226,7 @@ func clientDevelopmentGameDirectory(args []string) (string, error) {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
func buildDevelopmentPlugins(root, gameDir string) error {
|
||||
func buildDevelopmentPlugins(ctx context.Context, root, gameDir string) error {
|
||||
installation, err := clientlayout.Resolve(gameDir)
|
||||
if err != nil {
|
||||
return nil
|
||||
@@ -175,5 +235,5 @@ func buildDevelopmentPlugins(root, gameDir string) error {
|
||||
return nil
|
||||
}
|
||||
fmt.Fprintln(os.Stderr, "bd2client: preparing four development plugins; cached inputs will be reused")
|
||||
return clientplugin.BuildDevelopment(root, gameDir, os.Stderr)
|
||||
return clientplugin.BuildDevelopment(ctx, root, gameDir, os.Stderr)
|
||||
}
|
||||
@@ -4,6 +4,4 @@ package main
|
||||
|
||||
func relaunchDevelopmentIfNeeded([]string) (bool, error) { return false, nil }
|
||||
|
||||
func developmentRunOptions(args []string) ([]string, clientRunOptions, error) {
|
||||
return args, clientRunOptions{}, nil
|
||||
}
|
||||
func runClientDevelopmentCommand([]string) (bool, error) { return false, nil }
|
||||
@@ -0,0 +1,17 @@
|
||||
//go:build !release
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDevelopmentPlanSkipsBackendRebuildAndPluginPreparation(t *testing.T) {
|
||||
args := []string{"--dev", "run", "--plan", "--game-dir", t.TempDir()}
|
||||
if relaunched, err := relaunchDevelopmentIfNeeded(args); relaunched || err != nil {
|
||||
t.Fatalf("inspection rebuilt the desktop backend: %v, %v", relaunched, err)
|
||||
}
|
||||
if handled, err := runClientDevelopmentCommand(args); !handled || err != nil {
|
||||
t.Fatalf("inspection attempted to prepare an incomplete game or start its UI: %v, %v", handled, err)
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,16 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/signal"
|
||||
|
||||
clientapp "bd2server/internal/client/app"
|
||||
clientconfig "bd2server/internal/client/config"
|
||||
"bd2server/internal/client/download"
|
||||
"bd2server/internal/common/versionconfig"
|
||||
)
|
||||
|
||||
type clientRunOptions struct {
|
||||
@@ -19,6 +23,15 @@ type clientRunOptions struct {
|
||||
}
|
||||
|
||||
func main() {
|
||||
if len(os.Args) > 1 && os.Args[1] == "download-resources" {
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
|
||||
defer stop()
|
||||
if err := download.RunResources(ctx, os.Args[2:], os.Stdout); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "bd2client download-resources:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
return
|
||||
}
|
||||
if len(os.Args) > 1 && os.Args[1] == "prepare" {
|
||||
if err := prepareClient(os.Args[2:]); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "bd2client prepare:", err)
|
||||
@@ -35,9 +48,9 @@ func main() {
|
||||
if relaunched {
|
||||
return
|
||||
}
|
||||
args, options, err := developmentRunOptions(os.Args[1:])
|
||||
if err == nil {
|
||||
err = runClient(args, options)
|
||||
handled, err := runClientDevelopmentCommand(os.Args[1:])
|
||||
if !handled && err == nil {
|
||||
err = runClient(os.Args[1:], clientRunOptions{})
|
||||
}
|
||||
if err != nil {
|
||||
clientapp.ShowFatalError(err)
|
||||
@@ -63,11 +76,11 @@ func runClient(args []string, options clientRunOptions) error {
|
||||
defer func() { _ = logCloser.Close() }()
|
||||
logger.Info("bd2client starting", "log_path", logPath)
|
||||
|
||||
var versions clientconfig.ReleaseVersions
|
||||
var versions versionconfig.Config
|
||||
if options.versionConfigPath == "" {
|
||||
versions, err = clientconfig.ReleaseVersionsBesideExecutable()
|
||||
} else {
|
||||
versions, err = clientconfig.LoadReleaseVersions(options.versionConfigPath)
|
||||
versions, err = versionconfig.Load(options.versionConfigPath)
|
||||
}
|
||||
if err != nil {
|
||||
logger.Error("client release version manifest is invalid", "error", err)
|
||||
|
||||
+136
-19
@@ -2,12 +2,21 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
clientconfig "bd2server/internal/client/config"
|
||||
"bd2server/internal/client/download"
|
||||
clientsetup "bd2server/internal/client/setup"
|
||||
commonconfig "bd2server/internal/common/config"
|
||||
"bd2server/internal/common/taskgraph"
|
||||
"bd2server/internal/common/versionconfig"
|
||||
)
|
||||
|
||||
func prepareClient(args []string) error {
|
||||
@@ -15,35 +24,143 @@ func prepareClient(args []string) error {
|
||||
gameDir := fs.String("game-dir", "", "game installation directory")
|
||||
origin := fs.String("server-origin", "", "game server HTTPS origin")
|
||||
resources := fs.String("resource-dir", "", "directory containing ServerData and GameData")
|
||||
downloadOnly := fs.Bool("download", false, "only download and extract the game and resources")
|
||||
baseOnly := fs.Bool("base", false, "only initialize BepInEx, plugins, connection settings and launcher preferences")
|
||||
packageDir := fs.String("package-dir", "", "client package with plugins, BepInEx ZIP and versions; defaults beside bd2client")
|
||||
versionPath := fs.String("version-config", "", "versions.json override")
|
||||
manifest := fs.String("manifest", "", "download metadata; defaults to <package-dir>/client-download.json")
|
||||
workers := fs.Int("workers", 8, "parallel resource downloads (1-16)")
|
||||
probeOnly := fs.Bool("probe-only", false, "measure download origins without changing the installation")
|
||||
planOnly := fs.Bool("plan", false, "show ordered dependencies without running any stage")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
if errors.Is(err, flag.ErrHelp) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
if fs.NArg() != 0 || *gameDir == "" || *origin == "" || *resources == "" {
|
||||
return fmt.Errorf("prepare requires --game-dir, --server-origin and --resource-dir")
|
||||
if fs.NArg() != 0 || *workers < 1 || *workers > 16 {
|
||||
return errors.New("prepare accepts named options and workers must be 1-16")
|
||||
}
|
||||
versions, err := clientconfig.ReleaseVersionsBesideExecutable()
|
||||
if *downloadOnly && *baseOnly {
|
||||
return errors.New("--download and --base select separate stages; omit both to run all stages")
|
||||
}
|
||||
if *baseOnly && *probeOnly {
|
||||
return errors.New("--probe-only cannot be used with --base")
|
||||
}
|
||||
if *packageDir == "" {
|
||||
executable, err := os.Executable()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
*packageDir = filepath.Dir(executable)
|
||||
}
|
||||
var err error
|
||||
*packageDir, err = filepath.Abs(*packageDir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
settings, err := clientconfig.Normalize(clientconfig.Settings{ServerOrigin: *origin, CDNMode: clientconfig.CDNLocal, LocalResourceDirectory: *resources})
|
||||
if *versionPath == "" {
|
||||
*versionPath = filepath.Join(*packageDir, versionconfig.FileName)
|
||||
}
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
|
||||
defer stop()
|
||||
var versions, downloaded versionconfig.Config
|
||||
var settings clientconfig.Settings
|
||||
graph, err := taskgraph.New(
|
||||
taskgraph.Task{Name: "download", Run: func(ctx context.Context) error {
|
||||
installed, err := download.Client(ctx, download.Options{
|
||||
PackageDir: *packageDir, Manifest: *manifest,
|
||||
GameDir: *gameDir, ResourceDir: *resources, ServerOrigin: *origin,
|
||||
Workers: *workers, ProbeOnly: *probeOnly,
|
||||
}, os.Stdout)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
*gameDir, *resources, *origin = installed.GameDir, installed.ResourceDir, installed.ServerOrigin
|
||||
downloaded = installed.Versions
|
||||
return nil
|
||||
}},
|
||||
taskgraph.Task{Name: "base:configuration", Run: func(context.Context) error {
|
||||
if *gameDir == "" {
|
||||
*gameDir = filepath.Join(*packageDir, "game")
|
||||
}
|
||||
if *resources == "" {
|
||||
*resources = filepath.Join(*packageDir, "resources")
|
||||
}
|
||||
if *origin == "" {
|
||||
manifestPath := *manifest
|
||||
if manifestPath == "" {
|
||||
manifestPath = filepath.Join(*packageDir, "client-download.json")
|
||||
}
|
||||
defaults, err := commonconfig.Load(manifestPath, struct {
|
||||
ServerOrigin string `json:"server_origin"`
|
||||
}{}, commonconfig.DecodeOptions{AllowBOM: true, RejectTrailing: true})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
*origin = defaults.ServerOrigin
|
||||
}
|
||||
var err error
|
||||
versions, err = versionconfig.Load(*versionPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !*baseOnly && (versions.GameVersion != downloaded.GameVersion || versions.GameDataVersion != downloaded.GameDataVersion || versions.BundleVersion != downloaded.BundleVersion) {
|
||||
return errors.New("client package and download manifest versions differ")
|
||||
}
|
||||
return nil
|
||||
}},
|
||||
taskgraph.Task{Name: "base:settings", DependsOn: []string{"base:configuration"}, Run: func(context.Context) error {
|
||||
var err error
|
||||
settings, err = clientconfig.Normalize(clientconfig.Settings{ServerOrigin: *origin, CDNMode: clientconfig.CDNLocal, LocalResourceDirectory: *resources})
|
||||
return err
|
||||
}},
|
||||
taskgraph.Task{Name: "base:resources", DependsOn: []string{"base:settings"}, Run: func(ctx context.Context) error {
|
||||
policyContext, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||||
defer cancel()
|
||||
_, err := clientsetup.FetchResourcePolicy(policyContext, nil, settings, versions)
|
||||
return err
|
||||
}},
|
||||
taskgraph.Task{Name: "base:bepinex", DependsOn: []string{"base:resources"}, Run: func(context.Context) error {
|
||||
return download.InstallBepInEx(*packageDir, *gameDir)
|
||||
}},
|
||||
taskgraph.Task{Name: "base:patch", DependsOn: []string{"base:bepinex"}, Run: func(context.Context) error {
|
||||
_, err := clientsetup.Patch(*gameDir, settings, versions)
|
||||
return err
|
||||
}},
|
||||
taskgraph.Task{Name: "base:plugins", DependsOn: []string{"base:patch"}, Run: func(context.Context) error {
|
||||
plugins := filepath.Join(*packageDir, "plugins")
|
||||
_, err := clientsetup.InstallPlugins(*gameDir, settings, versions,
|
||||
filepath.Join(plugins, "BD2LocalIdentity.dll"), filepath.Join(plugins, "BD2LoginUI.dll"),
|
||||
filepath.Join(plugins, "BD2CashShop.dll"), filepath.Join(plugins, "BD2FChat.dll"))
|
||||
return err
|
||||
}},
|
||||
taskgraph.Task{Name: "base:preferences", DependsOn: []string{"base:plugins"}, Run: func(context.Context) error {
|
||||
return clientconfig.SavePreferences(*gameDir)
|
||||
}},
|
||||
taskgraph.Task{Name: "base", DependsOn: []string{"base:preferences"}, Run: func(context.Context) error {
|
||||
fmt.Println("Client prepared:", versions.GameVersion)
|
||||
fmt.Println("Server:", settings.ServerOrigin)
|
||||
return nil
|
||||
}},
|
||||
taskgraph.Task{Name: "prepare", DependsOn: []string{"download", "base"}},
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
if _, err := clientsetup.FetchResourcePolicy(ctx, nil, settings, versions); err != nil {
|
||||
return err
|
||||
target := "prepare"
|
||||
if *downloadOnly || *probeOnly {
|
||||
target = "download"
|
||||
} else if *baseOnly {
|
||||
target = "base"
|
||||
}
|
||||
if _, err := clientsetup.Patch(*gameDir, settings, versions); err != nil {
|
||||
return err
|
||||
if *planOnly {
|
||||
plan, err := graph.Plan(target)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Println(strings.Join(plan, " -> "))
|
||||
return nil
|
||||
}
|
||||
if _, err := clientsetup.InstallPlugins(*gameDir, settings, versions, "", "", "", ""); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := clientconfig.SavePreferences(*gameDir); err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Println("Client prepared:", versions.GameVersion)
|
||||
fmt.Println("Server:", settings.ServerOrigin)
|
||||
return nil
|
||||
return graph.Run(ctx, target)
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestExclusivePreparationStagesCannotBeCombined(t *testing.T) {
|
||||
err := prepareClient([]string{"--download", "--base"})
|
||||
if err == nil || !strings.Contains(err.Error(), "separate stages") {
|
||||
t.Fatalf("conflicting stages could modify the installation: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreparePlanDoesNotReadPackageOrWriteInstallation(t *testing.T) {
|
||||
for _, stage := range []string{"", "--download", "--base"} {
|
||||
t.Run(stage, func(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
packageDir := filepath.Join(root, "missing-package")
|
||||
args := []string{"--plan", "--package-dir", packageDir, "--manifest", filepath.Join(root, "missing-manifest.json")}
|
||||
if stage != "" {
|
||||
args = append(args, stage)
|
||||
}
|
||||
if err := prepareClient(args); err != nil {
|
||||
t.Fatal("planning required live package inputs", err)
|
||||
}
|
||||
entries, err := os.ReadDir(root)
|
||||
if err != nil || len(entries) != 0 {
|
||||
t.Fatalf("planning changed installation: %v, %v", entries, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrepareHelpNeedsNoInstalledGame(t *testing.T) {
|
||||
if err := prepareClient([]string{"--help"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -3,10 +3,13 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bd2server/internal/common/taskgraph"
|
||||
"bd2server/internal/server/app"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
@@ -18,18 +21,45 @@ func runDevelopmentCommand(args []string) (bool, error) {
|
||||
if len(args) < 2 || args[1] != "run" {
|
||||
return true, errors.New("usage: bd2server --dev run [serve options]")
|
||||
}
|
||||
root, err := findDevelopmentRoot()
|
||||
planOnly := false
|
||||
serveArgs := make([]string, 0, len(args)-2)
|
||||
for _, arg := range args[2:] {
|
||||
if arg == "--plan" {
|
||||
planOnly = true
|
||||
} else {
|
||||
serveArgs = append(serveArgs, arg)
|
||||
}
|
||||
}
|
||||
graph, err := taskgraph.New(
|
||||
taskgraph.Task{Name: "server:configuration", Run: func(context.Context) error {
|
||||
root, err := findDevelopmentRoot()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
serveArgs = appendDefaultFlag(serveArgs, "--version-config", filepath.Join(root, "versions.json"))
|
||||
serveArgs = appendDefaultFlag(serveArgs, "--authentication-config", filepath.Join(root, ".build", "config", "authentication.json"))
|
||||
serveArgs = appendDefaultFlag(serveArgs, "--resource-config", filepath.Join(root, ".build", "config", "resources.json"))
|
||||
serveArgs = appendDefaultFlag(serveArgs, "--game-config", filepath.Join(root, ".build", "config", "game.json"))
|
||||
serveArgs = appendDefaultFlag(serveArgs, "--data-dir", filepath.Join(root, "data"))
|
||||
serveArgs = appendDefaultFlag(serveArgs, "--state-dir", filepath.Join(root, "data", "state"))
|
||||
return nil
|
||||
}},
|
||||
taskgraph.Task{Name: "runServer", DependsOn: []string{"server:configuration"}, Run: func(context.Context) error { return app.Serve(serveArgs) }},
|
||||
)
|
||||
if err != nil {
|
||||
return true, err
|
||||
}
|
||||
serveArgs := append([]string(nil), args[2:]...)
|
||||
serveArgs = appendDefaultFlag(serveArgs, "--version-config", filepath.Join(root, "versions.json"))
|
||||
serveArgs = appendDefaultFlag(serveArgs, "--authentication-config", filepath.Join(root, ".build", "config", "authentication.json"))
|
||||
serveArgs = appendDefaultFlag(serveArgs, "--resource-config", filepath.Join(root, ".build", "config", "resources.json"))
|
||||
serveArgs = appendDefaultFlag(serveArgs, "--game-config", filepath.Join(root, ".build", "config", "game.json"))
|
||||
serveArgs = appendDefaultFlag(serveArgs, "--data-dir", filepath.Join(root, "data"))
|
||||
serveArgs = appendDefaultFlag(serveArgs, "--state-dir", filepath.Join(root, "data", "state"))
|
||||
return true, app.Serve(serveArgs)
|
||||
if planOnly {
|
||||
plan, err := graph.Plan("runServer")
|
||||
if err != nil {
|
||||
return true, err
|
||||
}
|
||||
fmt.Println(strings.Join(plan, " -> "))
|
||||
return true, nil
|
||||
}
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
|
||||
defer stop()
|
||||
return true, graph.Run(ctx, "runServer")
|
||||
}
|
||||
|
||||
func findDevelopmentRoot() (string, error) {
|
||||
@@ -68,5 +98,5 @@ func appendDefaultFlag(args []string, name, value string) []string {
|
||||
}
|
||||
|
||||
func developmentUsage() string {
|
||||
return "\n\nDevelopment build only:\n\tbd2server --dev run [serve options]"
|
||||
return "\n\nDevelopment build only:\n\tbd2server --dev run [--plan] [serve options]"
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
//go:build !release
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestDevelopmentPlanDoesNotCreateDataOrReadConfiguration(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
data := filepath.Join(root, "server-data")
|
||||
args := []string{"--dev", "run", "--plan", "--data-dir", data, "--version-config", filepath.Join(root, "missing-versions.json")}
|
||||
if handled, err := runDevelopmentCommand(args); !handled || err != nil {
|
||||
t.Fatalf("inspection attempted to start the server with nonexistent inputs: %v, %v", handled, err)
|
||||
}
|
||||
entries, err := os.ReadDir(root)
|
||||
if err != nil || len(entries) != 0 {
|
||||
t.Fatalf("server inspection created data or configuration: %v, %v", entries, err)
|
||||
}
|
||||
}
|
||||
@@ -3,8 +3,11 @@ module bd2server
|
||||
go 1.25.0
|
||||
|
||||
require (
|
||||
github.com/mattn/go-isatty v0.0.24
|
||||
github.com/tc-hib/winres v0.3.1
|
||||
github.com/wailsapp/wails/v2 v2.16.0
|
||||
golang.org/x/sys v0.47.0
|
||||
golang.org/x/text v0.39.0
|
||||
modernc.org/sqlite v1.59.0
|
||||
)
|
||||
|
||||
@@ -24,8 +27,8 @@ require (
|
||||
github.com/leaanthony/slicer v1.6.0 // indirect
|
||||
github.com/leaanthony/u v1.1.1 // indirect
|
||||
github.com/mattn/go-colorable v0.1.13 // indirect
|
||||
github.com/mattn/go-isatty v0.0.24 // indirect
|
||||
github.com/ncruces/go-strftime v1.0.0 // indirect
|
||||
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 // indirect
|
||||
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect
|
||||
github.com/pkg/errors v0.9.1 // indirect
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||
@@ -37,8 +40,8 @@ require (
|
||||
github.com/wailsapp/go-webview2 v1.0.22 // indirect
|
||||
github.com/wailsapp/mimetype v1.4.1 // indirect
|
||||
golang.org/x/crypto v0.53.0 // indirect
|
||||
golang.org/x/image v0.41.0 // indirect
|
||||
golang.org/x/net v0.56.0 // indirect
|
||||
golang.org/x/text v0.39.0 // indirect
|
||||
modernc.org/libc v1.75.7 // indirect
|
||||
modernc.org/mathutil v1.7.1 // indirect
|
||||
modernc.org/memory v1.12.1 // indirect
|
||||
|
||||
@@ -44,6 +44,8 @@ github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsRe
|
||||
github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
|
||||
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
|
||||
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
|
||||
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 h1:zYyBkD/k9seD2A7fsi6Oo2LfFZAehjjQMERAvZLEDnQ=
|
||||
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646/go.mod h1:jpp1/29i3P1S/RLdc7JQKbRpFeM1dOBd8T9ki5s+AY8=
|
||||
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ=
|
||||
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU=
|
||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||
@@ -59,6 +61,8 @@ github.com/samber/lo v1.49.1 h1:4BIFyVfuQSEpluc7Fua+j1NolZHiEHEpaSEKdsH0tew=
|
||||
github.com/samber/lo v1.49.1/go.mod h1:dO6KHFzUKXgP8LDhU0oI8d2hekjXnGOu0DB8Jecxd6o=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/tc-hib/winres v0.3.1 h1:CwRjEGrKdbi5CvZ4ID+iyVhgyfatxFoizjPhzez9Io4=
|
||||
github.com/tc-hib/winres v0.3.1/go.mod h1:C/JaNhH3KBvhNKVbvdlDWkbMDO9H4fKKDaN7/07SSuk=
|
||||
github.com/tkrajina/go-reflector v0.5.8 h1:yPADHrwmUbMq4RGEyaOUpz2H90sRsETNVpjzo3DLVQQ=
|
||||
github.com/tkrajina/go-reflector v0.5.8/go.mod h1:ECbqLgccecY5kPmPmXg1MrHW585yMcDkVl6IvJe64T4=
|
||||
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
|
||||
@@ -73,6 +77,8 @@ github.com/wailsapp/wails/v2 v2.16.0 h1:hLYrSHUUq6hRXl3rWT9ZXiyFIgM94nVN9Ns6iEJz
|
||||
github.com/wailsapp/wails/v2 v2.16.0/go.mod h1:scxrgwfsv6yR6fE6cCF+Flfl+JeU+SR87T9x4kILJ6M=
|
||||
golang.org/x/crypto v0.53.0 h1:QZ4Muo8THX6CizN2vPPd5fBGHyogrdK9fG4wLPFUsto=
|
||||
golang.org/x/crypto v0.53.0/go.mod h1:DNLU434OwVakk9PzuwV8w62mAJpRJL3vsgcfp4Qnsio=
|
||||
golang.org/x/image v0.41.0 h1:8wS72eGJMJaBxK6okTzd4WaXumUlTVlb753MlsSvTCo=
|
||||
golang.org/x/image v0.41.0/go.mod h1:uIc348UZMSvS5Z65CVZ7iDPaNobNFEPeJ4kbqTOszmA=
|
||||
golang.org/x/mod v0.38.0 h1:MECBjubtXD7yj4HrhIUcywNaGeNVUdfVnxmPajOk4yk=
|
||||
golang.org/x/mod v0.38.0/go.mod h1:V6Xz0pq8TQ3dGqVQ1FVHuelZpAL0uNhSkk9ogYP3c40=
|
||||
golang.org/x/net v0.0.0-20210505024714-0287a6fb4125/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
||||
|
||||
@@ -16,9 +16,10 @@ import (
|
||||
clientconfig "bd2server/internal/client/config"
|
||||
clientlayout "bd2server/internal/client/layout"
|
||||
clientsetup "bd2server/internal/client/setup"
|
||||
"bd2server/internal/common/versionconfig"
|
||||
)
|
||||
|
||||
//go:embed web/index.html
|
||||
//go:embed web/index.html web/icon.svg web/icon.png web/icon.ico
|
||||
var webFS embed.FS
|
||||
|
||||
var errGameAlreadyRunning = errors.New("Brown Dust II is already running") //nolint:staticcheck // ST1005
|
||||
@@ -27,7 +28,7 @@ type Options struct {
|
||||
InitialGameDir string
|
||||
Logger *slog.Logger
|
||||
LogPath string
|
||||
Versions clientconfig.ReleaseVersions
|
||||
Versions versionconfig.Config
|
||||
LocalIdentityPlugin string
|
||||
LoginUIPlugin string
|
||||
CashShopPlugin string
|
||||
|
||||
@@ -21,6 +21,10 @@ func Run(runOptions Options) error {
|
||||
if err != nil {
|
||||
return fmt.Errorf("load embedded client interface: %w", err)
|
||||
}
|
||||
icon, err := webFS.ReadFile("web/icon.png")
|
||||
if err != nil {
|
||||
return fmt.Errorf("load launcher icon: %w", err)
|
||||
}
|
||||
host := NativeHost{
|
||||
BrowseDirectory: func(ctx context.Context, title string) (string, error) {
|
||||
return wailsruntime.OpenDirectoryDialog(ctx, wailsruntime.OpenDialogOptions{Title: title})
|
||||
@@ -30,7 +34,7 @@ func Run(runOptions Options) error {
|
||||
studio := NewStudio(runOptions, host)
|
||||
studio.log().Info("starting native client window", "windows_engine", "WebView2", "macos_engine", "WKWebView")
|
||||
err = wails.Run(&options.App{
|
||||
Title: "BD2 Client Studio",
|
||||
Title: "BD2 Launcher",
|
||||
Frameless: true,
|
||||
Width: 1080,
|
||||
Height: 720,
|
||||
@@ -58,6 +62,7 @@ func Run(runOptions Options) error {
|
||||
EnableSwipeGestures: false,
|
||||
},
|
||||
Mac: &mac.Options{
|
||||
About: &mac.AboutInfo{Title: "BD2 Launcher", Icon: icon},
|
||||
TitleBar: &mac.TitleBar{HideTitle: true, HideTitleBar: true, FullSizeContent: true, TitlebarAppearsTransparent: true},
|
||||
Appearance: mac.NSAppearanceNameAqua,
|
||||
DisableZoom: true,
|
||||
|
||||
@@ -8,6 +8,8 @@ import (
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"sync"
|
||||
|
||||
"bd2server/internal/common/logging"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -38,7 +40,7 @@ func OpenPersistentLogger(executablePath string) (*slog.Logger, io.Closer, strin
|
||||
if homeErr != nil {
|
||||
return nil, nil, "", fmt.Errorf("locate macOS user home for logs: %w", homeErr)
|
||||
}
|
||||
logDirectory = filepath.Join(home, "Library", "Logs", "BD2 Client Studio")
|
||||
logDirectory = filepath.Join(home, "Library", "Logs", "BD2 Launcher")
|
||||
}
|
||||
if err := os.MkdirAll(logDirectory, 0o700); err != nil {
|
||||
return nil, nil, "", fmt.Errorf("create bd2client log directory: %w", err)
|
||||
@@ -48,7 +50,12 @@ func OpenPersistentLogger(executablePath string) (*slog.Logger, io.Closer, strin
|
||||
if err != nil {
|
||||
return nil, nil, "", err
|
||||
}
|
||||
logger := slog.New(slog.NewTextHandler(writer, &slog.HandlerOptions{Level: slog.LevelInfo}))
|
||||
handler, err := logging.NewHandler(writer, logging.Options{Level: slog.LevelInfo, Color: logging.ColorNever})
|
||||
if err != nil {
|
||||
_ = writer.Close()
|
||||
return nil, nil, "", err
|
||||
}
|
||||
logger := slog.New(handler)
|
||||
return logger, writer, path, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ import (
|
||||
|
||||
func ShowFatalError(err error) {
|
||||
if err != nil {
|
||||
_, _ = fmt.Fprintln(os.Stderr, "BD2 Client Studio:", err)
|
||||
_, _ = fmt.Fprintln(os.Stderr, "BD2 Launcher:", err)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ import (
|
||||
|
||||
func ShowFatalError(err error) {
|
||||
if err != nil {
|
||||
_, _ = fmt.Fprintln(os.Stderr, "BD2 Client Studio:", err)
|
||||
_, _ = fmt.Fprintln(os.Stderr, "BD2 Launcher:", err)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -34,12 +34,12 @@ func ShowFatalError(err error) {
|
||||
return
|
||||
}
|
||||
message, conversionErr := syscall.UTF16PtrFromString(fmt.Sprintf(
|
||||
"BD2 Client Studio could not start:\n\n%s\n\nSee the logs directory next to bd2client.exe for details.", err,
|
||||
"BD2 Launcher could not start:\n\n%s\n\nSee the logs directory next to bd2client.exe for details.", err,
|
||||
))
|
||||
if conversionErr != nil {
|
||||
return
|
||||
}
|
||||
title, conversionErr := syscall.UTF16PtrFromString("BD2 Client Studio")
|
||||
title, conversionErr := syscall.UTF16PtrFromString("BD2 Launcher")
|
||||
if conversionErr != nil {
|
||||
return
|
||||
}
|
||||
@@ -78,7 +78,7 @@ func launchGame(target, proxyURL string) error {
|
||||
return err
|
||||
}
|
||||
// Unity creates the top-level window asynchronously. Best-effort foreground
|
||||
// activation prevents the new window from opening behind Client Studio.
|
||||
// activation prevents the new window from opening behind BD2 Launcher.
|
||||
activateProcessWindow(uint32(command.Process.Pid), 15*time.Second)
|
||||
return nil
|
||||
}
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 23 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 70 KiB |
@@ -0,0 +1,13 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 64 64" fill="none">
|
||||
<title>BD2 Launcher — Threshold</title>
|
||||
<desc>Two ivory pillars suggest II and an open portal; a bronze arrow marks entry. Editable vector paths on a transparent canvas.</desc>
|
||||
<g id="app-tile">
|
||||
<rect x="3" y="3" width="58" height="58" rx="12" fill="#D7C5AA"/>
|
||||
<rect x="4" y="4" width="56" height="56" rx="11" fill="#382E26"/>
|
||||
</g>
|
||||
<g id="portal-pillars" fill="#EEE7DA">
|
||||
<path id="pillar-left" d="M12 45H15V23C15 21.7 15.65 20.48 16.73 19.76L29 11.5V20.5L23 24.5V45H26V50H12Z"/>
|
||||
<path id="pillar-right" d="M52 45H49V23C49 21.7 48.35 20.48 47.27 19.76L35 11.5V20.5L41 24.5V45H38V50H52Z"/>
|
||||
</g>
|
||||
<path id="enter-arrow" d="M28 28.5L38 35L28 41.5Z" fill="#BD905B"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 800 B |
@@ -4,13 +4,15 @@
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<meta name="theme-color" content="#e8decc">
|
||||
<title>BD2 Client Studio</title>
|
||||
<title>BD2 Launcher</title>
|
||||
<link rel="icon" type="image/svg+xml" href="/icon.svg">
|
||||
<link rel="alternate icon" href="/icon.ico">
|
||||
<style>
|
||||
:root{color-scheme:light;--paper:#eee7da;--ink:#382e26;--muted:#796c5d;--line:rgba(84,62,42,.18);--rust:#965437;--olive:#63704d;--bad:#9d4034;--ease:cubic-bezier(.22,1,.36,1);--serif:Georgia,'Songti SC','Noto Serif CJK SC',SimSun,serif;--sans:'Segoe UI','PingFang SC','Microsoft YaHei',sans-serif}
|
||||
*{box-sizing:border-box}body{margin:0;background:#e7dcc7;color:var(--ink);font:14px/1.65 var(--sans);overflow-x:hidden}button,input{font:inherit}button{cursor:pointer}button:disabled{cursor:wait;opacity:.5}button,input,a{-webkit-tap-highlight-color:transparent}button:focus-visible,input:focus-visible,summary:focus-visible{outline:2px solid var(--rust);outline-offset:5px}[hidden]{display:none!important}::selection{background:#b9764c;color:#fff9ef}
|
||||
.landscape{position:fixed;inset:0;z-index:-3;background:linear-gradient(130deg,#f1e9d9 0%,#e7d5b6 42%,#bc8665 100%);overflow:hidden}.landscape svg{position:absolute;width:100%;height:100%;transition:transform 2s var(--ease),opacity 1.6s;transform:scale(1.04);opacity:.87}.landscape:after{content:'';position:absolute;inset:0;background:linear-gradient(90deg,rgba(244,237,222,.8),rgba(240,228,207,.2) 65%,transparent),linear-gradient(0deg,rgba(73,48,31,.14),transparent 48%)}body[data-scene=server] .landscape svg{transform:scale(1.14) translateX(-2%)}body[data-scene=desk] .landscape svg{transform:scale(1.2) translateY(-3%);opacity:.27}body[data-scene=desk] .landscape:after{background:rgba(240,234,221,.55)}
|
||||
.grain{position:fixed;inset:0;pointer-events:none;z-index:20;opacity:.038;background-image:url("data:image/svg+xml,%3Csvg viewBox='0 0 180 180' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='grain'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.82' numOctaves='3' stitchTiles='stitch'/%3E%3C/filter%3E%3Cpath fill='%23000' filter='url(%23grain)' d='M0 0h180v180H0z'/%3E%3C/svg%3E")}.sunlight{position:fixed;inset:-40%;pointer-events:none;z-index:-2;background:radial-gradient(ellipse at 70% 23%,#fff7d777,transparent 38%);animation:drift 18s ease-in-out infinite alternate}
|
||||
.topbar{height:94px;max-width:1440px;margin:auto;padding:0 58px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid var(--line);gap:24px}.brand{display:flex;gap:13px;align-items:center;flex-shrink:0}.emblem{width:36px;height:36px;border:1px solid #7d624a;transform:rotate(45deg);display:grid;place-items:center}.emblem span{font:20px var(--serif);transform:rotate(-45deg)}.brand-name{font-size:13px;letter-spacing:.19em;line-height:1.4}.brand-name small{display:block;font-size:9px;letter-spacing:.28em;color:var(--muted);margin-top:4px}.top-note{font-size:11px;color:var(--muted);letter-spacing:.07em}.text-btn{background:none;border:0;color:var(--muted);padding:8px 0;border-bottom:1px solid transparent}.text-btn:hover{color:var(--rust);border-bottom-color:var(--rust)}
|
||||
.topbar{height:94px;max-width:1440px;margin:auto;padding:0 58px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid var(--line);gap:24px}.brand{display:flex;gap:13px;align-items:center;flex-shrink:0}.emblem{display:block;width:40px;height:40px;flex-shrink:0}.brand-name{font-size:13px;letter-spacing:.19em;line-height:1.4}.brand-name small{display:block;font-size:9px;letter-spacing:.28em;color:var(--muted);margin-top:4px}.top-note{font-size:11px;color:var(--muted);letter-spacing:.07em}.text-btn{background:none;border:0;color:var(--muted);padding:8px 0;border-bottom:1px solid transparent}.text-btn:hover{color:var(--rust);border-bottom-color:var(--rust)}
|
||||
main{max-width:1324px;margin:auto;padding:0 58px}.scene{position:relative}.intro-scene{min-height:calc(100svh - 178px);display:grid;grid-template-columns:1.1fr .9fr;align-items:center;gap:8%;padding:66px 0 82px}.eyebrow{font-size:10px;letter-spacing:.22em;text-transform:uppercase;display:flex;align-items:center;gap:12px;color:#81634c;margin-bottom:24px}.eyebrow:before{content:'';height:1px;width:32px;background:currentColor}h1,h2,h3,p{margin:0}h1{font:400 clamp(42px,4.8vw,68px)/1.28 var(--serif);letter-spacing:.035em}.lead{max-width:380px;font-size:14px;color:var(--muted);line-height:1.95;margin-top:26px}.intro-label{display:flex;gap:14px;align-items:center;margin-top:44px;font-size:11px;color:#8a7059}.intro-label i{height:1px;width:30px;background:#987759}.form-card{position:relative;background:linear-gradient(135deg,rgba(250,246,237,.89),rgba(238,225,203,.7));border:1px solid rgba(255,255,255,.6);box-shadow:0 24px 70px -35px #65472c77,inset 0 0 0 1px rgba(116,89,55,.035);backdrop-filter:blur(24px);border-radius:4px;padding:34px 32px}.card-number{font:italic 46px/1 var(--serif);color:#b2997e;opacity:.6;margin-bottom:30px}.form-card h2{font:400 23px var(--serif);margin-bottom:9px}.description{font-size:12px;line-height:1.8;color:var(--muted);margin-bottom:26px}code{font:11px/1.8 Consolas,monospace;overflow-wrap:anywhere}label.field-label{display:block;font-size:11px;margin-bottom:9px;color:#6f5c49}.input-row{display:flex;gap:8px}input[type=text]{width:100%;min-width:0;border:1px solid #aa927755;border-radius:3px;padding:13px 12px;background:#fffcf57d;color:var(--ink);outline:none;transition:background .2s,border-color .2s;font-size:12px}input[type=text]:focus{border-color:var(--rust);background:#fffaf0}.btn{border:1px solid #81664a55;border-radius:3px;padding:11px 18px;display:inline-flex;align-items:center;justify-content:center;gap:12px;min-height:43px;background:#fffcf533;color:var(--ink);transition:background .25s,box-shadow .25s,transform .25s;white-space:nowrap;font-size:12px}.btn:hover:not(:disabled){background:#fff9eb99;transform:translateY(-2px)}.btn.primary{background:#4b3a2c;color:#fff5e4;border-color:#4b3a2c}.btn.primary:hover:not(:disabled){background:#654932;box-shadow:0 6px 17px #4b3a2c24}.btn.rust{background:#985e40;color:#fff6e8;border-color:#985e40}.btn.rust:hover:not(:disabled){background:#ad6c49}.arrow{font-size:20px;font-weight:300;line-height:1}.wide{width:100%;justify-content:space-between;margin-top:28px;padding:14px 18px}.small-note{font-size:11px;color:#877460;margin-top:12px;line-height:1.8}.inline-result{font-size:11px;min-height:22px;margin-top:10px;color:var(--muted)}.inline-result.error{color:var(--bad)}.form-tools{display:flex;align-items:center;justify-content:space-between;margin-top:4px;gap:8px;font-size:11px}.server-back{margin-top:14px;text-align:center}.server-back .text-btn{font-size:11px}.bottom-bar{max-width:1324px;margin:auto;padding:0 58px 28px;display:flex;justify-content:space-between;align-items:center;gap:24px}.steps{display:flex;list-style:none;padding:0;margin:0;gap:26px;font-size:11px;color:#8f7d69}.steps li{display:flex;gap:8px;align-items:center}.steps .num{font:italic 14px var(--serif)}.steps li.active{color:#503b2b}.steps li.active:after{content:'';width:19px;height:1px;background:#86573b}.bottom-note{font-size:10px;color:#897963;letter-spacing:.04em}
|
||||
.scene.is-entering .reveal{animation:reveal 1.3s var(--ease) both;animation-delay:calc(var(--i,0)*110ms)}.scene.is-leaving{animation:leave .55s cubic-bezier(.4,0,.6,1) both;pointer-events:none}.transition-veil{position:fixed;inset:0;background:linear-gradient(115deg,#eee4d4ed,#dfc7a8e8);z-index:30;pointer-events:none;opacity:0;backdrop-filter:blur(8px)}.transition-veil.play{animation:veil 1.25s ease-in-out both}.opening-curtain{position:fixed;inset:0;background:#e8decc;pointer-events:none;z-index:40;animation:opening 1.65s ease forwards}
|
||||
.desk-scene{padding:46px 0 34px}.desk-header{display:flex;justify-content:space-between;align-items:end;gap:24px;margin-bottom:30px}.desk-header .eyebrow{margin-bottom:13px}.desk-header h1{font-size:42px}.desk-header p{margin-top:12px;font-size:12px;color:var(--muted)}.connection-chip{display:flex;align-items:center;gap:9px;font-size:11px;color:#74634f;border:1px solid var(--line);padding:8px 13px;border-radius:30px}.dot{width:6px;height:6px;border-radius:50%;background:#a99b85;display:inline-block;flex-shrink:0}.dot.good{background:var(--olive);box-shadow:0 0 0 4px #68744912}.dot.bad{background:var(--bad)}.desk-grid{display:grid;grid-template-columns:minmax(0,1fr) 298px;gap:24px}.main-panel{background:#f9f5ec94;border:1px solid #fff9;border-radius:4px;box-shadow:0 12px 50px -40px #5c412c55}.panel-section{padding:25px 28px;border-bottom:1px solid var(--line)}.panel-section:last-child{border-bottom:0}.section-title{display:flex;align-items:center;gap:11px;margin-bottom:22px}.section-title .index{font:italic 14px var(--serif);color:#a08569}.section-title h2{font-size:15px;font-weight:500}.section-title .end{margin-left:auto;font-size:10px;color:var(--muted)}.setting-row{display:flex;align-items:center;justify-content:space-between;gap:20px;margin-top:18px}.setting-name{font-size:10px;color:var(--muted);margin-bottom:4px}.setting-value{font-size:12px;overflow-wrap:anywhere}.setting-row>div{min-width:0}.setting-row .text-btn{font-size:11px;flex-shrink:0;color:var(--rust)}.route-options{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:10px}.route{position:relative;cursor:pointer}.route input{position:absolute;opacity:0;inset:0;width:100%;height:100%;margin:0}.route-content{display:block;position:relative;pointer-events:none;min-height:139px;padding:15px 14px;border:1px solid var(--line);border-radius:3px;transition:.25s;background:#f8f3e83d}.route-content .route-top{display:flex;align-items:center;justify-content:space-between;margin-bottom:16px}.route-code{font:10px var(--serif);letter-spacing:.08em;color:#98826b}.radio-dot{width:11px;height:11px;border-radius:50%;border:1px solid #aa9680;display:block}.route-content strong{font-size:12px;font-weight:500;display:block;margin-bottom:5px}.route-content small{font-size:10px;line-height:1.75;display:block;color:var(--muted)}.route input:checked+.route-content{border-color:#9e7551;background:#b9986920;box-shadow:inset 0 0 0 1px #9e755118}.route input:checked+.route-content .radio-dot{background:#916c4a;border:3px solid #e8d9c3;box-shadow:0 0 0 1px #916c4a}.route input:focus-visible+.route-content{outline:2px solid var(--rust);outline-offset:4px}.route input:disabled+.route-content{opacity:.55}.route-actions{display:flex;align-items:center;justify-content:space-between;gap:10px;margin-top:18px}.route-actions .text-btn{font-size:11px}.route-hint{font-size:10px;color:#927d64;margin-top:13px}.policy{font:11px/1.9 Consolas,monospace;white-space:pre-wrap;overflow-wrap:anywhere;background:#dfd2bc50;border-left:2px solid #a3835e;padding:13px;margin-top:16px}.prepare-note{font-size:11px;color:var(--muted);margin:-8px 0 19px;line-height:1.8}.prepare-actions{display:flex;gap:10px;flex-wrap:wrap}.prepare-actions .btn{flex:1}.status-panel{align-self:start;padding:25px 23px;background:#dfd1ba66;border:1px solid #9875501c;border-radius:4px}.status-title{display:flex;align-items:center;justify-content:space-between;margin-bottom:6px}.status-title h2{font:400 19px var(--serif)}.status-title span{font-size:9px;color:#927d65;letter-spacing:.1em}.check{display:flex;align-items:center;justify-content:space-between;padding:14px 0;border-bottom:1px solid var(--line);font-size:11px;gap:8px}.check span:last-child{color:#948471;font-size:10px}.check span.ok{color:var(--olive)}.check span.warn{color:var(--bad)}.status-foot{font-size:10px;color:#8d7a63;margin-top:14px;line-height:1.8}.log-wrap{border-top:1px solid var(--line);margin-top:24px;padding-top:19px}.log-heading{font-size:10px;color:#8d745b;display:flex;align-items:center;justify-content:space-between;margin-bottom:12px}.log{font-size:11px;color:#7e6c56;line-height:1.8;overflow-wrap:anywhere;min-height:65px}.log strong{display:block;color:var(--ink);font-size:12px;font-weight:500;margin-bottom:5px}.history{margin-top:14px;border-top:1px solid var(--line);padding-top:12px;font-size:10px;color:#806e59}.history summary{cursor:pointer}.history ol{list-style:none;padding:0;margin:10px 0 0;max-height:180px;overflow:auto}.history li{padding:7px 0;border-top:1px solid #a487651a;overflow-wrap:anywhere}.history time{display:block;color:#9a876f;font-size:9px}.history li.error{color:var(--bad)}.unsaved{font-size:10px;color:var(--rust);margin-top:12px}.desk-footer{display:flex;justify-content:space-between;gap:20px;margin-top:24px;color:#8a765e;font-size:10px}
|
||||
@@ -34,18 +36,18 @@ html,body{scrollbar-width:none}html::-webkit-scrollbar,body::-webkit-scrollbar{d
|
||||
<svg viewBox="0 0 1600 1000" preserveAspectRatio="xMidYMid slice" xmlns="http://www.w3.org/2000/svg"><defs><linearGradient id="sky" x2="0" y2="1"><stop stop-color="#f3e6c9"/><stop offset=".7" stop-color="#dab88e"/><stop offset="1" stop-color="#b98560"/></linearGradient><linearGradient id="mesa" x2="0.2" y2="1"><stop stop-color="#b48360"/><stop offset="1" stop-color="#8f624b"/></linearGradient><linearGradient id="sand" x2=".6" y2="1"><stop stop-color="#b8946e"/><stop offset="1" stop-color="#674b39"/></linearGradient><filter id="soft"><feGaussianBlur stdDeviation="18"/></filter></defs><path fill="url(#sky)" d="M0 0h1600v1000H0z"/><circle cx="1150" cy="270" r="91" fill="#fff4ce" opacity=".4" filter="url(#soft)"/><circle cx="1150" cy="270" r="68" fill="#fff0c7" opacity=".8"/><path d="M0 640 240 590 370 610 520 558 670 580 820 510 950 560 1120 492 1280 560 1420 482 1600 530V1000H0Z" fill="#bea17f" opacity=".6"/><path d="m835 710 60-133 43-18 17-104 32-8 17-45 130-2 18 48 32 6 15 112 35 14 36 114 58 38 212 18V1000H790Z" fill="url(#mesa)" opacity=".65"/><path d="m1004 400 15 162 24 39-12 110 75 112 18-203-23-111 33-109z" fill="#d3a079" opacity=".38"/><path d="m1280 760 81-113 24-160 47-12 13-59 122 3 14 67 19 18v496h-320Z" fill="#9a6b4f" opacity=".6"/><path d="M0 746Q260 652 525 746T1030 775 1600 724V1000H0Z" fill="#c8aa80"/><path d="M0 869Q300 687 660 860T1300 814 1600 830V1000H0Z" fill="url(#sand)" opacity=".65"/><path d="M860 1000q185-97 375-124t365-13v137Z" fill="#826045" opacity=".7"/><path d="M870 998q146-128 235-165t69-90" fill="none" stroke="#e1c397" stroke-width="3" opacity=".24"/></svg>
|
||||
</div>
|
||||
<div class="sunlight" aria-hidden="true"></div><div class="grain" aria-hidden="true"></div><div class="opening-curtain" aria-hidden="true"></div><div id="veil" class="transition-veil" aria-hidden="true"></div>
|
||||
<header class="topbar"><div class="brand"><div class="emblem" aria-hidden="true"><span>B</span></div><div class="brand-name">BD2 CLIENT STUDIO<small>CLIENT CONFIGURATION</small></div></div><div class="top-note">客户端设置工具 · 配置保存在本机</div><div class="window-controls" role="group" aria-label="窗口控制"><button class="window-control" id="windowMinimise" aria-label="最小化" title="最小化"><svg viewBox="0 0 12 12" aria-hidden="true"><path d="M1 9h10"/></svg></button><button class="window-control" id="windowMaximise" aria-label="最大化或还原" title="最大化或还原"><svg viewBox="0 0 12 12" aria-hidden="true"><rect x="1.5" y="1.5" width="9" height="9"/></svg></button><button class="window-control window-close" id="windowClose" aria-label="关闭" title="关闭"><svg viewBox="0 0 12 12" aria-hidden="true"><path d="m1.5 1.5 9 9m0-9-9 9"/></svg></button></div></header>
|
||||
<header class="topbar"><div class="brand"><img class="emblem" src="/icon.svg" width="40" height="40" alt=""><div class="brand-name">BD2 LAUNCHER<small>GAME LAUNCHER</small></div></div><div class="top-note">BD2 启动器 · 配置保存在本机</div><div class="window-controls" role="group" aria-label="窗口控制"><button class="window-control" id="windowMinimise" aria-label="最小化" title="最小化"><svg viewBox="0 0 12 12" aria-hidden="true"><path d="M1 9h10"/></svg></button><button class="window-control" id="windowMaximise" aria-label="最大化或还原" title="最大化或还原"><svg viewBox="0 0 12 12" aria-hidden="true"><rect x="1.5" y="1.5" width="9" height="9"/></svg></button><button class="window-control window-close" id="windowClose" aria-label="关闭" title="关闭"><svg viewBox="0 0 12 12" aria-hidden="true"><path d="m1.5 1.5 9 9m0-9-9 9"/></svg></button></div></header>
|
||||
<main>
|
||||
<section class="scene intro-scene is-entering" id="directoryScene" aria-labelledby="directoryTitle">
|
||||
<div><div class="eyebrow reveal" style="--i:1">01 / GAME DIRECTORY</div><h1 class="reveal" style="--i:2" id="directoryTitle" tabindex="-1">先从游戏目录<br>开始。</h1><p class="lead reveal" style="--i:3">选择已安装的游戏文件夹。<br>我们会检查游戏程序和资源文件,再继续设置连接。</p><div class="intro-label reveal" style="--i:4"><i></i>BrownDust II · 客户端配置</div></div>
|
||||
<div class="form-card reveal" style="--i:4"><div class="card-number" aria-hidden="true">01</div><h2>选择游戏目录</h2><p class="description">请选择包含 <code>BrownDust II.exe</code> 的文件夹。</p><div id="directoryHome"><div id="directoryFields"><label class="field-label" for="gameDir">游戏安装目录</label><div class="input-row"><input id="gameDir" type="text" value="" placeholder="例如 E:\Games\BrownDust II" autocomplete="off" spellcheck="false"><button class="btn" id="browse">浏览</button></div><div class="form-tools"><span id="directoryHint">可直接填写路径,也可以浏览目录。</span><button class="text-btn" id="inspect">检查目录</button></div><p class="inline-result" id="directoryResult" role="status"></p></div></div><button class="btn primary wide" id="directoryNext"><span>继续设置服务器</span><span class="arrow" aria-hidden="true">→</span></button><p class="small-note">此步骤只检查文件,不会修改游戏资源。</p></div>
|
||||
</section>
|
||||
<section class="scene intro-scene" id="serverScene" hidden aria-labelledby="serverTitle">
|
||||
<div><div class="eyebrow reveal" style="--i:1">02 / SERVER CONNECTION</div><h1 class="reveal" style="--i:2" id="serverTitle" tabindex="-1">接下来,<br>设置服务器。</h1><p class="lead reveal" style="--i:3">填写要连接的服务端地址。<br>进入工作台后,你可以选择资源来源、应用补丁和安装插件。</p><div class="intro-label reveal" style="--i:4"><i></i>目录已选择 · 之后仍可修改</div></div>
|
||||
<div class="form-card reveal" style="--i:4"><div class="card-number" aria-hidden="true">02</div><h2>服务器地址</h2><p class="description">填写完整地址,可以包含端口。</p><div id="serverHome"><div id="serverFields"><label class="field-label" for="origin">地址与端口</label><input id="origin" type="text" value="" placeholder="https://play.example.com" autocomplete="url" spellcheck="false" aria-describedby="originHint"><p class="small-note" id="originHint">例如 <code>http://192.168.1.8:8080</code><br>不要添加 <code>/game/</code> 或其他路径。真实连接地址由 LI 插件读取。</p><p class="inline-result" id="serverResult" role="status"></p></div></div><button class="btn primary wide" id="serverNext"><span>进入工作台</span><span class="arrow" aria-hidden="true">→</span></button><div class="server-back"><button class="text-btn" id="serverBack">← 返回目录设置</button></div></div>
|
||||
<div><div class="eyebrow reveal" style="--i:1">02 / SERVER CONNECTION</div><h1 class="reveal" style="--i:2" id="serverTitle" tabindex="-1">接下来,<br>设置服务器。</h1><p class="lead reveal" style="--i:3">填写要连接的服务端地址。<br>进入启动器后,你可以选择资源来源、应用补丁和安装插件。</p><div class="intro-label reveal" style="--i:4"><i></i>目录已选择 · 之后仍可修改</div></div>
|
||||
<div class="form-card reveal" style="--i:4"><div class="card-number" aria-hidden="true">02</div><h2>服务器地址</h2><p class="description">填写完整地址,可以包含端口。</p><div id="serverHome"><div id="serverFields"><label class="field-label" for="origin">地址与端口</label><input id="origin" type="text" value="" placeholder="https://play.example.com" autocomplete="url" spellcheck="false" aria-describedby="originHint"><p class="small-note" id="originHint">例如 <code>http://192.168.1.8:8080</code><br>不要添加 <code>/game/</code> 或其他路径。真实连接地址由 LI 插件读取。</p><p class="inline-result" id="serverResult" role="status"></p></div></div><button class="btn primary wide" id="serverNext"><span>进入启动器</span><span class="arrow" aria-hidden="true">→</span></button><div class="server-back"><button class="text-btn" id="serverBack">← 返回目录设置</button></div></div>
|
||||
</section>
|
||||
<section class="scene desk-scene" id="deskScene" hidden aria-labelledby="deskTitle">
|
||||
<header class="desk-header reveal" style="--i:0"><div><div class="eyebrow">03 / WORKSPACE</div><h1 id="deskTitle" tabindex="-1">客户端工作台</h1><p>管理连接设置,完成游戏启动前的准备。</p></div><div class="desk-actions"><div class="connection-chip"><span class="dot" id="pulse"></span><span id="overallStatus">等待检查</span></div><button class="btn primary" id="launch">启动游戏 <span aria-hidden="true">▶</span></button></div></header>
|
||||
<header class="desk-header reveal" style="--i:0"><div><div class="eyebrow">03 / LAUNCHER</div><h1 id="deskTitle" tabindex="-1">BD2 启动器</h1><p>管理连接设置,完成游戏启动前的准备。</p></div><div class="desk-actions"><div class="connection-chip"><span class="dot" id="pulse"></span><span id="overallStatus">等待检查</span></div><button class="btn primary" id="launch">启动游戏 <span aria-hidden="true">▶</span></button></div></header>
|
||||
<div class="desk-grid"><div class="main-panel reveal" style="--i:1">
|
||||
<section class="panel-section"><div class="section-title"><span class="index">01</span><h2>连接设置</h2><span class="end">随时可以修改</span></div><div class="setting-row"><div><div class="setting-name">游戏目录</div><div class="setting-value" id="directorySummary">尚未选择</div></div><button class="text-btn" id="editDirectory">修改目录 ↗</button></div><div class="setting-row"><div><div class="setting-name">服务器地址</div><div class="setting-value" id="serverSummary">尚未填写</div></div><button class="text-btn" id="editServer">修改地址 ↗</button></div><div class="setting-row"><div><div class="setting-name">代理</div><div class="setting-value" id="proxySummary">直接连接</div></div><button class="text-btn" id="editProxy">设置代理 ↗</button></div></section>
|
||||
<section class="panel-section"><div class="section-title"><span class="index">02</span><h2>资源来源</h2><span class="end">CDN</span></div><div class="route-options" role="radiogroup" aria-label="CDN 类型">
|
||||
@@ -55,15 +57,15 @@ html,body{scrollbar-width:none}html::-webkit-scrollbar,body::-webkit-scrollbar{d
|
||||
</div><div class="local-resource" id="localResource" hidden><label class="field-label" for="localResourceDir">本机 CDN 根目录</label><div class="input-row"><input id="localResourceDir" type="text" value="" placeholder="例如 E:\bd2\dl" autocomplete="off" spellcheck="false"><button class="btn" id="browseResources">浏览</button></div><p class="small-note">所选目录内必须同时包含 <code>ServerData</code> 和 <code>GameData</code>。</p></div><p class="route-hint" id="routeHint">官方模式由客户端直连版本锁定的官方 CDN。</p><div class="route-actions"><button class="text-btn" id="checkResources">验证资源来源 ↗</button><button class="btn" id="save">保存连接设置</button></div><p class="unsaved" id="dirtyNotice">当前设置尚未保存。</p><div class="policy" id="policy" role="status" hidden></div></section>
|
||||
<section class="panel-section"><div class="section-title"><span class="index">03</span><h2>补丁与插件</h2></div><p class="prepare-note">操作前请先关闭游戏。补丁只修改内置 Intro 地址,并保留 <code>resources.assets.bak</code> 备份。安装插件前,请先手动安装 BepInEx。</p><div class="prepare-actions"><button class="btn rust" id="patch">应用客户端补丁 <span aria-hidden="true">↗</span></button><button class="btn primary" id="install">安装 / 更新插件 <span aria-hidden="true">↗</span></button></div></section>
|
||||
</div><aside class="status-panel reveal" style="--i:3" aria-label="客户端状态"><div class="status-title"><h2>当前状态</h2><span>LOCAL STATUS</span></div><div><div class="check"><span>游戏程序</span><span id="sExe">等待检查</span></div><div class="check"><span>资源文件</span><span id="sAssets">等待检查</span></div><div class="check"><span>BepInEx</span><span id="sBep">等待检查</span></div><div class="check"><span>连接配置</span><span id="sConfig">尚未写入</span></div><p class="status-foot">状态来自本机文件检查,不代表服务器在线。<br>客户端版本:<code id="clientReleaseVersion"></code><br>游戏版本:<code id="gameReleaseVersion"></code><br>诊断日志:<code id="persistentLogPath"></code></p><button class="text-btn" style="font-size:11px" id="refresh">重新检查 ↻</button></div><div class="log-wrap"><div class="log-heading"><span>最近操作</span><time id="logTime">—</time></div><div class="log" id="log" role="status"><strong>等待操作</strong><span>选择游戏目录后即可开始检查。</span></div><details class="history"><summary>查看操作记录</summary><ol id="historyList"></ol></details></div></aside></div>
|
||||
<footer class="desk-footer reveal" style="--i:4"><span>BD2 CLIENT STUDIO <span aria-hidden="true">/</span> 配置仅保存在你的电脑上</span><span>不会保存账号凭据或服主密钥</span></footer>
|
||||
<footer class="desk-footer reveal" style="--i:4"><span>BD2 LAUNCHER <span aria-hidden="true">/</span> 配置仅保存在你的电脑上</span><span>不会保存账号凭据或服主密钥</span></footer>
|
||||
</section>
|
||||
<section class="scene quit-scene" id="quitScene" hidden aria-labelledby="quitTitle"><div class="eyebrow reveal">CLIENT STUDIO</div><h1 class="reveal" id="quitTitle" tabindex="-1">工具已退出</h1><p class="reveal">现在可以关闭这个页面。</p></section>
|
||||
<section class="scene quit-scene" id="quitScene" hidden aria-labelledby="quitTitle"><div class="eyebrow reveal">LAUNCHER</div><h1 class="reveal" id="quitTitle" tabindex="-1">工具已退出</h1><p class="reveal">现在可以关闭这个页面。</p></section>
|
||||
</main>
|
||||
<footer class="bottom-bar" id="journey"><ol class="steps" aria-label="设置进度"><li data-step="directory" class="active" aria-current="step"><span class="num">01</span>选择目录</li><li data-step="server"><span class="num">02</span>设置服务器</li><li data-step="desk"><span class="num">03</span>客户端工作台</li></ol><span class="bottom-note">BROWN DUST II · CLIENT UTILITY</span></footer>
|
||||
<footer class="bottom-bar" id="journey"><ol class="steps" aria-label="设置进度"><li data-step="directory" class="active" aria-current="step"><span class="num">01</span>选择目录</li><li data-step="server"><span class="num">02</span>设置服务器</li><li data-step="desk"><span class="num">03</span>BD2 启动器</li></ol><span class="bottom-note">BROWN DUST II · GAME LAUNCHER</span></footer>
|
||||
<div id="proxyHome" hidden><div id="proxyFields"><label class="field-label" for="proxyMode">连接方式</label><select id="proxyMode" class="proxy-select"><option value="direct">直接连接</option><option value="manual">手动 HTTP 代理</option></select><div id="proxyAddressField" hidden style="margin-top:18px"><label class="field-label" for="proxyURL">HTTP 代理地址</label><input id="proxyURL" type="text" placeholder="http://127.0.0.1:7890" autocomplete="off" spellcheck="false"><p class="small-note">填写 http://主机:端口,不支持账号、路径或查询参数。</p></div><p class="small-note">保存后在下次启动游戏时生效。本机地址 localhost、127.0.0.1 和 ::1 始终直接连接。</p><p class="small-note">HTTP 代理通过 CONNECT 支持游戏的 HTTPS 连接,仍会验证证书。浏览器使用自身的代理设置。</p><p id="proxyResult" class="inline-result" role="status"></p></div></div>
|
||||
<dialog id="editor" aria-labelledby="editorTitle"><div class="dialog-head"><h2 id="editorTitle">修改设置</h2><button class="dialog-close" id="closeEditor" aria-label="关闭设置">×</button></div><div id="editorContent"></div><p class="small-note">修改后请在工作台保存连接设置。</p><div class="dialog-actions"><button class="btn primary" id="doneEditor">完成修改</button></div></dialog>
|
||||
<dialog id="editor" aria-labelledby="editorTitle"><div class="dialog-head"><h2 id="editorTitle">修改设置</h2><button class="dialog-close" id="closeEditor" aria-label="关闭设置">×</button></div><div id="editorContent"></div><p class="small-note">修改后请在启动器保存连接设置。</p><div class="dialog-actions"><button class="btn primary" id="doneEditor">完成修改</button></div></dialog>
|
||||
<div class="toast" id="toast" role="status" aria-live="polite"></div>
|
||||
<noscript><p style="padding:20px">请启用 JavaScript 以使用客户端设置工具。</p></noscript>
|
||||
<noscript><p style="padding:20px">请启用 JavaScript 以使用BD2 启动器。</p></noscript>
|
||||
<script>
|
||||
(()=>{
|
||||
'use strict';
|
||||
@@ -76,9 +78,9 @@ const zhCN=CHINA_TIME_ZONES.has(detectedTimeZone);
|
||||
const localized=(zh,en)=>zhCN?zh:en;
|
||||
if(!zhCN){
|
||||
document.documentElement.lang='en';
|
||||
document.title='BD2 Client Studio';
|
||||
document.title='BD2 Launcher';
|
||||
const translations=new Map(Object.entries({
|
||||
'客户端设置工具 · 配置保存在本机':'Client setup utility · Settings stay on this computer','先从游戏目录':'Start with the game directory','开始。':'first.','选择已安装的游戏文件夹。':'Select the installed game folder.','我们会检查游戏程序和资源文件,再继续设置连接。':'We will inspect the game executable and assets before configuring the connection.','客户端配置':'Client configuration','选择游戏目录':'Select game directory','请选择包含':'Select the folder containing','的文件夹。':'.','游戏安装目录':'Game installation directory','浏览':'Browse','可直接填写路径,也可以浏览目录。':'Enter a path or browse for a directory.','检查目录':'Inspect directory','继续设置服务器':'Continue to server setup','此步骤只检查文件,不会修改游戏资源。':'This step only inspects files and does not modify game assets.','接下来,':'Next,','设置服务器。':'configure the server.','填写要连接的服务端地址。':'Enter the server you want to connect to.','进入工作台后,你可以选择资源来源、应用补丁和安装插件。':'In the workspace you can select a resource source, apply the patch, and install plugins.','目录已选择 · 之后仍可修改':'Directory selected · You can change it later','服务器地址':'Server address','填写完整地址,可以包含端口。':'Enter the complete origin, including a port when needed.','地址与端口':'Address and port','例如':'Example','不要添加':'Do not add','或其他路径。真实连接地址由 LI 插件读取。':'or another path. The LI plugin reads the actual connection address.','进入工作台':'Open workspace','返回目录设置':'Back to directory setup','客户端工作台':'Client workspace','管理连接设置,完成游戏启动前的准备。':'Manage connection settings and prepare the game client.','启动游戏':'Launch game','等待检查':'Waiting','连接设置':'Connection settings','随时可以修改':'Editable at any time','游戏目录':'Game directory','尚未选择':'Not selected','修改目录 ↗':'Change directory ↗','尚未填写':'Not entered','修改地址 ↗':'Change address ↗','资源来源':'Resource source','官方 CDN':'Official CDN','从官方节点下载资源,不占用服主的大文件流量。':'Download from official nodes without using the server owner’s bandwidth.','本机已下载资源':'Downloaded local resources','直接读取电脑上的 ServerData 和 GameData,不再下载相同文件。':'Read ServerData and GameData already stored on this computer.','服主资源':'Server-provided resources','由服务器提供资源地址;服主可自建 CDN,也可以反代官方 CDN。':'The server supplies resource URLs backed by either a private CDN or an official-CDN proxy.','本机 CDN 根目录':'Local CDN root directory','所选目录内必须同时包含':'The selected directory must contain both',' 和 ':' and ','。':'.','官方模式由客户端直连版本锁定的官方 CDN。':'Official mode connects directly to the release-locked official CDN.','验证资源来源 ↗':'Verify resource source ↗','保存连接设置':'Save connection settings','当前设置尚未保存。':'Current settings have not been saved.','补丁与插件':'Patch and plugins','操作前请先关闭游戏。补丁只修改内置 Intro 地址,并保留':'Close the game first. The patch only changes the built-in Intro address and retains a','备份。安装插件前,请先手动安装 BepInEx。':'backup. Install BepInEx manually before installing the plugins.','应用客户端补丁':'Apply client patch','安装 / 更新插件':'Install / update plugins','当前状态':'Current status','游戏程序':'Game executable','资源文件':'Asset file','需手动安装':'Manual install required','连接配置':'Connection configuration','尚未写入':'Not written','状态来自本机文件检查,不代表服务器在线。':'Status is based on local files and does not indicate server availability.','客户端版本:':'Client version:','游戏版本:':'Game version:','诊断日志:':'Diagnostic log:','重新检查 ↻':'Inspect again ↻','最近操作':'Recent operation','等待操作':'Waiting for an operation','选择游戏目录后即可开始检查。':'Select the game directory to begin.','查看操作记录':'View operation history','配置仅保存在你的电脑上':'Settings are stored only on your computer','不会保存账号凭据或服主密钥':'Account credentials and server-owner secrets are never stored','工具已退出':'Tool exited','现在可以关闭这个页面。':'You can close this page now.','选择目录':'Select directory','设置服务器':'Configure server','修改设置':'Edit settings','修改后请在工作台保存连接设置。':'Save changes from the workspace when finished.','完成修改':'Finish editing','请启用 JavaScripLine truncated
|
||||
'BD2 启动器 · 配置保存在本机':'BD2 Launcher · Settings stay on this computer','先从游戏目录':'Start with the game directory','开始。':'first.','选择已安装的游戏文件夹。':'Select the installed game folder.','我们会检查游戏程序和资源文件,再继续设置连接。':'We will inspect the game executable and assets before configuring the connection.','客户端配置':'Client configuration','选择游戏目录':'Select game directory','请选择包含':'Select the folder containing','的文件夹。':'.','游戏安装目录':'Game installation directory','浏览':'Browse','可直接填写路径,也可以浏览目录。':'Enter a path or browse for a directory.','检查目录':'Inspect directory','继续设置服务器':'Continue to server setup','此步骤只检查文件,不会修改游戏资源。':'This step only inspects files and does not modify game assets.','接下来,':'Next,','设置服务器。':'configure the server.','填写要连接的服务端地址。':'Enter the server you want to connect to.','进入启动器后,你可以选择资源来源、应用补丁和安装插件。':'In the launcher you can select a resource source, apply the patch, and install plugins.','目录已选择 · 之后仍可修改':'Directory selected · You can change it later','服务器地址':'Server address','填写完整地址,可以包含端口。':'Enter the complete origin, including a port when needed.','地址与端口':'Address and port','例如':'Example','不要添加':'Do not add','或其他路径。真实连接地址由 LI 插件读取。':'or another path. The LI plugin reads the actual connection address.','进入启动器':'Open launcher','返回目录设置':'Back to directory setup','BD2 启动器':'BD2 Launcher','管理连接设置,完成游戏启动前的准备。':'Manage connection settings and prepare the game client.','启动游戏':'Launch game','等待检查':'Waiting','连接设置':'Connection settings','随时可以修改':'Editable at any time','游戏目录':'Game directory','尚未选择':'Not selected','修改目录 ↗':'Change directory ↗','尚未填写':'Not entered','修改地址 ↗':'Change address ↗','资源来源':'Resource source','官方 CDN':'Official CDN','从官方节点下载资源,不占用服主的大文件流量。':'Download from official nodes without using the server owner’s bandwidth.','本机已下载资源':'Downloaded local resources','直接读取电脑上的 ServerData 和 GameData,不再下载相同文件。':'Read ServerData and GameData already stored on this computer.','服主资源':'Server-provided resources','由服务器提供资源地址;服主可自建 CDN,也可以反代官方 CDN。':'The server supplies resource URLs backed by either a private CDN or an official-CDN proxy.','本机 CDN 根目录':'Local CDN root directory','所选目录内必须同时包含':'The selected directory must contain both',' 和 ':' and ','。':'.','官方模式由客户端直连版本锁定的官方 CDN。':'Official mode connects directly to the release-locked official CDN.','验证资源来源 ↗':'Verify resource source ↗','保存连接设置':'Save connection settings','当前设置尚未保存。':'Current settings have not been saved.','补丁与插件':'Patch and plugins','操作前请先关闭游戏。补丁只修改内置 Intro 地址,并保留':'Close the game first. The patch only changes the built-in Intro address and retains a','备份。安装插件前,请先手动安装 BepInEx。':'backup. Install BepInEx manually before installing the plugins.','应用客户端补丁':'Apply client patch','安装 / 更新插件':'Install / update plugins','当前状态':'Current status','游戏程序':'Game executable','资源文件':'Asset file','需手动安装':'Manual install required','连接配置':'Connection configuration','尚未写入':'Not written','状态来自本机文件检查,不代表服务器在线。':'Status is based on local files and does not indicate server availability.','客户端版本:':'Client version:','游戏版本:':'Game version:','诊断日志:':'Diagnostic log:','重新检查 ↻':'Inspect again ↻','最近操作':'Recent operation','等待操作':'Waiting for an operation','选择游戏目录后即可开始检查。':'Select the game directory to begin.','查看操作记录':'View operation history','配置仅保存在你的电脑上':'Settings are stored only on your computer','不会保存账号凭据或服主密钥':'Account credentials and server-owner secrets are never stored','工具已退出':'Tool exited','现在可以关闭这个页面。':'You can close this page now.','选择目录':'Select directory','设置服务器':'Configure server','修改设置':'Edit settings','修改后请在启动器保存连接设置。':'Save changes from the launcher when finished.','完成修改':'Finish editing','请启用 JavaScript 以使用BD2 启动器。'Line truncated
|
||||
}));
|
||||
const walker=document.createTreeWalker(document.body,NodeFilter.SHOW_TEXT);let node;
|
||||
while(node=walker.nextNode()){if(node.parentElement&&['SCRIPT','STYLE'].includes(node.parentElement.tagName))continue;let value=node.nodeValue;for(const [source,target] of [...translations].sort((a,b)=>b[0].length-a[0].length))value=value.replaceAll(source,target);node.nodeValue=value}
|
||||
@@ -98,7 +100,7 @@ function show(message,error=false){message=message||(error?localized('操作未
|
||||
function mark(id,value,yes=localized('已就绪','Ready'),no=localized('未检测到','Not found')){const e=$(id);e.textContent=value===null?localized('等待检查','Waiting'):value?yes:no;e.className=value===null?'':value?'ok':'warn'}
|
||||
function renderStatus(){mark('sExe',status.executable);mark('sAssets',status.resources);mark('sBep',status.bepinex,localized('已安装','Installed'),localized('需手动安装','Manual install required'));mark('sConfig',status.config,localized('已写入','Written'),localized('尚未写入','Not written'));const checked=status.executable!==null&&status.resources!==null;const ready=status.executable&&status.resources;$('pulse').className='dot'+(checked?(ready?' good':' bad'):'');$('overallStatus').textContent=checked?(ready?localized('游戏文件已就绪','Game files ready'):localized('游戏文件待检查','Game files need attention')):localized('等待检查','Waiting');if(savedSignature&&signature()!==savedSignature){$('sConfig').textContent=localized('有未保存修改','Unsaved changes');$('sConfig').className='warn'}}
|
||||
function sync(){const p=payload();$('directorySummary').textContent=p.game_directory||localized('尚未选择','Not selected');$('serverSummary').textContent=p.server_origin||localized('尚未填写','Not entered');$('proxySummary').textContent=$('proxyMode').value==='manual'?(p.proxy_url||localized('手动 HTTP 代理 · 尚未填写','Manual HTTP proxy · Address required')):localized('直接连接','Direct connection');$('proxyAddressField').hidden=$('proxyMode').value!=='manual';$('localResource').hidden=p.cdn_mode!=='local';$('routeHint').textContent=p.cdn_mode==='official'?localized('官方模式由客户端直连版本锁定的官方 CDN。','Official mode connects directly to the release-locked official CDN.'):p.cdn_mode==='local'?localized('本机模式不会请求服务器资源接口;资源版本仍必须与当前客户端一致。','Local mode does not call the server resource API; resources must still match this client release.'):localized('服主自建与反代在客户端中是同一种来源,地址统一由服务器返回。','Private hosting and reverse proxying are one client mode; the server returns the resource URLs.');$('dirtyNotice').hidden=signature()===savedSignature;renderStatus()}
|
||||
function applyStatus(s){if(!s)return;if(s.game_directory)$('gameDir').value=s.game_directory;for(const key of Object.keys(status))status[key]=Boolean(s[key]);sync();$('directoryResult').textContent=status.executable&&status.resources?localized('游戏程序和资源文件已检测到。','Game executable and asset file found.'):localized('检查已完成,请在工作台查看缺失项。','Inspection completed; review missing items in the workspace.');$('directoryResult').className='inline-result'+(status.executable&&status.resources?'':' error')}
|
||||
function applyStatus(s){if(!s)return;if(s.game_directory)$('gameDir').value=s.game_directory;for(const key of Object.keys(status))status[key]=Boolean(s[key]);sync();$('directoryResult').textContent=status.executable&&status.resources?localized('游戏程序和资源文件已检测到。','Game executable and asset file found.'):localized('检查已完成,请在启动器查看缺失项。','Inspection completed; review missing items in the launcher.');$('directoryResult').className='inline-result'+(status.executable&&status.resources?'':' error')}
|
||||
function invalidate(directory=false){if(directory){for(const key of Object.keys(status))status[key]=null;$('directoryResult').textContent=localized('目录已修改,请重新检查。','The directory changed; inspect it again.')}$('policy').hidden=true;sync()}
|
||||
function requireDirectory(){if(!payload().game_directory){$('gameDir').focus();throw new Error(localized('请先选择游戏安装目录','Select the game installation directory first'))}}
|
||||
function requireOrigin(){const value=$('origin').value.trim();let u;try{u=new URL(value)}catch{throw new Error(localized('请输入完整服务器地址,例如 http://127.0.0.1:8080','Enter a complete server origin, for example http://127.0.0.1:8080'))}if(!['http:','https:'].includes(u.protocol)||u.username||u.password||u.search||u.hash||(u.pathname!=='/'&&u.pathname!==''))throw new Error(localized('服务器地址仅填写 http(s) 地址与端口,不要包含路径、查询参数或账号信息','Enter only an HTTP(S) origin and port, without a path, query, or credentials'));const loopback=['localhost','127.0.0.1','[::1]'].includes(u.hostname.toLowerCase());if(u.protocol!=='https:'&&!loopback)throw new Error(localized('公网或局域网服务器必须使用 HTTPS;只有本机 loopback 可以使用 HTTP','Public and LAN servers must use HTTPS; only loopback may use HTTP'));$('origin').value=value.replace(/\/$/,'');$('serverResult').textContent='';sync()}
|
||||
|
||||
@@ -3,17 +3,16 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
clientlayout "bd2server/internal/client/layout"
|
||||
commonconfig "bd2server/internal/common/config"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -149,48 +148,16 @@ func Save(gameDir string, in Settings) (Settings, error) {
|
||||
return Settings{}, err
|
||||
}
|
||||
path := Path(gameDir)
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||||
return Settings{}, fmt.Errorf("client config: create config directory: %w", err)
|
||||
}
|
||||
data, err := json.MarshalIndent(settings, "", " ")
|
||||
if err != nil {
|
||||
return Settings{}, err
|
||||
}
|
||||
data = append(data, '\n')
|
||||
temporary, err := os.CreateTemp(filepath.Dir(path), ".bd2-client-*.tmp")
|
||||
if err != nil {
|
||||
return Settings{}, fmt.Errorf("client config: create temporary config: %w", err)
|
||||
}
|
||||
temporaryPath := temporary.Name()
|
||||
defer func() { _ = os.Remove(temporaryPath) }()
|
||||
if err = temporary.Chmod(0o600); err == nil {
|
||||
_, err = temporary.Write(data)
|
||||
}
|
||||
if err == nil {
|
||||
err = temporary.Sync()
|
||||
}
|
||||
if closeErr := temporary.Close(); err == nil {
|
||||
err = closeErr
|
||||
}
|
||||
if err != nil {
|
||||
return Settings{}, fmt.Errorf("client config: stage config: %w", err)
|
||||
}
|
||||
if err := replaceFile(temporaryPath, path); err != nil {
|
||||
return Settings{}, fmt.Errorf("client config: install config: %w", err)
|
||||
if err := commonconfig.Save(path, settings, commonconfig.WriteOptions{}); err != nil {
|
||||
return Settings{}, fmt.Errorf("client config: save: %w", err)
|
||||
}
|
||||
return settings, nil
|
||||
}
|
||||
|
||||
func Load(gameDir string) (Settings, error) {
|
||||
data, err := os.ReadFile(Path(gameDir))
|
||||
settings, err := commonconfig.Load(Path(gameDir), Settings{}, commonconfig.DecodeOptions{DisallowUnknownFields: true})
|
||||
if err != nil {
|
||||
return Settings{}, err
|
||||
}
|
||||
var settings Settings
|
||||
decoder := json.NewDecoder(strings.NewReader(string(data)))
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(&settings); err != nil {
|
||||
return Settings{}, fmt.Errorf("client config: decode: %w", err)
|
||||
return Settings{}, fmt.Errorf("client config: load: %w", err)
|
||||
}
|
||||
if settings.SchemaVersion != SchemaVersion {
|
||||
return Settings{}, fmt.Errorf("client config: unsupported schema_version %d", settings.SchemaVersion)
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
commonconfig "bd2server/internal/common/config"
|
||||
)
|
||||
|
||||
const preferencesSchemaVersion = 1
|
||||
@@ -22,7 +22,7 @@ func PreferencesPath() (string, error) {
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("locate user configuration directory: %w", err)
|
||||
}
|
||||
return filepath.Join(root, "BD2 Client Studio", "preferences.json"), nil
|
||||
return filepath.Join(root, "BD2 Launcher", "preferences.json"), nil
|
||||
}
|
||||
|
||||
func LoadPreferences() (Preferences, error) {
|
||||
@@ -30,22 +30,12 @@ func LoadPreferences() (Preferences, error) {
|
||||
if err != nil {
|
||||
return Preferences{}, err
|
||||
}
|
||||
data, err := os.ReadFile(path)
|
||||
preferences, err := commonconfig.Load(path, Preferences{}, commonconfig.DecodeOptions{DisallowUnknownFields: true, RejectTrailing: true})
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return Preferences{}, nil
|
||||
}
|
||||
if err != nil {
|
||||
return Preferences{}, fmt.Errorf("read client preferences: %w", err)
|
||||
}
|
||||
decoder := json.NewDecoder(strings.NewReader(string(data)))
|
||||
decoder.DisallowUnknownFields()
|
||||
var preferences Preferences
|
||||
if err := decoder.Decode(&preferences); err != nil {
|
||||
return Preferences{}, fmt.Errorf("decode client preferences: %w", err)
|
||||
}
|
||||
var trailing any
|
||||
if err := decoder.Decode(&trailing); !errors.Is(err, io.EOF) {
|
||||
return Preferences{}, errors.New("client preferences must contain exactly one JSON object")
|
||||
return Preferences{}, fmt.Errorf("load client preferences: %w", err)
|
||||
}
|
||||
if preferences.SchemaVersion != preferencesSchemaVersion || strings.TrimSpace(preferences.GameDirectory) == "" {
|
||||
return Preferences{}, errors.New("client preferences are invalid")
|
||||
@@ -63,34 +53,9 @@ func SavePreferences(gameDirectory string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
|
||||
return fmt.Errorf("create client preferences directory: %w", err)
|
||||
}
|
||||
data, err := json.MarshalIndent(Preferences{SchemaVersion: preferencesSchemaVersion, GameDirectory: abs}, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
data = append(data, '\n')
|
||||
temporary, err := os.CreateTemp(filepath.Dir(path), ".preferences-*.tmp")
|
||||
if err != nil {
|
||||
return fmt.Errorf("stage client preferences: %w", err)
|
||||
}
|
||||
temporaryPath := temporary.Name()
|
||||
defer func() { _ = os.Remove(temporaryPath) }()
|
||||
if err = temporary.Chmod(0o600); err == nil {
|
||||
_, err = temporary.Write(data)
|
||||
}
|
||||
if err == nil {
|
||||
err = temporary.Sync()
|
||||
}
|
||||
if closeErr := temporary.Close(); err == nil {
|
||||
err = closeErr
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("stage client preferences: %w", err)
|
||||
}
|
||||
if err := replaceFile(temporaryPath, path); err != nil {
|
||||
return fmt.Errorf("install client preferences: %w", err)
|
||||
preferences := Preferences{SchemaVersion: preferencesSchemaVersion, GameDirectory: abs}
|
||||
if err := commonconfig.Save(path, preferences, commonconfig.WriteOptions{DirectoryMode: 0o700}); err != nil {
|
||||
return fmt.Errorf("save client preferences: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,86 +1,17 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"bd2server/internal/common/versionconfig"
|
||||
)
|
||||
|
||||
const ReleaseFileName = "versions.json"
|
||||
|
||||
var (
|
||||
gameVersionPattern = regexp.MustCompile(`^[0-9]+\.[0-9]+\.[0-9]+$`)
|
||||
releaseVersionPattern = regexp.MustCompile(`^([0-9]+\.[0-9]+\.[0-9]+)\+(client|server)\.([0-9]+\.[0-9]+\.[0-9]+)$`)
|
||||
resourceVersionPattern = regexp.MustCompile(`^[0-9]{14}$`)
|
||||
)
|
||||
|
||||
// ReleaseVersions separates the official game compatibility version from the
|
||||
// independently evolving client and server software release versions. The
|
||||
// release package carries the authoritative versions.json beside bd2client.
|
||||
type ReleaseVersions struct {
|
||||
GameVersion string `json:"game_version"`
|
||||
ClientVersion string `json:"client_version"`
|
||||
ServerVersion string `json:"server_version"`
|
||||
GameDataVersion string `json:"game_data_version"`
|
||||
BundleVersion string `json:"bundle_version"`
|
||||
SeedDirectory string `json:"seed_directory"`
|
||||
Plugins struct {
|
||||
LocalIdentity string `json:"local_identity"`
|
||||
CaptureEnvironment string `json:"capture_environment"`
|
||||
LoginUI string `json:"login_ui"`
|
||||
CashShop string `json:"cash_shop"`
|
||||
FChat string `json:"fchat"`
|
||||
} `json:"plugins"`
|
||||
}
|
||||
|
||||
func LoadReleaseVersions(path string) (ReleaseVersions, error) {
|
||||
data, err := os.ReadFile(filepath.Clean(path))
|
||||
if err != nil {
|
||||
return ReleaseVersions{}, fmt.Errorf("read client release versions: %w", err)
|
||||
}
|
||||
decoder := json.NewDecoder(strings.NewReader(string(data)))
|
||||
decoder.DisallowUnknownFields()
|
||||
var versions ReleaseVersions
|
||||
if err := decoder.Decode(&versions); err != nil {
|
||||
return ReleaseVersions{}, fmt.Errorf("decode client release versions: %w", err)
|
||||
}
|
||||
var trailing any
|
||||
if err := decoder.Decode(&trailing); !errors.Is(err, io.EOF) {
|
||||
return ReleaseVersions{}, errors.New("client release versions must contain exactly one JSON object")
|
||||
}
|
||||
if !gameVersionPattern.MatchString(versions.GameVersion) {
|
||||
return ReleaseVersions{}, fmt.Errorf("invalid game_version %q", versions.GameVersion)
|
||||
}
|
||||
if !validReleaseVersion(versions.ClientVersion, versions.GameVersion, "client") {
|
||||
return ReleaseVersions{}, fmt.Errorf("invalid client_version %q", versions.ClientVersion)
|
||||
}
|
||||
if !validReleaseVersion(versions.ServerVersion, versions.GameVersion, "server") {
|
||||
return ReleaseVersions{}, fmt.Errorf("invalid server_version %q", versions.ServerVersion)
|
||||
}
|
||||
if !resourceVersionPattern.MatchString(versions.BundleVersion) || !resourceVersionPattern.MatchString(versions.GameDataVersion) {
|
||||
return ReleaseVersions{}, errors.New("bundle_version and game_data_version must be 14-digit timestamps")
|
||||
}
|
||||
if versions.SeedDirectory == "" ||
|
||||
versions.Plugins.LocalIdentity == "" || versions.Plugins.LoginUI == "" || versions.Plugins.CaptureEnvironment == "" || versions.Plugins.FChat == "" {
|
||||
return ReleaseVersions{}, errors.New("client release versions are incomplete")
|
||||
}
|
||||
return versions, nil
|
||||
}
|
||||
|
||||
func validReleaseVersion(value, game, component string) bool {
|
||||
match := releaseVersionPattern.FindStringSubmatch(value)
|
||||
return len(match) == 4 && match[1] == game && match[2] == component
|
||||
}
|
||||
|
||||
func ReleaseVersionsBesideExecutable() (ReleaseVersions, error) {
|
||||
func ReleaseVersionsBesideExecutable() (versionconfig.Config, error) {
|
||||
executable, err := os.Executable()
|
||||
if err != nil {
|
||||
return ReleaseVersions{}, fmt.Errorf("locate bd2client executable: %w", err)
|
||||
return versionconfig.Config{}, fmt.Errorf("locate bd2client executable: %w", err)
|
||||
}
|
||||
return LoadReleaseVersions(filepath.Join(filepath.Dir(executable), ReleaseFileName))
|
||||
return versionconfig.Load(filepath.Join(filepath.Dir(executable), versionconfig.FileName))
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
package download
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var requiredGameFiles = []string{"BrownDust II.exe", "UnityPlayer.dll", "BrownDust II_Data/globalgamemanagers", "BrownDust II_Data/Managed/Assembly-CSharp.dll"}
|
||||
|
||||
func InstallBepInEx(packageDir, gameDir string) error {
|
||||
gameDir, err := filepath.Abs(gameDir)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := requireStopped(gameDir); err != nil {
|
||||
return err
|
||||
}
|
||||
return extractArchive(filepath.Join(packageDir, "bepinex.zip"), gameDir, false, "")
|
||||
}
|
||||
|
||||
func safeTarget(root, relative string) (string, error) {
|
||||
relative = strings.ReplaceAll(relative, "\\", "/")
|
||||
for part := range strings.SplitSeq(relative, "/") {
|
||||
if part == "" || part == "." || part == ".." || strings.ContainsAny(part, ":\x00") || strings.TrimRight(part, " .") != part {
|
||||
return "", fmt.Errorf("unsafe relative path %q", relative)
|
||||
}
|
||||
}
|
||||
target := filepath.Join(root, filepath.FromSlash(relative))
|
||||
for current := target; ; current = filepath.Dir(current) {
|
||||
info, err := os.Lstat(current)
|
||||
if err == nil && info.Mode()&os.ModeSymlink != 0 {
|
||||
return "", fmt.Errorf("symlink in output path %s", current)
|
||||
}
|
||||
if err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
return "", err
|
||||
}
|
||||
if current == root {
|
||||
break
|
||||
}
|
||||
if filepath.Dir(current) == current {
|
||||
return "", errors.New("path outside output root")
|
||||
}
|
||||
}
|
||||
return target, nil
|
||||
}
|
||||
|
||||
func validBundle(path string, size int64) bool {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
defer func() { _ = f.Close() }()
|
||||
header := make([]byte, 512)
|
||||
n, err := f.Read(header)
|
||||
if err != nil && err != io.EOF {
|
||||
return false
|
||||
}
|
||||
header = header[:n]
|
||||
if !bytes.HasPrefix(header, []byte("UnityFS\x00")) || len(header) < 12 {
|
||||
return false
|
||||
}
|
||||
offset := 12
|
||||
for range 2 {
|
||||
end := bytes.IndexByte(header[offset:], 0)
|
||||
if end < 0 {
|
||||
return false
|
||||
}
|
||||
offset += end + 1
|
||||
}
|
||||
return len(header) >= offset+8 && binary.BigEndian.Uint64(header[offset:offset+8]) == uint64(size)
|
||||
}
|
||||
|
||||
type archiveEntry struct {
|
||||
file *zip.File
|
||||
target string
|
||||
}
|
||||
|
||||
func archiveEntries(archive *zip.ReadCloser, root, prefix string) ([]archiveEntry, error) {
|
||||
var entries []archiveEntry
|
||||
seen := map[string]bool{}
|
||||
for _, entry := range archive.File {
|
||||
name := strings.ReplaceAll(entry.Name, "\\", "/")
|
||||
if !strings.HasPrefix(name, prefix) {
|
||||
continue
|
||||
}
|
||||
relative := strings.TrimSuffix(strings.TrimPrefix(name, prefix), "/")
|
||||
if relative == "" {
|
||||
continue
|
||||
}
|
||||
if entry.Mode()&os.ModeSymlink != 0 {
|
||||
return nil, fmt.Errorf("ZIP symlink %s is forbidden", name)
|
||||
}
|
||||
target, err := safeTarget(root, relative)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if seen[strings.ToLower(relative)] {
|
||||
return nil, fmt.Errorf("duplicate ZIP output %s", relative)
|
||||
}
|
||||
seen[strings.ToLower(relative)] = true
|
||||
entries = append(entries, archiveEntry{entry, target})
|
||||
}
|
||||
return entries, nil
|
||||
}
|
||||
|
||||
func extractEntry(entry archiveEntry) error {
|
||||
if entry.file.FileInfo().IsDir() {
|
||||
return os.MkdirAll(entry.target, 0755)
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(entry.target), 0755); err != nil {
|
||||
return err
|
||||
}
|
||||
in, err := entry.file.Open()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = in.Close() }()
|
||||
out, err := os.CreateTemp(filepath.Dir(entry.target), ".bd2-extract-*.part")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = out.Close(); _ = os.Remove(out.Name()) }()
|
||||
if _, err := io.Copy(out, in); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := out.Sync(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := out.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Rename(out.Name(), entry.target)
|
||||
}
|
||||
|
||||
func extractArchive(path, root string, game bool, digest string) error {
|
||||
archive, err := zip.OpenReader(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = archive.Close() }()
|
||||
prefix := ""
|
||||
if game {
|
||||
matches := 0
|
||||
for _, entry := range archive.File {
|
||||
name := strings.ReplaceAll(entry.Name, "\\", "/")
|
||||
if filepath.Base(name) == "BrownDust II.exe" {
|
||||
matches++
|
||||
prefix = strings.TrimSuffix(name, "BrownDust II.exe")
|
||||
}
|
||||
}
|
||||
if matches != 1 {
|
||||
return errors.New("game ZIP must contain exactly one BrownDust II.exe")
|
||||
}
|
||||
}
|
||||
entries, err := archiveEntries(archive, root, prefix)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
required := requiredGameFiles
|
||||
if !game {
|
||||
required = []string{"winhttp.dll", "doorstop_config.ini", "BepInEx/core/BepInEx.dll"}
|
||||
}
|
||||
present := map[string]bool{}
|
||||
for _, entry := range entries {
|
||||
relative, err := filepath.Rel(root, entry.target)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !entry.file.FileInfo().IsDir() {
|
||||
present[filepath.ToSlash(relative)] = true
|
||||
}
|
||||
}
|
||||
for _, name := range required {
|
||||
if !present[name] {
|
||||
return fmt.Errorf("ZIP missing %s", name)
|
||||
}
|
||||
}
|
||||
if !game {
|
||||
core, err := safeTarget(root, "BepInEx/core")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.RemoveAll(core); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
marker := filepath.Join(root, ".bd2-official-game-version")
|
||||
if game {
|
||||
value, err := os.ReadFile(marker)
|
||||
ready := err == nil && strings.TrimSpace(string(value)) == digest
|
||||
for _, entry := range entries {
|
||||
info, err := os.Stat(entry.target)
|
||||
if err != nil || info.IsDir() != entry.file.FileInfo().IsDir() || (!info.IsDir() && uint64(info.Size()) != entry.file.UncompressedSize64) {
|
||||
ready = false
|
||||
break
|
||||
}
|
||||
}
|
||||
if ready {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
for _, entry := range entries {
|
||||
if err := extractEntry(entry); err != nil {
|
||||
return fmt.Errorf("extract %s: %w", entry.file.Name, err)
|
||||
}
|
||||
}
|
||||
if game {
|
||||
return atomicWrite(marker, []byte(digest+"\n"))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateDataArchive(path string) (int, error) {
|
||||
archive, err := zip.OpenReader(path)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("GameData ZIP: %w", err)
|
||||
}
|
||||
defer func() { _ = archive.Close() }()
|
||||
if len(archive.File) == 0 {
|
||||
return 0, errors.New("empty GameData ZIP")
|
||||
}
|
||||
for _, entry := range archive.File {
|
||||
if entry.FileInfo().IsDir() {
|
||||
continue
|
||||
}
|
||||
reader, err := entry.Open()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
_, readErr := io.Copy(io.Discard, reader)
|
||||
if err := errors.Join(readErr, reader.Close()); err != nil {
|
||||
return 0, fmt.Errorf("GameData ZIP entry %s: %w", entry.Name, err)
|
||||
}
|
||||
}
|
||||
return len(archive.File), nil
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package download
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
commonconfig "bd2server/internal/common/config"
|
||||
"bd2server/internal/common/versionconfig"
|
||||
)
|
||||
|
||||
type Options struct {
|
||||
PackageDir, Manifest string
|
||||
GameDir, ResourceDir, ServerOrigin string
|
||||
Workers int
|
||||
ProbeOnly bool
|
||||
}
|
||||
|
||||
type Installation struct {
|
||||
GameDir, ResourceDir, ServerOrigin string
|
||||
Versions versionconfig.Config
|
||||
}
|
||||
|
||||
func Client(ctx context.Context, options Options, out io.Writer) (Installation, error) {
|
||||
var result Installation
|
||||
if options.Workers < 1 || options.Workers > 16 {
|
||||
return result, errors.New("download workers must be 1-16")
|
||||
}
|
||||
packageDir, err := filepath.Abs(options.PackageDir)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
manifestPath := options.Manifest
|
||||
if manifestPath == "" {
|
||||
manifestPath = filepath.Join(packageDir, "client-download.json")
|
||||
}
|
||||
m, err := commonconfig.Load(manifestPath, manifest{}, commonconfig.DecodeOptions{DisallowUnknownFields: true, RejectTrailing: true, AllowBOM: true, RejectNull: true})
|
||||
if err != nil {
|
||||
return result, fmt.Errorf("download manifest: %w", err)
|
||||
}
|
||||
if !timestamp.MatchString(m.GameDataVersion) || !timestamp.MatchString(m.BundleVersion) || !gameVersionPattern.MatchString(m.GameVersion) || m.Platform != "StandaloneWindows64" || !strings.HasPrefix(m.GamePath, "/Build/") {
|
||||
return result, errors.New("invalid Windows game download manifest")
|
||||
}
|
||||
if !sha256Pattern.MatchString(m.GameSHA256) || !sha256Pattern.MatchString(m.DataSHA256) || !sha256Pattern.MatchString(m.CatalogSHA256) || m.GameBytes <= 0 || m.DataBytes <= 0 || m.CatalogBytes <= 0 {
|
||||
return result, errors.New("download manifest requires pinned checksums and positive lengths")
|
||||
}
|
||||
result.Versions = versionconfig.Config{GameVersion: m.GameVersion, GameDataVersion: m.GameDataVersion, BundleVersion: m.BundleVersion}
|
||||
if options.GameDir == "" {
|
||||
options.GameDir = filepath.Join(packageDir, "game")
|
||||
}
|
||||
if options.ResourceDir == "" {
|
||||
options.ResourceDir = filepath.Join(packageDir, "resources")
|
||||
}
|
||||
result.GameDir, err = filepath.Abs(options.GameDir)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
result.ResourceDir, err = filepath.Abs(options.ResourceDir)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
result.ServerOrigin = options.ServerOrigin
|
||||
if result.ServerOrigin == "" {
|
||||
result.ServerOrigin = m.ServerOrigin
|
||||
}
|
||||
if !options.ProbeOnly {
|
||||
if err := requireStopped(result.GameDir); err != nil {
|
||||
return result, err
|
||||
}
|
||||
}
|
||||
d, err := newDownloader(packageDir, out)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
defer d.client.CloseIdleConnections()
|
||||
builds, err := d.fastest(ctx, m.BuildOrigins, m.GamePath, "Game ZIP")
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
dataPath := "/GameData/" + m.GameDataVersion
|
||||
serverPath := "/ServerData/" + m.Platform + "/HD/" + m.BundleVersion
|
||||
dataOrigins, err := d.fastest(ctx, m.ResourceOrigins, dataPath+"/release/common-dbdata.bin", "GameData")
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
bundleOrigins, err := d.fastest(ctx, m.ResourceOrigins, serverPath+"/catalog_alpha.json", "ServerData")
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
if options.ProbeOnly {
|
||||
return result, nil
|
||||
}
|
||||
archive := filepath.Join(packageDir, "downloads", "BrownDust-II-"+m.GameVersion+".zip")
|
||||
if err := d.receiveAll(ctx, []file{{remote: m.GamePath, target: archive, digest: m.GameSHA256, size: m.GameBytes}}, builds, 1); err != nil {
|
||||
return result, err
|
||||
}
|
||||
if err := extractArchive(archive, result.GameDir, true, m.GameSHA256); err != nil {
|
||||
return result, err
|
||||
}
|
||||
if err := d.resources(ctx, result.ResourceDir, m, serverPath, dataPath, bundleOrigins, dataOrigins, options.Workers); err != nil {
|
||||
return result, err
|
||||
}
|
||||
d.log("Downloaded: game=%s resources=%s", result.GameDir, result.ResourceDir)
|
||||
return result, nil
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package download
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
commonconfig "bd2server/internal/common/config"
|
||||
)
|
||||
|
||||
func TestClientProbeAndDownloadOnlyDoNotRequirePreparationPackage(t *testing.T) {
|
||||
const bundleVersion = "20261007175947"
|
||||
const dataVersion = "20261008155037"
|
||||
makeArchive := func(names []string) []byte {
|
||||
t.Helper()
|
||||
var raw bytes.Buffer
|
||||
archive := zip.NewWriter(&raw)
|
||||
for _, name := range names {
|
||||
entry, err := archive.CreateHeader(&zip.FileHeader{Name: name, Method: zip.Store})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := entry.Write(bytes.Repeat([]byte("archive-payload"), 32<<10)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := archive.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return raw.Bytes()
|
||||
}
|
||||
game := makeArchive(requiredGameFiles)
|
||||
data := makeArchive([]string{"common.db"})
|
||||
catalog := []byte(`{"m_InternalIds":["{BDNetwork.CdnInfo.Info}/StandaloneWindows64/HD/` + bundleVersion + `/scene.bundle"]}` + strings.Repeat(" ", 256<<10))
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case strings.HasPrefix(r.URL.Path, "/Build/"):
|
||||
_, _ = w.Write(game)
|
||||
case strings.HasSuffix(r.URL.Path, "/common-dbdata.bin"):
|
||||
_, _ = w.Write(data)
|
||||
case strings.HasSuffix(r.URL.Path, "/common-dbdata.info"):
|
||||
_, _ = fmt.Fprint(w, len(data))
|
||||
case strings.HasSuffix(r.URL.Path, "/design.version"):
|
||||
_, _ = fmt.Fprintf(w, `{"version":"%s"}`, dataVersion)
|
||||
case strings.HasSuffix(r.URL.Path, "/catalog_alpha.json"):
|
||||
_, _ = w.Write(catalog)
|
||||
case strings.HasSuffix(r.URL.Path, "/catalog_alpha.hash"):
|
||||
_, _ = io.WriteString(w, "0f90a94601be05737f86a4ec7a1c889f")
|
||||
case strings.HasSuffix(r.URL.Path, "/scene.bundle"):
|
||||
_, _ = w.Write([]byte{'U', 'n', 'i', 't', 'y', 'F', 'S', 0, 0, 0, 0, 6, 'v', 0, 'r', 0, 0, 0, 0, 0, 0, 0, 0, 24})
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
root := t.TempDir()
|
||||
m := manifest{
|
||||
GameVersion: "2.36.7", GameDataVersion: dataVersion, BundleVersion: bundleVersion, Platform: "StandaloneWindows64",
|
||||
BuildOrigins: []string{server.URL}, ResourceOrigins: []string{server.URL}, GamePath: "/Build/game.zip",
|
||||
GameSHA256: fmt.Sprintf("%x", sha256.Sum256(game)), GameBytes: int64(len(game)),
|
||||
DataSHA256: fmt.Sprintf("%x", sha256.Sum256(data)), DataBytes: int64(len(data)),
|
||||
CatalogSHA256: fmt.Sprintf("%x", sha256.Sum256(catalog)), CatalogBytes: int64(len(catalog)),
|
||||
}
|
||||
manifestPath := filepath.Join(root, "client-download.json")
|
||||
if err := commonconfig.Save(manifestPath, m, commonconfig.WriteOptions{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
installed, err := Client(context.Background(), Options{PackageDir: root, Workers: 2, ProbeOnly: true}, io.Discard)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
entries, err := os.ReadDir(root)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(entries) != 1 || entries[0].Name() != "client-download.json" {
|
||||
t.Fatalf("probe created installation or checkpoint files: %v", entries)
|
||||
}
|
||||
if installed.GameDir != filepath.Join(root, "game") || installed.ResourceDir != filepath.Join(root, "resources") {
|
||||
t.Fatalf("download returned incorrect preparation paths: %+v", installed)
|
||||
}
|
||||
installed, err = Client(context.Background(), Options{PackageDir: root, Workers: 2}, io.Discard)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, name := range requiredGameFiles {
|
||||
actual, err := os.ReadFile(filepath.Join(installed.GameDir, filepath.FromSlash(name)))
|
||||
if err != nil || !bytes.Equal(actual, bytes.Repeat([]byte("archive-payload"), 32<<10)) {
|
||||
t.Fatalf("game file was not downloaded intact: %s, %v", name, err)
|
||||
}
|
||||
}
|
||||
for _, name := range []string{"BepInEx", "winhttp.dll"} {
|
||||
if _, err := os.Stat(filepath.Join(installed.GameDir, name)); !os.IsNotExist(err) {
|
||||
t.Fatalf("download-only installed preparation files: %s, %v", name, err)
|
||||
}
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(installed.ResourceDir, "resource-fetch-manifest.json")); err != nil {
|
||||
t.Fatal("resource installation did not complete", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package download
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"flag"
|
||||
"io"
|
||||
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type manifest struct {
|
||||
GameVersion string `json:"game_version"`
|
||||
GameDataVersion string `json:"game_data_version"`
|
||||
BundleVersion string `json:"bundle_version"`
|
||||
Platform string `json:"platform"`
|
||||
ServerOrigin string `json:"server_origin"`
|
||||
BuildOrigins []string `json:"build_origins"`
|
||||
ResourceOrigins []string `json:"resource_origins"`
|
||||
GamePath string `json:"game_path"`
|
||||
GameSHA256 string `json:"game_sha256"`
|
||||
GameBytes int64 `json:"game_bytes"`
|
||||
DataSHA256 string `json:"data_sha256"`
|
||||
DataBytes int64 `json:"data_bytes"`
|
||||
CatalogSHA256 string `json:"catalog_sha256"`
|
||||
CatalogBytes int64 `json:"catalog_bytes"`
|
||||
CatalogHash string `json:"catalog_hash"`
|
||||
}
|
||||
|
||||
var timestamp = regexp.MustCompile(`^[0-9]{14}$`)
|
||||
var sha256Pattern = regexp.MustCompile(`^[a-f0-9]{64}$`)
|
||||
var gameVersionPattern = regexp.MustCompile(`^[0-9]+\.[0-9]+\.[0-9]+$`)
|
||||
|
||||
func RunResources(ctx context.Context, args []string, out io.Writer) error {
|
||||
fs := flag.NewFlagSet("download-resources", flag.ContinueOnError)
|
||||
fs.SetOutput(out)
|
||||
root := fs.String("output", "", "output directory containing ServerData and GameData")
|
||||
platform := fs.String("platform", "StandaloneWindows64", "resource platform")
|
||||
bundle := fs.String("bundle-version", "", "14-digit ServerData version")
|
||||
data := fs.String("game-data-version", "", "14-digit GameData version")
|
||||
serverURL := fs.String("server-data-url", "https://dl.bd2.pmang.cloud/ServerData", "ServerData root URL")
|
||||
dataURL := fs.String("game-data-url", "https://dl.bd2.pmang.cloud/GameData", "GameData root URL")
|
||||
workers := fs.Int("workers", 8, "parallel downloads (1-16)")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
if errors.Is(err, flag.ErrHelp) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
if fs.NArg() != 0 || *root == "" || !timestamp.MatchString(*bundle) || !timestamp.MatchString(*data) || *workers < 1 || *workers > 16 || strings.ContainsAny(*platform, "/\\") || *platform == "" {
|
||||
return errors.New("download-resources requires --output, --bundle-version, --game-data-version and workers 1-16")
|
||||
}
|
||||
abs, err := filepath.Abs(*root)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d, err := newDownloader(abs, out)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer d.client.CloseIdleConnections()
|
||||
m := manifest{BundleVersion: *bundle, GameDataVersion: *data, Platform: *platform}
|
||||
return d.resources(ctx, abs, m, "/"+*platform+"/HD/"+*bundle, "/"+*data, []string{strings.TrimRight(*serverURL, "/")}, []string{strings.TrimRight(*dataURL, "/")}, *workers)
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
package download
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// The resource paths follow the native Addressables catalog and GameData URL layout.
|
||||
func TestResourceDownloadRejectsCorruptionAndResumesCompleteInstallation(t *testing.T) {
|
||||
const bundleVersion = "20261007175947"
|
||||
const dataVersion = "20261008155037"
|
||||
header := bytes.NewBufferString("UnityFS\x00")
|
||||
if err := binary.Write(header, binary.BigEndian, uint32(6)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
header.WriteString("2022.3\x002022.3.62f1\x00")
|
||||
length := header.Len() + 8 + len("bundle-payload")
|
||||
if err := binary.Write(header, binary.BigEndian, uint64(length)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
header.WriteString("bundle-payload")
|
||||
valid := header.Bytes()
|
||||
var data bytes.Buffer
|
||||
dataArchive := zip.NewWriter(&data)
|
||||
entry, err := dataArchive.Create("common.db")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := io.WriteString(entry, "resource-database"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := dataArchive.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var requests, bundleAttempts atomic.Int32
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requests.Add(1)
|
||||
if r.Header.Get("Range") != "" {
|
||||
t.Error("resource transfer used a partial GET")
|
||||
}
|
||||
switch {
|
||||
case strings.HasSuffix(r.URL.Path, "/catalog_alpha.json"):
|
||||
_, _ = fmt.Fprintf(w, `{"m_InternalIds":["{BDNetwork.CdnInfo.Info}/StandaloneWindows64/HD/%s/nested/scene.bundle"]}`, bundleVersion)
|
||||
case strings.HasSuffix(r.URL.Path, "/catalog_alpha.hash"):
|
||||
_, _ = io.WriteString(w, "0f90a94601be05737f86a4ec7a1c889f")
|
||||
case strings.HasSuffix(r.URL.Path, "/design.version"):
|
||||
_, _ = fmt.Fprintf(w, `{"version":"%s"}`, dataVersion)
|
||||
case strings.HasSuffix(r.URL.Path, "/common-dbdata.info"):
|
||||
_, _ = fmt.Fprint(w, data.Len())
|
||||
case strings.HasSuffix(r.URL.Path, "/common-dbdata.bin"):
|
||||
_, _ = w.Write(data.Bytes())
|
||||
case strings.HasSuffix(r.URL.Path, "/nested/scene.bundle"):
|
||||
if bundleAttempts.Add(1) == 1 {
|
||||
_, _ = w.Write(valid[:len(valid)-1])
|
||||
return
|
||||
}
|
||||
_, _ = w.Write(valid)
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
root := t.TempDir()
|
||||
args := []string{"--output", root, "--bundle-version", bundleVersion, "--game-data-version", dataVersion, "--server-data-url", server.URL + "/ServerData", "--game-data-url", server.URL + "/GameData"}
|
||||
if err := RunResources(context.Background(), args, io.Discard); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if bundleAttempts.Load() != 2 {
|
||||
t.Fatalf("corrupt bundle did not require a full retry: %d", bundleAttempts.Load())
|
||||
}
|
||||
bundlePath := filepath.Join(root, "ServerData", "StandaloneWindows64", "HD", bundleVersion, "nested", "scene.bundle")
|
||||
installed, err := os.ReadFile(bundlePath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(installed, valid) {
|
||||
t.Fatal("corrupt or incomplete bundle was published")
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(root, "GameData", dataVersion, "release", "common-dbdata.bin")); err != nil {
|
||||
t.Fatal("native GameData layout missing", err)
|
||||
}
|
||||
before := requests.Load()
|
||||
if err := RunResources(context.Background(), args, io.Discard); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if requests.Load() != before {
|
||||
t.Fatal("reopened downloader fetched already verified installation")
|
||||
}
|
||||
if err := os.WriteFile(bundlePath, []byte("corrupt-local-file"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := RunResources(context.Background(), args, io.Discard); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if bundleAttempts.Load() != 3 {
|
||||
t.Fatal("damaged cached bundle was trusted")
|
||||
}
|
||||
repaired, err := os.ReadFile(bundlePath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(repaired, valid) {
|
||||
t.Fatal("download retry did not repair the installed bundle")
|
||||
}
|
||||
if err := filepath.WalkDir(root, func(path string, entry os.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if strings.HasSuffix(entry.Name(), ".part") {
|
||||
return fmt.Errorf("temporary file left: %s", path)
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnsafeArchiveDoesNotAlterAnExistingInstallation(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
game := filepath.Join(root, "game")
|
||||
if err := os.Mkdir(game, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sentinel := filepath.Join(game, "BrownDust II.exe")
|
||||
if err := os.WriteFile(sentinel, []byte("existing-game"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
path := filepath.Join(root, "game.zip")
|
||||
out, err := os.Create(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
archive := zip.NewWriter(out)
|
||||
for _, name := range []string{"BrownDust II.exe", "UnityPlayer.dll", "BrownDust II_Data/globalgamemanagers", "BrownDust II_Data/Managed/Assembly-CSharp.dll", "../escape.dll"} {
|
||||
entry, err := archive.Create(name)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := io.WriteString(entry, "replacement"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := archive.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := out.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := extractArchive(path, game, true, "digest"); err == nil {
|
||||
t.Fatal("unsafe archive was extracted")
|
||||
}
|
||||
value, err := os.ReadFile(sentinel)
|
||||
if err != nil || string(value) != "existing-game" {
|
||||
t.Fatal("rejected archive changed the existing game")
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(root, "escape.dll")); !os.IsNotExist(err) {
|
||||
t.Fatal("archive escaped game directory")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
//go:build !windows
|
||||
|
||||
package download
|
||||
|
||||
func requireStopped(string) error { return nil }
|
||||
@@ -0,0 +1,46 @@
|
||||
package download
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"unsafe"
|
||||
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
func requireStopped(game string) error {
|
||||
snapshot, err := windows.CreateToolhelp32Snapshot(windows.TH32CS_SNAPPROCESS, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = windows.CloseHandle(snapshot) }()
|
||||
entry := windows.ProcessEntry32{Size: uint32(unsafe.Sizeof(windows.ProcessEntry32{}))}
|
||||
for err = windows.Process32First(snapshot, &entry); err == nil; err = windows.Process32Next(snapshot, &entry) {
|
||||
if !strings.EqualFold(windows.UTF16ToString(entry.ExeFile[:]), "BrownDust II.exe") {
|
||||
continue
|
||||
}
|
||||
process, openErr := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, entry.ProcessID)
|
||||
if errors.Is(openErr, windows.ERROR_INVALID_PARAMETER) {
|
||||
continue
|
||||
}
|
||||
if openErr != nil {
|
||||
return fmt.Errorf("cannot inspect running game; close it before downloading: %w", openErr)
|
||||
}
|
||||
buffer := make([]uint16, 32768)
|
||||
size := uint32(len(buffer))
|
||||
queryErr := windows.QueryFullProcessImageName(process, 0, &buffer[0], &size)
|
||||
_ = windows.CloseHandle(process)
|
||||
if queryErr != nil {
|
||||
return fmt.Errorf("cannot inspect running game path: %w", queryErr)
|
||||
}
|
||||
if strings.EqualFold(filepath.Clean(windows.UTF16ToString(buffer[:size])), filepath.Join(game, "BrownDust II.exe")) {
|
||||
return errors.New("this game installation is running; exit it before downloading")
|
||||
}
|
||||
}
|
||||
if !errors.Is(err, windows.ERROR_NO_MORE_FILES) {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package download
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
commonconfig "bd2server/internal/common/config"
|
||||
"bd2server/internal/common/resourcecatalog"
|
||||
)
|
||||
|
||||
func (d *downloader) resources(ctx context.Context, root string, m manifest, serverPath, dataPath string, serverOrigins, dataOrigins []string, workers int) error {
|
||||
serverDir := filepath.Join(root, "ServerData", m.Platform, "HD", m.BundleVersion)
|
||||
dataDir := filepath.Join(root, "GameData", m.GameDataVersion)
|
||||
catalog := filepath.Join(serverDir, "catalog_alpha.json")
|
||||
hashPath := filepath.Join(serverDir, "catalog_alpha.hash")
|
||||
if err := d.receiveAll(ctx, []file{{remote: serverPath + "/catalog_alpha.json", target: catalog, digest: m.CatalogSHA256, size: m.CatalogBytes}, {remote: serverPath + "/catalog_alpha.hash", target: hashPath}}, serverOrigins, 2); err != nil {
|
||||
return err
|
||||
}
|
||||
hash, err := os.ReadFile(hashPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
actualHash := strings.TrimSpace(string(hash))
|
||||
if !regexp.MustCompile(`^[a-fA-F0-9]{32}$`).MatchString(actualHash) || (m.CatalogHash != "" && actualHash != m.CatalogHash) {
|
||||
return errors.New("ServerData catalog hash does not match the selected version")
|
||||
}
|
||||
raw, err := os.ReadFile(catalog)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, ids, err := resourcecatalog.Decode(raw)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, id := range ids {
|
||||
parts := strings.Split(strings.ReplaceAll(id, "\\", "/"), "/")
|
||||
if parts[0] != "{BDNetwork.CdnInfo.Info}" {
|
||||
continue
|
||||
}
|
||||
if len(parts) < 5 || parts[1] != m.Platform || (parts[2] != "HD" && parts[2] != "{BDNetwork.CdnInfo.Resolution}") || (parts[3] != m.BundleVersion && parts[3] != "{BDNetwork.CdnInfo.Version}") {
|
||||
return fmt.Errorf("catalog version/platform mismatch: %s", id)
|
||||
}
|
||||
}
|
||||
paths, err := resourcecatalog.BundlePaths(raw)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := d.receiveAll(ctx, []file{{remote: dataPath + "/design.version", target: filepath.Join(dataDir, "design.version")}, {remote: dataPath + "/release/common-dbdata.info", target: filepath.Join(dataDir, "release", "common-dbdata.info")}, {remote: dataPath + "/release/common-dbdata.bin", target: filepath.Join(dataDir, "release", "common-dbdata.bin"), digest: m.DataSHA256, size: m.DataBytes}}, dataOrigins, 3); err != nil {
|
||||
return err
|
||||
}
|
||||
var design struct {
|
||||
Version json.RawMessage `json:"version"`
|
||||
}
|
||||
designRaw, err := os.ReadFile(filepath.Join(dataDir, "design.version"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := json.Unmarshal(bytes.TrimPrefix(designRaw, []byte{0xef, 0xbb, 0xbf}), &design); err != nil {
|
||||
return err
|
||||
}
|
||||
if strings.Trim(string(design.Version), "\"") != m.GameDataVersion {
|
||||
return errors.New("GameData design.version mismatch")
|
||||
}
|
||||
info, err := os.ReadFile(filepath.Join(dataDir, "release", "common-dbdata.info"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
size, err := strconv.ParseInt(strings.TrimSpace(strings.TrimPrefix(string(info), "\ufeff")), 10, 64)
|
||||
if err != nil {
|
||||
return fmt.Errorf("GameData size metadata: %w", err)
|
||||
}
|
||||
stat, err := os.Stat(filepath.Join(dataDir, "release", "common-dbdata.bin"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if size != stat.Size() {
|
||||
return errors.New("GameData size metadata mismatch")
|
||||
}
|
||||
entries, err := validateDataArchive(filepath.Join(dataDir, "release", "common-dbdata.bin"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
files := make([]file, 0, len(paths))
|
||||
for _, path := range paths {
|
||||
target, err := safeTarget(serverDir, path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
files = append(files, file{remote: serverPath + "/" + escapedPath(path), target: target, bundle: true})
|
||||
}
|
||||
if err := d.receiveAll(ctx, files, serverOrigins, workers); err != nil {
|
||||
return err
|
||||
}
|
||||
var total int64
|
||||
for _, file := range files {
|
||||
info, err := os.Stat(file.target)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
total += info.Size()
|
||||
}
|
||||
return commonconfig.Save(filepath.Join(root, "resource-fetch-manifest.json"), map[string]any{
|
||||
"bundle_version": m.BundleVersion, "game_data_version": m.GameDataVersion, "platform": m.Platform,
|
||||
"server_data": map[string]any{"catalog_hash": strings.ToLower(actualHash), "bundles": len(files), "bytes": total},
|
||||
"game_data": map[string]any{"version": m.GameDataVersion, "entry_count": entries, "bytes": size},
|
||||
}, commonconfig.WriteOptions{FileMode: 0644})
|
||||
}
|
||||
@@ -0,0 +1,321 @@
|
||||
package download
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
commonconfig "bd2server/internal/common/config"
|
||||
)
|
||||
|
||||
type file struct {
|
||||
remote, target, digest string
|
||||
size int64
|
||||
bundle bool
|
||||
}
|
||||
|
||||
type receipt struct {
|
||||
Bytes int64 `json:"bytes"`
|
||||
SHA256 string `json:"sha256"`
|
||||
}
|
||||
|
||||
type downloader struct {
|
||||
root, checkpoint string
|
||||
client *http.Client
|
||||
out io.Writer
|
||||
mu sync.Mutex
|
||||
records map[string]receipt
|
||||
}
|
||||
|
||||
func newDownloader(root string, out io.Writer) (*downloader, error) {
|
||||
transport := http.DefaultTransport.(*http.Transport).Clone()
|
||||
transport.Proxy = nil
|
||||
transport.MaxIdleConnsPerHost = 16
|
||||
transport.ResponseHeaderTimeout = 30 * time.Second
|
||||
d := &downloader{root: root, checkpoint: filepath.Join(root, "downloads", "verified-downloads.json"), client: &http.Client{Transport: transport, Timeout: 30 * time.Minute}, out: out, records: map[string]receipt{}}
|
||||
saved, err := commonconfig.Load(d.checkpoint, struct {
|
||||
SchemaVersion int `json:"schema_version"`
|
||||
Files map[string]receipt `json:"files"`
|
||||
}{}, commonconfig.DecodeOptions{AllowBOM: true, RejectTrailing: true, RejectNull: true})
|
||||
if err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
return nil, err
|
||||
}
|
||||
if err == nil {
|
||||
if saved.SchemaVersion != 1 {
|
||||
return nil, errors.New("unsupported download checkpoint")
|
||||
}
|
||||
if saved.Files != nil {
|
||||
d.records = saved.Files
|
||||
}
|
||||
}
|
||||
return d, nil
|
||||
}
|
||||
|
||||
func (d *downloader) log(format string, args ...any) {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
_, _ = fmt.Fprintf(d.out, format+"\n", args...)
|
||||
}
|
||||
|
||||
func hashFile(path string) (string, error) {
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer func() { _ = f.Close() }()
|
||||
h := sha256.New()
|
||||
if _, err = io.Copy(h, f); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return hex.EncodeToString(h.Sum(nil)), nil
|
||||
}
|
||||
|
||||
func (d *downloader) verified(item file) bool {
|
||||
info, err := os.Stat(item.target)
|
||||
if err != nil || !info.Mode().IsRegular() || info.Size() == 0 || (item.size > 0 && item.size != info.Size()) {
|
||||
return false
|
||||
}
|
||||
if item.bundle && !validBundle(item.target, info.Size()) {
|
||||
return false
|
||||
}
|
||||
key, err := filepath.Rel(d.root, item.target)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
d.mu.Lock()
|
||||
previous := d.records[filepath.ToSlash(key)]
|
||||
d.mu.Unlock()
|
||||
expected := item.digest
|
||||
if expected == "" && previous.Bytes == info.Size() {
|
||||
expected = previous.SHA256
|
||||
}
|
||||
if expected == "" {
|
||||
return false
|
||||
}
|
||||
actual, err := hashFile(item.target)
|
||||
return err == nil && actual == expected
|
||||
}
|
||||
|
||||
func (d *downloader) receive(ctx context.Context, item file, origins []string) error {
|
||||
if d.verified(item) {
|
||||
return nil
|
||||
}
|
||||
if len(origins) == 0 {
|
||||
return errors.New("no download origins")
|
||||
}
|
||||
var last error
|
||||
for attempt := 0; attempt < max(4, len(origins)*2); attempt++ {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
last = d.receiveOnce(ctx, item, origins[attempt%len(origins)])
|
||||
if last == nil {
|
||||
return nil
|
||||
}
|
||||
d.log("Retry %s: %v", filepath.Base(item.target), last)
|
||||
}
|
||||
return fmt.Errorf("download %s: %w", item.remote, last)
|
||||
}
|
||||
|
||||
func (d *downloader) receiveOnce(ctx context.Context, item file, origin string) error {
|
||||
if err := os.MkdirAll(filepath.Dir(item.target), 0755); err != nil {
|
||||
return err
|
||||
}
|
||||
request, err := http.NewRequestWithContext(ctx, http.MethodGet, strings.TrimRight(origin, "/")+item.remote, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
request.Header.Set("Accept-Encoding", "identity")
|
||||
response, err := d.client.Do(request)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = response.Body.Close() }()
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("full GET requires HTTP 200, got %s", response.Status)
|
||||
}
|
||||
temporary, err := os.CreateTemp(filepath.Dir(item.target), ".bd2-download-*.part")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = temporary.Close(); _ = os.Remove(temporary.Name()) }()
|
||||
h := sha256.New()
|
||||
written, err := io.Copy(io.MultiWriter(temporary, h), response.Body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if written == 0 || (response.ContentLength >= 0 && written != response.ContentLength) || (item.size > 0 && written != item.size) {
|
||||
return errors.New("incomplete download length")
|
||||
}
|
||||
actual := hex.EncodeToString(h.Sum(nil))
|
||||
if item.digest != "" && item.digest != actual {
|
||||
return errors.New("SHA-256 mismatch")
|
||||
}
|
||||
if err := temporary.Sync(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := temporary.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
if item.bundle && !validBundle(temporary.Name(), written) {
|
||||
return errors.New("invalid UnityFS bundle length")
|
||||
}
|
||||
if err := os.Rename(temporary.Name(), item.target); err != nil {
|
||||
return err
|
||||
}
|
||||
key, err := filepath.Rel(d.root, item.target)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
d.records[filepath.ToSlash(key)] = receipt{Bytes: written, SHA256: actual}
|
||||
return commonconfig.Save(d.checkpoint, struct {
|
||||
SchemaVersion int `json:"schema_version"`
|
||||
Files map[string]receipt `json:"files"`
|
||||
}{1, d.records}, commonconfig.WriteOptions{FileMode: 0644})
|
||||
}
|
||||
|
||||
func (d *downloader) receiveAll(ctx context.Context, files []file, origins []string, workers int) error {
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
jobs := make(chan file)
|
||||
var wg sync.WaitGroup
|
||||
var first error
|
||||
var errOnce sync.Once
|
||||
completed := 0
|
||||
var progress sync.Mutex
|
||||
for range min(workers, len(files)) {
|
||||
wg.Go(func() {
|
||||
for item := range jobs {
|
||||
if err := d.receive(ctx, item, origins); err != nil {
|
||||
errOnce.Do(func() { first = err; cancel() })
|
||||
return
|
||||
}
|
||||
progress.Lock()
|
||||
completed++
|
||||
if completed%25 == 0 || completed == len(files) {
|
||||
d.log("Completed %d/%d", completed, len(files))
|
||||
}
|
||||
progress.Unlock()
|
||||
}
|
||||
})
|
||||
}
|
||||
feed:
|
||||
for _, item := range files {
|
||||
select {
|
||||
case jobs <- item:
|
||||
case <-ctx.Done():
|
||||
break feed
|
||||
}
|
||||
}
|
||||
close(jobs)
|
||||
wg.Wait()
|
||||
if first != nil {
|
||||
return first
|
||||
}
|
||||
return ctx.Err()
|
||||
}
|
||||
|
||||
func (d *downloader) fastest(ctx context.Context, origins []string, relative, label string) ([]string, error) {
|
||||
type result struct {
|
||||
origin string
|
||||
speed float64
|
||||
err error
|
||||
}
|
||||
results := make([]result, len(origins))
|
||||
var wg sync.WaitGroup
|
||||
for i, origin := range origins {
|
||||
wg.Go(func() {
|
||||
probe, cancel := context.WithTimeout(ctx, 18*time.Second)
|
||||
defer cancel()
|
||||
request, err := http.NewRequestWithContext(probe, http.MethodGet, strings.TrimRight(origin, "/")+relative, nil)
|
||||
if err != nil {
|
||||
results[i] = result{origin: origin, err: err}
|
||||
return
|
||||
}
|
||||
request.Header.Set("Accept-Encoding", "identity")
|
||||
start := time.Now()
|
||||
response, err := d.client.Do(request)
|
||||
if err != nil {
|
||||
results[i] = result{origin: origin, err: err}
|
||||
return
|
||||
}
|
||||
defer func() { _ = response.Body.Close() }()
|
||||
if response.StatusCode != http.StatusOK {
|
||||
results[i] = result{origin: origin, err: fmt.Errorf("HTTP %s", response.Status)}
|
||||
return
|
||||
}
|
||||
n, err := io.Copy(io.Discard, io.LimitReader(response.Body, 4<<20))
|
||||
speed := float64(0)
|
||||
if n >= 256<<10 {
|
||||
speed = float64(n) / time.Since(start).Seconds()
|
||||
}
|
||||
results[i] = result{origin: origin, speed: speed, err: err}
|
||||
})
|
||||
}
|
||||
wg.Wait()
|
||||
slices.SortStableFunc(results, func(a, b result) int {
|
||||
if a.speed > b.speed {
|
||||
return -1
|
||||
}
|
||||
if a.speed < b.speed {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
})
|
||||
var ranked []string
|
||||
for _, r := range results {
|
||||
if r.speed > 0 {
|
||||
ranked = append(ranked, r.origin)
|
||||
d.log("%s %s: %.2f MiB/s", label, r.origin, r.speed/(1<<20))
|
||||
} else {
|
||||
d.log("%s %s: unavailable (%v)", label, r.origin, r.err)
|
||||
}
|
||||
}
|
||||
if len(ranked) == 0 {
|
||||
return nil, fmt.Errorf("%s: all download origins unavailable", label)
|
||||
}
|
||||
d.log("%s selected: %s", label, ranked[0])
|
||||
return ranked, nil
|
||||
}
|
||||
|
||||
func escapedPath(path string) string {
|
||||
parts := strings.Split(filepath.ToSlash(path), "/")
|
||||
for i := range parts {
|
||||
parts[i] = url.PathEscape(parts[i])
|
||||
}
|
||||
return strings.Join(parts, "/")
|
||||
}
|
||||
|
||||
func atomicWrite(path string, data []byte) error {
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
|
||||
return err
|
||||
}
|
||||
tmp, err := os.CreateTemp(filepath.Dir(path), ".bd2-download-*.part")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = tmp.Close(); _ = os.Remove(tmp.Name()) }()
|
||||
if _, err := tmp.Write(data); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tmp.Sync(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tmp.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Rename(tmp.Name(), path)
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
// Package iconresource generates the Windows resource object for the launcher.
|
||||
package iconresource
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"bd2server/internal/common/versionconfig"
|
||||
|
||||
"github.com/tc-hib/winres"
|
||||
"github.com/tc-hib/winres/version"
|
||||
)
|
||||
|
||||
// Generate reuses an identical object so normal builds preserve its timestamp.
|
||||
func Generate(root, goos, arch string) (bool, error) {
|
||||
if goos != "windows" {
|
||||
return false, nil
|
||||
}
|
||||
architectures := map[string]winres.Arch{"amd64": winres.ArchAMD64, "386": winres.ArchI386, "arm64": winres.ArchARM64}
|
||||
target, supported := architectures[arch]
|
||||
if !supported {
|
||||
return false, fmt.Errorf("client icon: unsupported Windows architecture %q", arch)
|
||||
}
|
||||
icon, err := os.ReadFile(filepath.Join(root, "go", "internal", "client", "app", "web", "icon.ico"))
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
ico, err := winres.LoadICO(bytes.NewReader(icon))
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("client icon: load ICO: %w", err)
|
||||
}
|
||||
resources := winres.ResourceSet{}
|
||||
if err := resources.SetIcon(winres.ID(3), ico); err != nil {
|
||||
return false, err
|
||||
}
|
||||
info := version.Info{}
|
||||
for _, field := range []string{version.ProductName, version.FileDescription} {
|
||||
if err := info.Set(version.LangDefault, field, "BD2 Launcher"); err != nil {
|
||||
return false, err
|
||||
}
|
||||
}
|
||||
versions, err := versionconfig.Load(filepath.Join(root, "versions.json"))
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
_, componentVersion, _ := strings.Cut(versions.ClientVersion, "+client.")
|
||||
info.SetFileVersion(componentVersion)
|
||||
info.SetProductVersion(componentVersion)
|
||||
for _, field := range []string{version.FileVersion, version.ProductVersion} {
|
||||
if err := info.Set(version.LangDefault, field, versions.ClientVersion); err != nil {
|
||||
return false, err
|
||||
}
|
||||
}
|
||||
resources.SetVersionInfo(info)
|
||||
var object bytes.Buffer
|
||||
if err := resources.WriteObject(&object, target); err != nil {
|
||||
return false, err
|
||||
}
|
||||
path := filepath.Join(root, "go", "cmd", "bd2client", "icon_windows_"+arch+".syso")
|
||||
current, err := os.ReadFile(path)
|
||||
if err == nil && bytes.Equal(current, object.Bytes()) {
|
||||
return false, nil
|
||||
}
|
||||
if err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
return false, err
|
||||
}
|
||||
if err := os.WriteFile(path, object.Bytes(), 0o644); err != nil {
|
||||
return false, err
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
package introdb
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/hmac"
|
||||
"crypto/sha1"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
const PageSize = 4096
|
||||
|
||||
var Header = []byte("SQLite format 3\x00")
|
||||
|
||||
func decryptPages(in []byte) ([]byte, error) { return cryptPages(in, false) }
|
||||
func encryptPages(in []byte) ([]byte, error) { return cryptPages(in, true) }
|
||||
|
||||
func cryptPages(in []byte, encrypt bool) ([]byte, error) {
|
||||
if len(in) == 0 || len(in)%PageSize != 0 {
|
||||
return nil, fmt.Errorf("dbcrypt: database length %d is not a non-zero multiple of %d", len(in), PageSize)
|
||||
}
|
||||
block, err := aes.NewCipher(deriveKey())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]byte, len(in))
|
||||
for start := 0; start < len(in); start += PageSize {
|
||||
mode := cipher.NewCBCEncrypter(block, Header)
|
||||
if !encrypt {
|
||||
mode = cipher.NewCBCDecrypter(block, Header)
|
||||
}
|
||||
mode.CryptBlocks(out[start:start+PageSize], in[start:start+PageSize])
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func deriveKey() []byte {
|
||||
password := []byte(fmt.Sprintf("%X", sha1.Sum([]byte("spdhdnlwmrpavmtm"))))
|
||||
return pbkdf2SHA1(password, Header, 2010, 32)
|
||||
}
|
||||
|
||||
func pbkdf2SHA1(password, salt []byte, iterations, length int) []byte {
|
||||
var result []byte
|
||||
for block := uint32(1); len(result) < length; block++ {
|
||||
message := append(append([]byte{}, salt...), byte(block>>24), byte(block>>16), byte(block>>8), byte(block))
|
||||
u := hmacSHA1(password, message)
|
||||
t := append([]byte{}, u...)
|
||||
for i := 1; i < iterations; i++ {
|
||||
u = hmacSHA1(password, u)
|
||||
for j := range t {
|
||||
t[j] ^= u[j]
|
||||
}
|
||||
}
|
||||
result = append(result, t...)
|
||||
}
|
||||
return result[:length]
|
||||
}
|
||||
|
||||
func hmacSHA1(key, message []byte) []byte {
|
||||
h := hmac.New(sha1.New, key)
|
||||
_, _ = h.Write(message)
|
||||
return h.Sum(nil)
|
||||
}
|
||||
@@ -11,14 +11,13 @@ import (
|
||||
"os"
|
||||
|
||||
clientlayout "bd2server/internal/client/layout"
|
||||
"bd2server/internal/common/dbcrypt"
|
||||
)
|
||||
|
||||
const (
|
||||
oldURL = "https://mt.bd2.pmang.cloud/"
|
||||
)
|
||||
|
||||
var salt = Header
|
||||
|
||||
// Result describes a completed in-place client patch. BackupPath is the
|
||||
// immutable pre-patch copy and is never overwritten by a later invocation.
|
||||
type Result struct {
|
||||
@@ -61,7 +60,7 @@ func PatchClient(gameDir, newURL string) (Result, error) {
|
||||
if err != nil {
|
||||
return Result{}, err
|
||||
}
|
||||
plain, err := DecryptPages(script)
|
||||
plain, err := dbcrypt.DecryptPages(script)
|
||||
if err != nil {
|
||||
return Result{}, fmt.Errorf("introdb: decrypt Intro TextAsset: %w", err)
|
||||
}
|
||||
@@ -82,7 +81,7 @@ func PatchClient(gameDir, newURL string) (Result, error) {
|
||||
return Result{}, err
|
||||
}
|
||||
updated := bytes.Replace(plain, []byte(oldURL), []byte(newURL), 1)
|
||||
ciphertext, err := EncryptPages(updated)
|
||||
ciphertext, err := dbcrypt.EncryptPages(updated)
|
||||
if err != nil {
|
||||
return Result{}, err
|
||||
}
|
||||
@@ -93,7 +92,7 @@ func PatchClient(gameDir, newURL string) (Result, error) {
|
||||
if err != nil {
|
||||
return Result{}, fmt.Errorf("introdb: re-read staged Intro: %w", err)
|
||||
}
|
||||
stagedPlain, err := DecryptPages(stagedScript)
|
||||
stagedPlain, err := dbcrypt.DecryptPages(stagedScript)
|
||||
if err != nil {
|
||||
return Result{}, fmt.Errorf("introdb: decrypt staged Intro: %w", err)
|
||||
}
|
||||
@@ -130,11 +129,11 @@ func VerifyClient(gameDir string) (VerifyResult, error) {
|
||||
if err != nil {
|
||||
return VerifyResult{}, err
|
||||
}
|
||||
p, err := DecryptPages(script)
|
||||
p, err := dbcrypt.DecryptPages(script)
|
||||
if err != nil {
|
||||
return VerifyResult{}, fmt.Errorf("introdb: decrypt Intro TextAsset: %w", err)
|
||||
}
|
||||
if !bytes.HasPrefix(p, salt) {
|
||||
if !bytes.HasPrefix(p, dbcrypt.Header) {
|
||||
return VerifyResult{}, errors.New("introdb: decrypted Intro is not a SQLite database")
|
||||
}
|
||||
if !bytes.Contains(p, []byte("ServerURLTable")) || !bytes.Contains(p, []byte("LIVE_URL")) {
|
||||
@@ -167,14 +166,8 @@ func ResourcesPath(gameDir string) (string, error) {
|
||||
return p, nil
|
||||
}
|
||||
|
||||
// DecryptPages decrypts the game's independent 4096-byte AES-CBC pages.
|
||||
func DecryptPages(in []byte) ([]byte, error) { return decryptPages(in) }
|
||||
|
||||
// EncryptPages encrypts the game's independent 4096-byte AES-CBC pages.
|
||||
func EncryptPages(in []byte) ([]byte, error) { return encryptPages(in) }
|
||||
|
||||
func validateIntroDB(p []byte, expected string) error {
|
||||
if !bytes.HasPrefix(p, salt) {
|
||||
if !bytes.HasPrefix(p, dbcrypt.Header) {
|
||||
return errors.New("introdb: decrypted Intro is not a SQLite database (wrong cipher parameters or asset)")
|
||||
}
|
||||
if !bytes.Contains(p, []byte("ServerURLTable")) || !bytes.Contains(p, []byte("LIVE_URL")) {
|
||||
|
||||
@@ -2,6 +2,7 @@ package plugin
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
@@ -15,6 +16,7 @@ import (
|
||||
|
||||
"bd2server/internal/buildversion"
|
||||
clientlayout "bd2server/internal/client/layout"
|
||||
"bd2server/internal/common/taskgraph"
|
||||
)
|
||||
|
||||
var developmentProjects = []struct{ name, key string }{
|
||||
@@ -23,7 +25,10 @@ var developmentProjects = []struct{ name, key string }{
|
||||
|
||||
// BuildDevelopment compiles the client plugins as one dependency graph, sharing
|
||||
// the game SDK and version preparation across the four entry projects.
|
||||
func BuildDevelopment(root, gameDir string, progress io.Writer) error {
|
||||
func BuildDevelopment(ctx context.Context, root, gameDir string, progress io.Writer) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
started := time.Now()
|
||||
installation, err := clientlayout.Resolve(gameDir)
|
||||
if err != nil {
|
||||
@@ -39,7 +44,7 @@ func BuildDevelopment(root, gameDir string, progress io.Writer) error {
|
||||
if err := os.MkdirAll(work, 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
unlock, err := acquireBuildLock(filepath.Dir(work), progress)
|
||||
unlock, err := acquireBuildLock(ctx, filepath.Dir(work), progress)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -80,102 +85,141 @@ func BuildDevelopment(root, gameDir string, progress io.Writer) error {
|
||||
}
|
||||
sdkKey := digestInputs(sdkInputsKey)
|
||||
sdkManifestPath := filepath.Join(work, "sdk-build.json")
|
||||
if err := writeBuildInput(sdkInputs, sdkFingerprint); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := writeBuildInput(namesInputs, namesFingerprint); err != nil {
|
||||
return err
|
||||
}
|
||||
prepareStarted := time.Now()
|
||||
sdkTool := filepath.Join(root, "plugins", "GameSdk", "bin", "Release", "net8.0", "GameSdk.dll")
|
||||
if !currentBuild(sdkManifestPath, sdkKey, digests) {
|
||||
_, _ = fmt.Fprintln(progress, "Client plugins: preparing the shared game SDK...")
|
||||
if err := runPluginBuild(root, progress, "build", filepath.Join(root, "plugins", "GameSdk", "GameSdk.csproj"), "-c", "Release", "--nologo", "-v:quiet", "-clp:NoSummary", "-p:BD2SdkCompileInputsFile="+sdkInputs); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := runPluginBuild(root, progress, sdkTool, "prepare-embedded", filepath.Join(managed, "Assembly-CSharp.dll"), sdkDir, "--game-version", gameVersion); err != nil {
|
||||
return err
|
||||
}
|
||||
_, _ = fmt.Fprintf(progress, "Client plugins: SDK preparation completed in %s\n", time.Since(prepareStarted).Round(time.Millisecond))
|
||||
} else {
|
||||
_, _ = fmt.Fprintf(progress, "Client plugins: shared SDK reused (%s)\n", time.Since(prepareStarted).Round(time.Millisecond))
|
||||
}
|
||||
sharedRaw, err := os.ReadFile(filepath.Join(sdkDir, "shared-sdk.txt"))
|
||||
var sdkReused bool
|
||||
var shared string
|
||||
prepareStarted := time.Now()
|
||||
graph, err := taskgraph.New(
|
||||
taskgraph.Task{Name: "sdkInputs", Run: func(context.Context) error {
|
||||
if err := writeBuildInput(sdkInputs, sdkFingerprint); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := writeBuildInput(namesInputs, namesFingerprint); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
sdkReused = currentBuild(sdkManifestPath, sdkKey, digests)
|
||||
return nil
|
||||
}},
|
||||
taskgraph.Task{Name: "sdkCompile", DependsOn: []string{"sdkInputs"}, Run: func(context.Context) error {
|
||||
if sdkReused {
|
||||
return nil
|
||||
}
|
||||
_, _ = fmt.Fprintln(progress, "Client plugins: preparing the shared game SDK...")
|
||||
if err := runPluginBuild(ctx, root, progress, "build", filepath.Join(root, "plugins", "GameSdk", "GameSdk.csproj"), "-c", "Release", "--nologo", "-v:quiet", "-clp:NoSummary", "-p:BD2SdkCompileInputsFile="+sdkInputs); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}},
|
||||
taskgraph.Task{Name: "sdkPrepare", DependsOn: []string{"sdkCompile"}, Run: func(context.Context) error {
|
||||
if !sdkReused {
|
||||
if err := runPluginBuild(ctx, root, progress, sdkTool, "prepare-embedded", filepath.Join(managed, "Assembly-CSharp.dll"), sdkDir, "--game-version", gameVersion); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, _ = fmt.Fprintf(progress, "Client plugins: SDK preparation completed in %s\n", time.Since(prepareStarted).Round(time.Millisecond))
|
||||
} else {
|
||||
_, _ = fmt.Fprintf(progress, "Client plugins: shared SDK reused (%s)\n", time.Since(prepareStarted).Round(time.Millisecond))
|
||||
}
|
||||
sharedRaw, err := os.ReadFile(filepath.Join(sdkDir, "shared-sdk.txt"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
shared = strings.TrimSpace(string(sharedRaw))
|
||||
|
||||
return nil
|
||||
}},
|
||||
taskgraph.Task{Name: "versionSources", DependsOn: []string{"sdkPrepare"}, Run: func(context.Context) error {
|
||||
versionStarted := time.Now()
|
||||
_, _ = fmt.Fprintln(progress, "Client plugins: generating version and compilation fingerprints...")
|
||||
for _, project := range developmentProjects {
|
||||
if err := buildversion.Generate(versionConfig, filepath.Join(versionDir, project.key+".g.cs"), project.key); err != nil {
|
||||
return err
|
||||
}
|
||||
inputStamp, err := projectFingerprint(root, inputs, project.name, filepath.Join(versionDir, project.key+".g.cs"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := writeBuildInput(filepath.Join(compileInputsDir, project.key+".g.cs"), inputStamp); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
_, _ = fmt.Fprintf(progress, "Client plugins: version sources prepared in %s\n", time.Since(versionStarted).Round(time.Millisecond))
|
||||
|
||||
return nil
|
||||
}},
|
||||
taskgraph.Task{Name: "pluginsCompile", DependsOn: []string{"versionSources"}, Run: func(context.Context) error {
|
||||
compileStarted := time.Now()
|
||||
_, _ = fmt.Fprintln(progress, "Client plugins: compiling all four plugins as one parallel dependency graph...")
|
||||
if err := runPluginBuild(ctx, root, progress, "build", filepath.Join(root, "plugins", "ClientPlugins.proj"), "-m", "-c", "Release", "--nologo",
|
||||
"-p:GameDir="+installation.Root, "-p:BD2ManagedDir="+managed, "-p:BD2BepInExDir="+installation.BepInEx,
|
||||
"-p:BD2SdkPrepared=true", "-p:BD2SdkDir="+sdkDir, "-p:BD2SharedSdkDir="+shared,
|
||||
"-p:BD2PreparedVersionDir="+versionDir, "-p:BD2CompileInputsDir="+compileInputsDir, "-p:BD2NamesCompileInputsFile="+namesInputs, "-v:quiet", "-clp:NoSummary"); err != nil {
|
||||
return err
|
||||
}
|
||||
_, _ = fmt.Fprintf(progress, "Client plugins: compilation and reobfuscation completed in %s\n", time.Since(compileStarted).Round(time.Millisecond))
|
||||
|
||||
return nil
|
||||
}},
|
||||
taskgraph.Task{Name: "cacheCommit", DependsOn: []string{"pluginsCompile"}, Run: func(context.Context) error {
|
||||
outputs := []string{sdkTool, sdkInputs, namesInputs, strings.TrimSuffix(sdkTool, ".dll") + ".deps.json", strings.TrimSuffix(sdkTool, ".dll") + ".runtimeconfig.json",
|
||||
filepath.Join(sdkDir, "GameSdkIdentity.g.cs"), filepath.Join(sdkDir, "shared-sdk.txt"), filepath.Join(sdkDir, "GameSourceNavigation.props"),
|
||||
filepath.Join(shared, "ref", "Assembly-CSharp.Readable.dll"), filepath.Join(shared, "names.json"), filepath.Join(shared, "names.json.gz")}
|
||||
for _, name := range []string{"ready.txt", "navigation.json", "GameSourceNavigation.props", "Assembly-CSharp.Readable.dll", "Assembly-CSharp.Readable.xml",
|
||||
"ref/Assembly-CSharp.Readable.xml", "lib/Assembly-CSharp.Readable.dll", "lib/Assembly-CSharp.Readable.pdb", "lib/Assembly-CSharp.Readable.xml", "lib/navigation.json"} {
|
||||
outputs = append(outputs, filepath.Join(shared, filepath.FromSlash(name)))
|
||||
}
|
||||
toolDependencies, err := filepath.Glob(filepath.Join(filepath.Dir(sdkTool), "*.dll"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
outputs = append(outputs, toolDependencies...)
|
||||
sdkOutputs := append([]string(nil), outputs...)
|
||||
for _, project := range developmentProjects {
|
||||
output := filepath.Join(root, "plugins", project.name, "bin", "Release", "netstandard2.1")
|
||||
outputs = append(outputs, filepath.Join(output, "BD2"+project.name+".dll"), filepath.Join(output, GameNames.fileName), filepath.Join(versionDir, project.key+".g.cs"), filepath.Join(compileInputsDir, project.key+".g.cs"))
|
||||
}
|
||||
sums := make(map[string]string, len(outputs))
|
||||
for _, output := range outputs {
|
||||
sum, err := digests.digest(output)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sums[output] = sum
|
||||
}
|
||||
finalInputs, err := snapshotInputs(root, managed, installation.BepInEx, digests)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if digestInputs(finalInputs) != fingerprint {
|
||||
return errors.New("client plugin inputs changed during compilation; run preparation again")
|
||||
}
|
||||
if err := saveBuildManifest(manifestPath, buildManifest{Input: fingerprint, Outputs: sums}); err != nil {
|
||||
return err
|
||||
}
|
||||
sdkSums := make(map[string]string, len(sdkOutputs))
|
||||
for _, output := range sdkOutputs {
|
||||
sdkSums[output] = sums[output]
|
||||
}
|
||||
if err := saveBuildManifest(sdkManifestPath, buildManifest{Input: sdkKey, Outputs: sdkSums}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}},
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
shared := strings.TrimSpace(string(sharedRaw))
|
||||
versionStarted := time.Now()
|
||||
_, _ = fmt.Fprintln(progress, "Client plugins: generating version and compilation fingerprints...")
|
||||
for _, project := range developmentProjects {
|
||||
if err := buildversion.Generate(versionConfig, filepath.Join(versionDir, project.key+".g.cs"), project.key); err != nil {
|
||||
return err
|
||||
}
|
||||
inputStamp, err := projectFingerprint(root, inputs, project.name, filepath.Join(versionDir, project.key+".g.cs"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := writeBuildInput(filepath.Join(compileInputsDir, project.key+".g.cs"), inputStamp); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
_, _ = fmt.Fprintf(progress, "Client plugins: version sources prepared in %s\n", time.Since(versionStarted).Round(time.Millisecond))
|
||||
compileStarted := time.Now()
|
||||
_, _ = fmt.Fprintln(progress, "Client plugins: compiling all four plugins as one parallel dependency graph...")
|
||||
if err := runPluginBuild(root, progress, "build", filepath.Join(root, "plugins", "ClientPlugins.proj"), "-m", "-c", "Release", "--nologo",
|
||||
"-p:GameDir="+installation.Root, "-p:BD2ManagedDir="+managed, "-p:BD2BepInExDir="+installation.BepInEx,
|
||||
"-p:BD2SdkPrepared=true", "-p:BD2SdkDir="+sdkDir, "-p:BD2SharedSdkDir="+shared,
|
||||
"-p:BD2PreparedVersionDir="+versionDir, "-p:BD2CompileInputsDir="+compileInputsDir, "-p:BD2NamesCompileInputsFile="+namesInputs, "-v:quiet", "-clp:NoSummary"); err != nil {
|
||||
return err
|
||||
}
|
||||
_, _ = fmt.Fprintf(progress, "Client plugins: compilation and reobfuscation completed in %s\n", time.Since(compileStarted).Round(time.Millisecond))
|
||||
outputs := []string{sdkTool, sdkInputs, namesInputs, strings.TrimSuffix(sdkTool, ".dll") + ".deps.json", strings.TrimSuffix(sdkTool, ".dll") + ".runtimeconfig.json",
|
||||
filepath.Join(sdkDir, "GameSdkIdentity.g.cs"), filepath.Join(sdkDir, "shared-sdk.txt"), filepath.Join(sdkDir, "GameSourceNavigation.props"),
|
||||
filepath.Join(shared, "ref", "Assembly-CSharp.Readable.dll"), filepath.Join(shared, "names.json"), filepath.Join(shared, "names.json.gz")}
|
||||
for _, name := range []string{"ready.txt", "navigation.json", "GameSourceNavigation.props", "Assembly-CSharp.Readable.dll", "Assembly-CSharp.Readable.xml",
|
||||
"ref/Assembly-CSharp.Readable.xml", "lib/Assembly-CSharp.Readable.dll", "lib/Assembly-CSharp.Readable.pdb", "lib/Assembly-CSharp.Readable.xml", "lib/navigation.json"} {
|
||||
outputs = append(outputs, filepath.Join(shared, filepath.FromSlash(name)))
|
||||
}
|
||||
toolDependencies, err := filepath.Glob(filepath.Join(filepath.Dir(sdkTool), "*.dll"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
outputs = append(outputs, toolDependencies...)
|
||||
sdkOutputs := append([]string(nil), outputs...)
|
||||
for _, project := range developmentProjects {
|
||||
output := filepath.Join(root, "plugins", project.name, "bin", "Release", "netstandard2.1")
|
||||
outputs = append(outputs, filepath.Join(output, "BD2"+project.name+".dll"), filepath.Join(output, GameNames.fileName), filepath.Join(versionDir, project.key+".g.cs"), filepath.Join(compileInputsDir, project.key+".g.cs"))
|
||||
}
|
||||
sums := make(map[string]string, len(outputs))
|
||||
for _, output := range outputs {
|
||||
sum, err := digests.digest(output)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sums[output] = sum
|
||||
}
|
||||
finalInputs, err := snapshotInputs(root, managed, installation.BepInEx, digests)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if digestInputs(finalInputs) != fingerprint {
|
||||
return errors.New("client plugin inputs changed during compilation; run preparation again")
|
||||
}
|
||||
if err := saveBuildManifest(manifestPath, buildManifest{Input: fingerprint, Outputs: sums}); err != nil {
|
||||
return err
|
||||
}
|
||||
sdkSums := make(map[string]string, len(sdkOutputs))
|
||||
for _, output := range sdkOutputs {
|
||||
sdkSums[output] = sums[output]
|
||||
}
|
||||
if err := saveBuildManifest(sdkManifestPath, buildManifest{Input: sdkKey, Outputs: sdkSums}); err != nil {
|
||||
if err := graph.Run(ctx, "cacheCommit"); err != nil {
|
||||
return err
|
||||
}
|
||||
_, _ = fmt.Fprintf(progress, "Client plugins: all four ready in %s\n", time.Since(started).Round(time.Millisecond))
|
||||
return nil
|
||||
}
|
||||
|
||||
func acquireBuildLock(work string, progress io.Writer) (func(), error) {
|
||||
func acquireBuildLock(ctx context.Context, work string, progress io.Writer) (func(), error) {
|
||||
lock := filepath.Join(work, "build.lock")
|
||||
file, err := os.OpenFile(lock, os.O_CREATE|os.O_RDWR, 0o644)
|
||||
if err != nil {
|
||||
@@ -185,6 +229,10 @@ func acquireBuildLock(work string, progress io.Writer) (func(), error) {
|
||||
announced := false
|
||||
lastNotice := started
|
||||
for {
|
||||
if err := ctx.Err(); err != nil {
|
||||
_ = file.Close()
|
||||
return nil, err
|
||||
}
|
||||
locked, err := tryBuildFileLock(file)
|
||||
if err != nil {
|
||||
_ = file.Close()
|
||||
@@ -205,12 +253,19 @@ func acquireBuildLock(work string, progress io.Writer) (func(), error) {
|
||||
_, _ = fmt.Fprintf(progress, "Client plugins: still waiting for the current build (%s)...\n", time.Since(started).Round(time.Second))
|
||||
lastNotice = time.Now()
|
||||
}
|
||||
time.Sleep(250 * time.Millisecond)
|
||||
timer := time.NewTimer(250 * time.Millisecond)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
timer.Stop()
|
||||
_ = file.Close()
|
||||
return nil, ctx.Err()
|
||||
case <-timer.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func runPluginBuild(root string, progress io.Writer, args ...string) error {
|
||||
command := exec.Command("dotnet", args...)
|
||||
func runPluginBuild(ctx context.Context, root string, progress io.Writer, args ...string) error {
|
||||
command := exec.CommandContext(ctx, "dotnet", args...)
|
||||
command.Dir = root
|
||||
for _, entry := range os.Environ() {
|
||||
key, _, _ := strings.Cut(entry, "=")
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
package plugin
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestVerifiedPluginCacheSkipsSDKVersionAndCompilationStages(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
game := filepath.Join(root, "game")
|
||||
write := func(relative string, value string) {
|
||||
t.Helper()
|
||||
path := filepath.Join(root, filepath.FromSlash(relative))
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(path, []byte(value), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
write("game/BrownDust II.exe", "fixture")
|
||||
write("game/BrownDust II_Data/resources.assets", "fixture")
|
||||
write("game/BrownDust II_Data/Managed/Assembly-CSharp.dll", "fixture")
|
||||
write("game/BepInEx/core/BepInEx.dll", "fixture")
|
||||
write("plugins/LocalIdentity/Plugin.cs", "fixture")
|
||||
write("go/internal/client/plugin/build.go", "fixture")
|
||||
write("go/internal/buildversion/version.go", "fixture")
|
||||
write("versions.json", "invalid JSON must not be read when cache is current")
|
||||
var progress bytes.Buffer
|
||||
if err := BuildDevelopment(context.Background(), root, game, &progress); err == nil {
|
||||
t.Fatal("uncached build accepted invalid versions")
|
||||
}
|
||||
workRoot := filepath.Join(root, ".build", "client-plugins")
|
||||
entries, err := os.ReadDir(workRoot)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var work string
|
||||
for _, entry := range entries {
|
||||
if entry.IsDir() {
|
||||
work = filepath.Join(workRoot, entry.Name())
|
||||
}
|
||||
}
|
||||
if work == "" {
|
||||
t.Fatal("build did not establish a cache workspace")
|
||||
}
|
||||
inputs, err := snapshotInputs(root, filepath.Join(game, "BrownDust II_Data", "Managed"), filepath.Join(game, "BepInEx"), make(fileDigestCache))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
write("plugins/LocalIdentity/bin/Release/netstandard2.1/BD2LocalIdentity.dll", "verified-output")
|
||||
output := filepath.Join(root, "plugins", "LocalIdentity", "bin", "Release", "netstandard2.1", "BD2LocalIdentity.dll")
|
||||
digest, err := fileDigest(output)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := saveBuildManifest(filepath.Join(work, "build.json"), buildManifest{Input: digestInputs(inputs), Outputs: map[string]string{output: digest}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
progress.Reset()
|
||||
if err := BuildDevelopment(context.Background(), root, game, &progress); err != nil {
|
||||
t.Fatal("cache hit ran SDK/version/compile actions", err)
|
||||
}
|
||||
if !strings.Contains(progress.String(), "inputs and outputs unchanged") {
|
||||
t.Fatal("cache was not reused", progress.String())
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(work, "compile-inputs")); !os.IsNotExist(err) {
|
||||
t.Fatal("cache hit staged compilation inputs", err)
|
||||
}
|
||||
write("plugins/LocalIdentity/bin/Release/netstandard2.1/BD2LocalIdentity.dll", "damaged-output")
|
||||
if err := BuildDevelopment(context.Background(), root, game, &progress); err == nil {
|
||||
t.Fatal("damaged plugin output bypassed version validation as a cache hit")
|
||||
}
|
||||
}
|
||||
@@ -12,10 +12,10 @@ import (
|
||||
"strings"
|
||||
|
||||
clientlayout "bd2server/internal/client/layout"
|
||||
"bd2server/internal/common/resourcecatalog"
|
||||
)
|
||||
|
||||
const (
|
||||
remoteCatalogPrefix = "{BDNetwork.CdnInfo.Info}\\"
|
||||
localCatalogPrefix = "{UnityEngine.AddressableAssets.Addressables.RuntimePath}\\"
|
||||
localCatalogBackup = "catalog.json.bd2-before-local-sync"
|
||||
maximumCatalogBytes = 128 << 20
|
||||
@@ -159,19 +159,19 @@ func readCatalog(path string) ([]byte, error) {
|
||||
}
|
||||
|
||||
func localizeCatalog(raw []byte, release, aa string) ([]byte, error) {
|
||||
document, ids, err := decodeCatalog(raw)
|
||||
document, ids, err := resourcecatalog.Decode(raw)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
remoteCount := 0
|
||||
for index, internalID := range ids {
|
||||
if strings.HasPrefix(internalID, remoteCatalogPrefix) {
|
||||
relative, err := catalogBundlePath(internalID)
|
||||
if strings.HasPrefix(internalID, resourcecatalog.RemotePrefix) {
|
||||
relative, err := resourcecatalog.BundlePath(internalID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
source := filepath.Join(release, relative)
|
||||
destination := filepath.Join(aa, relative)
|
||||
source := filepath.Join(release, filepath.FromSlash(relative))
|
||||
destination := filepath.Join(aa, filepath.FromSlash(relative))
|
||||
if err := ensureCatalogBundleLink(source, destination); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -201,23 +201,6 @@ func localizeCatalog(raw []byte, release, aa string) ([]byte, error) {
|
||||
return localized, nil
|
||||
}
|
||||
|
||||
func decodeCatalog(raw []byte) (map[string]json.RawMessage, []string, error) {
|
||||
var document map[string]json.RawMessage
|
||||
decoder := json.NewDecoder(bytes.NewReader(raw))
|
||||
if err := decoder.Decode(&document); err != nil {
|
||||
return nil, nil, fmt.Errorf("decode local ServerData catalog: %w", err)
|
||||
}
|
||||
var trailing any
|
||||
if err := decoder.Decode(&trailing); !errors.Is(err, io.EOF) {
|
||||
return nil, nil, errors.New("local ServerData catalog must contain exactly one JSON object")
|
||||
}
|
||||
var ids []string
|
||||
if err := json.Unmarshal(document["m_InternalIds"], &ids); err != nil || len(ids) == 0 {
|
||||
return nil, nil, errors.New("local ServerData catalog has no valid internal IDs")
|
||||
}
|
||||
return document, ids, nil
|
||||
}
|
||||
|
||||
func ensureCatalogBundleLink(source, destination string) error {
|
||||
sourceInfo, err := os.Stat(source)
|
||||
if err != nil || !sourceInfo.Mode().IsRegular() {
|
||||
@@ -240,24 +223,6 @@ func ensureCatalogBundleLink(source, destination string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func catalogBundlePath(internalID string) (string, error) {
|
||||
parts := strings.Split(strings.ReplaceAll(internalID, "\\", "/"), "/")
|
||||
if len(parts) < 5 {
|
||||
return "", fmt.Errorf("local ServerData catalog has an invalid CDN path: %q", internalID)
|
||||
}
|
||||
parts = parts[4:]
|
||||
for _, part := range parts {
|
||||
if part == "" || part == "." || part == ".." || strings.ContainsAny(part, `:{}`) {
|
||||
return "", fmt.Errorf("local ServerData catalog has an unsafe bundle path: %q", internalID)
|
||||
}
|
||||
}
|
||||
relative := filepath.Join(parts...)
|
||||
if !strings.EqualFold(filepath.Ext(relative), ".bundle") {
|
||||
return "", fmt.Errorf("local ServerData catalog CDN path is not a bundle: %q", internalID)
|
||||
}
|
||||
return relative, nil
|
||||
}
|
||||
|
||||
func writeExclusiveFile(path string, data []byte, mode os.FileMode) error {
|
||||
file, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, mode)
|
||||
if err != nil {
|
||||
|
||||
@@ -22,6 +22,7 @@ import (
|
||||
"bd2server/internal/client/introdb"
|
||||
clientlayout "bd2server/internal/client/layout"
|
||||
"bd2server/internal/client/plugin"
|
||||
"bd2server/internal/common/versionconfig"
|
||||
)
|
||||
|
||||
const PatchPlaceholder = "http://127.0.0.1:8080/game/"
|
||||
@@ -54,7 +55,7 @@ type InstallResult struct {
|
||||
FChat plugin.Result `json:"fchat"`
|
||||
}
|
||||
|
||||
func Inspect(gameDir string, versions clientconfig.ReleaseVersions) (GameStatus, error) {
|
||||
func Inspect(gameDir string, versions versionconfig.Config) (GameStatus, error) {
|
||||
if strings.TrimSpace(gameDir) == "" {
|
||||
return GameStatus{}, errors.New("select the Brown Dust II installation directory")
|
||||
}
|
||||
@@ -80,7 +81,7 @@ func Inspect(gameDir string, versions clientconfig.ReleaseVersions) (GameStatus,
|
||||
return status, nil
|
||||
}
|
||||
|
||||
func SaveSettings(gameDir string, settings clientconfig.Settings, versions clientconfig.ReleaseVersions) (clientconfig.Settings, error) {
|
||||
func SaveSettings(gameDir string, settings clientconfig.Settings, versions versionconfig.Config) (clientconfig.Settings, error) {
|
||||
if _, err := Inspect(gameDir, versions); err != nil {
|
||||
return clientconfig.Settings{}, err
|
||||
}
|
||||
@@ -96,7 +97,7 @@ func SaveSettings(gameDir string, settings clientconfig.Settings, versions clien
|
||||
return clientconfig.Save(gameDir, normalized)
|
||||
}
|
||||
|
||||
func Patch(gameDir string, settings clientconfig.Settings, versions clientconfig.ReleaseVersions) (introdb.Result, error) {
|
||||
func Patch(gameDir string, settings clientconfig.Settings, versions versionconfig.Config) (introdb.Result, error) {
|
||||
if _, err := SaveSettings(gameDir, settings, versions); err != nil {
|
||||
return introdb.Result{}, err
|
||||
}
|
||||
@@ -116,7 +117,7 @@ func Patch(gameDir string, settings clientconfig.Settings, versions clientconfig
|
||||
func InstallPlugins(
|
||||
gameDir string,
|
||||
settings clientconfig.Settings,
|
||||
versions clientconfig.ReleaseVersions,
|
||||
versions versionconfig.Config,
|
||||
localIdentitySource string,
|
||||
loginUISource string,
|
||||
cashShopSource string,
|
||||
@@ -167,7 +168,7 @@ func InstallPlugins(
|
||||
return InstallResult{LocalIdentity: local, LoginUI: login, CashShop: cash, FChat: fchat}, nil
|
||||
}
|
||||
|
||||
func FetchResourcePolicy(ctx context.Context, client *http.Client, settings clientconfig.Settings, versions clientconfig.ReleaseVersions) (ResourcePolicy, error) {
|
||||
func FetchResourcePolicy(ctx context.Context, client *http.Client, settings clientconfig.Settings, versions versionconfig.Config) (ResourcePolicy, error) {
|
||||
normalized, err := clientconfig.Normalize(settings)
|
||||
if err != nil {
|
||||
return ResourcePolicy{}, err
|
||||
@@ -257,7 +258,7 @@ func FetchResourcePolicy(ctx context.Context, client *http.Client, settings clie
|
||||
return policy, nil
|
||||
}
|
||||
|
||||
func inspectLocalResourceDirectory(raw string, versions clientconfig.ReleaseVersions) (string, error) {
|
||||
func inspectLocalResourceDirectory(raw string, versions versionconfig.Config) (string, error) {
|
||||
root, err := filepath.Abs(filepath.Clean(strings.TrimSpace(raw)))
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("resolve local resource directory: %w", err)
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
// Package config provides JSON configuration I/O with explicit decoding policies.
|
||||
package config
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
)
|
||||
|
||||
type DecodeOptions struct {
|
||||
DisallowUnknownFields bool
|
||||
RejectTrailing bool
|
||||
AllowBOM bool
|
||||
RejectNull bool
|
||||
}
|
||||
|
||||
type WriteOptions struct {
|
||||
FileMode os.FileMode
|
||||
DirectoryMode os.FileMode
|
||||
}
|
||||
|
||||
// Decode overlays one JSON value onto initial, preserving defaults for omissions.
|
||||
func Decode[T any](raw []byte, initial T, options DecodeOptions) (T, error) {
|
||||
var zero T
|
||||
if options.AllowBOM {
|
||||
raw = bytes.TrimPrefix(raw, []byte{0xef, 0xbb, 0xbf})
|
||||
}
|
||||
decoder := json.NewDecoder(bytes.NewReader(raw))
|
||||
if options.DisallowUnknownFields {
|
||||
decoder.DisallowUnknownFields()
|
||||
}
|
||||
if err := decoder.Decode(&initial); err != nil {
|
||||
return zero, err
|
||||
}
|
||||
if options.RejectTrailing {
|
||||
var trailing any
|
||||
if err := decoder.Decode(&trailing); !errors.Is(err, io.EOF) {
|
||||
return zero, errors.New("configuration must contain exactly one JSON value")
|
||||
}
|
||||
}
|
||||
if options.RejectNull {
|
||||
var document any
|
||||
if err := json.NewDecoder(bytes.NewReader(raw)).Decode(&document); err != nil {
|
||||
return zero, err
|
||||
}
|
||||
if containsNull(document) {
|
||||
return zero, errors.New("configuration must not contain null")
|
||||
}
|
||||
}
|
||||
return initial, nil
|
||||
}
|
||||
|
||||
func Load[T any](path string, initial T, options DecodeOptions) (T, error) {
|
||||
raw, err := os.ReadFile(filepath.Clean(path))
|
||||
if err != nil {
|
||||
var zero T
|
||||
return zero, err
|
||||
}
|
||||
return Decode(raw, initial, options)
|
||||
}
|
||||
|
||||
func Save[T any](path string, value T, options WriteOptions) error {
|
||||
temporary, err := stage(path, value, options)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = os.Remove(temporary) }()
|
||||
return replaceFile(temporary, path)
|
||||
}
|
||||
|
||||
// Ensure publishes defaults atomically and never replaces an existing file.
|
||||
func Ensure[T any](path string, defaults T, options WriteOptions) error {
|
||||
if _, err := os.Stat(path); err == nil {
|
||||
return nil
|
||||
} else if !errors.Is(err, os.ErrNotExist) {
|
||||
return err
|
||||
}
|
||||
temporary, err := stage(path, defaults, options)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = os.Remove(temporary) }()
|
||||
if err := os.Link(temporary, path); errors.Is(err, os.ErrExist) {
|
||||
return nil
|
||||
} else if err != nil {
|
||||
return fmt.Errorf("create default configuration %s: %w", path, err)
|
||||
}
|
||||
slog.Info("default configuration created", "path", path)
|
||||
return nil
|
||||
}
|
||||
|
||||
func stage[T any](path string, value T, options WriteOptions) (string, error) {
|
||||
raw, err := json.MarshalIndent(value, "", " ")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if options.FileMode == 0 {
|
||||
options.FileMode = 0o600
|
||||
}
|
||||
if options.DirectoryMode == 0 {
|
||||
options.DirectoryMode = 0o755
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(path), options.DirectoryMode); err != nil {
|
||||
return "", fmt.Errorf("create configuration directory: %w", err)
|
||||
}
|
||||
file, err := os.CreateTemp(filepath.Dir(path), ".config-*.tmp")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err = file.Chmod(options.FileMode); err == nil {
|
||||
_, err = file.Write(append(raw, '\n'))
|
||||
}
|
||||
if err == nil {
|
||||
err = file.Sync()
|
||||
}
|
||||
if closeErr := file.Close(); err == nil {
|
||||
err = closeErr
|
||||
}
|
||||
if err != nil {
|
||||
_ = os.Remove(file.Name())
|
||||
return "", err
|
||||
}
|
||||
return file.Name(), nil
|
||||
}
|
||||
|
||||
func containsNull(value any) bool {
|
||||
switch value := value.(type) {
|
||||
case nil:
|
||||
return true
|
||||
case map[string]any:
|
||||
for _, child := range value {
|
||||
if containsNull(child) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
case []any:
|
||||
return slices.ContainsFunc(value, containsNull)
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package config_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"bd2server/internal/common/config"
|
||||
)
|
||||
|
||||
func TestDecodePoliciesAndDefaults(t *testing.T) {
|
||||
type settings struct {
|
||||
Name string `json:"name"`
|
||||
Limit int `json:"limit"`
|
||||
}
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
raw string
|
||||
options config.DecodeOptions
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "omission retains default", raw: `{"name":"saved"}`},
|
||||
{name: "unknown accepted by default", raw: `{"name":"saved","future":1}`},
|
||||
{name: "unknown rejected", raw: `{"name":"saved","future":1}`, options: config.DecodeOptions{DisallowUnknownFields: true}, wantErr: true},
|
||||
{name: "trailing accepted", raw: `{"name":"saved"} not JSON`},
|
||||
{name: "trailing JSON rejected", raw: `{"name":"saved"} {}`, options: config.DecodeOptions{RejectTrailing: true}, wantErr: true},
|
||||
{name: "trailing junk rejected", raw: `{"name":"saved"} broken`, options: config.DecodeOptions{RejectTrailing: true}, wantErr: true},
|
||||
{name: "BOM accepted explicitly", raw: "\xef\xbb\xbf" + `{"name":"saved"}`, options: config.DecodeOptions{AllowBOM: true}},
|
||||
{name: "BOM rejected by default", raw: "\xef\xbb\xbf" + `{"name":"saved"}`, wantErr: true},
|
||||
{name: "null cannot select a default", raw: `{"name":"saved","limit":null}`, options: config.DecodeOptions{RejectNull: true}, wantErr: true},
|
||||
{name: "null policy preserves trailing policy", raw: `{"name":"saved"} broken`, options: config.DecodeOptions{RejectNull: true}},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
got, err := config.Decode([]byte(test.raw), settings{Name: "default", Limit: 7}, test.options)
|
||||
if test.wantErr {
|
||||
if err == nil {
|
||||
t.Fatal("invalid configuration was accepted")
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got != (settings{Name: "saved", Limit: 7}) {
|
||||
t.Fatalf("omitted setting lost its default: %+v", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnsureKeepsUserFileAndSaveReplacesCompleteDocument(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "nested", "settings.json")
|
||||
type settings struct {
|
||||
Name string `json:"name"`
|
||||
}
|
||||
if err := config.Ensure(path, settings{Name: "default"}, config.WriteOptions{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := config.Save(path, settings{Name: "operator"}, config.WriteOptions{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := config.Ensure(path, settings{Name: "new default"}, config.WriteOptions{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
after, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(before, after) {
|
||||
t.Fatal("default publication replaced operator configuration")
|
||||
}
|
||||
if err := config.Save(path, make(chan int), config.WriteOptions{}); err == nil {
|
||||
t.Fatal("unsupported JSON value was saved")
|
||||
}
|
||||
got, err := config.Load(path, settings{}, config.DecodeOptions{DisallowUnknownFields: true, RejectTrailing: true})
|
||||
if err != nil || got.Name != "operator" {
|
||||
t.Fatalf("failed save damaged configuration: %+v, %v", got, err)
|
||||
}
|
||||
entries, err := os.ReadDir(filepath.Dir(path))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(entries) != 1 || entries[0].Name() != filepath.Base(path) {
|
||||
t.Fatalf("temporary files remain: %v", entries)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFailedInstallRemovesStagedFile(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
target := filepath.Join(root, "directory")
|
||||
if err := os.Mkdir(target, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := config.Save(target, struct{}{}, config.WriteOptions{}); err == nil {
|
||||
t.Fatal("directory was replaced with a configuration file")
|
||||
}
|
||||
entries, err := os.ReadDir(root)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(entries) != 1 || !entries[0].IsDir() {
|
||||
t.Fatalf("failed install left temporary files: %v", entries)
|
||||
}
|
||||
}
|
||||
File renamed without changes.
File renamed without changes.
@@ -1,6 +1,5 @@
|
||||
// Package dbcrypt implements the page cipher used by versioned GameData
|
||||
// SQLite archives. Client resource patching owns a separate copy so the pure
|
||||
// server dependency graph never imports internal/client.
|
||||
// Package dbcrypt implements the database page cipher shared by client Intro
|
||||
// assets and versioned GameData SQLite archives.
|
||||
package dbcrypt
|
||||
|
||||
import (
|
||||
+2
-2
@@ -1,4 +1,4 @@
|
||||
// Package logging configures the server's structured console logging.
|
||||
// Package logging provides structured text handlers, levels, and terminal colors.
|
||||
package logging
|
||||
|
||||
import (
|
||||
@@ -28,7 +28,7 @@ type Options struct {
|
||||
Color ColorMode
|
||||
}
|
||||
|
||||
// OptionsFromEnv reads process-wide defaults for every server command.
|
||||
// OptionsFromEnv reads process-wide BD2 logging defaults.
|
||||
func OptionsFromEnv() (Options, error) {
|
||||
options := Options{Level: slog.LevelInfo, Color: ColorAuto}
|
||||
if value := os.Getenv("BD2_LOG_LEVEL"); value != "" {
|
||||
@@ -0,0 +1,45 @@
|
||||
package logging_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"bd2server/internal/common/logging"
|
||||
)
|
||||
|
||||
func TestHandlerColorsOnlyBuiltinLevel(t *testing.T) {
|
||||
var output bytes.Buffer
|
||||
handler, err := logging.NewHandler(&output, logging.Options{Level: logging.LevelTrace, Color: logging.ColorAlways})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
slog.New(handler).Log(context.Background(), logging.LevelTrace, "level=ERROR is message text", "level", "ERROR")
|
||||
text := output.String()
|
||||
if !strings.Contains(text, "level=\x1b[90mTRACE\x1b[0m msg=") {
|
||||
t.Fatalf("TRACE label did not receive its color: %q", text)
|
||||
}
|
||||
if strings.Count(text, "\x1b[") != 2 || !strings.Contains(text, `msg="level=ERROR is message text" level=ERROR`) {
|
||||
t.Fatalf("message or attributes were colored or changed: %q", text)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandlerUsesDynamicLevelAndHonorsColorNever(t *testing.T) {
|
||||
var output bytes.Buffer
|
||||
var threshold slog.LevelVar
|
||||
threshold.Set(slog.LevelWarn)
|
||||
handler, err := logging.NewHandler(&output, logging.Options{Level: &threshold, Color: logging.ColorNever})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
logger := slog.New(handler)
|
||||
logger.Info("filtered")
|
||||
threshold.Set(slog.LevelDebug)
|
||||
logger.Debug("visible")
|
||||
text := output.String()
|
||||
if strings.Contains(text, "filtered") || !strings.Contains(text, "level=DEBUG msg=visible") || strings.Contains(text, "\x1b[") {
|
||||
t.Fatalf("threshold or color policy was ignored: %q", text)
|
||||
}
|
||||
}
|
||||
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,77 @@
|
||||
// Package resourcecatalog reads Addressables catalog IDs and resolves CDN bundles.
|
||||
package resourcecatalog
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"path"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const RemotePrefix = "{BDNetwork.CdnInfo.Info}"
|
||||
|
||||
func Decode(raw []byte) (map[string]json.RawMessage, []string, error) {
|
||||
var document map[string]json.RawMessage
|
||||
decoder := json.NewDecoder(bytes.NewReader(raw))
|
||||
if err := decoder.Decode(&document); err != nil {
|
||||
return nil, nil, fmt.Errorf("resource catalog: decode: %w", err)
|
||||
}
|
||||
var trailing any
|
||||
if err := decoder.Decode(&trailing); !errors.Is(err, io.EOF) {
|
||||
return nil, nil, errors.New("resource catalog: must contain exactly one JSON object")
|
||||
}
|
||||
var ids []string
|
||||
if err := json.Unmarshal(document["m_InternalIds"], &ids); err != nil || len(ids) == 0 {
|
||||
return nil, nil, errors.New("resource catalog: no valid internal IDs")
|
||||
}
|
||||
return document, ids, nil
|
||||
}
|
||||
|
||||
func BundlePath(internalID string) (string, error) {
|
||||
parts := strings.Split(strings.ReplaceAll(internalID, "\\", "/"), "/")
|
||||
if len(parts) < 5 || parts[0] != RemotePrefix {
|
||||
return "", fmt.Errorf("resource catalog: invalid CDN path %q", internalID)
|
||||
}
|
||||
parts = parts[4:]
|
||||
for _, part := range parts {
|
||||
if part == "" || part == "." || part == ".." || strings.ContainsAny(part, `:{}`) {
|
||||
return "", fmt.Errorf("resource catalog: unsafe bundle path %q", internalID)
|
||||
}
|
||||
}
|
||||
relative := strings.Join(parts, "/")
|
||||
if !strings.EqualFold(path.Ext(relative), ".bundle") {
|
||||
return "", fmt.Errorf("resource catalog: CDN path is not a bundle %q", internalID)
|
||||
}
|
||||
return relative, nil
|
||||
}
|
||||
|
||||
func BundlePaths(raw []byte) ([]string, error) {
|
||||
_, ids, err := Decode(raw)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
unique := make(map[string]struct{})
|
||||
for _, id := range ids {
|
||||
if !strings.HasPrefix(id, RemotePrefix) {
|
||||
continue
|
||||
}
|
||||
relative, err := BundlePath(id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
unique[relative] = struct{}{}
|
||||
}
|
||||
if len(unique) == 0 {
|
||||
return nil, errors.New("resource catalog: no CDN bundle paths")
|
||||
}
|
||||
paths := make([]string, 0, len(unique))
|
||||
for relative := range unique {
|
||||
paths = append(paths, relative)
|
||||
}
|
||||
sort.Strings(paths)
|
||||
return paths, nil
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
// Package taskgraph plans and runs ordered dependency tasks.
|
||||
package taskgraph
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"slices"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type Task struct {
|
||||
Name string
|
||||
DependsOn []string
|
||||
// A nil Run groups dependencies without adding an action.
|
||||
Run func(context.Context) error
|
||||
}
|
||||
|
||||
// Graph keeps an immutable copy of task declarations. Execution state belongs
|
||||
// to each Run; callers own any data captured by their actions.
|
||||
type Graph struct {
|
||||
tasks map[string]Task
|
||||
}
|
||||
|
||||
func New(tasks ...Task) (*Graph, error) {
|
||||
graph := &Graph{tasks: make(map[string]Task, len(tasks))}
|
||||
names := make([]string, 0, len(tasks))
|
||||
for _, task := range tasks {
|
||||
if strings.TrimSpace(task.Name) == "" {
|
||||
return nil, fmt.Errorf("taskgraph: task name must not be empty")
|
||||
}
|
||||
if _, exists := graph.tasks[task.Name]; exists {
|
||||
return nil, fmt.Errorf("taskgraph: duplicate task %q", task.Name)
|
||||
}
|
||||
task.DependsOn = slices.Clone(task.DependsOn)
|
||||
graph.tasks[task.Name] = task
|
||||
names = append(names, task.Name)
|
||||
}
|
||||
if _, err := graph.Plan(names...); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return graph, nil
|
||||
}
|
||||
|
||||
// Plan validates all requested targets before returning their dependency order.
|
||||
// Targets and each task's dependencies retain declaration order, and shared
|
||||
// dependencies appear only once.
|
||||
func (g *Graph) Plan(targets ...string) ([]string, error) {
|
||||
const visiting, complete = 1, 2
|
||||
state := make(map[string]int, len(g.tasks))
|
||||
var stack, plan []string
|
||||
var visit func(string) error
|
||||
visit = func(name string) error {
|
||||
task, exists := g.tasks[name]
|
||||
if !exists {
|
||||
if len(stack) != 0 {
|
||||
return fmt.Errorf("taskgraph: task %q depends on unknown task %q", stack[len(stack)-1], name)
|
||||
}
|
||||
return fmt.Errorf("taskgraph: unknown target %q", name)
|
||||
}
|
||||
switch state[name] {
|
||||
case complete:
|
||||
return nil
|
||||
case visiting:
|
||||
cycle := append(slices.Clone(stack[slices.Index(stack, name):]), name)
|
||||
return fmt.Errorf("taskgraph: dependency cycle: %s", strings.Join(cycle, " -> "))
|
||||
}
|
||||
state[name] = visiting
|
||||
stack = append(stack, name)
|
||||
for _, dependency := range task.DependsOn {
|
||||
if err := visit(dependency); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
stack = stack[:len(stack)-1]
|
||||
state[name] = complete
|
||||
plan = append(plan, name)
|
||||
return nil
|
||||
}
|
||||
for _, target := range targets {
|
||||
if err := visit(target); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return plan, nil
|
||||
}
|
||||
|
||||
// Run completes validation before invoking any action, then runs synchronously.
|
||||
// Failure or cancellation stops the run before any later task can start.
|
||||
func (g *Graph) Run(ctx context.Context, targets ...string) error {
|
||||
plan, err := g.Plan(targets...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, name := range plan {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
if action := g.tasks[name].Run; action != nil {
|
||||
if err := action(ctx); err != nil {
|
||||
return fmt.Errorf("taskgraph: task %q: %w", name, err)
|
||||
}
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
return fmt.Errorf("taskgraph: after task %q: %w", name, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
package taskgraph_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"bd2server/internal/common/taskgraph"
|
||||
)
|
||||
|
||||
func TestSharedProductionFeedsBothConsumersOncePerRun(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
artifact := filepath.Join(root, "generated.txt")
|
||||
var events []string
|
||||
productions := 0
|
||||
consume := func(name string) func(context.Context) error {
|
||||
return func(context.Context) error {
|
||||
payload, err := os.ReadFile(artifact)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
events = append(events, name+":"+string(payload))
|
||||
return os.WriteFile(filepath.Join(root, name+".txt"), payload, 0o600)
|
||||
}
|
||||
}
|
||||
dependencies := []string{"generate"}
|
||||
declarations := []taskgraph.Task{
|
||||
{Name: "generate", Run: func(context.Context) error {
|
||||
productions++
|
||||
events = append(events, fmt.Sprintf("generate:%d", productions))
|
||||
return os.WriteFile(artifact, fmt.Appendf(nil, "generation-%d", productions), 0o600)
|
||||
}},
|
||||
{Name: "server", DependsOn: dependencies, Run: consume("server")},
|
||||
{Name: "client", DependsOn: []string{"generate"}, Run: consume("client")},
|
||||
{Name: "launch", DependsOn: []string{"client", "server"}, Run: func(context.Context) error {
|
||||
client, err := os.ReadFile(filepath.Join(root, "client.txt"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
server, err := os.ReadFile(filepath.Join(root, "server.txt"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if string(client) != string(server) {
|
||||
return errors.New("consumers received different generations")
|
||||
}
|
||||
events = append(events, "launch:"+string(client))
|
||||
return os.WriteFile(filepath.Join(root, "launched.txt"), client, 0o600)
|
||||
}},
|
||||
}
|
||||
graph, err := taskgraph.New(declarations...)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dependencies[0] = "missing"
|
||||
declarations[0].Run = func(context.Context) error { return errors.New("mutated declaration") }
|
||||
plan, err := graph.Plan("launch", "server")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !slices.Equal(plan, []string{"generate", "client", "server", "launch"}) {
|
||||
t.Fatalf("plan does not preserve declared dependency order: %v", plan)
|
||||
}
|
||||
plan[0] = "missing"
|
||||
for generation := 1; generation <= 2; generation++ {
|
||||
if err := graph.Run(context.Background(), "launch", "server"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
launched, err := os.ReadFile(filepath.Join(root, "launched.txt"))
|
||||
if err != nil || string(launched) != fmt.Sprintf("generation-%d", generation) {
|
||||
t.Fatalf("run did not publish current generation: %q, %v", launched, err)
|
||||
}
|
||||
}
|
||||
want := []string{"generate:1", "client:generation-1", "server:generation-1", "launch:generation-1", "generate:2", "client:generation-2", "server:generation-2", "launch:generation-2"}
|
||||
if !slices.Equal(events, want) {
|
||||
t.Fatalf("shared production repeated or execution order changed: %v", events)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvalidGraphAndTargetListCannotProduceFiles(t *testing.T) {
|
||||
for _, invalid := range []struct {
|
||||
name, diagnostic string
|
||||
tasks []taskgraph.Task
|
||||
}{
|
||||
{name: "cycle", diagnostic: "prepare -> verify -> prepare", tasks: []taskgraph.Task{{Name: "prepare", DependsOn: []string{"verify"}}, {Name: "verify", DependsOn: []string{"prepare"}}}},
|
||||
{name: "unknown dependency", diagnostic: `depends on unknown task "missing"`, tasks: []taskgraph.Task{{Name: "prepare", DependsOn: []string{"missing"}}}},
|
||||
{name: "duplicate", diagnostic: `duplicate task "generate"`, tasks: []taskgraph.Task{{Name: "generate"}}},
|
||||
{name: "empty", diagnostic: "must not be empty", tasks: []taskgraph.Task{{Name: " "}}},
|
||||
} {
|
||||
t.Run(invalid.name, func(t *testing.T) {
|
||||
output := filepath.Join(t.TempDir(), "generated.txt")
|
||||
tasks := append([]taskgraph.Task{{Name: "generate", Run: func(context.Context) error { return os.WriteFile(output, []byte("generated"), 0o600) }}}, invalid.tasks...)
|
||||
_, err := taskgraph.New(tasks...)
|
||||
if err == nil || !strings.Contains(err.Error(), invalid.diagnostic) {
|
||||
t.Fatalf("invalid graph was accepted or diagnosis lost: %v", err)
|
||||
}
|
||||
assertAbsent(t, output)
|
||||
})
|
||||
}
|
||||
output := filepath.Join(t.TempDir(), "generated.txt")
|
||||
graph, err := taskgraph.New(taskgraph.Task{Name: "generate", Run: func(context.Context) error { return os.WriteFile(output, []byte("generated"), 0o600) }})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := graph.Run(context.Background(), "generate", "unknown-launch"); err == nil || !strings.Contains(err.Error(), `unknown target "unknown-launch"`) {
|
||||
t.Fatalf("late unknown target was not rejected: %v", err)
|
||||
}
|
||||
assertAbsent(t, output)
|
||||
}
|
||||
|
||||
func TestFailedVerificationDoesNotLaunchAndPreservesCause(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
artifact := filepath.Join(root, "generated.txt")
|
||||
launch := filepath.Join(root, "launched.txt")
|
||||
cause := errors.New("bad generated resource")
|
||||
graph, err := taskgraph.New(
|
||||
taskgraph.Task{Name: "generate", Run: func(context.Context) error { return os.WriteFile(artifact, []byte("invalid"), 0o600) }},
|
||||
taskgraph.Task{Name: "verify", DependsOn: []string{"generate"}, Run: func(context.Context) error {
|
||||
payload, err := os.ReadFile(artifact)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if string(payload) != "valid" {
|
||||
return cause
|
||||
}
|
||||
return nil
|
||||
}},
|
||||
taskgraph.Task{Name: "launch", DependsOn: []string{"verify"}, Run: func(context.Context) error { return os.WriteFile(launch, []byte("started"), 0o600) }},
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := graph.Run(context.Background(), "launch"); !errors.Is(err, cause) || !strings.Contains(err.Error(), `task "verify"`) {
|
||||
t.Fatalf("task failure lost its source or cause: %v", err)
|
||||
}
|
||||
assertAbsent(t, launch)
|
||||
}
|
||||
|
||||
func TestCancellationStopsLaunchEvenWhenTaskReturnsSuccess(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
graph, err := taskgraph.New(
|
||||
taskgraph.Task{Name: "prepare", Run: func(ctx context.Context) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(root, "prepared.txt"), []byte("prepared"), 0o600); err != nil {
|
||||
return err
|
||||
}
|
||||
cancel()
|
||||
return nil
|
||||
}},
|
||||
taskgraph.Task{Name: "launch", DependsOn: []string{"prepare"}, Run: func(context.Context) error {
|
||||
return os.WriteFile(filepath.Join(root, "launched.txt"), []byte("started"), 0o600)
|
||||
}},
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := graph.Run(ctx, "launch"); !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("cancellation lost after successful action: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(root, "prepared.txt")); err != nil {
|
||||
t.Fatal("preparation did not execute", err)
|
||||
}
|
||||
assertAbsent(t, filepath.Join(root, "launched.txt"))
|
||||
|
||||
preCanceled, stop := context.WithCancel(context.Background())
|
||||
stop()
|
||||
if err := os.Remove(filepath.Join(root, "prepared.txt")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := graph.Run(preCanceled, "launch"); !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("pre-canceled context was ignored: %v", err)
|
||||
}
|
||||
assertAbsent(t, filepath.Join(root, "prepared.txt"))
|
||||
assertAbsent(t, filepath.Join(root, "launched.txt"))
|
||||
}
|
||||
|
||||
func assertAbsent(t *testing.T, path string) {
|
||||
t.Helper()
|
||||
if _, err := os.Stat(path); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatalf("unexpected output %s: %v", path, err)
|
||||
}
|
||||
}
|
||||
+6
-18
@@ -1,17 +1,17 @@
|
||||
// Package versionconfig loads repository-wide game compatibility, component
|
||||
// release, seed, and resource versions. The same versions.json drives plugins.
|
||||
// release, seed, and resource versions for the server, client, and build tools.
|
||||
package versionconfig
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
commonconfig "bd2server/internal/common/config"
|
||||
)
|
||||
|
||||
const FileName = "versions.json"
|
||||
@@ -24,7 +24,7 @@ var (
|
||||
current *Config
|
||||
)
|
||||
|
||||
// Config is the single version selection shared by the server and plugins.
|
||||
// Config is the version contract shared by the server, client, and plugins.
|
||||
// SourcePath is populated by Load and is not part of the JSON document.
|
||||
type Config struct {
|
||||
GameVersion string `json:"game_version"`
|
||||
@@ -52,21 +52,9 @@ func Load(path string) (Config, error) {
|
||||
if err != nil {
|
||||
return Config{}, fmt.Errorf("versionconfig: resolve path: %w", err)
|
||||
}
|
||||
data, err := os.ReadFile(path)
|
||||
cfg, err := commonconfig.Load(path, Config{}, commonconfig.DecodeOptions{DisallowUnknownFields: true, RejectTrailing: true})
|
||||
if err != nil {
|
||||
return Config{}, fmt.Errorf("versionconfig: read %s: %w", path, err)
|
||||
}
|
||||
var cfg Config
|
||||
decoder := json.NewDecoder(strings.NewReader(string(data)))
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(&cfg); err != nil {
|
||||
return Config{}, fmt.Errorf("versionconfig: decode %s: %w", path, err)
|
||||
}
|
||||
var trailing any
|
||||
if err := decoder.Decode(&trailing); err == nil {
|
||||
return Config{}, fmt.Errorf("versionconfig: trailing JSON in %s", path)
|
||||
} else if !errors.Is(err, io.EOF) {
|
||||
return Config{}, fmt.Errorf("versionconfig: trailing data in %s: %w", path, err)
|
||||
return Config{}, fmt.Errorf("versionconfig: load %s: %w", path, err)
|
||||
}
|
||||
cfg.SourcePath = path
|
||||
if err := cfg.Validate(); err != nil {
|
||||
@@ -1,13 +1,13 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"bd2server/internal/common/versionconfig"
|
||||
"bd2server/internal/server/design/gameconfig"
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/events/calendar"
|
||||
"bd2server/internal/server/gateway/authconfig"
|
||||
"bd2server/internal/server/gateway/bootstrap"
|
||||
"bd2server/internal/server/platform/textmoderation"
|
||||
"bd2server/internal/server/platform/versionconfig"
|
||||
"bd2server/internal/server/resources/policy"
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
@@ -3,7 +3,7 @@ package app
|
||||
import (
|
||||
"io"
|
||||
|
||||
"bd2server/internal/server/platform/logging"
|
||||
"bd2server/internal/common/logging"
|
||||
)
|
||||
|
||||
func ConfigureLogging(writer io.Writer, levelOverride, colorOverride string) error {
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"bd2server/internal/common/versionconfig"
|
||||
"bd2server/internal/server/design/gameconfig"
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/command"
|
||||
@@ -10,7 +11,6 @@ import (
|
||||
"bd2server/internal/server/domain/identity"
|
||||
"bd2server/internal/server/domain/roster"
|
||||
"bd2server/internal/server/platform/textmoderation"
|
||||
"bd2server/internal/server/platform/versionconfig"
|
||||
"bd2server/internal/server/runtime/player"
|
||||
identitystore "bd2server/internal/server/storage/identity"
|
||||
"bytes"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"bd2server/internal/server/platform/versionconfig"
|
||||
"bd2server/internal/common/versionconfig"
|
||||
"bd2server/internal/server/resources/fetch"
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
@@ -2,16 +2,12 @@
|
||||
package gameconfig
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
|
||||
"bd2server/internal/server/platform/configfile"
|
||||
commonconfig "bd2server/internal/common/config"
|
||||
)
|
||||
|
||||
const FileName = "game.json"
|
||||
@@ -128,33 +124,15 @@ func Default() Config {
|
||||
|
||||
// Load generates defaults when missing and strictly validates existing files.
|
||||
func Load(path string) (Config, error) {
|
||||
if err := configfile.Ensure(path, Default()); err != nil {
|
||||
if err := commonconfig.Ensure(path, Default(), commonconfig.WriteOptions{}); err != nil {
|
||||
return Config{}, fmt.Errorf("game configuration: initialize %s: %w", path, err)
|
||||
}
|
||||
data, err := os.ReadFile(filepath.Clean(path))
|
||||
if err != nil {
|
||||
return Config{}, fmt.Errorf("game configuration: read %s: %w", path, err)
|
||||
}
|
||||
cfg := Default()
|
||||
defaults := Default()
|
||||
// The format version is required even when gameplay sections are omitted.
|
||||
cfg.SchemaVersion = 0
|
||||
decoder := json.NewDecoder(bytes.NewReader(data))
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(&cfg); err != nil {
|
||||
return Config{}, fmt.Errorf("game configuration: decode %s: %w", path, err)
|
||||
}
|
||||
var trailing any
|
||||
if err := decoder.Decode(&trailing); !errors.Is(err, io.EOF) {
|
||||
return Config{}, fmt.Errorf("game configuration: trailing data in %s", path)
|
||||
}
|
||||
// encoding/json accepts null for scalar and struct fields. These rules have
|
||||
// explicit defaults for omissions, while null is a configuration error.
|
||||
var document any
|
||||
if err := json.Unmarshal(data, &document); err != nil {
|
||||
return Config{}, fmt.Errorf("game configuration: decode %s: %w", path, err)
|
||||
}
|
||||
if containsNull(document) {
|
||||
return Config{}, fmt.Errorf("game configuration: null is not allowed in %s", path)
|
||||
defaults.SchemaVersion = 0
|
||||
cfg, err := commonconfig.Load(path, defaults, commonconfig.DecodeOptions{DisallowUnknownFields: true, RejectTrailing: true, RejectNull: true})
|
||||
if err != nil {
|
||||
return Config{}, fmt.Errorf("game configuration: load %s: %w", path, err)
|
||||
}
|
||||
if err := cfg.Validate(); err != nil {
|
||||
return Config{}, fmt.Errorf("game configuration: %s: %w", path, err)
|
||||
@@ -162,22 +140,6 @@ func Load(path string) (Config, error) {
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func containsNull(value any) bool {
|
||||
switch value := value.(type) {
|
||||
case nil:
|
||||
return true
|
||||
case map[string]any:
|
||||
for _, child := range value {
|
||||
if containsNull(child) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
case []any:
|
||||
return slices.ContainsFunc(value, containsNull)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (c Config) Validate() error {
|
||||
if err := c.Realtime.Validate(); err != nil {
|
||||
return err
|
||||
|
||||
@@ -9,7 +9,7 @@ import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"bd2server/internal/server/design/dbcrypt"
|
||||
"bd2server/internal/common/dbcrypt"
|
||||
)
|
||||
|
||||
// DatabaseName maps a logical client DB name to its GameData archive entry.
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
package schedule
|
||||
|
||||
import (
|
||||
"bd2server/internal/server/platform/versionconfig"
|
||||
"bd2server/internal/common/versionconfig"
|
||||
"errors"
|
||||
"math"
|
||||
)
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
package hunting
|
||||
|
||||
import (
|
||||
"bd2server/internal/common/versionconfig"
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/command"
|
||||
"bd2server/internal/server/platform/versionconfig"
|
||||
"bd2server/internal/server/storage/stateio"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
@@ -2,10 +2,10 @@
|
||||
package hunting
|
||||
|
||||
import (
|
||||
"bd2server/internal/common/versionconfig"
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/command"
|
||||
assets "bd2server/internal/server/domain/inventory"
|
||||
"bd2server/internal/server/platform/versionconfig"
|
||||
"bd2server/internal/server/storage/stateio"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
package hunting
|
||||
|
||||
import (
|
||||
"bd2server/internal/common/versionconfig"
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/command"
|
||||
"bd2server/internal/server/platform/versionconfig"
|
||||
"bd2server/internal/server/storage/stateio"
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
package hunting
|
||||
|
||||
import (
|
||||
"bd2server/internal/common/versionconfig"
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/command"
|
||||
assets "bd2server/internal/server/domain/inventory"
|
||||
"bd2server/internal/server/platform/versionconfig"
|
||||
"bd2server/internal/server/protocol/wire"
|
||||
"bd2server/internal/server/storage/stateio"
|
||||
"bytes"
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
package monsterhunt
|
||||
|
||||
import (
|
||||
"bd2server/internal/common/versionconfig"
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/command"
|
||||
assets "bd2server/internal/server/domain/inventory"
|
||||
"bd2server/internal/server/domain/roster"
|
||||
"bd2server/internal/server/platform/versionconfig"
|
||||
"bd2server/internal/server/protocol/staticdata"
|
||||
"bd2server/internal/server/protocol/wire"
|
||||
"bd2server/internal/server/storage/stateio"
|
||||
|
||||
@@ -3,10 +3,10 @@
|
||||
package eventactions
|
||||
|
||||
import (
|
||||
"bd2server/internal/common/versionconfig"
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/command"
|
||||
"bd2server/internal/server/domain/events"
|
||||
"bd2server/internal/server/platform/versionconfig"
|
||||
"bd2server/internal/server/storage/stateio"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
package eventexchange
|
||||
|
||||
import (
|
||||
"bd2server/internal/common/versionconfig"
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/command"
|
||||
"bd2server/internal/server/domain/events"
|
||||
assets "bd2server/internal/server/domain/inventory"
|
||||
"bd2server/internal/server/platform/versionconfig"
|
||||
"bd2server/internal/server/storage/stateio"
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package eventplay
|
||||
|
||||
import (
|
||||
"bd2server/internal/server/platform/versionconfig"
|
||||
"bd2server/internal/common/versionconfig"
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
@@ -4,10 +4,10 @@
|
||||
package eventtasks
|
||||
|
||||
import (
|
||||
"bd2server/internal/common/versionconfig"
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/command"
|
||||
"bd2server/internal/server/domain/events"
|
||||
"bd2server/internal/server/platform/versionconfig"
|
||||
"bd2server/internal/server/storage/stateio"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
package inventory
|
||||
|
||||
import (
|
||||
"bd2server/internal/common/versionconfig"
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/command"
|
||||
"bd2server/internal/server/platform/versionconfig"
|
||||
"bd2server/internal/server/storage/stateio"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
package inventory
|
||||
|
||||
import (
|
||||
"bd2server/internal/common/versionconfig"
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/command"
|
||||
"bd2server/internal/server/platform/versionconfig"
|
||||
"bd2server/internal/server/storage/stateio"
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
package inventory
|
||||
|
||||
import (
|
||||
"bd2server/internal/common/versionconfig"
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/command"
|
||||
"bd2server/internal/server/platform/versionconfig"
|
||||
"bd2server/internal/server/storage/stateio"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
|
||||
@@ -7,9 +7,9 @@ import (
|
||||
"maps"
|
||||
"math"
|
||||
|
||||
"bd2server/internal/common/versionconfig"
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/command"
|
||||
"bd2server/internal/server/platform/versionconfig"
|
||||
"bd2server/internal/server/storage/stateio"
|
||||
)
|
||||
|
||||
|
||||
@@ -3,11 +3,11 @@
|
||||
package mail
|
||||
|
||||
import (
|
||||
"bd2server/internal/common/versionconfig"
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/command"
|
||||
assets "bd2server/internal/server/domain/inventory"
|
||||
"bd2server/internal/server/domain/roster"
|
||||
"bd2server/internal/server/platform/versionconfig"
|
||||
"bd2server/internal/server/storage/stateio"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
|
||||
Loaded 100 of 123 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user