feat: Workshop tool creates items, sets title and preview, adds -Check

One tool for every Blax Gaming mod, configured from About.xml. It creates a missing Workshop item (id written before the upload), sets the title and preview like the in-game uploader, and -Check runs every publish gate without uploading. The gates also need test results from this checkout with no stray mod errors, newer than any shipped file, and source links that open without a login. Test runs record their checkout and keep -Compat results apart.
This commit is contained in:
Fabian @ Blax Software 2026-11-29 20:49:45 +01:00
parent 52a602c7c7
commit b013051a90
7 changed files with 527 additions and 120 deletions

View File

@ -78,17 +78,26 @@ RimWorld 1.7 no longer runs on Unity/Mono. It runs on .NET 10 (CoreCLR) with Lud
### Workshop upload ### Workshop upload
`Tools/workshop-upload.ps1` updates the Workshop item from the command line. A small tool (`Tools/WorkshopUpload`) uses the Steamworks.NET build and `steam_api64.dll` that ship with RimWorld and attaches to the running, logged-in Steam client as RimWorld, so it needs no password, no game window and no dev mode. `Tools/workshop-upload.ps1` updates the Workshop item from the command line (and creates it for a mod that has none yet). A small tool (`Tools/WorkshopUpload`) uses the Steamworks.NET build and `steam_api64.dll` that ship with RimWorld and attaches to the running, logged-in Steam client as RimWorld, so it needs no password, no game window and no dev mode. The same tool ships in every Blax Gaming mod.
```powershell ```powershell
.\Tools\workshop-upload.ps1 # dry run: stage, check the item and ownership .\Tools\workshop-upload.ps1 # dry run: build, stage, check the Steam login, the item and ownership
.\Tools\workshop-upload.ps1 -Publish # upload .\Tools\workshop-upload.ps1 -Check # release check: every -Publish gate, then the list of problems
.\Tools\workshop-upload.ps1 -Publish -DescriptionFile docs\workshop-description.txt # also replace the description .\Tools\workshop-upload.ps1 -Publish -DescriptionFile docs\workshop-description.txt # upload and replace the description
``` ```
It stages only what players need (About, 1.7, Defs, Patches, Languages) in `%TEMP%`, sets the tags the game would (Mod plus the supported versions), and writes every CHANGELOG.md entry since the version in `Tools/workshop-published.txt` as the change note. `-Publish` refuses unless the shipped files are committed and pushed, the top CHANGELOG entry matches `modVersion`, and two test runs passed after the last build: one with every installed DLC and one with `-NoDlc`. It leaves the title and preview alone; the game's uploader resets the title from About.xml and never updates the description. The in-game route still works: `Tools/workshop-stage.ps1` swaps the junction for a clean copy, upload from Mods > Blax Slaves > More actions (dev mode), then `workshop-stage.ps1 -Done`. The dry run and `-Check` upload nothing. The script stages only what players need (About, 1.7, Defs, Patches, Languages) in `%TEMP%`, sets the tags the game would (Mod plus the supported versions), the title from About.xml and the preview from `About/Preview.png`. The change note is every CHANGELOG.md entry newer than the version in `Tools/workshop-published.txt`, which a successful upload updates; commit it afterwards.
The Workshop description is `docs/workshop-description.txt` (Steam BBCode); `-DescriptionOnly -DescriptionFile docs\workshop-description.txt` replaces just the text, with no build, no content upload and no change note. Steam loads description images as cross-origin requests, so every `[img]` host must send an `Access-Control-Allow-Origin` header or the image shows broken; the script checks each one and `-Publish` refuses otherwise. Forgejo's raw URLs send no such header, so the Steam images are served from `cdn.blax.at/blax-gaming/`, which does. `Source/Art/README.md` has the render and upload commands. `-Publish` refuses unless:
- the shipped files are committed and pushed, and the top CHANGELOG.md entry matches `modVersion` in About.xml;
- two `Tests/run-tests.ps1` runs from this checkout passed after the last change to the shipped files, one with every installed DLC and one with `-NoDlc` (`BlaxSlavesTestResults.all.txt` and `BlaxSlavesTestResults.nodlc.txt` in `%TEMP%\BlaxSlavesTest`), with no mod errors logged outside the tests;
- `About/Preview.png` is under 1 MB;
- the description fits Steam's 8000-byte limit, every forgejo.blax.at link in it opens without a login, and every `[img]` host sends an `Access-Control-Allow-Origin` header. Steam loads description images cross-origin and shows a broken image otherwise. Forgejo's raw URLs send no such header, so the images are served from `cdn.blax.at/blax-gaming/slaves/`, which does.
The Workshop page is `docs/workshop-description.txt` (Steam BBCode). Its art is rendered from `Source/Art` (see `Source/Art/README.md`), and `docs/workshop-media.md` lists the in-game clips worth recording. `-DescriptionOnly -DescriptionFile docs\workshop-description.txt` replaces just the text, with no build, no content upload and no change note.
The in-game route still works: `Tools/workshop-stage.ps1` swaps the junction for a clean copy, upload from Mods > Blax Slaves > Advanced... > Update on Steam Workshop (dev mode), then `Tools/workshop-stage.ps1 -Done` restores the junction. The game's uploader resets the title from About.xml and never updates the description.
### Tests ### Tests

