unicode

Branch: main

Switch branches or tags

Branch: main
Go to file t

413 files indexed

History
Code

tools/release/main.mbt
1///|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