feat: remove NWScript compiler support
This commit is contained in:
@@ -6,11 +6,9 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -544,228 +542,10 @@ func collectModuleResources(p *project.Project, moduleHakOrder []string) ([]erf.
|
||||
moduleResources = append(moduleResources, resource)
|
||||
}
|
||||
|
||||
compiledScripts, err := compileReferencedScripts(p)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
moduleResources = append(moduleResources, compiledScripts...)
|
||||
|
||||
sortResources(moduleResources)
|
||||
return moduleResources, nil
|
||||
}
|
||||
|
||||
func compileReferencedScripts(p *project.Project) ([]erf.Resource, error) {
|
||||
if skipNSSCompilation() {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
referenced, err := referencedScriptResrefs(p)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(referenced) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
scriptSources := make(map[string]string, len(p.Inventory.ScriptFiles))
|
||||
for _, rel := range p.Inventory.ScriptFiles {
|
||||
resref := strings.ToLower(strings.TrimSuffix(filepath.Base(rel), filepath.Ext(rel)))
|
||||
scriptSources[resref] = filepath.Join(p.SourceDir(), filepath.FromSlash(rel))
|
||||
}
|
||||
|
||||
compiler, err := resolveScriptCompiler(p)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
compilerEnv, err := resolveScriptCompilerEnvironment(p)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
cacheDir := compiledScriptCacheDir(p)
|
||||
if err := os.RemoveAll(cacheDir); err != nil {
|
||||
return nil, fmt.Errorf("clear script compiler cache dir: %w", err)
|
||||
}
|
||||
if err := os.MkdirAll(cacheDir, 0o755); err != nil {
|
||||
return nil, fmt.Errorf("create script compiler cache dir: %w", err)
|
||||
}
|
||||
|
||||
resources := make([]erf.Resource, 0, len(referenced))
|
||||
scriptsDir := p.ScriptSourceDir()
|
||||
for _, resref := range referenced {
|
||||
sourcePath, ok := scriptSources[resref]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
outputPath := filepath.Join(cacheDir, resref+".ncs")
|
||||
cmd := exec.Command(compiler, "--dirs", scriptsDir, "-o", outputPath, sourcePath)
|
||||
cmd.Env = compilerEnv
|
||||
output, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
message := strings.TrimSpace(string(output))
|
||||
if message == "" {
|
||||
message = err.Error()
|
||||
}
|
||||
return nil, fmt.Errorf("compile script %s: %s", filepath.Base(sourcePath), message)
|
||||
}
|
||||
resource, err := rawResource(outputPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("load compiled script %s: %w", filepath.Base(outputPath), err)
|
||||
}
|
||||
resources = append(resources, resource)
|
||||
}
|
||||
|
||||
return resources, nil
|
||||
}
|
||||
|
||||
func skipNSSCompilation() bool {
|
||||
switch strings.ToLower(strings.TrimSpace(os.Getenv("SOW_MODULE_SKIP_NSS_COMPILATION"))) {
|
||||
case "1", "true", "yes", "on":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func compiledScriptCacheDir(p *project.Project) string {
|
||||
return p.ScriptCacheDir()
|
||||
}
|
||||
|
||||
func referencedScriptResrefs(p *project.Project) ([]string, error) {
|
||||
referenced := map[string]struct{}{}
|
||||
for _, rel := range p.Inventory.SourceFiles {
|
||||
abs := filepath.Join(p.SourceDir(), filepath.FromSlash(rel))
|
||||
document, _, _, err := validatorLoadDocument(abs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
validatorWalkFields(document.Root, func(fieldLabel, value string) {
|
||||
if !validatorIsScriptField(fieldLabel) {
|
||||
return
|
||||
}
|
||||
value = strings.TrimSpace(value)
|
||||
if value == "" {
|
||||
return
|
||||
}
|
||||
referenced[strings.ToLower(value)] = struct{}{}
|
||||
})
|
||||
}
|
||||
|
||||
resrefs := make([]string, 0, len(referenced))
|
||||
for resref := range referenced {
|
||||
resrefs = append(resrefs, resref)
|
||||
}
|
||||
slices.Sort(resrefs)
|
||||
return resrefs, nil
|
||||
}
|
||||
|
||||
func resolveScriptCompiler(p *project.Project) (string, error) {
|
||||
candidates := make([]string, 0, 2+len(p.ScriptCompilerSearchPaths()))
|
||||
if configured := p.ScriptCompilerPath(); configured != "" {
|
||||
candidates = append(candidates, configured)
|
||||
}
|
||||
if configured := strings.TrimSpace(os.Getenv(p.ScriptCompilerPathEnv())); configured != "" {
|
||||
candidates = append(candidates, configured)
|
||||
}
|
||||
candidates = append(candidates, p.ScriptCompilerSearchPaths()...)
|
||||
|
||||
if runtime.GOOS == "windows" {
|
||||
slices.SortStableFunc(candidates, func(a, b string) int {
|
||||
aExe := strings.HasSuffix(strings.ToLower(a), ".exe")
|
||||
bExe := strings.HasSuffix(strings.ToLower(b), ".exe")
|
||||
if aExe == bExe {
|
||||
return strings.Compare(a, b)
|
||||
}
|
||||
if aExe {
|
||||
return -1
|
||||
}
|
||||
return 1
|
||||
})
|
||||
}
|
||||
for _, candidate := range candidates {
|
||||
if binary, ok := strings.CutPrefix(candidate, "PATH:"); ok {
|
||||
if compiler, err := exec.LookPath(binary); err == nil && scriptCompilerRunnable(compiler) {
|
||||
return compiler, nil
|
||||
}
|
||||
continue
|
||||
}
|
||||
if info, err := os.Stat(candidate); err == nil && !info.IsDir() && scriptCompilerRunnable(candidate) {
|
||||
return candidate, nil
|
||||
}
|
||||
}
|
||||
|
||||
return "", fmt.Errorf("script compiler not found; configure scripts.compiler.path or set %s", p.ScriptCompilerPathEnv())
|
||||
}
|
||||
|
||||
func scriptCompilerRunnable(path string) bool {
|
||||
if strings.TrimSpace(path) == "" {
|
||||
return false
|
||||
}
|
||||
info, err := os.Stat(path)
|
||||
if err != nil || info.IsDir() {
|
||||
return false
|
||||
}
|
||||
cmd := exec.Command(path, "--help")
|
||||
cmd.Stdout = io.Discard
|
||||
cmd.Stderr = io.Discard
|
||||
return cmd.Run() == nil
|
||||
}
|
||||
|
||||
func validatorLoadDocument(path string) (gff.Document, string, string, error) {
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return gff.Document{}, "", "", fmt.Errorf("read %s: %w", path, err)
|
||||
}
|
||||
|
||||
stem := strings.TrimSuffix(filepath.Base(path), ".json")
|
||||
extension := strings.TrimPrefix(strings.ToLower(filepath.Ext(stem)), ".")
|
||||
if extension == "" {
|
||||
return gff.Document{}, "", "", fmt.Errorf("missing resource extension before .json: %s", path)
|
||||
}
|
||||
resref := strings.ToLower(strings.TrimSuffix(stem, "."+extension))
|
||||
|
||||
var document gff.Document
|
||||
if err := json.Unmarshal(raw, &document); err != nil {
|
||||
return gff.Document{}, "", "", fmt.Errorf("parse %s: %w", path, err)
|
||||
}
|
||||
return document, resref, extension, nil
|
||||
}
|
||||
|
||||
func validatorWalkFields(root gff.Struct, visit func(string, string)) {
|
||||
walkScriptFields(root, visit)
|
||||
}
|
||||
|
||||
func validatorIsScriptField(label string) bool {
|
||||
return strings.HasPrefix(label, "On") || strings.HasSuffix(label, "Script") || strings.Contains(label, "Script")
|
||||
}
|
||||
|
||||
func walkScriptFields(s gff.Struct, visit func(string, string)) {
|
||||
for _, field := range s.Fields {
|
||||
if value, ok := fieldStringValueForScripts(field.Value); ok {
|
||||
visit(field.Label, value)
|
||||
}
|
||||
switch typed := field.Value.(type) {
|
||||
case gff.Struct:
|
||||
walkScriptFields(typed, visit)
|
||||
case gff.ListValue:
|
||||
for _, item := range typed {
|
||||
walkScriptFields(item, visit)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func fieldStringValueForScripts(value gff.Value) (string, bool) {
|
||||
switch typed := value.(type) {
|
||||
case gff.StringValue:
|
||||
return string(typed), true
|
||||
case gff.ResRefValue:
|
||||
return string(typed), true
|
||||
default:
|
||||
return "", false
|
||||
}
|
||||
}
|
||||
|
||||
func collectAssetResources(p *project.Project, requireContent bool, allowed map[string]struct{}, musicAssets *preparedMusicAssets, generated2DAAssets []topdata.Generated2DAAsset) ([]assetResource, error) {
|
||||
var hakResources []assetResource
|
||||
assetCreatedAt, err := collectGitAssetCreationTimes(p)
|
||||
|
||||
@@ -164,23 +164,6 @@ func expectedResources(p *project.Project) (map[string]resourceExpectation, erro
|
||||
}
|
||||
}
|
||||
|
||||
compiledScripts, err := compileReferencedScripts(p)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, resource := range compiledScripts {
|
||||
extension, ok := erf.ExtensionForResourceType(resource.Type)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("unsupported compiled resource type for %s", resource.Name)
|
||||
}
|
||||
key := resourceKey(resource.Name, extension)
|
||||
out[key] = resourceExpectation{
|
||||
Key: key,
|
||||
Kind: "compiled-script",
|
||||
Bytes: resource.Data,
|
||||
}
|
||||
}
|
||||
|
||||
for _, rel := range p.Inventory.AssetFiles {
|
||||
abs := filepath.Join(p.AssetsDir(), filepath.FromSlash(rel))
|
||||
data, err := os.ReadFile(abs)
|
||||
|
||||
@@ -289,7 +289,7 @@ func extractedFile(p *project.Project, resource erf.Resource, extension string)
|
||||
|
||||
switch extension {
|
||||
case "nss":
|
||||
target, err := extractionTarget(p, "paths.source", effective.Paths.Source, p.SourceDir(), filepath.FromSlash(effective.Scripts.SourceDir), resref+".nss")
|
||||
target, err := extractionTarget(p, "paths.source", effective.Paths.Source, p.SourceDir(), "scripts", resref+".nss")
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
|
||||
@@ -1028,205 +1028,6 @@ func TestBuildSplitsConfiguredHAKs(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildModuleCompilesReferencedScripts(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
mustMkdir(t, filepath.Join(root, "src", "module"))
|
||||
mustMkdir(t, filepath.Join(root, "src", "placeables"))
|
||||
mustMkdir(t, filepath.Join(root, "src", "scripts"))
|
||||
mustMkdir(t, filepath.Join(root, ".nwn-assets"))
|
||||
mustMkdir(t, filepath.Join(root, "build"))
|
||||
|
||||
mustWriteFile(t, filepath.Join(root, "nwn-tool.json"), `{
|
||||
"module": {
|
||||
"name": "Test Module",
|
||||
"resref": "testmod"
|
||||
},
|
||||
"paths": {
|
||||
"source": "src",
|
||||
"assets": ".nwn-assets",
|
||||
"build": "build"
|
||||
}
|
||||
}
|
||||
`)
|
||||
|
||||
mustWriteFile(t, filepath.Join(root, "src", "module", "module.ifo.json"), `{
|
||||
"file_type": "IFO ",
|
||||
"file_version": "V3.2",
|
||||
"root": {
|
||||
"struct_type": 0,
|
||||
"fields": [
|
||||
{
|
||||
"label": "Mod_Name",
|
||||
"type": "CExoString",
|
||||
"value": "Test Module"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
`)
|
||||
|
||||
mustWriteFile(t, filepath.Join(root, "src", "placeables", "thing.utp.json"), `{
|
||||
"file_type": "UTP ",
|
||||
"file_version": "V3.2",
|
||||
"root": {
|
||||
"struct_type": 0,
|
||||
"fields": [
|
||||
{
|
||||
"label": "OnUsed",
|
||||
"type": "ResRef",
|
||||
"value": "use_thing"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
`)
|
||||
|
||||
mustWriteFile(t, filepath.Join(root, "src", "scripts", "use_thing.nss"), `void main() {}`)
|
||||
|
||||
compiler := filepath.Join(root, "fake-compiler.sh")
|
||||
mustWriteFile(t, compiler, `#!/bin/sh
|
||||
set -eu
|
||||
if [ "${1:-}" = "--help" ]; then
|
||||
exit 0
|
||||
fi
|
||||
out=""
|
||||
src=""
|
||||
while [ "$#" -gt 0 ]; do
|
||||
case "$1" in
|
||||
-o)
|
||||
out="$2"
|
||||
shift 2
|
||||
;;
|
||||
--dirs)
|
||||
shift 2
|
||||
;;
|
||||
*)
|
||||
src="$1"
|
||||
shift
|
||||
;;
|
||||
esac
|
||||
done
|
||||
[ -n "$out" ]
|
||||
[ -n "$src" ]
|
||||
printf 'compiled:%s\nNWN_ROOT=%s\nNWN_HOME=%s\nNWN_USER_DIRECTORY=%s\n' "$(basename "$src")" "${NWN_ROOT-}" "${NWN_HOME-}" "${NWN_USER_DIRECTORY-}" > "$out"
|
||||
`)
|
||||
if err := os.Chmod(compiler, 0o755); err != nil {
|
||||
t.Fatalf("chmod fake compiler: %v", err)
|
||||
}
|
||||
t.Setenv("SOW_NWN_SCRIPT_COMPILER", compiler)
|
||||
installRoot := filepath.Join(root, "nwn-install")
|
||||
mustMkdir(t, filepath.Join(installRoot, "data"))
|
||||
t.Setenv("SOW_NWN_ROOT", installRoot)
|
||||
userDir := filepath.Join(root, "nwn-user")
|
||||
t.Setenv("SOW_NWN_USER_DIRECTORY", userDir)
|
||||
|
||||
p, err := project.Load(root)
|
||||
if err != nil {
|
||||
t.Fatalf("load project: %v", err)
|
||||
}
|
||||
if err := p.ValidateLayout(); err != nil {
|
||||
t.Fatalf("validate layout: %v", err)
|
||||
}
|
||||
if err := p.Scan(); err != nil {
|
||||
t.Fatalf("scan: %v", err)
|
||||
}
|
||||
|
||||
result, err := BuildModule(p)
|
||||
if err != nil {
|
||||
t.Fatalf("build module: %v", err)
|
||||
}
|
||||
if result.Resources != 4 {
|
||||
t.Fatalf("expected 4 resources, got %d", result.Resources)
|
||||
}
|
||||
|
||||
fh, err := os.Open(result.ModulePath)
|
||||
if err != nil {
|
||||
t.Fatalf("open built module: %v", err)
|
||||
}
|
||||
defer fh.Close()
|
||||
archive, err := erf.Read(fh)
|
||||
if err != nil {
|
||||
t.Fatalf("read built module: %v", err)
|
||||
}
|
||||
|
||||
foundSource := false
|
||||
foundCompiled := false
|
||||
for _, resource := range archive.Resources {
|
||||
if resource.Name != "use_thing" {
|
||||
continue
|
||||
}
|
||||
if extension, ok := erf.ExtensionForResourceType(resource.Type); ok {
|
||||
switch extension {
|
||||
case "nss":
|
||||
foundSource = true
|
||||
case "ncs":
|
||||
foundCompiled = true
|
||||
if !strings.Contains(string(resource.Data), "compiled:use_thing.nss") {
|
||||
t.Fatalf("unexpected compiled payload: %q", string(resource.Data))
|
||||
}
|
||||
if !strings.Contains(string(resource.Data), "NWN_ROOT="+installRoot) {
|
||||
t.Fatalf("compiled payload missing NWN_ROOT: %q", string(resource.Data))
|
||||
}
|
||||
if !strings.Contains(string(resource.Data), "NWN_HOME="+userDir) {
|
||||
t.Fatalf("compiled payload missing NWN_HOME: %q", string(resource.Data))
|
||||
}
|
||||
if !strings.Contains(string(resource.Data), "NWN_USER_DIRECTORY="+userDir) {
|
||||
t.Fatalf("compiled payload missing NWN_USER_DIRECTORY: %q", string(resource.Data))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !foundSource {
|
||||
t.Fatalf("expected source script resource in archive")
|
||||
}
|
||||
if !foundCompiled {
|
||||
t.Fatalf("expected compiled script resource in archive")
|
||||
}
|
||||
if _, err := os.Stat(userDir); err != nil {
|
||||
t.Fatalf("expected build to prepare NWN user directory: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(root, ".cache", "ncs", "use_thing.ncs")); err != nil {
|
||||
t.Fatalf("expected compiled script in .cache/ncs: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(root, ".nwn-assets", "ncs", "use_thing.ncs")); !os.IsNotExist(err) {
|
||||
t.Fatalf("expected no compiled script in .nwn-assets/ncs, got err=%v", err)
|
||||
}
|
||||
|
||||
compareResult, err := Compare(p)
|
||||
if err != nil {
|
||||
t.Fatalf("compare: %v", err)
|
||||
}
|
||||
if compareResult.Checked != 4 {
|
||||
t.Fatalf("expected 4 compared resources, got %d", compareResult.Checked)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseSteamLibraryFolders(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
vdf := filepath.Join(root, "libraryfolders.vdf")
|
||||
mustWriteFile(t, vdf, `"libraryfolders"
|
||||
{
|
||||
"0"
|
||||
{
|
||||
"path" "/mnt/games/Steam"
|
||||
}
|
||||
"1" "D:\\SteamLibrary"
|
||||
}
|
||||
`)
|
||||
|
||||
got := parseSteamLibraryFolders(vdf)
|
||||
if len(got) != 2 {
|
||||
t.Fatalf("expected 2 library roots, got %d (%v)", len(got), got)
|
||||
}
|
||||
if got[0] != filepath.Clean("/mnt/games/Steam") {
|
||||
t.Fatalf("unexpected first library root: %q", got[0])
|
||||
}
|
||||
if got[1] != filepath.Clean(`D:\SteamLibrary`) {
|
||||
t.Fatalf("unexpected second library root: %q", got[1])
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildBuildsTopPackageAndInjectsHAKList(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
mustMkdir(t, filepath.Join(root, "src", "module"))
|
||||
@@ -1344,118 +1145,6 @@ func TestBuildBuildsTopPackageAndInjectsHAKList(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildModuleSkipsReferencedScriptCompilationWhenRequested(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
mustMkdir(t, filepath.Join(root, "src", "module"))
|
||||
mustMkdir(t, filepath.Join(root, "src", "placeables"))
|
||||
mustMkdir(t, filepath.Join(root, "src", "scripts"))
|
||||
mustMkdir(t, filepath.Join(root, ".nwn-assets"))
|
||||
mustMkdir(t, filepath.Join(root, "build"))
|
||||
|
||||
mustWriteFile(t, filepath.Join(root, "nwn-tool.json"), `{
|
||||
"module": {
|
||||
"name": "Test Module",
|
||||
"resref": "testmod"
|
||||
},
|
||||
"paths": {
|
||||
"source": "src",
|
||||
"assets": ".nwn-assets",
|
||||
"build": "build"
|
||||
}
|
||||
}
|
||||
`)
|
||||
|
||||
mustWriteFile(t, filepath.Join(root, "src", "module", "module.ifo.json"), `{
|
||||
"file_type": "IFO ",
|
||||
"file_version": "V3.2",
|
||||
"root": {
|
||||
"struct_type": 0,
|
||||
"fields": [
|
||||
{
|
||||
"label": "Mod_Name",
|
||||
"type": "CExoString",
|
||||
"value": "Test Module"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
`)
|
||||
|
||||
mustWriteFile(t, filepath.Join(root, "src", "placeables", "thing.utp.json"), `{
|
||||
"file_type": "UTP ",
|
||||
"file_version": "V3.2",
|
||||
"root": {
|
||||
"struct_type": 0,
|
||||
"fields": [
|
||||
{
|
||||
"label": "OnUsed",
|
||||
"type": "ResRef",
|
||||
"value": "use_thing"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
`)
|
||||
|
||||
mustWriteFile(t, filepath.Join(root, "src", "scripts", "use_thing.nss"), `void main() {}`)
|
||||
t.Setenv("SOW_MODULE_SKIP_NSS_COMPILATION", "1")
|
||||
|
||||
p, err := project.Load(root)
|
||||
if err != nil {
|
||||
t.Fatalf("load project: %v", err)
|
||||
}
|
||||
if err := p.ValidateLayout(); err != nil {
|
||||
t.Fatalf("validate layout: %v", err)
|
||||
}
|
||||
if err := p.Scan(); err != nil {
|
||||
t.Fatalf("scan: %v", err)
|
||||
}
|
||||
|
||||
result, err := BuildModule(p)
|
||||
if err != nil {
|
||||
t.Fatalf("build module: %v", err)
|
||||
}
|
||||
if result.Resources != 3 {
|
||||
t.Fatalf("expected 3 resources without compiled script, got %d", result.Resources)
|
||||
}
|
||||
|
||||
fh, err := os.Open(result.ModulePath)
|
||||
if err != nil {
|
||||
t.Fatalf("open built module: %v", err)
|
||||
}
|
||||
defer fh.Close()
|
||||
archive, err := erf.Read(fh)
|
||||
if err != nil {
|
||||
t.Fatalf("read built module: %v", err)
|
||||
}
|
||||
|
||||
foundSource := false
|
||||
foundCompiled := false
|
||||
for _, resource := range archive.Resources {
|
||||
if resource.Name != "use_thing" {
|
||||
continue
|
||||
}
|
||||
if extension, ok := erf.ExtensionForResourceType(resource.Type); ok {
|
||||
switch extension {
|
||||
case "nss":
|
||||
foundSource = true
|
||||
case "ncs":
|
||||
foundCompiled = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !foundSource {
|
||||
t.Fatalf("expected source script resource in archive")
|
||||
}
|
||||
if foundCompiled {
|
||||
t.Fatalf("did not expect compiled script resource in archive")
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(root, ".cache", "ncs", "use_thing.ncs")); !os.IsNotExist(err) {
|
||||
t.Fatalf("expected no compiled script cache file, got err=%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildModuleDoesNotCompileTopData(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
mustMkdir(t, filepath.Join(root, "src", "module"))
|
||||
|
||||
@@ -1,287 +0,0 @@
|
||||
package pipeline
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"runtime"
|
||||
"strings"
|
||||
|
||||
"gitea.westgate.pw/ShadowsOverWestgate/sow-tools/internal/project"
|
||||
)
|
||||
|
||||
func resolveScriptCompilerEnvironment(p *project.Project) ([]string, error) {
|
||||
env := os.Environ()
|
||||
|
||||
userDir, err := resolveNWNUserDirectory(p.ScriptCompilerNWNUserDirectoryEnvKeys())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
env = upsertEnv(env, "NWN_HOME", userDir)
|
||||
env = upsertEnv(env, "NWN_USER_DIRECTORY", userDir)
|
||||
|
||||
root, err := resolveNWNRoot(p.ScriptCompilerNWNRootEnvKeys())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if root != "" {
|
||||
env = upsertEnv(env, "NWN_ROOT", root)
|
||||
}
|
||||
|
||||
return env, nil
|
||||
}
|
||||
|
||||
func resolveNWNUserDirectory(envKeys []string) (string, error) {
|
||||
for _, key := range envKeys {
|
||||
if value := strings.TrimSpace(os.Getenv(key)); value != "" {
|
||||
path := filepath.Clean(expandUserPath(value))
|
||||
if err := os.MkdirAll(path, 0o755); err != nil {
|
||||
return "", fmt.Errorf("prepare NWN user directory %s from %s: %w", path, key, err)
|
||||
}
|
||||
return path, nil
|
||||
}
|
||||
}
|
||||
|
||||
path, err := defaultNWNUserDirectory()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := os.MkdirAll(path, 0o755); err != nil {
|
||||
return "", fmt.Errorf("prepare default NWN user directory %s: %w", path, err)
|
||||
}
|
||||
return path, nil
|
||||
}
|
||||
|
||||
func defaultNWNUserDirectory() (string, error) {
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("resolve user home directory: %w", err)
|
||||
}
|
||||
|
||||
switch runtime.GOOS {
|
||||
case "windows", "darwin":
|
||||
return filepath.Join(home, "Documents", "Neverwinter Nights"), nil
|
||||
default:
|
||||
base := strings.TrimSpace(os.Getenv("XDG_DATA_HOME"))
|
||||
if base == "" {
|
||||
base = filepath.Join(home, ".local", "share")
|
||||
}
|
||||
return filepath.Join(base, "Neverwinter Nights"), nil
|
||||
}
|
||||
}
|
||||
|
||||
func resolveNWNRoot(envKeys []string) (string, error) {
|
||||
for _, key := range envKeys {
|
||||
if value := strings.TrimSpace(os.Getenv(key)); value != "" {
|
||||
path := filepath.Clean(expandUserPath(value))
|
||||
if !looksLikeNWNInstall(path) {
|
||||
return "", fmt.Errorf("%s does not point to a Neverwinter Nights install root: %s", key, path)
|
||||
}
|
||||
return path, nil
|
||||
}
|
||||
}
|
||||
|
||||
for _, root := range candidateNWNInstallRoots() {
|
||||
if looksLikeNWNInstall(root) {
|
||||
return root, nil
|
||||
}
|
||||
}
|
||||
|
||||
return "", nil
|
||||
}
|
||||
|
||||
func candidateNWNInstallRoots() []string {
|
||||
candidates := make([]string, 0, 8)
|
||||
for _, library := range steamLibraryRoots() {
|
||||
candidates = append(candidates, filepath.Join(library, "steamapps", "common", "Neverwinter Nights"))
|
||||
}
|
||||
|
||||
switch runtime.GOOS {
|
||||
case "windows":
|
||||
for _, base := range []string{
|
||||
strings.TrimSpace(os.Getenv("PROGRAMFILES(X86)")),
|
||||
strings.TrimSpace(os.Getenv("PROGRAMFILES")),
|
||||
} {
|
||||
if base == "" {
|
||||
continue
|
||||
}
|
||||
candidates = append(candidates, filepath.Join(base, "Steam", "steamapps", "common", "Neverwinter Nights"))
|
||||
}
|
||||
case "darwin":
|
||||
if home, err := os.UserHomeDir(); err == nil {
|
||||
candidates = append(candidates, filepath.Join(home, "Library", "Application Support", "Steam", "steamapps", "common", "Neverwinter Nights"))
|
||||
}
|
||||
default:
|
||||
if home, err := os.UserHomeDir(); err == nil {
|
||||
candidates = append(candidates,
|
||||
filepath.Join(home, ".local", "share", "Steam", "steamapps", "common", "Neverwinter Nights"),
|
||||
filepath.Join(home, ".steam", "steam", "steamapps", "common", "Neverwinter Nights"),
|
||||
filepath.Join(home, ".var", "app", "com.valvesoftware.Steam", ".local", "share", "Steam", "steamapps", "common", "Neverwinter Nights"),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return dedupePaths(candidates)
|
||||
}
|
||||
|
||||
func steamLibraryRoots() []string {
|
||||
steamRoots := defaultSteamRoots()
|
||||
roots := make([]string, 0, len(steamRoots)+4)
|
||||
roots = append(roots, steamRoots...)
|
||||
for _, steamRoot := range steamRoots {
|
||||
roots = append(roots, parseSteamLibraryFolders(filepath.Join(steamRoot, "steamapps", "libraryfolders.vdf"))...)
|
||||
}
|
||||
return dedupePaths(roots)
|
||||
}
|
||||
|
||||
func defaultSteamRoots() []string {
|
||||
roots := make([]string, 0, 6)
|
||||
if runtime.GOOS == "windows" {
|
||||
roots = append(roots, detectWindowsSteamRoot())
|
||||
roots = append(roots,
|
||||
filepath.Join(strings.TrimSpace(os.Getenv("PROGRAMFILES(X86)")), "Steam"),
|
||||
filepath.Join(strings.TrimSpace(os.Getenv("PROGRAMFILES")), "Steam"),
|
||||
)
|
||||
return dedupePaths(filterNonEmpty(roots))
|
||||
}
|
||||
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
switch runtime.GOOS {
|
||||
case "darwin":
|
||||
roots = append(roots, filepath.Join(home, "Library", "Application Support", "Steam"))
|
||||
default:
|
||||
roots = append(roots,
|
||||
filepath.Join(home, ".local", "share", "Steam"),
|
||||
filepath.Join(home, ".steam", "steam"),
|
||||
filepath.Join(home, ".var", "app", "com.valvesoftware.Steam", ".local", "share", "Steam"),
|
||||
)
|
||||
}
|
||||
return dedupePaths(filterNonEmpty(roots))
|
||||
}
|
||||
|
||||
func detectWindowsSteamRoot() string {
|
||||
for _, args := range [][]string{
|
||||
{"query", `HKCU\Software\Valve\Steam`, "/v", "SteamPath"},
|
||||
{"query", `HKLM\SOFTWARE\WOW6432Node\Valve\Steam`, "/v", "InstallPath"},
|
||||
{"query", `HKLM\SOFTWARE\Valve\Steam`, "/v", "InstallPath"},
|
||||
} {
|
||||
out, err := exec.Command("reg", args...).CombinedOutput()
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if path := parseWindowsRegistryPath(string(out)); path != "" {
|
||||
return filepath.Clean(path)
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func parseWindowsRegistryPath(raw string) string {
|
||||
index := strings.Index(raw, "REG_SZ")
|
||||
if index == -1 {
|
||||
return ""
|
||||
}
|
||||
return strings.TrimSpace(raw[index+len("REG_SZ"):])
|
||||
}
|
||||
|
||||
func parseSteamLibraryFolders(path string) []string {
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
pathPattern := regexp.MustCompile(`"path"\s*"([^"]+)"`)
|
||||
legacyPattern := regexp.MustCompile(`^\s*"\d+"\s*"([^"]+)"\s*$`)
|
||||
|
||||
roots := make([]string, 0, 8)
|
||||
scanner := bufio.NewScanner(strings.NewReader(string(raw)))
|
||||
for scanner.Scan() {
|
||||
line := scanner.Text()
|
||||
if match := pathPattern.FindStringSubmatch(line); len(match) == 2 {
|
||||
roots = append(roots, normalizeSteamPath(match[1]))
|
||||
continue
|
||||
}
|
||||
if match := legacyPattern.FindStringSubmatch(line); len(match) == 2 {
|
||||
roots = append(roots, normalizeSteamPath(match[1]))
|
||||
}
|
||||
}
|
||||
|
||||
return dedupePaths(filterNonEmpty(roots))
|
||||
}
|
||||
|
||||
func normalizeSteamPath(value string) string {
|
||||
value = strings.TrimSpace(value)
|
||||
value = strings.ReplaceAll(value, `\\`, `\`)
|
||||
return filepath.Clean(expandUserPath(value))
|
||||
}
|
||||
|
||||
func looksLikeNWNInstall(path string) bool {
|
||||
if strings.TrimSpace(path) == "" {
|
||||
return false
|
||||
}
|
||||
info, err := os.Stat(filepath.Join(path, "data"))
|
||||
return err == nil && info.IsDir()
|
||||
}
|
||||
|
||||
func expandUserPath(path string) string {
|
||||
if path == "" || path[0] != '~' {
|
||||
return path
|
||||
}
|
||||
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return path
|
||||
}
|
||||
if path == "~" {
|
||||
return home
|
||||
}
|
||||
if path[1] == '/' || path[1] == '\\' {
|
||||
return filepath.Join(home, path[2:])
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
func upsertEnv(env []string, key, value string) []string {
|
||||
prefix := key + "="
|
||||
for i, entry := range env {
|
||||
if strings.HasPrefix(entry, prefix) {
|
||||
env[i] = prefix + value
|
||||
return env
|
||||
}
|
||||
}
|
||||
return append(env, prefix+value)
|
||||
}
|
||||
|
||||
func dedupePaths(paths []string) []string {
|
||||
seen := make(map[string]struct{}, len(paths))
|
||||
out := make([]string, 0, len(paths))
|
||||
for _, path := range paths {
|
||||
if strings.TrimSpace(path) == "" {
|
||||
continue
|
||||
}
|
||||
clean := filepath.Clean(path)
|
||||
if _, ok := seen[clean]; ok {
|
||||
continue
|
||||
}
|
||||
seen[clean] = struct{}{}
|
||||
out = append(out, clean)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func filterNonEmpty(values []string) []string {
|
||||
out := make([]string, 0, len(values))
|
||||
for _, value := range values {
|
||||
if strings.TrimSpace(value) != "" {
|
||||
out = append(out, value)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
Reference in New Issue
Block a user