View File

@ -13,8 +13,10 @@ the Harmony mod from the Workshop. Exit code: 0 all passed, 1 failures, 2 the ru
While it runs, the test mod is linked into the game's Mods folder; the link is removed afterwards. While it runs, the test mod is linked into the game's Mods folder; the link is removed afterwards.
Only one run at a time: a lock file in the data folder holds the running script's process id. Only one run at a time: a lock file in the data folder holds the running script's process id.
The results go to BlaxSlavesTestResults.txt in the data folder, and a copy per DLC set next to it: The results go to BlaxSlavesTestResults.txt in the data folder, and a copy per DLC set next to it:
BlaxSlavesTestResults.all.txt (every installed DLC), .nodlc.txt, or .dlc-<names>.txt. The Workshop BlaxSlavesTestResults.all.txt (every installed DLC), .nodlc.txt, or .dlc-<names>.txt. Runs with -Compat
upload checks the "all" and "nodlc" copies. write .<set>-compat.txt instead (.all-compat.txt, .nodlc-compat.txt, ...). Each copy starts with a
"REPO <path>" line naming the copy of the repo that was tested. The Workshop upload checks the "all" and
"nodlc" copies.
#> #>
param( param(
[string]$RimWorldDir = 'E:\SteamLibrary\steamapps\common\RimWorld', [string]$RimWorldDir = 'E:\SteamLibrary\steamapps\common\RimWorld',
@ -105,6 +107,8 @@ try {
Write-Host ("DLCs: " + $(if ($loadDlcs.Count) { $loadDlcs -join ', ' } else { 'none' })) Write-Host ("DLCs: " + $(if ($loadDlcs.Count) { $loadDlcs -join ', ' } else { 'none' }))
# Name of this DLC set for the per-set copy of the results. # 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() } $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) { $dlcSet += '-compat' }
$setResults = Join-Path $DataDir "BlaxSlavesTestResults.$dlcSet.txt" $setResults = Join-Path $DataDir "BlaxSlavesTestResults.$dlcSet.txt"
if ($Compat) { if ($Compat) {
foreach ($id in 'unlimitedhugs.hugslib', 'orion.hospitality', 'smuffle.harvestorganspostmortem', foreach ($id in 'unlimitedhugs.hugslib', 'orion.hospitality', 'smuffle.harvestorganspostmortem',
@ -155,7 +159,8 @@ finally {
$results = Join-Path $DataDir 'BlaxSlavesTestResults.txt' $results = Join-Path $DataDir 'BlaxSlavesTestResults.txt'
if (-not (Test-Path $results)) { Write-Host 'No results file: the suite never started. See game.log.'; exit 2 } if (-not (Test-Path $results)) { Write-Host 'No results file: the suite never started. See game.log.'; exit 2 }
Copy-Item -LiteralPath $results -Destination $setResults -Force # 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 = Get-Content -LiteralPath $results -Encoding UTF8
$lines | ForEach-Object { Write-Host $_ } $lines | ForEach-Object { Write-Host $_ }
if (-not ($lines -match '^END$')) { Write-Host 'The run did not finish.'; exit 2 } if (-not ($lines -match '^END$')) { Write-Host 'The run did not finish.'; exit 2 }

View File

@ -7,13 +7,19 @@ using System.Text;
using System.Threading; using System.Threading;
using Steamworks; using Steamworks;
// Updates an existing RimWorld Steam Workshop item through the running, logged-in Steam client. // 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. // No password: SteamAPI attaches to the client as RimWorld (app 294100), like the game does.
// Without --publish it only reads the item and checks that this Steam account owns it. // 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 internal static class Program
{ {
private const uint RimWorldAppId = 294100; private const uint RimWorldAppId = 294100;
private const int MaxTextBytes = 8000; // Steam's limit for a description (k_cchPublishedDocumentDescriptionMax) 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) private static int Main(string[] args)
{ {
@ -26,7 +32,14 @@ internal static class Program
return 64; return 64;
} }
// Everything that can be checked without Steam comes first.
if (o.Content != null && !CheckContent(o.Content)) return 65; 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 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; string description = o.DescriptionFile != null ? File.ReadAllText(o.DescriptionFile, Encoding.UTF8).Trim() : null;
if (description != null && Encoding.UTF8.GetByteCount(description) > MaxTextBytes) if (description != null && Encoding.UTF8.GetByteCount(description) > MaxTextBytes)
@ -34,6 +47,16 @@ internal static class Program
Console.Error.WriteLine($"The description is over Steam's {MaxTextBytes}-byte limit."); Console.Error.WriteLine($"The description is over Steam's {MaxTextBytes}-byte limit.");
return 65; 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. // SteamAPI.Init looks for steam_appid.txt in the working directory; the env var covers other callers.
Directory.SetCurrentDirectory(AppContext.BaseDirectory); Directory.SetCurrentDirectory(AppContext.BaseDirectory);
@ -61,15 +84,29 @@ internal static class Program
private static int Run(Options o, string note, string description) private static int Run(Options o, string note, string description)
{ {
var item = new PublishedFileId_t(o.Item);
Console.WriteLine($"Steam account: {SteamFriends.GetPersonaName()}"); 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; if (!QueryDetails(item, o.Timeout, out SteamUGCDetails_t d, out string[] descriptors)) return 3;
Console.WriteLine($"Item {o.Item}: \"{d.m_rgchTitle}\""); Console.WriteLine($"Item {o.Item}: \"{d.m_rgchTitle}\"");
Console.WriteLine($" updated {DateTimeOffset.FromUnixTimeSeconds(d.m_rtimeUpdated).ToLocalTime():yyyy-MM-dd HH:mm}"); Console.WriteLine($" updated {DateTimeOffset.FromUnixTimeSeconds(d.m_rtimeUpdated).ToLocalTime():yyyy-MM-dd HH:mm}");
Console.WriteLine($" tags {d.m_rgchTags}"); Console.WriteLine($" tags {d.m_rgchTags}");
Console.WriteLine($" size {d.m_nFileSize / 1024.0:N0} KB"); Console.WriteLine($" size {d.m_nFileSize / 1024.0:N0} KB");
Console.WriteLine($" visible {d.m_eVisibility.ToString().Replace("k_ERemoteStoragePublishedFileVisibility", "")}"); Console.WriteLine($" visible {VisibilityName(d.m_eVisibility)}");
if (d.m_bBanned) Console.WriteLine(" BANNED on Steam"); 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. // 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")}"); Console.WriteLine($" content {(descriptors.Length > 0 ? string.Join(", ", descriptors) : "no mature-content descriptors")}");
@ -89,10 +126,9 @@ internal static class Program
{ {
Console.WriteLine(); Console.WriteLine();
Console.WriteLine("Dry run: nothing was uploaded."); Console.WriteLine("Dry run: nothing was uploaded.");
if (o.Content != null) Console.WriteLine($" would upload {o.Content}"); if (o.Title != null)
if (o.Tags != null) Console.WriteLine($" would tag {string.Join(", ", o.Tags)}"); Console.WriteLine($" would set the title \"{o.Title}\"" + (o.Title == d.m_rgchTitle ? " (unchanged)" : $" (now \"{d.m_rgchTitle}\")"));
if (description != null) Console.WriteLine($" would replace the description ({Encoding.UTF8.GetByteCount(description)} bytes)"); PrintPlan(o, note, description);
if (note != null) Console.WriteLine(" change note:\n" + Indent(note));
return 0; return 0;
} }
@ -102,16 +138,137 @@ internal static class Program
Console.Error.WriteLine("--publish needs --content and --note-file, or only --description-file."); Console.Error.WriteLine("--publish needs --content and --note-file, or only --description-file.");
return 64; return 64;
} }
return Submit(item, o, note, description); return Submit(item, o, note, description, false);
} }
private static int Submit(PublishedFileId_t item, Options o, string note, string description) 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<CreateItemResult_t>.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<SteamUGCQueryCompleted_t>.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<string>();
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); 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. // Description-only updates send no content and no change note (null), so Steam lists no new change note.
if (o.Content != null && !SteamUGC.SetItemContent(h, o.Content)) return Fail("SetItemContent refused the content folder.");
if (o.Tags != null && !SteamUGC.SetItemTags(h, o.Tags)) return Fail("SetItemTags refused the tags.");
if (description != null && !SteamUGC.SetItemDescription(h, description)) return Fail("SetItemDescription refused the text."); 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; bool got = false, ioFailure = false;
SubmitItemUpdateResult_t result = default; SubmitItemUpdateResult_t result = default;
@ -138,9 +295,8 @@ internal static class Program
if (ioFailure) return Fail("Steam reported an IO failure."); 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)}"); 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={o.Item}"); Console.WriteLine($"Done: https://steamcommunity.com/sharedfiles/filedetails/?id={item.m_PublishedFileId}");
if (result.m_bUserNeedsToAcceptWorkshopLegalAgreement) if (legalAgreementPending || result.m_bUserNeedsToAcceptWorkshopLegalAgreement) Console.WriteLine(LegalAgreementHint);
Console.WriteLine("Steam hides the item until you accept the Workshop legal agreement: https://steamcommunity.com/sharedfiles/workshoplegalagreement");
return 0; return 0;
} }
@ -209,13 +365,32 @@ internal static class Program
return true; 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 private static string Hint(EResult r) => r switch
{ {
EResult.k_EResultAccessDenied => "The account needs a RimWorld license.", EResult.k_EResultAccessDenied => "The account needs a RimWorld license.",
EResult.k_EResultFileNotFound => "Steam couldn't read the content folder or the preview.", 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_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_EResultLockingFailed => "Steam couldn't lock the item; try again in a minute.",
EResult.k_EResultInvalidParam => "Steam rejected a field; check the tags and the content path.", 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.",
_ => "", _ => "",
}; };
@ -230,14 +405,22 @@ internal static class Program
private sealed class Options private sealed class Options
{ {
public const string Usage = public const string Usage =
"Usage: WorkshopUpload --item <publishedFileId> [--content <dir>] [--note-file <file>] [--tags Mod,1.7]\n" + "Usage: WorkshopUpload (--item <publishedFileId> | --create --id-file <file>) [--content <dir>] [--note-file <file>]\n" +
" [--description-file <file>] [--timeout <seconds>] [--publish]\n" + " [--tags Mod,1.7] [--title <text>] [--preview <png>] [--description-file <file>]\n" +
"Without --publish it only reads the item and checks ownership. With only --description-file it\n" + " [--visibility public|friends|private|unlisted] [--timeout <seconds>] [--publish]\n" +
"replaces the description and nothing else."; "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 ulong Item;
public string Content, NoteFile, DescriptionFile; public bool Create;
public string Content, NoteFile, DescriptionFile, Title, Preview, IdFile;
public List<string> Tags; public List<string> Tags;
public ERemoteStoragePublishedFileVisibility? Visibility;
public TimeSpan Timeout = TimeSpan.FromMinutes(15); public TimeSpan Timeout = TimeSpan.FromMinutes(15);
public bool Publish; public bool Publish;
@ -252,19 +435,46 @@ internal static class Program
case "--item": case "--item":
if (!ulong.TryParse(Next(), out o.Item)) throw new ArgumentException("--item must be a number."); if (!ulong.TryParse(Next(), out o.Item)) throw new ArgumentException("--item must be a number.");
break; 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 "--content": o.Content = Path.GetFullPath(Next()); break;
case "--note-file": o.NoteFile = ExistingFile(Next()); break; case "--note-file": o.NoteFile = ExistingFile(Next()); break;
case "--description-file": o.DescriptionFile = 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 "--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 "--timeout": o.Timeout = TimeSpan.FromSeconds(int.Parse(Next())); break;
case "--publish": o.Publish = true; break; case "--publish": o.Publish = true; break;
default: throw new ArgumentException($"Unknown argument {args[i]}."); default: throw new ArgumentException($"Unknown argument {args[i]}.");
} }
} }
if (o.Item == 0) throw new ArgumentException("--item is required."); 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; 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) private static string ExistingFile(string path)
{ {
string full = Path.GetFullPath(path); string full = Path.GetFullPath(path);

View File

@ -1,9 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<!-- <!--
Command-line Steam Workshop updater for RimWorld mods. It uses the Steamworks.NET build and the Command-line Steam Workshop uploader for RimWorld mods: creates a new item or updates one. It uses the
steam_api64.dll that ship with RimWorld 1.7, and attaches to the running Steam client as app 294100. Steamworks.NET build and the steam_api64.dll that ship with RimWorld 1.7, and attaches to the running Steam
Run it through Tools\workshop-upload.ps1. client as app 294100. Run it through Tools\workshop-upload.ps1.
--> -->
<PropertyGroup> <PropertyGroup>
<OutputType>Exe</OutputType> <OutputType>Exe</OutputType>

View File

@ -1,11 +1,15 @@
<# <#
Prepares a Steam Workshop upload. RimWorld's uploader copies the whole mod folder, hidden files Fallback for the game's own Workshop button; the usual way is Tools\workshop-upload.ps1. RimWorld's uploader
included, and this repo is the mod folder (junctioned into Mods\BlaxSlaves). So: copies the whole mod folder, hidden files included, and this repo is the mod folder (junctioned into
Mods\<Prefix>, where <Prefix> 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) .\Tools\workshop-stage.ps1 swap the dev junction for a clean copy (only what players need)
(upload in game: Options > Development mode, Mods > Blax Slaves > More actions > Upload to Steam Workshop) (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 .\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. Run with RimWorld closed.
#> #>
param( param(
@ -14,7 +18,10 @@ param(
) )
$ErrorActionPreference = 'Stop' $ErrorActionPreference = 'Stop'
$repo = Split-Path -Parent $PSScriptRoot $repo = Split-Path -Parent $PSScriptRoot
$modDir = Join-Path $RimWorldDir 'Mods\BlaxSlaves' $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' $ship = 'About', '1.7', 'Defs', 'Patches', 'Languages', 'Textures', 'Sounds'
if (Get-Process -Name RimWorld -ErrorAction SilentlyContinue) { throw 'Close RimWorld first.' } if (Get-Process -Name RimWorld -ErrorAction SilentlyContinue) { throw 'Close RimWorld first.' }
@ -29,15 +36,17 @@ if (-not $Done) {
cmd /c rmdir "$modDir" | Out-Null cmd /c rmdir "$modDir" | Out-Null
} }
New-Item -ItemType Directory $modDir | Out-Null New-Item -ItemType Directory $modDir | Out-Null
foreach ($name in $ship) { foreach ($dir in $ship) {
$src = Join-Path $repo $name $src = Join-Path $repo $dir
if (Test-Path $src) { Copy-Item $src (Join-Path $modDir $name) -Recurse } if (Test-Path $src) { Copy-Item $src (Join-Path $modDir $dir) -Recurse }
} }
Get-ChildItem $modDir -Recurse -File | Where-Object { $_.Extension -in '.pdb' } | Remove-Item Get-ChildItem $modDir -Recurse -File | Where-Object { $_.Extension -in '.pdb' } | Remove-Item
$files = Get-ChildItem $modDir -Recurse -File $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)) 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 $files | ForEach-Object { ' ' + $_.FullName.Substring($modDir.Length + 1) } | Write-Host
Write-Host 'Now upload in game, then run: .\Tools\workshop-stage.ps1 -Done' $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 { else {
if (Test-Junction $modDir) { Write-Host 'Already restored.'; exit 0 } if (Test-Junction $modDir) { Write-Host 'Already restored.'; exit 0 }
@ -45,6 +54,7 @@ else {
if (Test-Path $id) { if (Test-Path $id) {
Copy-Item $id (Join-Path $repo 'About\PublishedFileId.txt') -Force 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 ("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).' } else { Write-Warning 'No PublishedFileId.txt: the upload did not happen (or failed).' }
if (Test-Path $modDir) { Remove-Item $modDir -Recurse -Force } if (Test-Path $modDir) { Remove-Item $modDir -Recurse -Force }

View File

@ -1,44 +1,158 @@
<# <#
Updates the Steam Workshop item from the command line, through the running Steam client: no password, 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. 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.
.\Tools\workshop-upload.ps1 dry run: builds, stages a clean copy, checks the item and Without About\PublishedFileId.txt it creates a new Workshop item; with it, it updates that item.
that this Steam account owns it. Uploads nothing.
.\Tools\workshop-upload.ps1 -Publish uploads the staged copy. The change note is the CHANGELOG.md
entry for the version in About.xml.
-DescriptionFile docs\workshop-description.txt also replaces the Workshop description (BBCode)
-DescriptionOnly with -DescriptionFile: replaces only the description. No build,
no content upload, no change note.
Every [img] in the description must load with an Access-Control-Allow-Origin header: Steam loads .\Tools\workshop-upload.ps1 dry run: builds, stages a clean copy, checks the Steam login and the
description images as cross-origin requests and shows a broken image otherwise. -Publish refuses RimWorld license, and for an existing item reads it and checks that
when one doesn't. 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.
-Publish refuses unless the shipped files are committed and pushed, the top CHANGELOG.md entry matches The title is About.xml's name and the preview is About\Preview.png (under 1 MB), set on every upload like the
About.xml's modVersion, and two Tests\run-tests.ps1 runs passed after the last build: one with every in-game uploader does.
installed DLC (BlaxSlavesTestResults.all.txt) and one with -NoDlc (BlaxSlavesTestResults.nodlc.txt).
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 (<Prefix>TestResults.all.txt)
and one with -NoDlc (<Prefix>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). <Prefix> is the mod name without spaces; the files are in -TestResultsDir, by default
$env:TEMP\<Prefix>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. -SkipChecks skips those checks. The in-game button (Tools\workshop-stage.ps1) still works as a fallback.
#> #>
param( param(
[string]$RimWorldDir = 'E:\SteamLibrary\steamapps\common\RimWorld', [string]$RimWorldDir = 'E:\SteamLibrary\steamapps\common\RimWorld',
[switch]$Publish, [switch]$Publish,
[switch]$Check,
[string]$DescriptionFile, [string]$DescriptionFile,
[switch]$DescriptionOnly, [switch]$DescriptionOnly,
[string]$TestResultsDir = (Join-Path $env:TEMP 'BlaxSlavesTest'), [ValidateSet('public', 'friends', 'private', 'unlisted')]
[string]$Visibility,
[string]$TestResultsDir,
[switch]$SkipChecks [switch]$SkipChecks
) )
$ErrorActionPreference = 'Stop' $ErrorActionPreference = 'Stop'
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$repo = Split-Path -Parent $PSScriptRoot $repo = Split-Path -Parent $PSScriptRoot
$ship = 'About', '1.7', 'Defs', 'Patches', 'Languages', 'Textures', 'Sounds' $ship = 'About', '1.7', 'Defs', 'Patches', 'Languages', 'Textures', 'Sounds'
$toolProj = Join-Path $PSScriptRoot 'WorkshopUpload\WorkshopUpload.csproj' $toolProj = Join-Path $PSScriptRoot 'WorkshopUpload\WorkshopUpload.csproj'
$toolExe = Join-Path $PSScriptRoot 'WorkshopUpload\bin\Release\WorkshopUpload.exe' $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.' } 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 "## <version>" 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. # Steam adds crossorigin to description images, so a host without Access-Control-Allow-Origin shows a broken image.
function Test-DescriptionImages([string]$file) { function Test-DescriptionImages([string]$text) {
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$found = @() $found = @()
$text = [IO.File]::ReadAllText((Resolve-Path $file).Path, [Text.Encoding]::UTF8)
foreach ($m in [regex]::Matches($text, '\[img\](.*?)\[/img\]')) { foreach ($m in [regex]::Matches($text, '\[img\](.*?)\[/img\]')) {
$url = $m.Groups[1].Value.Trim() $url = $m.Groups[1].Value.Trim()
try { try {
@ -53,33 +167,18 @@ function Test-DescriptionImages([string]$file) {
$found $found
} }
$itemId = (Get-Content -LiteralPath (Join-Path $repo 'About\PublishedFileId.txt') -Raw).Trim() # A link to a private Forgejo repo shows players a 404 or a login page. Every form counts: [url=...],
$about = [xml](Get-Content -LiteralPath (Join-Path $repo 'About\About.xml') -Raw -Encoding UTF8) # [url]...[/url] and a bare link, which Steam turns into a link too.
$packageId = $about.ModMetaData.packageId.Trim() function Test-DescriptionLinks([string]$text) {
$modVersion = "$($about.ModMetaData.modVersion)".Trim() $found = @()
# Same tags the in-game uploader sets: "Mod" plus Major.Minor of every supported version. $urls = @([regex]::Matches($text, 'https?://forgejo\.blax\.at/[^\s\[\]"]+') | ForEach-Object { $_.Value.TrimEnd('.', ',', ';', ':', '!', '?', ')') } | Select-Object -Unique)
$tags = @('Mod') + @($about.ModMetaData.supportedVersions.li | ForEach-Object { $v = [version]"$_".Trim(); "$($v.Major).$($v.Minor)" }) foreach ($url in $urls) {
if ($url -like 'http://*') { $found += "$url uses http. Link to the https address."; continue }
# Change note: every CHANGELOG.md entry newer than the last version published from here $status = Get-HttpStatus $url
# (Tools\workshop-published.txt, written after each successful -Publish). if ($status -ne 200) { $found += "$url answers $status without a login: the repo is private. Make it public first." }
$publishedFile = Join-Path $PSScriptRoot 'workshop-published.txt' }
$lastPublished = if (Test-Path $publishedFile) { [version](Get-Content -LiteralPath $publishedFile -Raw).Trim() } else { [version]'0.0' } $found
$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 "## <version>" entry.' }
$topVersion = @($sections.Keys)[0]
$noteLines = @()
foreach ($v in $sections.Keys) {
if ([version]$v -le $lastPublished) { break }
if ($noteLines) { $noteLines += '' }
$noteLines += @("$($about.ModMetaData.name) $v") + $sections[$v]
}
if (-not $noteLines) { $noteLines = @("$($about.ModMetaData.name) $topVersion") + $sections[$topVersion] }
$note = ($noteLines -join "`n").Trim()
if (-not $DescriptionOnly) { if (-not $DescriptionOnly) {
foreach ($proj in Get-ChildItem (Join-Path $repo 'Source\*\*.csproj')) { foreach ($proj in Get-ChildItem (Join-Path $repo 'Source\*\*.csproj')) {
@ -90,41 +189,89 @@ if (-not $DescriptionOnly) {
& dotnet build $toolProj -c Release -nologo -v q "-p:RimWorldDir=$RimWorldDir" & dotnet build $toolProj -c Release -nologo -v q "-p:RimWorldDir=$RimWorldDir"
if ($LASTEXITCODE -ne 0) { throw 'build failed: WorkshopUpload' } if ($LASTEXITCODE -ne 0) { throw 'build failed: WorkshopUpload' }
# Publish checks. Image problems are always shown; the rest is skipped with -SkipChecks.
$imageProblems = @() $imageProblems = @()
$problems = @()
if ($DescriptionFile) { if ($DescriptionFile) {
$imageProblems = @(Test-DescriptionImages $DescriptionFile) $descText = [IO.File]::ReadAllText($DescriptionFile, [Text.Encoding]::UTF8).Trim()
foreach ($p in $imageProblems) { Write-Warning $p } $imageProblems = @(Test-DescriptionImages $descText)
} }
if (-not $SkipChecks) {
if ($Publish -and -not $SkipChecks) { $problems += $imageProblems
$problems = @() + $imageProblems if ($DescriptionFile) {
$ahead = & git -C $repo rev-list --count '@{u}..HEAD' 2>$null $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.' } 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." } elseif ([int]$ahead -gt 0) { $problems += "$ahead commit(s) not pushed yet, so the Workshop would show what the repo doesn't." }
if ($DescriptionOnly) { # The description and the change note go to Steam too, so they must be in the pushed repo like the shipped files.
$dirty = & git -C $repo status --porcelain -- (Resolve-Path $DescriptionFile).Path $textFiles = @()
if ($dirty) { $problems += "The description file has uncommitted changes: $dirty" } 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." }
} }
else { 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." } if ($topVersion -ne $modVersion) { $problems += "CHANGELOG.md's top entry is $topVersion, About.xml says $modVersion." }
$dirty = & git -C $repo status --porcelain -- $ship $dirty = @(Invoke-Git (@('status', '--porcelain', '--') + $ship))
if ($dirty) { $problems += "Uncommitted changes in shipped files:`n$($dirty -join "`n")" } if ($LASTEXITCODE -ne 0) { $problems += 'git status failed for the shipped files.' }
$dll = Get-ChildItem (Join-Path $repo '1.7\Assemblies\*.dll') | Sort-Object LastWriteTime -Descending | Select-Object -First 1 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. # 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' })) { foreach ($set in @(@{ name = 'all'; run = '.\Tests\run-tests.ps1' }, @{ name = 'nodlc'; run = '.\Tests\run-tests.ps1 -NoDlc' })) {
$file = Join-Path $TestResultsDir "BlaxSlavesTestResults.$($set.name).txt" $file = Join-Path $TestResultsDir "${prefix}TestResults.$($set.name).txt"
if (-not (Test-Path $file)) { $problems += "No test results at $file. Run $($set.run) first."; continue } if (-not (Test-Path -LiteralPath $file)) { $problems += "No test results at $file. Run $($set.run) first."; continue }
$res = Get-Item $file $res = Get-Item -LiteralPath $file
$lines = Get-Content -LiteralPath $file -Encoding UTF8 $lines = @(Get-Content -LiteralPath $file -Encoding UTF8)
if (-not ($lines -match '^END$') -or ($lines -match '^FAIL ')) { $problems += "The last $($set.run) run failed or did not finish." } # Errors the mod logs between tests (save and reload, later phases, after the last test) write no FAIL
elseif ($dll -and $res.LastWriteTime -lt $dll.LastWriteTime) { $problems += "The last $($set.run) run ($($res.LastWriteTime)) is older than the build ($($dll.LastWriteTime)). Run it again." } # 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 ($problems) { throw ("Not publishing:`n- " + ($problems -join "`n- ")) } }
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) { if ($DescriptionOnly) {
$toolArgs = @('--item', $itemId, '--description-file', (Resolve-Path $DescriptionFile).Path) $toolArgs += @('--description-file', $DescriptionFile)
} }
else { else {
# Clean copy outside the repo: only what players need, no PDBs. TEMP has no spaces in its path. # Clean copy outside the repo: only what players need, no PDBs. TEMP has no spaces in its path.
@ -132,29 +279,55 @@ else {
$stage = Join-Path $root $packageId $stage = Join-Path $root $packageId
if (Test-Path $stage) { Remove-Item $stage -Recurse -Force } if (Test-Path $stage) { Remove-Item $stage -Recurse -Force }
New-Item -ItemType Directory $stage -Force | Out-Null New-Item -ItemType Directory $stage -Force | Out-Null
foreach ($name in $ship) { foreach ($dir in $ship) {
$src = Join-Path $repo $name $src = Join-Path $repo $dir
if (Test-Path $src) { Copy-Item $src (Join-Path $stage $name) -Recurse } if (Test-Path $src) { Copy-Item $src (Join-Path $stage $dir) -Recurse }
} }
Get-ChildItem $stage -Recurse -File -Filter *.pdb | Remove-Item Get-ChildItem $stage -Recurse -File -Filter *.pdb | Remove-Item
$noteFile = Join-Path $root "$packageId.note.txt" $noteFile = Join-Path $root "$packageId.note.txt"
[IO.File]::WriteAllText($noteFile, $note, (New-Object Text.UTF8Encoding $false)) [IO.File]::WriteAllText($noteFile, $note, $utf8)
$toolArgs = @('--item', $itemId, '--content', $stage, '--note-file', $noteFile, '--tags', ($tags -join ',')) $toolArgs += @('--content', $stage, '--note-file', $noteFile, '--tags', ($tags -join ','), '--title', $name)
if ($DescriptionFile) { $toolArgs += @('--description-file', (Resolve-Path $DescriptionFile).Path) } # 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' } if ($Publish) { $toolArgs += '--publish' }
# steam_api writes status lines to stderr; under 'Stop' PowerShell 5.1 would turn them into errors. # steam_api writes status lines to stderr; under 'Stop' PowerShell 5.1 would turn them into errors.
$ErrorActionPreference = 'Continue' $ErrorActionPreference = 'Continue'
$toolOut = New-Object System.Collections.Generic.List[string]
Push-Location (Split-Path $toolExe) Push-Location (Split-Path $toolExe)
try { try {
& $toolExe @toolArgs 2>&1 | ForEach-Object { "$_" } | Where-Object { $_ -notmatch '^(Setting breakpad|SteamInternal_)' } & $toolExe @toolArgs 2>&1 | ForEach-Object { "$_" } | Where-Object { $_ -notmatch '^(Setting breakpad|SteamInternal_)' } | ForEach-Object { $toolOut.Add($_); $_ }
$code = $LASTEXITCODE $code = $LASTEXITCODE
} }
finally { Pop-Location } finally { Pop-Location }
if ($Publish -and $code -eq 0 -and -not $DescriptionOnly) {
[IO.File]::WriteAllText($publishedFile, "$topVersion`n") if ($Check) {
Write-Host "Recorded $topVersion in Tools\workshop-published.txt. Commit it." 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 exit $code

View File

@ -12,7 +12,7 @@ The Steam description shows GIFs inline (`[img]`), the same way as the section h
Recording: Windows Game Bar (Win+Alt+R) records the game window as MP4 without extra software. Put the raw recordings in `docs/media/raw/` (git-ignored). Recording: Windows Game Bar (Win+Alt+R) records the game window as MP4 without extra software. Put the raw recordings in `docs/media/raw/` (git-ignored).
Converting to a GIF needs ffmpeg (on the nixos desktop, or a Windows build). 640 px wide at 15 fps keeps a 6-second clip around 2 to 4 MB: Converting to a GIF needs ffmpeg. 640 px wide at 15 fps keeps a 6-second clip around 2 to 4 MB:
```sh ```sh
ffmpeg -i raw/trade-buy-mode.mp4 -vf "fps=15,scale=640:-1:flags=lanczos,split[a][b];[a]palettegen[p];[b][p]paletteuse" trade-buy-mode.gif ffmpeg -i raw/trade-buy-mode.mp4 -vf "fps=15,scale=640:-1:flags=lanczos,split[a][b];[a]palettegen[p];[b][p]paletteuse" trade-buy-mode.gif