<# 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