web-game-ecs-three-docs/tools/put-diagram.ps1

83 lines
2 KiB
PowerShell

param(
[string]$RepoPath = "architecture.mmd",
[string]$LocalFile = "architecture.mmd",
[string]$Message = "update diagram",
[string]$Branch = "dev"
)
$ErrorActionPreference = "Stop"
function Set-EnvFromFile {
param([string]$EnvPath)
if (-not (Test-Path $EnvPath)) {
return
}
foreach ($line in Get-Content $EnvPath) {
if ([string]::IsNullOrWhiteSpace($line) -or $line.StartsWith("#")) {
continue
}
$parts = $line -split "=", 2
if ($parts.Length -ne 2) {
continue
}
[System.Environment]::SetEnvironmentVariable($parts[0], $parts[1], "Process")
}
}
function Get-OriginInfo {
$origin = (git remote get-url origin).Trim()
if ($origin -match "^https?://([^/]+)/([^/]+)/([^/]+?)(?:\.git)?$") {
return @{
BaseUrl = "https://$($matches[1])"
Owner = $matches[2]
Repo = $matches[3]
}
}
throw "Unsupported origin URL format: $origin"
}
Set-EnvFromFile ".env.local"
$originInfo = Get-OriginInfo
$baseUrl = $originInfo.BaseUrl
$owner = $originInfo.Owner
$repo = $originInfo.Repo
$token = $env:FORGEJO_TOKEN
if (-not (Test-Path $LocalFile)) {
throw "Local file not found: $LocalFile"
}
if (-not $token) {
throw "FORGEJO_TOKEN is missing. Add it to .env.local."
}
$encodedPath = [System.Uri]::EscapeDataString($RepoPath).Replace("%2F", "/")
$url = "$baseUrl/api/v1/repos/$owner/$repo/contents/$encodedPath"
$headers = @{ Authorization = "token $token" }
$sha = $null
try {
$current = Invoke-RestMethod -Headers $headers -Uri "${url}?ref=${Branch}" -Method Get
$sha = $current.sha
} catch {
# If file does not exist on the branch yet, create it without sha.
if (-not $_.Exception.Message.Contains("couldn't be found")) {
throw
}
}
$content = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes((Get-Content $LocalFile -Raw)))
$body = @{
message = $Message
content = $content
branch = $Branch
}
if ($sha) {
$body.sha = $sha
}
Invoke-RestMethod -Headers $headers -Uri $url -Method Put -ContentType "application/json" -Body ($body | ConvertTo-Json)