From 182bf06974ea7428b6032984d959ebdf0ed598c5 Mon Sep 17 00:00:00 2001 From: "Fabian @ Blax Software" Date: Sun, 29 Nov 2026 20:49:46 +0100 Subject: [PATCH] feat: Workshop upload tool and per-DLC test result copies The shared Blax Gaming uploader: dry run, -Check release gate, -Publish creates the item on first use. --- Tests/run-tests.ps1 | 14 +- Tools/WorkshopUpload/Program.cs | 485 +++++++++++++++++++++ Tools/WorkshopUpload/WorkshopUpload.csproj | 33 ++ Tools/workshop-stage.ps1 | 63 +++ Tools/workshop-upload.ps1 | 333 ++++++++++++++ 5 files changed, 927 insertions(+), 1 deletion(-) create mode 100644 Tools/WorkshopUpload/Program.cs create mode 100644 Tools/WorkshopUpload/WorkshopUpload.csproj create mode 100644 Tools/workshop-stage.ps1 create mode 100644 Tools/workshop-upload.ps1 diff --git a/Tests/run-tests.ps1 b/Tests/run-tests.ps1 index 253111b..0822034 100644 --- a/Tests/run-tests.ps1 +++ b/Tests/run-tests.ps1 @@ -16,6 +16,11 @@ Mods\BlaxCastes must be a directory junction to this repo; it is created if miss While the suite runs, the test mod is linked into the game's Mods folder; that link is removed afterwards. Only one run at a time: a lock file in the data folder holds the running script's process id. Every run starts from default mod settings: the Blax Castes and Blax Slaves settings files in the data folder are deleted. +The results go to BlaxCastesTestResults.txt in the data folder, and a copy per DLC set next to it: +BlaxCastesTestResults.all.txt (every installed DLC), .nodlc.txt, or .dlc-.txt. Runs with -Compat or +-Tasoc write .-compat.txt instead (.all-compat.txt, .nodlc-compat.txt, ...). Each copy starts with a +"REPO " line naming the copy of the repo that was tested. The Workshop upload checks the "all" and +"nodlc" copies. #> param( [string]$RimWorldDir = 'E:\SteamLibrary\steamapps\common\RimWorld', @@ -125,6 +130,11 @@ try { [void]$mods.Add('ludeon.rimworld') foreach ($d in $loadDlcs) { [void]$mods.Add('ludeon.rimworld.' + $d.ToLower()) } Write-Host ("DLCs: " + $(if ($loadDlcs.Count) { $loadDlcs -join ', ' } else { 'none' })) + # Name of this DLC set for the per-set copy of the results. + $dlcSet = if ($loadDlcs.Count -eq 0) { 'nodlc' } elseif ($loadDlcs.Count -eq $installedDlcs.Count) { 'all' } else { 'dlc-' + ($loadDlcs -join '-').ToLower() } + # Other mods change what runs and what skips, so their runs never stand in for the plain ones. + if ($Compat -or $Tasoc) { $dlcSet += '-compat' } + $setResults = Join-Path $DataDir "BlaxCastesTestResults.$dlcSet.txt" if ($Compat) { # Trade as Slave or Colonist is left out, so Blax Slaves' own buy mode is the one tested; -Tasoc adds it. foreach ($id in 'orion.hospitality', 'mlie.customprisonerinteractions', 'legator.prisonerrealism', 'papercrane1001.weaponstab') { @@ -138,7 +148,7 @@ try { # fresh test data folder: mod list only, no old save, results or mod settings (files are named Mod__.xml) New-Item -ItemType Directory -Force (Join-Path $DataDir 'Config') | Out-Null - Remove-Item -Force -ErrorAction SilentlyContinue (Join-Path $DataDir 'Saves\BlaxCastesTest.rws'), (Join-Path $DataDir 'BlaxCastesTestResults.txt') + Remove-Item -Force -ErrorAction SilentlyContinue (Join-Path $DataDir 'Saves\BlaxCastesTest.rws'), (Join-Path $DataDir 'BlaxCastesTestResults.txt'), $setResults Get-ChildItem -LiteralPath (Join-Path $DataDir 'Config') -Filter 'Mod_*.xml' -ErrorAction SilentlyContinue | Where-Object { $_.Name -like 'Mod_BlaxCastes_*' -or $_.Name -like 'Mod_BlaxSlaves_*' -or $_.Name -like 'Mod_blax.castes_*' } | Remove-Item -Force -ErrorAction SilentlyContinue @@ -178,6 +188,8 @@ finally { $results = Join-Path $DataDir 'BlaxCastesTestResults.txt' if (-not (Test-Path $results)) { Write-Host 'No results file: the suite never started. See game.log.'; exit 2 } +# The per-set copy names the tested copy of the repo, so the Workshop upload never takes another copy's run. +[IO.File]::WriteAllLines($setResults, [string[]](@("REPO $repo") + @(Get-Content -LiteralPath $results -Encoding UTF8)), (New-Object Text.UTF8Encoding $false)) $lines = Get-Content -LiteralPath $results -Encoding UTF8 $lines | ForEach-Object { Write-Host $_ } if (-not ($lines -match '^END$')) { Write-Host 'The run did not finish.'; exit 2 } diff --git a/Tools/WorkshopUpload/Program.cs b/Tools/WorkshopUpload/Program.cs new file mode 100644 index 0000000..7d22f13 --- /dev/null +++ b/Tools/WorkshopUpload/Program.cs @@ -0,0 +1,485 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading; +using Steamworks; + +// Creates or updates a RimWorld Steam Workshop item through the running, logged-in Steam client. +// No password: SteamAPI attaches to the client as RimWorld (app 294100), like the game does. +// Without --publish it never calls a Steam write API: it checks the login and the RimWorld license, for an +// existing item reads it and checks that this Steam account owns it, and for a new one checks that no earlier, +// cut-off create left an item behind. +internal static class Program +{ + private const uint RimWorldAppId = 294100; + private const int MaxTextBytes = 8000; // Steam's limit for a description and a change note (k_cchPublishedDocumentDescriptionMax) + private const int MaxTitleBytes = 128; // k_cchPublishedDocumentTitleMax without the terminating zero + private const long MaxPreviewBytes = 1024 * 1024; // Steam refuses a preview over 1 MB + private const string LegalAgreementHint = + "Steam hides the item until you accept the Workshop legal agreement: https://steamcommunity.com/sharedfiles/workshoplegalagreement"; + + private static int Main(string[] args) + { + Options o; + try { o = Options.Parse(args); } + catch (ArgumentException e) + { + Console.Error.WriteLine(e.Message); + Console.Error.WriteLine(Options.Usage); + return 64; + } + + // Everything that can be checked without Steam comes first. + if (o.Content != null && !CheckContent(o.Content)) return 65; + if (o.Preview != null && !CheckPreview(o.Preview)) return 65; + if (o.Title != null && Encoding.UTF8.GetByteCount(o.Title) > MaxTitleBytes) + { + Console.Error.WriteLine($"The title is over Steam's {MaxTitleBytes}-byte limit."); + return 65; + } + string note = o.NoteFile != null ? File.ReadAllText(o.NoteFile, Encoding.UTF8).Trim() : null; + string description = o.DescriptionFile != null ? File.ReadAllText(o.DescriptionFile, Encoding.UTF8).Trim() : null; + if (description != null && Encoding.UTF8.GetByteCount(description) > MaxTextBytes) + { + Console.Error.WriteLine($"The description is over Steam's {MaxTextBytes}-byte limit."); + return 65; + } + if (note != null && Encoding.UTF8.GetByteCount(note) > MaxTextBytes) + { + Console.Error.WriteLine($"The change note is over Steam's {MaxTextBytes}-byte limit."); + return 65; + } + if (o.Create && File.Exists(o.IdFile)) + { + Console.Error.WriteLine($"{o.IdFile} already exists ({File.ReadAllText(o.IdFile).Trim()}): the item was created before. Update it with --item."); + return 65; + } + + // SteamAPI.Init looks for steam_appid.txt in the working directory; the env var covers other callers. + Directory.SetCurrentDirectory(AppContext.BaseDirectory); + Environment.SetEnvironmentVariable("SteamAppId", RimWorldAppId.ToString()); + if (!Packsize.Test() || !DllCheck.Test()) + { + Console.Error.WriteLine("Steamworks.NET and steam_api64.dll don't match. Rebuild the tool against the current RimWorld install."); + return 2; + } + // Never call SteamAPI.RestartAppIfNecessary here: it would make Steam launch RimWorld. + if (!SteamAPI.Init()) + { + Console.Error.WriteLine("SteamAPI.Init failed. Is Steam running and logged in, under the same Windows user, not as administrator?"); + return 2; + } + try + { + return Run(o, note, description); + } + finally + { + SteamAPI.Shutdown(); + } + } + + private static int Run(Options o, string note, string description) + { + Console.WriteLine($"Steam account: {SteamFriends.GetPersonaName()}"); + if (!SteamUser.BLoggedOn()) + { + Console.Error.WriteLine("Steam is not logged on (offline mode?). Go online in Steam and try again."); + return 3; + } + if (!SteamApps.BIsSubscribedApp(new AppId_t(RimWorldAppId))) + { + Console.Error.WriteLine("This Steam account has no RimWorld license, so it can't publish RimWorld Workshop items."); + return 3; + } + return o.Create ? RunCreate(o, note, description) : RunUpdate(o, note, description); + } + + private static int RunUpdate(Options o, string note, string description) + { + var item = new PublishedFileId_t(o.Item); + if (!QueryDetails(item, o.Timeout, out SteamUGCDetails_t d, out string[] descriptors)) return 3; + Console.WriteLine($"Item {o.Item}: \"{d.m_rgchTitle}\""); + Console.WriteLine($" updated {DateTimeOffset.FromUnixTimeSeconds(d.m_rtimeUpdated).ToLocalTime():yyyy-MM-dd HH:mm}"); + Console.WriteLine($" tags {d.m_rgchTags}"); + Console.WriteLine($" size {d.m_nFileSize / 1024.0:N0} KB"); + Console.WriteLine($" visible {VisibilityName(d.m_eVisibility)}"); + if (d.m_bBanned) Console.WriteLine(" BANNED on Steam"); + // Mature-content descriptors hide the item page from logged-out visitors and from players who didn't opt in. + Console.WriteLine($" content {(descriptors.Length > 0 ? string.Join(", ", descriptors) : "no mature-content descriptors")}"); + if (d.m_nConsumerAppID.m_AppId != RimWorldAppId) + { + Console.Error.WriteLine($"The item belongs to app {d.m_nConsumerAppID.m_AppId}, not RimWorld."); + return 3; + } + if (d.m_ulSteamIDOwner != SteamUser.GetSteamID().m_SteamID) + { + Console.Error.WriteLine("This Steam account doesn't own the item."); + return 3; + } + Console.WriteLine(" owner this account"); + + if (!o.Publish) + { + Console.WriteLine(); + Console.WriteLine("Dry run: nothing was uploaded."); + if (o.Title != null) + Console.WriteLine($" would set the title \"{o.Title}\"" + (o.Title == d.m_rgchTitle ? " (unchanged)" : $" (now \"{d.m_rgchTitle}\")")); + PrintPlan(o, note, description); + return 0; + } + + bool descriptionOnly = o.Content == null && note == null && description != null; + if (!descriptionOnly && (o.Content == null || note == null)) + { + Console.Error.WriteLine("--publish needs --content and --note-file, or only --description-file."); + return 64; + } + return Submit(item, o, note, description, false); + } + + private static int RunCreate(Options o, string note, string description) + { + Console.WriteLine(" logged on, owns RimWorld"); + int found = CheckNoEarlierItem(o); + if (found != 0) return found; + if (!o.Publish) + { + Console.WriteLine(); + Console.WriteLine("Dry run: nothing was created or uploaded."); + Console.WriteLine($" would create a new RimWorld Workshop item \"{o.Title}\""); + Console.WriteLine($" would write its id to {o.IdFile}"); + PrintPlan(o, note, description); + if (o.Visibility == null) Console.WriteLine(" visibility Steam's default for a new item, as with the in-game uploader"); + return 0; + } + + Console.WriteLine("Creating the Workshop item..."); + bool got = false, ioFailure = false; + CreateItemResult_t created = default; + var call = CallResult.Create((r, io) => { created = r; ioFailure = io; got = true; }); + call.Set(SteamUGC.CreateItem(new AppId_t(RimWorldAppId), EWorkshopFileType.k_EWorkshopFileTypeFirst)); + bool finished = Pump(() => got, o.Timeout); + GC.KeepAlive(call); + string myItems = $"https://steamcommunity.com/profiles/{SteamUser.GetSteamID().m_SteamID}/myworkshopfiles/?appid={RimWorldAppId}"; + if (!finished) + { + Console.Error.WriteLine($"No answer from Steam in time. Steam may still create the item: check {myItems} before retrying."); + return 5; + } + if (ioFailure) return Fail($"Steam reported an IO failure while creating the item. Check {myItems} before retrying."); + if (created.m_eResult != EResult.k_EResultOK) return Fail($"Steam refused to create the item: {created.m_eResult}. {Hint(created.m_eResult)}"); + + // Write the id before anything else: a failed upload must lead to an update on retry, never to a second item. + PublishedFileId_t item = created.m_nPublishedFileId; + string id = item.m_PublishedFileId.ToString(); + try + { + File.WriteAllText(o.IdFile, id); + // The game copies the id into the uploaded folder too, so the uploaded About folder matches the repo. + if (o.Content != null) File.WriteAllText(Path.Combine(o.Content, "About", "PublishedFileId.txt"), id); + } + catch (Exception e) + { + Console.Error.WriteLine($"Created item {id}, but couldn't write {o.IdFile}: {e.Message}"); + Console.Error.WriteLine($"Write {id} into that file by hand before retrying, or the next run creates a second item."); + return 4; + } + Console.WriteLine($"Created item {id}: https://steamcommunity.com/sharedfiles/filedetails/?id={id}"); + Console.WriteLine($" wrote {o.IdFile}"); + + int code = Submit(item, o, note, description, created.m_bUserNeedsToAcceptWorkshopLegalAgreement); + if (code != 0) + Console.Error.WriteLine($"Item {id} exists, but the upload didn't finish. Run the upload again: with {Path.GetFileName(o.IdFile)} in place it updates this item instead of creating another."); + return code; + } + + // A create that was cut off (no answer in time, an IO failure, the process killed or Ctrl+C between Steam + // creating the item and the answer) can leave an item on Steam with no id file, and the next run would create + // a second one. Such an item has no title yet: the title only comes with the first SubmitItemUpdate. So before + // creating, look at this account's newest RimWorld items for one with this title or none. + private static int CheckNoEarlierItem(Options o) + { + var appId = new AppId_t(RimWorldAppId); + UGCQueryHandle_t q = SteamUGC.CreateQueryUserUGCRequest(SteamUser.GetSteamID().GetAccountID(), + EUserUGCList.k_EUserUGCList_Published, EUGCMatchingUGCType.k_EUGCMatchingUGCType_Items, + EUserUGCListSortOrder.k_EUserUGCListSortOrder_CreationOrderDesc, appId, appId, 1); + bool got = false, ioFailure = false; + SteamUGCQueryCompleted_t done = default; + var call = CallResult.Create((r, io) => { done = r; ioFailure = io; got = true; }); + call.Set(SteamUGC.SendQueryUGCRequest(q)); + try + { + if (!Pump(() => got, o.Timeout)) + { + Console.Error.WriteLine("No answer from Steam for this account's Workshop items, so it is unclear whether an earlier create left an item. Try again."); + return 3; + } + if (ioFailure || done.m_eResult != EResult.k_EResultOK) + { + Console.Error.WriteLine($"The query for this account's Workshop items failed: {(ioFailure ? "IO failure" : done.m_eResult.ToString())}. Try again."); + return 3; + } + var earlier = new List(); + for (uint i = 0; i < done.m_unNumResultsReturned; i++) + { + if (!SteamUGC.GetQueryUGCResult(q, i, out SteamUGCDetails_t d) || d.m_eResult != EResult.k_EResultOK) continue; + string title = (d.m_rgchTitle ?? "").Trim(); + if (title.Length == 0 || string.Equals(title, o.Title, StringComparison.OrdinalIgnoreCase)) + earlier.Add($"{d.m_nPublishedFileId.m_PublishedFileId} ({(title.Length == 0 ? "no title" : $"\"{title}\"")})"); + } + if (earlier.Count > 0) + { + Console.Error.WriteLine("This Steam account already has a RimWorld Workshop item with this title or with no title: " + string.Join(", ", earlier) + "."); + Console.Error.WriteLine($"If it is this mod (an untitled one is an earlier create that was cut off), write its id to {o.IdFile} and run again to update it."); + Console.Error.WriteLine($"If it is not, rename or delete it on Steam first: https://steamcommunity.com/profiles/{SteamUser.GetSteamID().m_SteamID}/myworkshopfiles/?appid={RimWorldAppId}"); + return 65; + } + Console.WriteLine($" no earlier item with this title or without a title ({done.m_unNumResultsReturned} newest checked)"); + return 0; + } + finally + { + GC.KeepAlive(call); + SteamUGC.ReleaseQueryUGCRequest(q); + } + } + + private static void PrintPlan(Options o, string note, string description) + { + if (o.Content != null) Console.WriteLine($" would upload {o.Content}"); + if (o.Tags != null) Console.WriteLine($" would tag {string.Join(", ", o.Tags)}"); + if (o.Preview != null) Console.WriteLine($" would set the preview {o.Preview} ({new FileInfo(o.Preview).Length / 1024.0:N0} KB)"); + if (description != null) Console.WriteLine($" would {(o.Create ? "set" : "replace")} the description ({Encoding.UTF8.GetByteCount(description)} bytes)"); + if (o.Visibility != null) Console.WriteLine($" would set the visibility to {VisibilityName(o.Visibility.Value)}"); + if (note != null) Console.WriteLine(" change note:\n" + Indent(note)); + } + + private static int Submit(PublishedFileId_t item, Options o, string note, string description, bool legalAgreementPending) + { + UGCUpdateHandle_t h = SteamUGC.StartItemUpdate(new AppId_t(RimWorldAppId), item); + // Same fields as the game's uploader: title, description, preview, tags, content. + if (o.Title != null && !SteamUGC.SetItemTitle(h, o.Title)) return Fail("SetItemTitle refused the title."); + // Description-only updates send no content and no change note (null), so Steam lists no new change note. + if (description != null && !SteamUGC.SetItemDescription(h, description)) return Fail("SetItemDescription refused the text."); + if (o.Preview != null && !SteamUGC.SetItemPreview(h, o.Preview)) return Fail("SetItemPreview refused the preview image."); + if (o.Tags != null && !SteamUGC.SetItemTags(h, o.Tags)) return Fail("SetItemTags refused the tags."); + if (o.Content != null && !SteamUGC.SetItemContent(h, o.Content)) return Fail("SetItemContent refused the content folder."); + if (o.Visibility != null && !SteamUGC.SetItemVisibility(h, o.Visibility.Value)) return Fail("SetItemVisibility refused the visibility."); + + bool got = false, ioFailure = false; + SubmitItemUpdateResult_t result = default; + var call = CallResult.Create((r, io) => { result = r; ioFailure = io; got = true; }); + call.Set(SteamUGC.SubmitItemUpdate(h, note)); + + Console.WriteLine("Uploading..."); + EItemUpdateStatus last = EItemUpdateStatus.k_EItemUpdateStatusInvalid; + bool finished = Pump(() => got, o.Timeout, () => + { + EItemUpdateStatus s = SteamUGC.GetItemUpdateProgress(h, out ulong done, out ulong total); + if (s != last && s != EItemUpdateStatus.k_EItemUpdateStatusInvalid) + { + Console.WriteLine($" {s.ToString().Replace("k_EItemUpdateStatus", "")}" + (total > 0 ? $" {done / 1024}/{total / 1024} KB" : "")); + last = s; + } + }); + GC.KeepAlive(call); + if (!finished) + { + Console.Error.WriteLine("No answer from Steam in time. Steam may still finish the upload; check the item page before retrying."); + return 5; + } + if (ioFailure) return Fail("Steam reported an IO failure."); + if (result.m_eResult != EResult.k_EResultOK) return Fail($"Steam refused the update: {result.m_eResult}. {Hint(result.m_eResult)}"); + + Console.WriteLine($"Done: https://steamcommunity.com/sharedfiles/filedetails/?id={item.m_PublishedFileId}"); + if (legalAgreementPending || result.m_bUserNeedsToAcceptWorkshopLegalAgreement) Console.WriteLine(LegalAgreementHint); + return 0; + } + + private static bool QueryDetails(PublishedFileId_t item, TimeSpan timeout, out SteamUGCDetails_t details, out string[] descriptors) + { + details = default; + descriptors = Array.Empty(); + UGCQueryHandle_t q = SteamUGC.CreateQueryUGCDetailsRequest(new[] { item }, 1); + bool got = false, ioFailure = false; + SteamUGCQueryCompleted_t done = default; + var call = CallResult.Create((r, io) => { done = r; ioFailure = io; got = true; }); + call.Set(SteamUGC.SendQueryUGCRequest(q)); + try + { + if (!Pump(() => got, timeout)) { Console.Error.WriteLine("No answer from Steam for the item query."); return false; } + if (ioFailure || done.m_eResult != EResult.k_EResultOK || done.m_unNumResultsReturned < 1) + { + Console.Error.WriteLine($"The item query failed: {(ioFailure ? "IO failure" : done.m_eResult.ToString())}."); + return false; + } + if (!SteamUGC.GetQueryUGCResult(q, 0, out details) || details.m_eResult != EResult.k_EResultOK) + { + Console.Error.WriteLine($"Steam has no item {item}: {details.m_eResult}."); + return false; + } + var ids = new EUGCContentDescriptorID[8]; + uint count = SteamUGC.GetQueryUGCContentDescriptors(q, 0, ids, (uint)ids.Length); + descriptors = ids.Take((int)Math.Min(count, (uint)ids.Length)) + .Select(id => id.ToString().Replace("k_EUGCContentDescriptor_", "")).ToArray(); + return true; + } + finally + { + GC.KeepAlive(call); + SteamUGC.ReleaseQueryUGCRequest(q); + } + } + + private static bool Pump(Func done, TimeSpan timeout, Action eachTick = null) + { + var sw = Stopwatch.StartNew(); + while (!done()) + { + SteamAPI.RunCallbacks(); + eachTick?.Invoke(); + if (sw.Elapsed > timeout) return false; + Thread.Sleep(100); + } + return true; + } + + private static bool CheckContent(string dir) + { + if (!Directory.Exists(dir)) { Console.Error.WriteLine($"No content folder at {dir}."); return false; } + if (!File.Exists(Path.Combine(dir, "About", "About.xml"))) { Console.Error.WriteLine($"{dir} has no About\\About.xml."); return false; } + string[] devOnly = { ".git", "Source", "Tests", "obj", "bin" }; + var found = Directory.GetDirectories(dir, "*", SearchOption.AllDirectories) + .Where(p => devOnly.Contains(Path.GetFileName(p), StringComparer.OrdinalIgnoreCase)).ToList(); + if (found.Count > 0) + { + Console.Error.WriteLine("The content folder holds development folders that players don't need:\n" + Indent(string.Join("\n", found))); + return false; + } + var files = Directory.GetFiles(dir, "*", SearchOption.AllDirectories); + Console.WriteLine($"Content: {dir} ({files.Length} files, {files.Sum(f => new FileInfo(f).Length) / 1024.0:N0} KB)"); + return true; + } + + private static bool CheckPreview(string file) + { + if (!File.Exists(file)) { Console.Error.WriteLine($"No preview image at {file}."); return false; } + long size = new FileInfo(file).Length; + if (size > MaxPreviewBytes) + { + Console.Error.WriteLine($"The preview {file} is {size / 1024.0:N0} KB; Steam takes at most 1 MB."); + return false; + } + return true; + } + + private static string VisibilityName(ERemoteStoragePublishedFileVisibility v) => + v.ToString().Replace("k_ERemoteStoragePublishedFileVisibility", ""); + + private static string Hint(EResult r) => r switch + { + EResult.k_EResultAccessDenied => "The account needs a RimWorld license.", + EResult.k_EResultFileNotFound => "Steam couldn't read the content folder or the preview.", + EResult.k_EResultLimitExceeded => "The preview is over 1 MB, or the Steam Cloud quota is full.", + EResult.k_EResultLockingFailed => "Steam couldn't lock the item; try again in a minute.", + EResult.k_EResultInvalidParam => "Steam rejected a field; check the title, the tags and the content path.", + EResult.k_EResultInsufficientPrivilege => "Steam restricts this account from uploading (a ban, an account lock or a limited account).", + EResult.k_EResultBanned => "Steam restricts this account from uploading (a ban, an account lock or a limited account).", + EResult.k_EResultNotLoggedOn => "Steam is not logged on.", + EResult.k_EResultTimeout or EResult.k_EResultServiceUnavailable => "The Workshop didn't answer; try again later.", + _ => "", + }; + + private static int Fail(string message) + { + Console.Error.WriteLine(message); + return 4; + } + + private static string Indent(string text) => string.Join("\n", text.Split('\n').Select(l => " " + l.TrimEnd('\r'))); + + private sealed class Options + { + public const string Usage = + "Usage: WorkshopUpload (--item | --create --id-file ) [--content ] [--note-file ]\n" + + " [--tags Mod,1.7] [--title ] [--preview ] [--description-file ]\n" + + " [--visibility public|friends|private|unlisted] [--timeout ] [--publish]\n" + + "Without --publish it calls no Steam write API: it checks the login and the RimWorld license, and with --item\n" + + "reads the item and checks ownership. With --item and only --description-file (title, preview and visibility\n" + + "optional) --publish replaces the description and nothing else. --create --publish creates a new item, writes\n" + + "its id to --id-file at once, then uploads; it needs --title, --content, --note-file, --description-file and\n" + + "--preview. --create, also without --publish, first refuses if this account has an item with the same title\n" + + "or with no title (an earlier create that was cut off). Without --visibility the item keeps its visibility\n" + + "(a new item gets Steam's default)."; + + public ulong Item; + public bool Create; + public string Content, NoteFile, DescriptionFile, Title, Preview, IdFile; + public List Tags; + public ERemoteStoragePublishedFileVisibility? Visibility; + public TimeSpan Timeout = TimeSpan.FromMinutes(15); + public bool Publish; + + public static Options Parse(string[] args) + { + var o = new Options(); + for (int i = 0; i < args.Length; i++) + { + string Next() => i + 1 < args.Length ? args[++i] : throw new ArgumentException($"{args[i]} needs a value."); + switch (args[i]) + { + case "--item": + if (!ulong.TryParse(Next(), out o.Item)) throw new ArgumentException("--item must be a number."); + break; + case "--create": o.Create = true; break; + case "--id-file": o.IdFile = Path.GetFullPath(Next()); break; + case "--content": o.Content = Path.GetFullPath(Next()); break; + case "--note-file": o.NoteFile = ExistingFile(Next()); break; + case "--description-file": o.DescriptionFile = ExistingFile(Next()); break; + case "--tags": o.Tags = Next().Split(',').Select(t => t.Trim()).Where(t => t.Length > 0).ToList(); break; + case "--title": + o.Title = Next().Trim(); + if (o.Title.Length == 0) throw new ArgumentException("--title is empty."); + break; + case "--preview": o.Preview = Path.GetFullPath(Next()); break; + case "--visibility": o.Visibility = ParseVisibility(Next()); break; + case "--timeout": o.Timeout = TimeSpan.FromSeconds(int.Parse(Next())); break; + case "--publish": o.Publish = true; break; + default: throw new ArgumentException($"Unknown argument {args[i]}."); + } + } + if (o.Create && o.Item != 0) throw new ArgumentException("--item and --create don't go together."); + if (!o.Create && o.Item == 0) throw new ArgumentException("--item or --create is required."); + if (o.Create) + { + if (o.IdFile == null) throw new ArgumentException("--create needs --id-file, where the new item's id goes."); + if (!Directory.Exists(Path.GetDirectoryName(o.IdFile))) throw new ArgumentException($"No folder for --id-file {o.IdFile}."); + if (o.Title == null) throw new ArgumentException("--create needs --title."); + if (o.Publish && (o.Content == null || o.NoteFile == null || o.DescriptionFile == null || o.Preview == null)) + throw new ArgumentException("--create --publish needs --content, --note-file, --description-file and --preview."); + } + else if (o.IdFile != null) throw new ArgumentException("--id-file goes with --create."); + return o; + } + + private static ERemoteStoragePublishedFileVisibility ParseVisibility(string value) => value.ToLowerInvariant() switch + { + "public" => ERemoteStoragePublishedFileVisibility.k_ERemoteStoragePublishedFileVisibilityPublic, + "friends" => ERemoteStoragePublishedFileVisibility.k_ERemoteStoragePublishedFileVisibilityFriendsOnly, + "private" => ERemoteStoragePublishedFileVisibility.k_ERemoteStoragePublishedFileVisibilityPrivate, + "unlisted" => ERemoteStoragePublishedFileVisibility.k_ERemoteStoragePublishedFileVisibilityUnlisted, + _ => throw new ArgumentException($"--visibility must be public, friends, private or unlisted, not {value}."), + }; + + private static string ExistingFile(string path) + { + string full = Path.GetFullPath(path); + if (!File.Exists(full)) throw new ArgumentException($"No file at {full}."); + return full; + } + } +} diff --git a/Tools/WorkshopUpload/WorkshopUpload.csproj b/Tools/WorkshopUpload/WorkshopUpload.csproj new file mode 100644 index 0000000..dfe772d --- /dev/null +++ b/Tools/WorkshopUpload/WorkshopUpload.csproj @@ -0,0 +1,33 @@ + + + + + Exe + net10.0 + x64 + latest + disable + disable + false + false + E:\SteamLibrary\steamapps\common\RimWorld + + + + + $(RimWorldDir)\com.rlabrecque.steamworks.net.dll + true + + + + + + + + + + diff --git a/Tools/workshop-stage.ps1 b/Tools/workshop-stage.ps1 new file mode 100644 index 0000000..d18b7f1 --- /dev/null +++ b/Tools/workshop-stage.ps1 @@ -0,0 +1,63 @@ +<# +Fallback for the game's own Workshop button; the usual way is Tools\workshop-upload.ps1. RimWorld's uploader +copies the whole mod folder, hidden files included, and this repo is the mod folder (junctioned into +Mods\, where is the name in About\About.xml without spaces). So: + + .\Tools\workshop-stage.ps1 swap the dev junction for a clean copy (only what players need) + (upload in game: Options > Development mode, Mods > the mod > Advanced... > Upload to Steam Workshop) + .\Tools\workshop-stage.ps1 -Done copy About\PublishedFileId.txt back into the repo, restore the junction + +A first upload in game creates the Workshop item and writes About\PublishedFileId.txt into the clean copy. +-Done copies it into the repo; commit it. From then on Tools\workshop-upload.ps1 updates that item. + +Run with RimWorld closed. +#> +param( + [string]$RimWorldDir = 'E:\SteamLibrary\steamapps\common\RimWorld', + [switch]$Done +) +$ErrorActionPreference = 'Stop' +$repo = Split-Path -Parent $PSScriptRoot +$about = [xml](Get-Content -LiteralPath (Join-Path $repo 'About\About.xml') -Raw -Encoding UTF8) +$name = "$($about.ModMetaData.name)".Trim() +if (-not $name) { throw 'About.xml has no name.' } +$modDir = Join-Path $RimWorldDir ('Mods\' + ($name -replace '\s', '')) +$ship = 'About', '1.7', 'Defs', 'Patches', 'Languages', 'Textures', 'Sounds' + +if (Get-Process -Name RimWorld -ErrorAction SilentlyContinue) { throw 'Close RimWorld first.' } + +function Test-Junction([string]$path) { + (Test-Path $path) -and ((Get-Item $path -Force).Attributes -band [IO.FileAttributes]::ReparsePoint) +} + +if (-not $Done) { + if (Test-Path $modDir) { + if (-not (Test-Junction $modDir)) { throw "$modDir is already a real folder. Run with -Done first." } + cmd /c rmdir "$modDir" | Out-Null + } + New-Item -ItemType Directory $modDir | Out-Null + foreach ($dir in $ship) { + $src = Join-Path $repo $dir + if (Test-Path $src) { Copy-Item $src (Join-Path $modDir $dir) -Recurse } + } + Get-ChildItem $modDir -Recurse -File | Where-Object { $_.Extension -in '.pdb' } | Remove-Item + $files = Get-ChildItem $modDir -Recurse -File + Write-Host ("Clean copy ready at {0}: {1} files, {2:N0} KB" -f $modDir, $files.Count, (($files | Measure-Object Length -Sum).Sum / 1KB)) + $files | ForEach-Object { ' ' + $_.FullName.Substring($modDir.Length + 1) } | Write-Host + $action = if (Test-Path (Join-Path $repo 'About\PublishedFileId.txt')) { 'Update on Steam Workshop' } else { 'Upload to Steam Workshop (creates the item)' } + Write-Host "Now in game: Options > Development mode, Mods > $name > Advanced... > $action." + Write-Host 'Then run: .\Tools\workshop-stage.ps1 -Done' +} +else { + if (Test-Junction $modDir) { Write-Host 'Already restored.'; exit 0 } + $id = Join-Path $modDir 'About\PublishedFileId.txt' + if (Test-Path $id) { + Copy-Item $id (Join-Path $repo 'About\PublishedFileId.txt') -Force + Write-Host ("Workshop item: https://steamcommunity.com/sharedfiles/filedetails/?id=" + (Get-Content $id -Raw).Trim()) + Write-Host 'Commit About\PublishedFileId.txt.' + } + else { Write-Warning 'No PublishedFileId.txt: the upload did not happen (or failed).' } + if (Test-Path $modDir) { Remove-Item $modDir -Recurse -Force } + New-Item -ItemType Junction -Path $modDir -Target $repo | Out-Null + Write-Host 'Dev junction restored.' +} diff --git a/Tools/workshop-upload.ps1 b/Tools/workshop-upload.ps1 new file mode 100644 index 0000000..82ce5a0 --- /dev/null +++ b/Tools/workshop-upload.ps1 @@ -0,0 +1,333 @@ +<# +Uploads this mod to the Steam Workshop from the command line, through the running Steam client: no password, +no game window, no dev mode. RimWorld may stay open. Everything per mod comes from About\About.xml (name, +packageId, modVersion, supportedVersions), so the same script works in every mod that has this Tools folder. + +Without About\PublishedFileId.txt it creates a new Workshop item; with it, it updates that item. + + .\Tools\workshop-upload.ps1 dry run: builds, stages a clean copy, checks the Steam login and the + RimWorld license, and for an existing item reads it and checks that + this Steam account owns it. Lists what -Publish would refuse. Uploads nothing. + .\Tools\workshop-upload.ps1 -Check release check: runs every -Publish check and the dry run, then lists + each problem. Exit code 0 when there is none, 1 otherwise. Uploads nothing. + .\Tools\workshop-upload.ps1 -Publish uploads the staged copy. The change note is every CHANGELOG.md entry + newer than the version in Tools\workshop-published.txt. + -DescriptionFile docs\workshop-description.txt also replaces the Workshop description (BBCode). It defaults + to docs\workshop-description.txt when that file exists and nothing was + published from here yet (no Tools\workshop-published.txt). A new item needs one. + -DescriptionOnly with -DescriptionFile: replaces only the description. No build, no + content upload, no change note, no title or preview. + -Visibility public|friends|private|unlisted who sees the item. Left out, the item keeps its visibility, and a + new item gets Steam's default, as with the in-game uploader. + +The title is About.xml's name and the preview is About\Preview.png (under 1 MB), set on every upload like the +in-game uploader does. + +A new item: -Publish creates it and writes its id to About\PublishedFileId.txt at once, before the content +upload, so a failed upload is retried as an update and never makes a second item. After a successful upload +it writes Tools\workshop-published.txt. Commit both files. Before it creates an item, and in the dry run, the +tool looks at this Steam account's newest RimWorld items and refuses if one has the same title or no title (an +earlier create that was cut off before its id was written): put that id into About\PublishedFileId.txt instead. + +-Publish refuses unless: +- the shipped files, CHANGELOG.md and the description file are committed and pushed, and the top CHANGELOG.md + entry matches About.xml's modVersion; +- two Tests\run-tests.ps1 runs from this copy of the repo passed after the last change to the shipped files + (1.7, Defs, Patches, Languages, About\About.xml): one with every installed DLC (TestResults.all.txt) + and one with -NoDlc (TestResults.nodlc.txt). Passed means its SUMMARY line shows fail=0, at least one + pass and no strayModErrors or strayModWarnings (errors the mod logged between tests, for example while a save + loads). is the mod name without spaces; the files are in -TestResultsDir, by default + $env:TEMP\Test like the runner's -DataDir. -Compat runs write .all-compat.txt and .nodlc-compat.txt + copies, which don't count; +- About\Preview.png exists and is under 1 MB; +- the description file is in the repo, fits Steam's 8000-byte limit, every [img] in it loads with an + Access-Control-Allow-Origin header (Steam loads description images cross-origin and shows a broken image + otherwise), and every forgejo.blax.at link in it, in any form, opens without a login; +- a new item has a description file. +With -DescriptionOnly only the description checks apply, plus: pushed, and the description file committed. +-SkipChecks skips those checks. The in-game button (Tools\workshop-stage.ps1) still works as a fallback. +#> +param( + [string]$RimWorldDir = 'E:\SteamLibrary\steamapps\common\RimWorld', + [switch]$Publish, + [switch]$Check, + [string]$DescriptionFile, + [switch]$DescriptionOnly, + [ValidateSet('public', 'friends', 'private', 'unlisted')] + [string]$Visibility, + [string]$TestResultsDir, + [switch]$SkipChecks +) +$ErrorActionPreference = 'Stop' +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$repo = Split-Path -Parent $PSScriptRoot +$ship = 'About', '1.7', 'Defs', 'Patches', 'Languages', 'Textures', 'Sounds' +$toolProj = Join-Path $PSScriptRoot 'WorkshopUpload\WorkshopUpload.csproj' +$toolExe = Join-Path $PSScriptRoot 'WorkshopUpload\bin\Release\WorkshopUpload.exe' +$idFile = Join-Path $repo 'About\PublishedFileId.txt' +$previewFile = Join-Path $repo 'About\Preview.png' +$publishedFile = Join-Path $PSScriptRoot 'workshop-published.txt' +$utf8 = New-Object Text.UTF8Encoding $false +if ($Publish -and $Check) { throw '-Publish and -Check do not go together: -Check never uploads.' } +if ($Check -and $SkipChecks) { throw '-Check and -SkipChecks do not go together.' } +if ($DescriptionOnly -and -not $DescriptionFile) { throw '-DescriptionOnly needs -DescriptionFile.' } + +$about = [xml](Get-Content -LiteralPath (Join-Path $repo 'About\About.xml') -Raw -Encoding UTF8) +$name = "$($about.ModMetaData.name)".Trim() +$packageId = "$($about.ModMetaData.packageId)".Trim() +$modVersion = "$($about.ModMetaData.modVersion)".Trim() +if (-not $name -or -not $packageId) { throw 'About.xml needs a name and a packageId.' } +# Same prefix as the mod folder junction and the test runner's files: the name without spaces. +$prefix = $name -replace '\s', '' +if (-not $TestResultsDir) { $TestResultsDir = Join-Path $env:TEMP "${prefix}Test" } +# Same tags the in-game uploader sets: "Mod" plus Major.Minor of every supported version. +$tags = @('Mod') + @($about.ModMetaData.supportedVersions.li | ForEach-Object { $v = [version]"$_".Trim(); "$($v.Major).$($v.Minor)" }) + +$create = -not (Test-Path -LiteralPath $idFile) +if ($create) { + if ($DescriptionOnly) { throw 'There is no Workshop item yet (no About\PublishedFileId.txt), so there is no description to replace.' } + Write-Host "$name ${modVersion}: creates a new Workshop item (no About\PublishedFileId.txt yet)." +} +else { + $itemId = (Get-Content -LiteralPath $idFile -Raw).Trim() + if ($itemId -notmatch '^\d+$') { throw "About\PublishedFileId.txt holds '$itemId', not a Workshop item id." } + Write-Host "$name ${modVersion}: updates Workshop item $itemId." +} +$defaultDescription = Join-Path $repo 'docs\workshop-description.txt' +if (-not $DescriptionFile -and ($create -or -not (Test-Path -LiteralPath $publishedFile)) -and (Test-Path -LiteralPath $defaultDescription)) { + $DescriptionFile = $defaultDescription + Write-Host 'Description: docs\workshop-description.txt' +} +if ($DescriptionFile) { $DescriptionFile = (Resolve-Path -LiteralPath $DescriptionFile).Path } + +# Change note: every CHANGELOG.md entry newer than the last version published from here +# (Tools\workshop-published.txt, written after each successful -Publish). +$lastPublished = if (Test-Path -LiteralPath $publishedFile) { [version](Get-Content -LiteralPath $publishedFile -Raw).Trim() } else { [version]'0.0' } +$sections = [ordered]@{} +$current = $null +foreach ($line in Get-Content -LiteralPath (Join-Path $repo 'CHANGELOG.md') -Encoding UTF8) { + if ($line -match '^##\s+(.+)$') { $current = $Matches[1].Trim(); $sections[$current] = New-Object System.Collections.ArrayList; continue } + if ($current -and $line.Trim()) { [void]$sections[$current].Add($line.TrimEnd()) } +} +if ($sections.Count -eq 0) { throw 'CHANGELOG.md has no "## " entry.' } +$topVersion = @($sections.Keys)[0] +$noteLines = @() +foreach ($v in $sections.Keys) { + if ([version]$v -le $lastPublished) { break } + if ($noteLines) { $noteLines += '' } + $noteLines += @("$name $v") + $sections[$v] +} +if (-not $noteLines) { $noteLines = @("$name $topVersion") + $sections[$topVersion] } +$note = ($noteLines -join "`n").Trim() + +# Native commands write to stderr; under 'Stop' PowerShell 5.1 would turn that into an error. +function Invoke-Git([string[]]$gitArgs) { + $ErrorActionPreference = 'Continue' + & git -C $repo $gitArgs 2>$null +} + +# HTTP status of a GET without following redirects (a login redirect must not count as "opens"). +function Get-HttpStatus([string]$url) { + $req = [Net.HttpWebRequest]::Create($url) + $req.AllowAutoRedirect = $false + $req.Timeout = 20000 + $req.UserAgent = 'workshop-upload' + try { + $resp = $req.GetResponse() + $code = [int]$resp.StatusCode + $resp.Close() + return $code + } + catch { + $e = $_.Exception + while ($e -and -not ($e -is [Net.WebException])) { $e = $e.InnerException } + if ($e -and $e.Response) { + $code = [int]$e.Response.StatusCode + $e.Response.Close() + return $code + } + return "no answer ($(if ($e) { $e.Message } else { $_.Exception.Message }))" + } +} + +# Steam adds crossorigin to description images, so a host without Access-Control-Allow-Origin shows a broken image. +function Test-DescriptionImages([string]$text) { + $found = @() + foreach ($m in [regex]::Matches($text, '\[img\](.*?)\[/img\]')) { + $url = $m.Groups[1].Value.Trim() + try { + $r = Invoke-WebRequest -Uri $url -UseBasicParsing -Headers @{ Origin = 'https://steamcommunity.com' } + $type = "$($r.Headers['Content-Type'])" + $acao = "$($r.Headers['Access-Control-Allow-Origin'])" + if ($type -notlike 'image/*') { $found += "$url is not an image ($type)." } + elseif ($acao -ne '*' -and $acao -ne 'https://steamcommunity.com') { $found += "$url sends no Access-Control-Allow-Origin header; Steam would show it broken." } + } + catch { $found += "$url does not load: $($_.Exception.Message)" } + } + $found +} + +# A link to a private Forgejo repo shows players a 404 or a login page. Every form counts: [url=...], +# [url]...[/url] and a bare link, which Steam turns into a link too. +function Test-DescriptionLinks([string]$text) { + $found = @() + $urls = @([regex]::Matches($text, 'https?://forgejo\.blax\.at/[^\s\[\]"]+') | ForEach-Object { $_.Value.TrimEnd('.', ',', ';', ':', '!', '?', ')') } | Select-Object -Unique) + foreach ($url in $urls) { + if ($url -like 'http://*') { $found += "$url uses http. Link to the https address."; continue } + $status = Get-HttpStatus $url + if ($status -ne 200) { $found += "$url answers $status without a login: the repo is private. Make it public first." } + } + $found +} + +if (-not $DescriptionOnly) { + foreach ($proj in Get-ChildItem (Join-Path $repo 'Source\*\*.csproj')) { + & dotnet build $proj.FullName -c Release -nologo -v q "-p:RimWorldDir=$RimWorldDir" + if ($LASTEXITCODE -ne 0) { throw "build failed: $($proj.Name)" } + } +} +& dotnet build $toolProj -c Release -nologo -v q "-p:RimWorldDir=$RimWorldDir" +if ($LASTEXITCODE -ne 0) { throw 'build failed: WorkshopUpload' } + +# Publish checks. Image problems are always shown; the rest is skipped with -SkipChecks. +$imageProblems = @() +$problems = @() +if ($DescriptionFile) { + $descText = [IO.File]::ReadAllText($DescriptionFile, [Text.Encoding]::UTF8).Trim() + $imageProblems = @(Test-DescriptionImages $descText) +} +if (-not $SkipChecks) { + $problems += $imageProblems + if ($DescriptionFile) { + $bytes = [Text.Encoding]::UTF8.GetByteCount($descText) + if ($bytes -gt 8000) { $problems += "The description is $bytes bytes; Steam takes at most 8000." } + $problems += @(Test-DescriptionLinks $descText) + } + elseif ($create) { $problems += 'A new Workshop item needs a description: write docs\workshop-description.txt or pass -DescriptionFile.' } + $ahead = Invoke-Git @('rev-list', '--count', '@{u}..HEAD') + if ($LASTEXITCODE -ne 0) { $problems += 'The branch has no upstream to compare with.' } + elseif ([int]$ahead -gt 0) { $problems += "$ahead commit(s) not pushed yet, so the Workshop would show what the repo doesn't." } + # The description and the change note go to Steam too, so they must be in the pushed repo like the shipped files. + $textFiles = @() + if ($DescriptionFile) { + if ($DescriptionFile.StartsWith($repo + '\', [StringComparison]::OrdinalIgnoreCase)) { $textFiles += $DescriptionFile } + else { $problems += "The description file $DescriptionFile is not in the repo, so it cannot be committed." } + } + if (-not $DescriptionOnly) { $textFiles += 'CHANGELOG.md' } + if ($textFiles) { + # --ignored: an ignored description file never reaches the repo either. + $dirty = @(Invoke-Git (@('status', '--porcelain', '--ignored', '--') + $textFiles)) + if ($LASTEXITCODE -ne 0) { $problems += "git status failed for $($textFiles -join ', ')." } + elseif ($dirty) { $problems += "Uncommitted changes in the description or changelog:`n$($dirty -join "`n")" } + } + if (-not $DescriptionOnly) { + if (-not (Test-Path -LiteralPath $previewFile)) { $problems += 'About\Preview.png is missing; Steam shows it as the item picture.' } + elseif ((Get-Item -LiteralPath $previewFile).Length -gt 1MB) { $problems += ('About\Preview.png is {0:N0} KB; Steam takes at most 1 MB.' -f ((Get-Item -LiteralPath $previewFile).Length / 1KB)) } + if ($topVersion -ne $modVersion) { $problems += "CHANGELOG.md's top entry is $topVersion, About.xml says $modVersion." } + $dirty = @(Invoke-Git (@('status', '--porcelain', '--') + $ship)) + if ($LASTEXITCODE -ne 0) { $problems += 'git status failed for the shipped files.' } + elseif ($dirty) { $problems += "Uncommitted changes in shipped files:`n$($dirty -join "`n")" } + # Everything the game loads from the mod. A change to any of it after a test run makes that run stale, + # also when the DLL stays the same (Defs, Patches, Languages, loadAfter or dependencies in About.xml). + $newest = @(foreach ($d in '1.7', 'Defs', 'Patches', 'Languages') { + $p = Join-Path $repo $d + if (Test-Path -LiteralPath $p) { Get-ChildItem -LiteralPath $p -Recurse -File | Where-Object Extension -ne '.pdb' } + }) + @(Get-Item -LiteralPath (Join-Path $repo 'About\About.xml')) | Sort-Object LastWriteTime -Descending | Select-Object -First 1 + # The mod must work with and without DLCs: a passing run with every installed DLC and one with none. + foreach ($set in @(@{ name = 'all'; run = '.\Tests\run-tests.ps1' }, @{ name = 'nodlc'; run = '.\Tests\run-tests.ps1 -NoDlc' })) { + $file = Join-Path $TestResultsDir "${prefix}TestResults.$($set.name).txt" + if (-not (Test-Path -LiteralPath $file)) { $problems += "No test results at $file. Run $($set.run) first."; continue } + $res = Get-Item -LiteralPath $file + $lines = @(Get-Content -LiteralPath $file -Encoding UTF8) + # Errors the mod logs between tests (save and reload, later phases, after the last test) write no FAIL + # line, only MODERR lines and the counts on the SUMMARY line. + $summary = @($lines -match '^SUMMARY ') | Select-Object -Last 1 + $ranFrom = @($lines -match '^REPO ') | Select-Object -First 1 + $last = "The last $($set.run) run" + if (-not ($lines -match '^END$') -or -not $summary) { $problems += "$last did not finish." } + elseif (-not $ranFrom) { $problems += "$last is from a runner that doesn't record which copy of the repo it tested. Run it again." } + elseif ($lines -notcontains "REPO $repo") { $problems += "$last ran from another copy of the repo ($($ranFrom.Substring(5)))." } + elseif ($summary -notmatch '\bfail=0\b' -or ($lines -match '^FAIL ')) { + $failed = if ($summary -match '\bfail=(\d+)') { $Matches[1] } else { 'some' } + $problems += "$last failed $failed test(s)." + } + elseif ($summary -notmatch '\bpass=[1-9]') { $problems += "$last passed no test: $summary" } + elseif ($summary -match '\bstrayModErrors=([1-9]\d*)') { $problems += "$last logged $($Matches[1]) mod error(s) outside the tests (MODERR lines in $file)." } + elseif ($summary -match '\bstrayModWarnings=([1-9]\d*)') { $problems += "$last logged $($Matches[1]) mod warning(s) outside the tests." } + elseif ($newest -and $res.LastWriteTime -lt $newest.LastWriteTime) { + $problems += "$last ($($res.LastWriteTime)) is older than the last change to the shipped files ($($newest.FullName.Substring($repo.Length + 1)), $($newest.LastWriteTime)). Run it again." + } + } + } +} +if ($Publish) { + if ($SkipChecks) { foreach ($p in $imageProblems) { Write-Warning $p } } + elseif ($problems) { throw ("Not publishing:`n- " + ($problems -join "`n- ")) } +} +elseif (-not $Check) { + if ($SkipChecks) { foreach ($p in $imageProblems) { Write-Warning $p } } + else { foreach ($p in $problems) { Write-Warning "-Publish would refuse: $p" } } +} + +if ($create) { $toolArgs = @('--create', '--id-file', $idFile) } else { $toolArgs = @('--item', $itemId) } +if ($DescriptionOnly) { + $toolArgs += @('--description-file', $DescriptionFile) +} +else { + # Clean copy outside the repo: only what players need, no PDBs. TEMP has no spaces in its path. + $root = Join-Path $env:TEMP 'BlaxWorkshopUpload' + $stage = Join-Path $root $packageId + if (Test-Path $stage) { Remove-Item $stage -Recurse -Force } + New-Item -ItemType Directory $stage -Force | Out-Null + foreach ($dir in $ship) { + $src = Join-Path $repo $dir + if (Test-Path $src) { Copy-Item $src (Join-Path $stage $dir) -Recurse } + } + Get-ChildItem $stage -Recurse -File -Filter *.pdb | Remove-Item + $noteFile = Join-Path $root "$packageId.note.txt" + [IO.File]::WriteAllText($noteFile, $note, $utf8) + + $toolArgs += @('--content', $stage, '--note-file', $noteFile, '--tags', ($tags -join ','), '--title', $name) + # The tool refuses a missing preview. A dry run or -Check without one still checks the Steam side; the + # missing preview is listed above. + if ($Publish -or (Test-Path -LiteralPath $previewFile)) { $toolArgs += @('--preview', $previewFile) } + if ($DescriptionFile) { $toolArgs += @('--description-file', $DescriptionFile) } +} +if ($Visibility) { $toolArgs += @('--visibility', $Visibility) } +if ($Publish) { $toolArgs += '--publish' } + +# steam_api writes status lines to stderr; under 'Stop' PowerShell 5.1 would turn them into errors. +$ErrorActionPreference = 'Continue' +$toolOut = New-Object System.Collections.Generic.List[string] +Push-Location (Split-Path $toolExe) +try { + & $toolExe @toolArgs 2>&1 | ForEach-Object { "$_" } | Where-Object { $_ -notmatch '^(Setting breakpad|SteamInternal_)' } | ForEach-Object { $toolOut.Add($_); $_ } + $code = $LASTEXITCODE +} +finally { Pop-Location } + +if ($Check) { + if ($code -ne 0) { + $last = @($toolOut | Where-Object { $_.Trim() }) | Select-Object -Last 1 + $problems += "The Steam dry run failed (exit code $code): $last" + } + Write-Host '' + if ($problems) { + Write-Host "Release check: $($problems.Count) problem(s) before $name $modVersion can be published:" + foreach ($p in $problems) { Write-Host "- $p" } + exit 1 + } + Write-Host "Release check: no problems. $name $modVersion is ready for .\Tools\workshop-upload.ps1 -Publish." + exit 0 +} +if ($Publish -and -not $DescriptionOnly) { + if ($code -eq 0) { + [IO.File]::WriteAllText($publishedFile, "$topVersion`n", $utf8) + if ($create) { Write-Host "Recorded $topVersion in Tools\workshop-published.txt. Commit it and About\PublishedFileId.txt." } + else { Write-Host "Recorded $topVersion in Tools\workshop-published.txt. Commit it." } + } + elseif ($create -and (Test-Path -LiteralPath $idFile)) { + Write-Host 'The Workshop item exists now (About\PublishedFileId.txt), but the upload did not finish. Commit that file; -Publish again updates the item.' + } +} +exit $code