tools/release/main.mbt1///|2async fn find_project_root() -> String {3 if @fs.exists("moon.work") && @fs.exists("tools/moon.mod") {4 "."5 } else if @fs.exists("../moon.work") && @fs.exists("moon.mod") {6 ".."7 } else {8 raise ReleaseError(9 "Run the release tool from the repository root or tools directory",10 )11 }12}1314///|15async fn[X] wait_with_heartbeat(16 description : StringView,17 action : async () -> X,18) -> X {19 let mut result : X? = None20 @async.with_task_group(group => {21 group.spawn_bg(no_wait=true, () => {22 for ;; {23 @async.sleep(10000)24 println(" Still waiting for \{description}...")25 }26 })27 result = Some(action())28 })29 guard result is Some(value) else {30 // Unreachable: a raising action propagates out of the task group.31 raise ReleaseError("The heartbeat action returned no result")32 }33 value34}3536///|37async fn run_checked(38 root : StringView,39 program : StringView,40 arguments : ArrayView[String],41 description : StringView,42) -> Unit {43 println("==> \{description}")44 let status = @shell.Cmd(program.to_owned(), arguments, cwd=root.to_owned()).status()45 guard status == 0 else {46 raise ReleaseError("\{description} failed with exit status \{status}")47 }48 println(" Completed successfully")49}5051///|52async fn run_publish_dry_run(53 root : StringView,54 release_module : ReleaseModule,55 version : String,56) -> Unit {57 let package_name = "moonbit-community/\{release_module.name}"58 let description = "Dry-running \{package_name}@\{version}"59 println("==> \{description}")60 // `moon publish` validates the archive in a fresh directory, so it must be61 // allowed to install registry dependencies there.62 println(" $ moon -C \{release_module.directory} publish --dry-run")63 let output = wait_with_heartbeat(description, () => {64 @shell.Cmd(65 "moon",66 ["-C", release_module.directory, "publish", "--dry-run"],67 cwd=root.to_owned(),68 ).output()69 })70 let status = output.exit_code()71 // `@shell` cannot merge the two streams at the descriptor level, so the72 // captured streams are concatenated; `moon` reports failures on stderr.73 let output_text = "\{output.stdout()}\{output.stderr()}"74 println(output_text.trim_end())75 guard publish_dry_run_succeeded(status, output_text, package_name, version) else {76 raise ReleaseError("\{description} failed with exit status \{status}")77 }78 println(" Dry-run accepted with exit status \{status}")79}8081///|82async fn ensure_clean_worktree(root : StringView) -> Unit {83 println("==> Checking that the Git worktree is clean")84 let output = @shell.Cmd(85 "git",86 ["status", "--porcelain=v1"],87 cwd=root.to_owned(),88 // Only the porcelain lines are inspected; git's own diagnostics belong on89 // the terminal, as they were before the migration.90 stderr=Inherit,91 ).output()92 let status = output.exit_code()93 guard status == 0 else {94 raise ReleaseError("git status failed with exit status \{status}")95 }96 let changes = output.stdout().trim()97 guard changes == "" else {98 raise ReleaseError(99 "The Git worktree must be clean before this operation:\n\{changes}",100 )101 }102 println(" Git worktree is clean")103}104105///|106async fn update_published_versions(root : StringView, version : String) -> Unit {107 let updates : Array[(String, String)] = []108 let mut previous_version : String? = None109 for release_module in published_modules {110 let path = release_module.manifest_path()111 let source = @fs.read_text("\{root}/\{path}")112 let current_version = manifest_version(source, path)113 if previous_version is Some(expected) {114 guard current_version == expected else {115 raise ReleaseError(116 "Published module versions are inconsistent: \{path} has \{current_version}, expected \{expected}",117 )118 }119 } else {120 previous_version = Some(current_version)121 }122 updates.push((path, replace_manifest_version(source, path, version)))123 }124 guard previous_version is Some(current_version) else {125 raise ReleaseError("No published modules are configured")126 }127 guard current_version != version else {128 raise ReleaseError("Published modules are already at version \{version}")129 }130 for update in updates {131 @fs.write_text("\{root}/\{update.0}", update.1, permission=0o644)132 }133}134135///|136async fn verify_published_versions(root : StringView) -> String {137 let versions : Array[(String, String)] = []138 for release_module in published_modules {139 let path = release_module.manifest_path()140 let source = @fs.read_text("\{root}/\{path}")141 let actual_version = manifest_version(source, path)142 versions.push((path, actual_version))143 }144 let version = release_version_from_manifests(versions)145 println("==> Verifying published module versions")146 for manifest in versions {147 let (path, actual_version) = manifest148 println(" \{path}: \{actual_version}")149 }150 version151}152153///|154async fn prepare_release(root : StringView, version : String) -> Unit {155 validate_release_version(version)156 ensure_clean_worktree(root)157 update_published_versions(root, version)158 run_checked(159 root,160 "moon",161 ["work", "sync"],162 "Synchronizing workspace versions",163 )164 run_checked(root, "moon", ["fmt"], "Formatting the workspace")165 run_checked(root, "moon", ["info"], "Refreshing generated interfaces")166 run_checked(167 root,168 "moon",169 ["check", "tools/release", "--target", "native"],170 "Checking the native release tool",171 )172 run_checked(173 root,174 "moon",175 ["test", "tools/release", "--target", "native"],176 "Testing the native release tool",177 )178 run_checked(root, "moon", ["check"], "Checking the workspace")179 run_checked(root, "moon", ["test"], "Testing the workspace")180 for release_module in published_modules {181 run_checked(182 root,183 "moon",184 ["-C", release_module.directory, "package", "--list", "--frozen"],185 "Listing moonbit-community/\{release_module.name}@\{version}",186 )187 }188 println("==> Preparation completed without publishing or dry-running")189 println(190 "Release \{version} is prepared. Review and commit the manifest changes,",191 )192 println("push the branch, then publish it with the publish-package workflow")193 println("or run the following command from this checkout:")194 println("moon run --target native tools/release -- publish --execute")195}196197///|198async fn publish_release(root : StringView) -> Unit {199 println(200 "No registry changes will be made until every preflight check passes.",201 )202 ensure_clean_worktree(root)203 let version = verify_published_versions(root)204 println("Publishing release \{version}")205 run_checked(root, "moon", ["whoami"], "Checking mooncakes.io login")206 // Check the modules that can be validated before anything is published207 // first, so a rejected archive cannot leave a partial release behind.208 println("==> Dry-running the modules that do not depend on this release")209 for release_module in preflight_modules() {210 run_publish_dry_run(root, release_module, version)211 }212 println("==> All preflight checks passed; starting module publication")213 for index, release_module in published_modules {214 println(215 "==> [\{index + 1}/\{published_modules.length()}] Releasing moonbit-community/\{release_module.name}@\{version}",216 )217 if release_module.requires_published_dependencies {218 run_checked(219 root,220 "moon",221 ["-C", release_module.directory, "update"],222 "Refreshing the registry for moonbit-community/\{release_module.name}@\{version}",223 )224 run_publish_dry_run(root, release_module, version)225 }226 println(227 "==> Publishing moonbit-community/\{release_module.name}@\{version}",228 )229 println(" $ moon -C \{release_module.directory} publish")230 // `@process` keeps its default graceful cancellation handler (SIGTERM,231 // five seconds), unlike `@shell`, which kills its child immediately: an232 // interrupted publish must be able to stop on its own mid-request.233 let result = @process.run(234 "moon",235 ["-C", release_module.directory, "publish"],236 cwd=root,237 )238 let status = result.exit_code239 guard status == 0 else {240 raise ReleaseError(241 "Publishing moonbit-community/\{release_module.name}@\{version} failed with exit status \{status}. The modules published before it stay at \{version}: resolve the problem and release the whole set again at a new version.",242 )243 }244 println(" Published moonbit-community/\{release_module.name}@\{version}")245 }246 println("Published all modules for version \{version}")247}248249///|250async fn run_cli() -> Unit {251 let command = @argparse.Command(252 "unicode-release",253 about="Prepare and publish the Unicode workspace modules",254 subcommand_required=true,255 subcommands=[256 Command(257 "prepare",258 about="Bump versions and validate the workspace without publishing or dry-running",259 options=[260 OptionArg(261 "version",262 long="version",263 about="Release version in MAJOR.MINOR.PATCH form",264 required=true,265 ),266 ],267 ),268 Command("publish", about="Publish all modules in dependency order", flags=[269 FlagArg(270 "execute",271 long="execute",272 about="Confirm the irreversible publication step",273 required=true,274 ),275 ]),276 ],277 )278 let matches = command.parse()279 let root = find_project_root()280 match matches.subcommand {281 Some(("prepare", child)) => {282 guard child.values.get("version") is Some([version]) else {283 raise ReleaseError("Missing required --version option")284 }285 prepare_release(root, version)286 }287 Some(("publish", child)) => {288 guard child.flags.get("execute").unwrap_or(false) else {289 raise ReleaseError("Publication requires the explicit --execute flag")290 }291 publish_release(root)292 }293 Some((name, _)) => raise ReleaseError("Unknown release command \{name}")294 None => raise ReleaseError("A release command is required")295 }296}297298///|299async fn main {300 run_cli() catch {301 ReleaseError(message) => fail(message)302 error => raise error303 }304}305
///|
async fn find_project_root() -> String {
if @fs.exists("moon.work") && @fs.exists("tools/moon.mod") {
"."
} else if @fs.exists("../moon.work") && @fs.exists("moon.mod") {
".."
} else {
raise ReleaseError(
"Run the release tool from the repository root or tools directory",
)
}
}
///|
async fn[X] wait_with_heartbeat(
description : StringView,
action : async () -> X,
) -> X {
let mut result : X? = None
@async.with_task_group(group => {
group.spawn_bg(no_wait=true, () => {
for ;; {
@async.sleep(10000)
println(" Still waiting for \{description}...")
}
})
result = Some(action())
})
guard result is Some(value) else {
// Unreachable: a raising action propagates out of the task group.
raise ReleaseError("The heartbeat action returned no result")
}
value
}
///|
async fn run_checked(
root : StringView,
program : StringView,
arguments : ArrayView[String],
description : StringView,
) -> Unit {
println("==> \{description}")
let status = @shell.Cmd(program.to_owned(), arguments, cwd=root.to_owned()).status()
guard status == 0 else {
raise ReleaseError("\{description} failed with exit status \{status}")
}
println(" Completed successfully")
}
///|
async fn run_publish_dry_run(
root : StringView,
release_module : ReleaseModule,
version : String,
) -> Unit {
let package_name = "moonbit-community/\{release_module.name}"
let description = "Dry-running \{package_name}@\{version}"
println("==> \{description}")
// `moon publish` validates the archive in a fresh directory, so it must be
// allowed to install registry dependencies there.
println(" $ moon -C \{release_module.directory} publish --dry-run")
let output = wait_with_heartbeat(description, () => {
@shell.Cmd(
"moon",
["-C", release_module.directory, "publish", "--dry-run"],
cwd=root.to_owned(),
).output()
})
let status = output.exit_code()
// `@shell` cannot merge the two streams at the descriptor level, so the
// captured streams are concatenated; `moon` reports failures on stderr.
let output_text = "\{output.stdout()}\{output.stderr()}"
println(output_text.trim_end())
guard publish_dry_run_succeeded(status, output_text, package_name, version) else {
raise ReleaseError("\{description} failed with exit status \{status}")
}
println(" Dry-run accepted with exit status \{status}")
}
///|
async fn ensure_clean_worktree(root : StringView) -> Unit {
println("==> Checking that the Git worktree is clean")
let output = @shell.Cmd(
"git",
["status", "--porcelain=v1"],
cwd=root.to_owned(),
// Only the porcelain lines are inspected; git's own diagnostics belong on
// the terminal, as they were before the migration.
stderr=Inherit,
).output()
let status = output.exit_code()
guard status == 0 else {
raise ReleaseError("git status failed with exit status \{status}")
}
let changes = output.stdout().trim()
guard changes == "" else {
raise ReleaseError(
"The Git worktree must be clean before this operation:\n\{changes}",
)
}
println(" Git worktree is clean")
}
///|
async fn update_published_versions(root : StringView, version : String) -> Unit {
let updates : Array[(String, String)] = []
let mut previous_version : String? = None
for release_module in published_modules {
let path = release_module.manifest_path()
let source = @fs.read_text("\{root}/\{path}")
let current_version = manifest_version(source, path)
if previous_version is Some(expected) {
guard current_version == expected else {
raise ReleaseError(
"Published module versions are inconsistent: \{path} has \{current_version}, expected \{expected}",
)
}
} else {
previous_version = Some(current_version)
}
updates.push((path, replace_manifest_version(source, path, version)))
}
guard previous_version is Some(current_version) else {
raise ReleaseError("No published modules are configured")
}
guard current_version != version else {
raise ReleaseError("Published modules are already at version \{version}")
}
for update in updates {
@fs.write_text("\{root}/\{update.0}", update.1, permission=0o644)
}
}
///|
async fn verify_published_versions(root : StringView) -> String {
let versions : Array[(String, String)] = []
for release_module in published_modules {
let path = release_module.manifest_path()
let source = @fs.read_text("\{root}/\{path}")
let actual_version = manifest_version(source, path)
versions.push((path, actual_version))
}
let version = release_version_from_manifests(versions)
println("==> Verifying published module versions")
for manifest in versions {
let (path, actual_version) = manifest
println(" \{path}: \{actual_version}")
}
version
}
///|
async fn prepare_release(root : StringView, version : String) -> Unit {
validate_release_version(version)
ensure_clean_worktree(root)
update_published_versions(root, version)
run_checked(
root,
"moon",
["work", "sync"],
"Synchronizing workspace versions",
)
run_checked(root, "moon", ["fmt"], "Formatting the workspace")
run_checked(root, "moon", ["info"], "Refreshing generated interfaces")
run_checked(
root,
"moon",
["check", "tools/release", "--target", "native"],
"Checking the native release tool",
)
run_checked(
root,
"moon",
["test", "tools/release", "--target", "native"],
"Testing the native release tool",
)
run_checked(root, "moon", ["check"], "Checking the workspace")
run_checked(root, "moon", ["test"], "Testing the workspace")
for release_module in published_modules {
run_checked(
root,
"moon",
["-C", release_module.directory, "package", "--list", "--frozen"],
"Listing moonbit-community/\{release_module.name}@\{version}",
)
}
println("==> Preparation completed without publishing or dry-running")
println(
"Release \{version} is prepared. Review and commit the manifest changes,",
)
println("push the branch, then publish it with the publish-package workflow")
println("or run the following command from this checkout:")
println("moon run --target native tools/release -- publish --execute")
}
///|
async fn publish_release(root : StringView) -> Unit {
println(
"No registry changes will be made until every preflight check passes.",
)
ensure_clean_worktree(root)
let version = verify_published_versions(root)
println("Publishing release \{version}")
run_checked(root, "moon", ["whoami"], "Checking mooncakes.io login")
// Check the modules that can be validated before anything is published
// first, so a rejected archive cannot leave a partial release behind.
println("==> Dry-running the modules that do not depend on this release")
for release_module in preflight_modules() {
run_publish_dry_run(root, release_module, version)
}
println("==> All preflight checks passed; starting module publication")
for index, release_module in published_modules {
println(
"==> [\{index + 1}/\{published_modules.length()}] Releasing moonbit-community/\{release_module.name}@\{version}",
)
if release_module.requires_published_dependencies {
run_checked(
root,
"moon",
["-C", release_module.directory, "update"],
"Refreshing the registry for moonbit-community/\{release_module.name}@\{version}",
)
run_publish_dry_run(root, release_module, version)
}
println(
"==> Publishing moonbit-community/\{release_module.name}@\{version}",
)
println(" $ moon -C \{release_module.directory} publish")
// `@process` keeps its default graceful cancellation handler (SIGTERM,
// five seconds), unlike `@shell`, which kills its child immediately: an
// interrupted publish must be able to stop on its own mid-request.
let result = @process.run(
"moon",
["-C", release_module.directory, "publish"],
cwd=root,
)
let status = result.exit_code
guard status == 0 else {
raise ReleaseError(
"Publishing moonbit-community/\{release_module.name}@\{version} failed with exit status \{status}. The modules published before it stay at \{version}: resolve the problem and release the whole set again at a new version.",
)
}
println(" Published moonbit-community/\{release_module.name}@\{version}")
}
println("Published all modules for version \{version}")
}
///|
async fn run_cli() -> Unit {
let command = @argparse.Command(
"unicode-release",
about="Prepare and publish the Unicode workspace modules",
subcommand_required=true,
subcommands=[
Command(
"prepare",
about="Bump versions and validate the workspace without publishing or dry-running",
options=[
OptionArg(
"version",
long="version",
about="Release version in MAJOR.MINOR.PATCH form",
required=true,
),
],
),
Command("publish", about="Publish all modules in dependency order", flags=[
FlagArg(
"execute",
long="execute",
about="Confirm the irreversible publication step",
required=true,
),
]),
],
)
let matches = command.parse()
let root = find_project_root()
match matches.subcommand {
Some(("prepare", child)) => {
guard child.values.get("version") is Some([version]) else {
raise ReleaseError("Missing required --version option")
}
prepare_release(root, version)
}
Some(("publish", child)) => {
guard child.flags.get("execute").unwrap_or(false) else {
raise ReleaseError("Publication requires the explicit --execute flag")
}
publish_release(root)
}
Some((name, _)) => raise ReleaseError("Unknown release command \{name}")
None => raise ReleaseError("A release command is required")
}
}
///|
async fn main {
run_cli() catch {
ReleaseError(message) => fail(message)
error => raise error
}
}