diff --git a/.github/scripts/central-release.sh b/.github/scripts/central-release.sh new file mode 100755 index 000000000..def12f450 --- /dev/null +++ b/.github/scripts/central-release.sh @@ -0,0 +1,96 @@ +#!/bin/bash +##===----------------------------------------------------------------------===## +## +## This source file is part of the Swift.org open source project +## +## Copyright (c) 2026 Apple Inc. and the Swift.org project authors +## Licensed under Apache License v2.0 +## +## See LICENSE.txt for license information +## See CONTRIBUTORS.txt for the list of Swift.org project authors +## +## SPDX-License-Identifier: Apache-2.0 +## +##===----------------------------------------------------------------------===## + +# Releases a version to Maven Central after publish.yml uploaded it with +# `./gradlew publishAllPublicationsToSonatypeRepository`. +# +# The upload went to a staging repository of the Central Portal's OSSRH Staging +# API. This hands that repository to the Central Portal as a deployment, which +# Central publishes automatically once it has validated it, and waits until +# Central has validated it. It fails if Central rejects the deployment, printing +# Central's errors, so a release run only succeeds once Central accepted it. +# +# Usage: central-release.sh +# Needs SONATYPE_USER and SONATYPE_TOKEN (a Central Portal user token), curl, jq. + +set -euo pipefail + +version="${1:?usage: $0 }" +namespace="org.swift.swiftjava" +staging_api="https://ossrh-staging-api.central.sonatype.com" +portal_api="https://central.sonatype.com/api/v1/publisher" +deployments_url="https://central.sonatype.com/publishing/deployments" +timeout_seconds="${CENTRAL_TIMEOUT_SECONDS:-1800}" +interval_seconds="${CENTRAL_POLL_INTERVAL_SECONDS:-20}" + +token="$(printf '%s:%s' "${SONATYPE_USER:?}" "${SONATYPE_TOKEN:?}" | base64 | tr -d '\n')" +# GitHub masks the secrets themselves in the log, but not values derived from them +if [[ -n "${GITHUB_ACTIONS:-}" ]]; then + echo "::add-mask::$token" +fi + +# Both the staging API and the Portal API take the token as a Bearer token, as +# in ServiceTalk's release workflow. +api() { + curl --fail-with-body --silent --show-error --retry 5 -H "Authorization: Bearer $token" "$@" +} + +# Prints the Portal status of the deployment of $version. The deployments are +# found through the staging repositories, `ip=any` includes ones opened from a +# different runner by an earlier attempt. +deployment_status() { + local ids id status + ids="$(api "$staging_api/manual/search/repositories?ip=any" | jq -r '.repositories[].portal_deployment_id // empty')" + for id in $ids; do + status="$(api -X POST "$portal_api/status?id=$id")" + # `purls` stays empty until Central has looked at the deployment + if jq -e --arg suffix "@$version" '(.purls // []) as $p | ($p | length) == 0 or ($p | any(endswith($suffix)))' \ + <<< "$status" > /dev/null; then + echo "$status" + return + fi + done +} + +echo "Handing the staging repository for $version to the Central Portal" +api -X POST "$staging_api/manual/upload/defaultRepository/$namespace?publishing_type=automatic" +echo + +deadline=$(($(date +%s) + timeout_seconds)) +while true; do + status="$(deployment_status || true)" + state="$(jq -r '.deploymentState // empty' <<< "${status:-null}")" + case "$state" in + PUBLISHING | PUBLISHED) + echo "Central validated $version and is publishing it ($state)" + exit 0 + ;; + FAILED) + echo "::error::Central rejected $version: $(jq -c '.errors' <<< "$status")" + exit 1 + ;; + VALIDATED) + # Doesn't change on its own: automatic publishing didn't engage + echo "::error::Central validated $version but didn't publish it, someone with access to $deployments_url has to publish it" + exit 1 + ;; + esac + if (($(date +%s) > deadline)); then + echo "::error::$version is still ${state:-not visible} at Central after $((timeout_seconds / 60)) minutes, see $deployments_url" + exit 1 + fi + echo "$version is ${state:-not visible yet} at Central, checking again in ${interval_seconds}s" + sleep "$interval_seconds" +done diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml new file mode 100644 index 000000000..7a06ca813 --- /dev/null +++ b/.github/workflows/publish.yml @@ -0,0 +1,250 @@ +name: Publish + +# Publishes swiftkit-core, swiftkit-ffm and swiftkit-native to Maven Central: +# - push to `main` -> `X.Y.Z-SNAPSHOT` to https://central.sonatype.com/repository/maven-snapshots/ +# - push of an `N.N.N` tag -> release `N.N.N` to Maven Central +# - pull request changing the publishing setup -> dry run only +# +# A dry run builds, signs and checks the signatures of everything a real publish +# would upload, into build/staging-deploy. Pull requests always dry-run, and so does +# everything else until the repository variable `MAVEN_CENTRAL_PUBLISHING` is set +# to `true`, see RELEASING.md. +# +# The version is derived from git tags (see build.gradle.kts) and decides whether +# the upload goes to the snapshots repository or to a release, so both cases run +# the same jobs: +# 1. `tests` runs the full test suite (pull_request.yml) on the commit being +# published. Nothing is built or published unless it passes. Pull requests +# skip it, since pull_request.yml already runs on them. +# 2. `natives` builds libSwiftJava and libSwiftRuntimeFunctions on every platform +# and uploads them as a workflow artifact, in a directory named after the +# platform's Maven classifier. +# 3. `wrapper-validation` checks gradle/wrapper/gradle-wrapper.jar against the +# checksum Gradle publishes for the version in gradle-wrapper.properties, +# since `publish` runs it with the signing key and the Maven Central +# credentials. +# 4. `publish` signs all modules, with one swiftkit-native classifier jar per +# platform, and uploads them to Maven Central with Gradle's `maven-publish`. +# A release is uploaded to the Central Portal's OSSRH Staging API and then +# turned into a single deployment, which Central publishes automatically. +# The run waits until Central has validated it, and fails if Central +# rejects it (.github/scripts/central-release.sh). +# +# Maintainer setup (credentials, signing key) and the release procedure are +# described in RELEASING.md. + +on: + push: + branches: [main] + tags: ['[0-9]+.[0-9]+.[0-9]+'] + # Only applies to branch pushes, tag pushes always publish + paths-ignore: + - '**.md' + - '**.docc/**' + pull_request: + paths: + - '.github/workflows/publish.yml' + - 'build.gradle.kts' + - 'settings.gradle.kts' + - 'gradle.properties' + - 'BuildLogic/**' + - 'SwiftKitCore/build.gradle.kts' + - 'SwiftKitFFM/build.gradle.kts' + - 'SwiftKitNative/**' + # Re-run a publish, e.g. after a transient failure. Select `main` or a release tag. + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: publish-${{ github.ref }} + cancel-in-progress: false + +env: + # When bumping, also update the `swift:X.Y-*` images and classifiers below. + SWIFT_VERSION: '6.3' + DRY_RUN: ${{ github.event_name == 'pull_request' || vars.MAVEN_CENTRAL_PUBLISHING != 'true' }} + +jobs: + tests: + name: Tests + # Pull requests run pull_request.yml on their own, and only dry-run here. + if: github.repository == 'swiftlang/swift-java' && github.event_name != 'pull_request' + uses: ./.github/workflows/pull_request.yml + + natives: + name: Build natives (${{ matrix.classifier }}) + needs: tests + # `tests` is skipped in pull requests, everywhere else it has to pass. + if: >- + ${{ !cancelled() && github.repository == 'swiftlang/swift-java' && + (needs.tests.result == 'success' || github.event_name == 'pull_request') }} + runs-on: ${{ matrix.runs-on }} + container: ${{ matrix.container }} + strategy: + matrix: + include: + - classifier: osx-aarch_64 + runs-on: macos-15 + - classifier: ubuntu22.04-swift_6.3-x86_64 + runs-on: ubuntu-latest + container: swift:6.3-jammy + - classifier: ubuntu22.04-swift_6.3-aarch_64 + runs-on: ubuntu-24.04-arm + container: swift:6.3-jammy + - classifier: ubuntu24.04-swift_6.3-x86_64 + runs-on: ubuntu-latest + container: swift:6.3-noble + - classifier: ubuntu24.04-swift_6.3-aarch_64 + runs-on: ubuntu-24.04-arm + container: swift:6.3-noble + steps: + - uses: actions/checkout@v7 + - name: Install Swift + if: runner.os == 'macOS' + run: ./.github/scripts/install_swiftly.sh + - name: Build native libraries + shell: bash + run: | + set -euo pipefail + # One invocation per product, `swift build` only builds the last `--product` + for product in SwiftRuntimeFunctions SwiftJava; do + swift build --disable-experimental-prebuilts -c release --product "$product" + done + ext=so; [[ "$RUNNER_OS" == macOS ]] && ext=dylib + bin="$(swift build -c release --show-bin-path)" + mkdir -p "natives/${{ matrix.classifier }}" + cp "$bin/libSwiftRuntimeFunctions.$ext" "$bin/libSwiftJava.$ext" "natives/${{ matrix.classifier }}/" + - uses: actions/upload-artifact@v7 + with: + name: native-${{ matrix.classifier }} + path: natives/ + if-no-files-found: error + + wrapper-validation: + name: Validate Gradle wrapper + # `publish` runs ./gradlew with the signing key and the Maven Central + # credentials, so the wrapper jar has to be an official Gradle release. + # Checked by hand, because the swiftlang organization doesn't allow + # third-party actions like gradle/actions/wrapper-validation. + if: github.repository == 'swiftlang/swift-java' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - name: Check the wrapper jar against Gradle's published checksum + run: | + set -euo pipefail + version="$(sed -nE 's#^distributionUrl=.*/gradle-(.+)-(bin|all)\.zip$#\1#p' gradle/wrapper/gradle-wrapper.properties)" + echo "Gradle $version" + checksum="$(curl --fail --silent --show-error --location --retry 3 \ + "https://services.gradle.org/distributions/gradle-$version-wrapper.jar.sha256")" + echo "$checksum gradle/wrapper/gradle-wrapper.jar" | sha256sum --check + + publish: + name: Publish to Maven Central + needs: [natives, wrapper-validation] + # Explicit, because a skipped `tests` (pull requests) would otherwise skip this too. + if: ${{ !cancelled() && needs.natives.result == 'success' && needs.wrapper-validation.result == 'success' }} + runs-on: ubuntu-latest + container: swift:6.3-noble + steps: + - uses: actions/checkout@v7 + with: + fetch-depth: 0 # the version is derived from git tags + - uses: actions/setup-java@v5 + with: + distribution: corretto + java-version: 25 + - uses: actions/download-artifact@v8 + with: + pattern: native-* + path: natives + merge-multiple: true + - name: Make the git tags readable + # The version is derived from git tags. The swift container runs as root, + # the checkout belongs to the runner's user, and git refuses to read a + # repository owned by someone else, so the version would silently fall + # back to 0.0.1. Fail here instead if the tags still can't be read. + shell: bash + run: | + git config --global --add safe.directory "$GITHUB_WORKSPACE" + tag="$(git describe --tags --abbrev=0 --match '[0-9]*.[0-9]*.[0-9]*')" + echo "Latest release tag: $tag" + - name: Install curl and jq + # central-release.sh needs both and the swift image ships without them. + # Installed before anything is uploaded, so an apt failure can't leave a + # release uploaded but not handed to the Central Portal. + run: apt-get -q update && apt-get -q install -y curl jq + - name: Publish + shell: bash + # Only this step gets the credentials, not the actions above. + env: + SONATYPE_USER: ${{ secrets.SONATYPE_USER }} + SONATYPE_TOKEN: ${{ secrets.SONATYPE_TOKEN }} + ORG_GRADLE_PROJECT_signingKey: ${{ secrets.ORG_GRADLE_PROJECT_SIGNINGKEY }} + ORG_GRADLE_PROJECT_signingPassword: ${{ secrets.ORG_GRADLE_PROJECT_SIGNINGPASSWORD }} + run: | + set -euo pipefail + VERSION="$(./gradlew -q printVersion | tail -n 1)" + echo "Version: $VERSION" + case "$GITHUB_REF" in + refs/tags/*) + if [[ "$VERSION" != "$GITHUB_REF_NAME" ]]; then + echo "::error::Tag $GITHUB_REF_NAME does not match the computed version $VERSION" + exit 1 + fi + ;; + refs/heads/main) + if [[ "$VERSION" != *-SNAPSHOT ]]; then + echo "::notice::HEAD is tagged $VERSION, the workflow run for the tag publishes it" + exit 0 + fi + ;; + refs/pull/*) + ;; # always a dry run + *) + echo "::error::Only main (snapshots) and N.N.N tags (releases) are published, not $GITHUB_REF" + exit 1 + ;; + esac + + gradle() { + ./gradlew -PnativeLibsDir=natives -PswiftVersion="$SWIFT_VERSION" --no-daemon --no-parallel --stacktrace "$@" + } + + if [[ "$DRY_RUN" != true ]]; then + gradle publishAllPublicationsToSonatypeRepository + if [[ "$VERSION" != *-SNAPSHOT ]]; then + # The upload above went to a staging repository of the OSSRH Staging API. + # Hand it to the Central Portal, which publishes it automatically, and + # wait until Central has validated it. + .github/scripts/central-release.sh "$VERSION" + echo "::notice::Released $VERSION, it shows up on Maven Central shortly" + fi + exit 0 + fi + + echo "::notice::Dry run: $VERSION is built and signed into build/staging-deploy, but not uploaded" + export GNUPGHOME="$(mktemp -d)" + if [[ -z "$ORG_GRADLE_PROJECT_signingKey" ]]; then + # No signing key, e.g. in pull requests from forks: sign with a throwaway key. + export ORG_GRADLE_PROJECT_signingPassword=dry-run + gpg --batch --pinentry-mode loopback --passphrase "$ORG_GRADLE_PROJECT_signingPassword" \ + --quick-gen-key 'swift-java dry run ' rsa3072 sign 1d + export ORG_GRADLE_PROJECT_signingKey="$(gpg --batch --pinentry-mode loopback --passphrase "$ORG_GRADLE_PROJECT_signingPassword" --armor --export-secret-keys)" + else + gpg --batch --pinentry-mode loopback --passphrase "$ORG_GRADLE_PROJECT_signingPassword" --import <<< "$ORG_GRADLE_PROJECT_signingKey" + fi + rm -rf build/staging-deploy + gradle publishAllPublicationsToStagingRepository + + # Central rejects anything without a valid signature, so check them all. + find build/staging-deploy -type f ! -name '*.asc' ! -name '*.md5' ! -name '*.sha*' ! -name 'maven-metadata.xml' -print0 | sort -z | + while IFS= read -r -d '' file; do + if ! gpg --batch --verify "$file.asc" "$file" 2>/dev/null; then + echo "::error::Missing or bad signature: $file" + exit 1 + fi + echo "signed: ${file#build/staging-deploy/}" + done diff --git a/.github/workflows/pull_request.yml b/.github/workflows/pull_request.yml index d58604c71..48f0c8593 100644 --- a/.github/workflows/pull_request.yml +++ b/.github/workflows/pull_request.yml @@ -6,9 +6,14 @@ permissions: on: pull_request: types: [opened, reopened, synchronize] + # publish.yml runs the tests before it builds and publishes anything. + workflow_call: concurrency: - group: ${{ github.workflow }}-${{ github.ref }} + # When called from publish.yml, `github.workflow` is the caller's name. The + # `tests-` prefix keeps this group distinct from publish.yml's own group, which + # GitHub would otherwise cancel as a deadlock. + group: tests-${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true jobs: diff --git a/BuildLogic/src/main/kotlin/build-logic.java-publishing-conventions.gradle.kts b/BuildLogic/src/main/kotlin/build-logic.java-publishing-conventions.gradle.kts new file mode 100644 index 000000000..fe5b53af8 --- /dev/null +++ b/BuildLogic/src/main/kotlin/build-logic.java-publishing-conventions.gradle.kts @@ -0,0 +1,156 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2024-2026 Apple Inc. and the Swift.org project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of Swift.org project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +// Publishing convention for swift-java's published modules (SwiftKitCore, +// SwiftKitFFM, SwiftKitNative). +// +// Each subproject that applies this convention publishes a single MavenPublication +// named "maven" containing the main jar, sources jar, and javadoc jar, with the +// POM metadata Maven Central requires, to one of two repositories: +// +// publishAllPublicationsToStagingRepository the shared `/build/staging-deploy/` +// directory, for dry runs and inspection +// publishAllPublicationsToSonatypeRepository Maven Central, see the root build.gradle.kts +// +// `publishToMavenLocal` works as usual. +// +// The artifactId is taken from `base.archivesName` so that e.g. SwiftKitCore (the +// Gradle project) publishes as `swiftkit-core` (the Maven artifact). + +plugins { + // Applying `java` on top of `application` is fine, and gives type-safe access + // to `withSourcesJar()` / `withJavadocJar()`. + java + `maven-publish` + signing +} + +java { + withSourcesJar() + withJavadocJar() +} + +publishing { + publications { + create("maven") { + from(components["java"]) + pom { + name.set(provider { project.name }) + description.set(provider { project.description ?: project.name }) + url.set(providers.gradleProperty("projectUrl")) + inceptionYear.set("2024") + licenses { + license { + name.set(providers.gradleProperty("licenseName")) + url.set(providers.gradleProperty("licenseUrl")) + distribution.set("repo") + } + } + developers { + developer { + id.set("swift") + name.set("Swift.org project authors") + url.set("https://swift.org") + } + } + val scmHost: String = providers.gradleProperty("scmHost").orNull ?: "" + val scmPath: String = providers.gradleProperty("scmPath").orNull ?: "" + scm { + url.set("https://$scmHost/$scmPath") + connection.set("scm:git:git://$scmHost/$scmPath.git") + developerConnection.set("scm:git:ssh://git@$scmHost/$scmPath.git") + } + issueManagement { + system.set("GitHub Issues") + url.set(providers.gradleProperty("issueManagementUrl")) + } + ciManagement { + system.set("GitHub Actions") + url.set(providers.gradleProperty("ciManagementUrl")) + } + } + } + } + repositories { + maven { + name = "staging" + url = uri(rootProject.layout.buildDirectory.dir("staging-deploy")) + } + maven { + name = "sonatype" + // Releases go to the Central Portal's OSSRH Staging API, which collects the + // upload in a staging repository. publish.yml then turns that into a Portal + // deployment. Snapshots go straight to the snapshots repository. + url = uri( + if (version.toString().endsWith("-SNAPSHOT")) { + "https://central.sonatype.com/repository/maven-snapshots/" + } else { + "https://ossrh-staging-api.central.sonatype.com/service/local/staging/deploy/maven2/" + } + ) + credentials { + // A Central Portal user token + username = providers.environmentVariable("SONATYPE_USER").orNull + password = providers.environmentVariable("SONATYPE_TOKEN").orNull + } + } + } +} + +// Signing uses an ASCII-armored secret key held in memory, passed as the Gradle +// properties `signingKey` and `signingPassword` (in CI the environment variables +// `ORG_GRADLE_PROJECT_signingKey` and `ORG_GRADLE_PROJECT_signingPassword`). +// Without a key nothing is signed, which is fine for publishToMavenLocal and the +// staging repository. Maven Central rejects unsigned artifacts though, so +// publishing to `sonatype` without a key fails before uploading anything. +val signingKey: String? = providers.gradleProperty("signingKey").orNull?.takeIf { it.isNotBlank() } +val signingPassword: String = providers.gradleProperty("signingPassword").orNull ?: "" +if (signingKey != null) { + signing { + useInMemoryPgpKeys(signingKey, signingPassword) + sign(publishing.publications["maven"]) + } +} +// Checked once the task graph is known, before Gradle validates the publish tasks +// (which would only complain about a missing `credentials.username`). +gradle.taskGraph.whenReady { + val publishesToCentral = allTasks.any { + it.project == project && it is PublishToMavenRepository && it.repository.name == "sonatype" + } + if (publishesToCentral) { + val missing = buildList { + if (signingKey == null) { + add("a signing key (signingKey/signingPassword)") + } + if (listOf("SONATYPE_USER", "SONATYPE_TOKEN").any { providers.environmentVariable(it).orNull.isNullOrBlank() }) { + add("Central Portal credentials (SONATYPE_USER/SONATYPE_TOKEN)") + } + } + if (missing.isNotEmpty()) { + throw GradleException("Publishing to Maven Central needs ${missing.joinToString(" and ")}, see RELEASING.md") + } + } +} + +// Use base.archivesName (set per-module to e.g. "swiftkit-core") as the artifactId +// instead of the Gradle project name ("SwiftKitCore"). Done in afterEvaluate so the +// module's `base { archivesName = ... }` block has already run. +afterEvaluate { + val archivesName = extensions.findByType()?.archivesName?.orNull + if (!archivesName.isNullOrBlank()) { + publishing.publications.withType().configureEach { + artifactId = archivesName + } + } +} diff --git a/BuildLogic/src/main/kotlin/org/swift/build/utils/gitVersion.kt b/BuildLogic/src/main/kotlin/org/swift/build/utils/gitVersion.kt deleted file mode 100644 index e4279d2c4..000000000 --- a/BuildLogic/src/main/kotlin/org/swift/build/utils/gitVersion.kt +++ /dev/null @@ -1,47 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2026 Apple Inc. and the Swift.org project authors -// Licensed under Apache License v2.0 -// -// See LICENSE.txt for license information -// See CONTRIBUTORS.txt for the list of Swift.org project authors -// -// SPDX-License-Identifier: Apache-2.0 -// -//===----------------------------------------------------------------------===// - -package org.swift.build.utils - -import org.gradle.api.Project - -/** - * Resolve the publication version for swift-java's Java artifacts. - * - * Resolution order: - * 1. `-PswiftkitVersion=` project property, for CI/release overrides. - * 2. `git describe --tags --always`, for normal local builds with full git history. - * 3. `GITHUB_SHA` (truncated) — useful in shallow CI checkouts where git history is not available. - * 4. `0.0.0-SNAPSHOT` fallback. - * - * `git describe` is allowed to fail without breaking the build, because some CI - * environments do not have a full checkout (e.g. `fetch-depth: 1`) or any tags - * reachable, in which case the command exits with code 128. - */ -fun Project.resolveSwiftKitVersion(): String { - findProperty("swiftkitVersion")?.toString()?.takeIf { it.isNotBlank() }?.let { return it } - - val gitVersion = runCatching { - providers.exec { - commandLine("git", "describe", "--tags", "--always") - workingDir = rootDir - isIgnoreExitValue = true - }.standardOutput.asText.get().trim() - }.getOrNull() - if (!gitVersion.isNullOrBlank()) return gitVersion - - System.getenv("GITHUB_SHA")?.take(12)?.takeIf { it.isNotBlank() }?.let { return it } - - return "0.0.0-SNAPSHOT" -} diff --git a/PUBLISHING.md b/PUBLISHING.md new file mode 100644 index 000000000..aa87fdb9c --- /dev/null +++ b/PUBLISHING.md @@ -0,0 +1,143 @@ +# Using the swift-java Java libraries + +swift-java's Java runtime libraries are published to Maven Central under the +`org.swift.swiftjava` group. This document covers what is published, how to +depend on it (including `-SNAPSHOT` builds of `main`), and how to publish the +libraries to your local Maven repository. + +How the libraries get published, and how to cut a release, is described in +[`RELEASING.md`](./RELEASING.md). + +> [!NOTE] +> Publishing to Maven Central is not enabled yet: the publish workflow only does +> dry runs until the Maven Central credentials are set up, so the coordinates +> below don't resolve yet. Until then, [publish your checkout to your local Maven +> repository](#publishing-to-your-local-maven-repository). + +## Artifacts + +| Artifact | Contents | +| -------------------------------------- | ------------------------------------------------------------------- | +| `org.swift.swiftjava:swiftkit-core` | Java runtime support for JNI mode, Java 11+ | +| `org.swift.swiftjava:swiftkit-ffm` | Java runtime support for FFM mode, JDK 25+ (depends on core) | +| `org.swift.swiftjava:swiftkit-native` | `libSwiftJava` and `libSwiftRuntimeFunctions`, one jar per platform | + +`swiftkit-core` and `swiftkit-ffm` contain no native code. At runtime they load +`libSwiftJava` and `libSwiftRuntimeFunctions` from `java.library.path`, or else +from the classpath, which is where `swiftkit-native` comes in. Pick its jar +for your platform with a classifier: + +| Classifier | Platform | +| --------------------------------- | ---------------------------- | +| `osx-aarch_64` | macOS, Apple silicon | +| `ubuntu22.04-swift_6.3-x86_64` | Ubuntu 22.04, x86_64 | +| `ubuntu22.04-swift_6.3-aarch_64` | Ubuntu 22.04, arm64 | +| `ubuntu24.04-swift_6.3-x86_64` | Ubuntu 24.04, x86_64 | +| `ubuntu24.04-swift_6.3-aarch_64` | Ubuntu 24.04, arm64 | + +The Linux libraries link against the Swift runtime, so the machine needs the +Swift runtime of the same Swift version installed, as in the official +`swift:6.3` Docker images. The Linux classifiers therefore name the Swift +version: Swift's runtime ABI is not stable across versions on Linux. On macOS +the libraries use the Swift runtime that ships with the OS. + +## Versions + +The version is derived from git tags (see [`build.gradle.kts`](./build.gradle.kts)): + +| Git state | Version | +| ---------------------------------- | --------------------------------------------------------------------------- | +| HEAD is exactly at an `N.N.N` tag | that tag, a release such as `0.8.0` | +| HEAD is after the latest tag | latest tag with patch + 1, plus `-SNAPSHOT`: `0.8.1-SNAPSHOT` after `0.8.0` | + +Every tagged release is on Maven Central. Every commit on `main` is published as +the current `-SNAPSHOT` to https://central.sonatype.com/repository/maven-snapshots/. +`./gradlew -q printVersion` prints the version of your checkout. + +## Depending on the libraries + +### Gradle + +```kotlin +repositories { + mavenCentral() +} + +val swiftJavaVersion = "0.8.0" // the release you want + +dependencies { + implementation("org.swift.swiftjava:swiftkit-core:$swiftJavaVersion") + // For FFM mode (JDK 25+), instead of swiftkit-core: + // implementation("org.swift.swiftjava:swiftkit-ffm:$swiftJavaVersion") + + runtimeOnly("org.swift.swiftjava:swiftkit-native:$swiftJavaVersion:osx-aarch_64") +} +``` + +To use a `-SNAPSHOT` of `main`, add the snapshots repository and use a +`-SNAPSHOT` version: + +```kotlin +repositories { + mavenCentral() + maven("https://central.sonatype.com/repository/maven-snapshots/") { + mavenContent { snapshotsOnly() } + } +} +``` + +### Maven + +```xml + + + org.swift.swiftjava + swiftkit-core + 0.8.0 + + + org.swift.swiftjava + swiftkit-native + 0.8.0 + ubuntu24.04-swift_6.3-x86_64 + runtime + + +``` + +For snapshots, add the snapshots repository: + +```xml + + + central-snapshots + https://central.sonatype.com/repository/maven-snapshots/ + false + true + + +``` + +## Publishing to your local Maven repository + +To use your own swift-java checkout from another project, publish it to +`~/.m2/repository`: + +```bash +./gradlew :SwiftKitCore:publishToMavenLocal :SwiftKitFFM:publishToMavenLocal :SwiftKitNative:publishToMavenLocal +``` + +This needs no credentials and doesn't sign anything. It publishes the version +printed by `./gradlew -q printVersion`, and builds `swiftkit-native` for your +machine only (`swift build -c release`), with the classifier `osx-aarch_64`, +`linux-x86_64` or `linux-aarch_64`. Then add `mavenLocal()` to the consuming +project's repositories. + +To see exactly what CI would upload to Maven Central, stage everything without +uploading: + +```bash +rm -rf build/staging-deploy +./gradlew publishAllPublicationsToStagingRepository +find build/staging-deploy -type f +``` diff --git a/README.md b/README.md index 222322b03..63defddf1 100644 --- a/README.md +++ b/README.md @@ -40,26 +40,52 @@ E.g sdkman install command: sdk install java 25.0.1-amzn ``` -## Self-publish supporting Java libraries +## Consuming the Java libraries -swift-java relies on supporting libraries that are under active development and not yet published to Maven Central. To use the project, you'll need to self-publish these libraries locally so your Java project can depend on them. +swift-java's supporting Java libraries are published to Maven Central as +`org.swift.swiftjava:swiftkit-core` (JNI mode) and `org.swift.swiftjava:swiftkit-ffm` +(FFM mode), together with `org.swift.swiftjava:swiftkit-native`, which ships the +Swift libraries they load at runtime as one classifier jar per platform: -To publish the libraries to your local maven repository (`$HOME/.m2`), run this in `swift-java/`: +```kotlin +repositories { + mavenLocal() + mavenCentral() +} -```bash -./gradlew publishToMavenLocal +dependencies { + implementation("org.swift.swiftjava:swiftkit-core:") + runtimeOnly("org.swift.swiftjava:swiftkit-native::osx-aarch_64") +} ``` -To consume these libraries in your Java project built using Gradle, include the local repository in the repositories to resolve dependencies from: +Rather than hardcoding the classifier, you can let the +[osdetector Gradle plugin](https://github.com/google/osdetector-gradle-plugin) +pick the one for the machine running the build. On Linux the classifier also +names the Ubuntu release and the Swift version installed on the machine: ```kotlin -repositories { - mavenLocal() - mavenCentral() +plugins { + id("com.google.osdetector") version "1.7.3" +} + +// e.g. `osx-aarch_64` or `ubuntu24.04-swift_6.3-x86_64` +val swiftkitNativeClassifier = + if (osdetector.os == "linux") { + "${osdetector.release.id}${osdetector.release.version}-swift_6.3-${osdetector.arch}" + } else { + osdetector.classifier + } + +dependencies { + implementation("org.swift.swiftjava:swiftkit-core:") + runtimeOnly("org.swift.swiftjava:swiftkit-native::$swiftkitNativeClassifier") } ``` -We anticipate simplifying this in the future. +See [PUBLISHING.md](./PUBLISHING.md) for the available classifiers, `-SNAPSHOT` +builds of `main`, and how to publish your own checkout to `~/.m2` with +`publishToMavenLocal`. ## SwiftJava macros: calling Java from Swift diff --git a/RELEASING.md b/RELEASING.md new file mode 100644 index 000000000..969a0c843 --- /dev/null +++ b/RELEASING.md @@ -0,0 +1,248 @@ +# Releasing swift-java + +This document is for maintainers: how swift-java's Java libraries get published +to Maven Central, the one-time setup that needs, and how to cut a release. + +What gets published and how to depend on it is described in +[`PUBLISHING.md`](./PUBLISHING.md). + +## How publishing works + +[`.github/workflows/publish.yml`](.github/workflows/publish.yml) publishes +`swiftkit-core`, `swiftkit-ffm` and `swiftkit-native`: + +| Trigger | Version | Published to | +| ------------------------------------------ | ---------------- | -------------------------------------------------------- | +| Push to `main` | `X.Y.Z-SNAPSHOT` | https://central.sonatype.com/repository/maven-snapshots/ | +| Push of an `N.N.N` tag | `N.N.N` | Maven Central | +| Pull request changing the publishing setup | both | nothing, [dry run](#dry-runs) | + +Nothing is built or published until the full test suite passes on the commit: +the workflow first runs [`pull_request.yml`](.github/workflows/pull_request.yml) +as its `tests` job. Pull requests skip that job, since `pull_request.yml` already +runs on them. Before anything runs `./gradlew` with the secrets, the +`wrapper-validation` job checks `gradle/wrapper/gradle-wrapper.jar` against the +checksum Gradle publishes for the version in `gradle-wrapper.properties`. When +updating Gradle, run `./gradlew wrapper --gradle-version ` twice: the +first run only updates `gradle-wrapper.properties`, the second, now running the +new Gradle, also updates the jar. After that, all triggers run the same two jobs: + +1. **`natives`** builds `libSwiftJava` and `libSwiftRuntimeFunctions` on every + platform in its matrix (macOS arm64, Ubuntu 22.04 and 24.04 on x86_64 and + arm64), and uploads them in a directory named after the platform's Maven + classifier. +2. **`publish`** runs `./gradlew publishAllPublicationsToSonatypeRepository + -PnativeLibsDir=natives`, which signs every module, with one `swiftkit-native` + classifier jar per platform, and uploads it with Gradle's `maven-publish`. The + version decides where it goes. A snapshot goes straight to the snapshots + repository. A release goes to the Central Portal's OSSRH Staging API, and + [`central-release.sh`](.github/scripts/central-release.sh) then turns it into + a single deployment with `publishing_type=automatic` and waits until Central + has validated it. Central publishes it right after, so no manual step in the + Portal is needed. + +To build with a newer Swift version, update `SWIFT_VERSION`, the `swift:X.Y-*` +container images and the Linux classifiers in `publish.yml`, and the classifier +table in `PUBLISHING.md`. To add a platform, add a matrix entry. + +The Gradle side lives in: +- [`build.gradle.kts`](./build.gradle.kts): version computation +- [`build-logic.java-publishing-conventions`](BuildLogic/src/main/kotlin/build-logic.java-publishing-conventions.gradle.kts): POM metadata, signing, and the `staging` and `sonatype` repositories, applied by every published module +- [`SwiftKitNative/build.gradle.kts`](SwiftKitNative/build.gradle.kts): the per-platform classifier jars + +### Dry runs + +A dry run does everything a real publish does except the upload: it builds the +native libraries on every platform, publishes all artifacts with signatures and +checksums to `build/staging-deploy`, and checks every signature. + +Pull requests that change the publishing setup (see the `pull_request` paths in +`publish.yml`) always dry-run. All +other runs are dry runs as well until publishing is enabled with the +`MAVEN_CENTRAL_PUBLISHING` repository variable, see +[Enabling publishing](#enabling-publishing). Without the real signing key, for +example in pull requests from forks, a dry run signs with a throwaway key. + +### Re-running and skipped runs + +A push to `main` whose commit is already tagged skips publishing, because the +run for the tag publishes it. To repeat a publish, for example after a +transient failure, run the workflow manually (**Actions → Publish → Run +workflow**) on `main` or on the release tag. Re-publishing a release that already +reached Maven Central fails, because releases are immutable. + +## One-time setup + +These steps need an account with access to the `org.swift.swiftjava` namespace +in the Sonatype Central Portal. Maintainers without Portal access only need the +repository secrets to be in place; releasing itself happens entirely through +git tags and the publish workflow. + +### Maven Central credentials + +In the Sonatype Central Portal at https://central.sonatype.com, click your +username, then **View Account**, then **Generate User Token**. The token's +username and password are used for both releases and snapshots. + +The `org.swift.swiftjava` namespace must be verified in the Portal, and +**SNAPSHOTs must be enabled** for it (Namespaces → the namespace's menu → +Enable SNAPSHOTs), otherwise snapshot uploads are rejected. + +### PGP signing key + +Maven Central requires every artifact to be signed with a PGP key whose public +key is on a public keyserver. Use a dedicated key for swift-java releases, not a +personal one. A signing-only RSA key is all that's needed: + +```bash +gpg --quick-gen-key 'swift-java release signing ' rsa4096 sign 3y # asks for a passphrase +gpg --list-secret-keys --keyid-format=long 'swift-java release signing' # sec rsa4096/ ... +gpg --armor --export > public.asc +gpg --armor --export-secret-keys > private.asc # still protected by the passphrase + +# Maven Central verifies signatures against public keyservers +gpg --keyserver keyserver.ubuntu.com --send-keys +gpg --keyserver keys.openpgp.org --send-keys +``` + +Before putting the key into GitHub, check that Gradle can sign with it, see +[Troubleshooting](#troubleshooting). + +Keep `private.asc`, `public.asc` and the passphrase in the team's password +manager. GitHub secrets can't be read back, and every future release is signed +with this key. The key expires after the 3 years given above, see +[Rotating keys and tokens](#rotating-keys-and-tokens). + +### Repository secrets + +The publish workflow reads four repository secrets: + +| Secret | Value | +| ------------------------------------ | -------------------------------------------------------- | +| `SONATYPE_USER` | Portal user token username | +| `SONATYPE_TOKEN` | Portal user token password | +| `ORG_GRADLE_PROJECT_SIGNINGKEY` | Contents of `private.asc`, including the BEGIN/END lines | +| `ORG_GRADLE_PROJECT_SIGNINGPASSWORD` | The key's passphrase | + +Setting them needs admin access to the repository. Either add each one in +**Settings → Secrets and variables → Actions → New repository secret**, pasting +`private.asc` in full, from `-----BEGIN PGP PRIVATE KEY BLOCK-----` to +`-----END PGP PRIVATE KEY BLOCK-----`. Or use the GitHub CLI, which reads the +values from a file or prompts for them, so they don't end up in the shell +history: + +```bash +gh secret set ORG_GRADLE_PROJECT_SIGNINGKEY -R swiftlang/swift-java < private.asc +gh secret set ORG_GRADLE_PROJECT_SIGNINGPASSWORD -R swiftlang/swift-java # prompts +gh secret set SONATYPE_USER -R swiftlang/swift-java # prompts +gh secret set SONATYPE_TOKEN -R swiftlang/swift-java # prompts +gh secret list -R swiftlang/swift-java +``` + +Don't paste the key material into chats, tickets or command lines. + +How the workflow uses them: + +- Only the `Publish` step of `publish.yml` gets the secrets, not the actions + that run before it. +- GitHub stores secret names in upper case. The step passes the signing secrets + on as the environment variables `ORG_GRADLE_PROJECT_signingKey` and + `ORG_GRADLE_PROJECT_signingPassword`, which Gradle turns into the `signingKey` + and `signingPassword` properties that + [`build-logic.java-publishing-conventions`](BuildLogic/src/main/kotlin/build-logic.java-publishing-conventions.gradle.kts) + signs with. `SONATYPE_USER` and `SONATYPE_TOKEN` are the credentials of the + `sonatype` repository there. +- Pull requests from forks don't get secrets. Their dry runs sign with a + throwaway key. +- These are the same secret names [ServiceTalk](https://github.com/apple/servicetalk) + uses. + +### Enabling publishing + +Until the repository variable `MAVEN_CENTRAL_PUBLISHING` is set to `true`, the +publish workflow only does [dry runs](#dry-runs). To turn publishing on: + +1. Verify the namespace, enable SNAPSHOTs and add the secrets, as described + above. +2. Run the workflow manually on `main` (**Actions → Publish → Run workflow**). + It's still a dry run, but now it signs with the real key and checks every + signature, without uploading anything. The Portal credentials are only + used by a real upload, so this doesn't check them. +3. Add the variable, in **Settings → Secrets and variables → Actions → + Variables**, or with: + + ```bash + gh variable set MAVEN_CENTRAL_PUBLISHING --body true -R swiftlang/swift-java + ``` + +4. The next push to `main` publishes the first snapshot, which also checks the + Portal credentials. Check that run before tagging a release. + +Deleting the variable turns publishing off again. + +### Rotating keys and tokens + +- **The signing key expires**: extend it rather than making a new one, so users + who already trust the key keep doing so. Then update the secret and the + keyservers: + + ```bash + gpg --quick-set-expire 3y + gpg --armor --export-secret-keys > private.asc + gh secret set ORG_GRADLE_PROJECT_SIGNINGKEY -R swiftlang/swift-java < private.asc + gpg --keyserver keyserver.ubuntu.com --send-keys + gpg --keyserver keys.openpgp.org --send-keys + ``` + +- **A new signing key**: update both `ORG_GRADLE_PROJECT_SIGNING*` secrets and + publish the new public key to the keyservers. Earlier releases stay validly + signed with the old key. +- **A new Portal user token**: update `SONATYPE_USER` and `SONATYPE_TOKEN`. + +## Cutting a release + +1. From a clean `main`, run `./scripts/release.sh`. It asks for the version, + pins `swift-java-jni-core` to its latest release in `Package.swift`, checks + that the Swift and Gradle builds pass, and pushes a `release/` branch. +2. Open a pull request for that branch, qualify the release, and merge it. +3. Tag the merge commit on `main` and push the tag: + + ```bash + git tag -s -m + git push origin + ``` + + This starts the publish workflow, which publishes `` to Maven + Central, or only dry-runs it while publishing isn't + [enabled](#enabling-publishing). Follow it in the workflow run on GitHub: + the `Publish` step uploads the artifacts, hands them to the Central Portal as + a deployment, and polls the Portal until Central has validated it (up to 30 + minutes). If Central rejects the deployment, the run fails and prints + Central's errors. Once published, it can take a while until the artifacts + show up on https://central.sonatype.com and in Maven Central's search. +4. Create a GitHub release for the tag. +5. Run `./scripts/release.sh --next` (or press Enter in the still running script) + to point `swift-java-jni-core` back at `main` for the next development cycle. + +> **Releases are permanent.** A published version can't be changed or deleted. +> If something ships broken, fix it and release the next patch version. + +## Troubleshooting + +- Check what would be uploaded, without credentials (unsigned without a key): + + ```bash + rm -rf build/staging-deploy + ./gradlew publishAllPublicationsToStagingRepository + find build/staging-deploy -type f + ``` + +- Check that signing works with the real key, without uploading anything: + + ```bash + export ORG_GRADLE_PROJECT_signingKey="$(gpg --armor --export-secret-keys )" + read -rs ORG_GRADLE_PROJECT_signingPassword && export ORG_GRADLE_PROJECT_signingPassword # type the passphrase + rm -rf build/staging-deploy + ./gradlew --no-daemon publishAllPublicationsToStagingRepository + find build/staging-deploy -name '*.jar' -exec gpg --verify {}.asc {} \; + ``` diff --git a/SwiftKitCore/build.gradle.kts b/SwiftKitCore/build.gradle.kts index f17364c2a..309f940a9 100644 --- a/SwiftKitCore/build.gradle.kts +++ b/SwiftKitCore/build.gradle.kts @@ -12,17 +12,13 @@ // //===----------------------------------------------------------------------===// -import org.swift.build.utils.resolveSwiftKitVersion - plugins { id("build-logic.java-application-conventions") + id("build-logic.java-publishing-conventions") id("me.champeau.jmh") version "0.7.2" - `maven-publish` } -group = "org.swift.swiftkit" - -version = resolveSwiftKitVersion() +description = "SwiftKit Core: shared runtime support for Swift/Java interop (JNI mode)." base { archivesName = "swiftkit-core" @@ -33,16 +29,6 @@ repositories { mavenCentral() } -publishing { - publications { - create("maven") { - groupId = group as? String - artifactId = "swiftkit-core" - from(components["java"]) - } - } -} - java { toolchain { languageVersion.set(JavaLanguageVersion.of((gradle.extra.properties["swiftJavaJdk"] as? Int) ?: 25)) @@ -111,4 +97,4 @@ tasks.build { dependsOn(compileSwift) } -registerCleanSwift(rootDir) \ No newline at end of file +registerCleanSwift(rootDir) diff --git a/SwiftKitFFM/build.gradle.kts b/SwiftKitFFM/build.gradle.kts index 7d3bbd619..4227b0e3b 100644 --- a/SwiftKitFFM/build.gradle.kts +++ b/SwiftKitFFM/build.gradle.kts @@ -12,16 +12,13 @@ // //===----------------------------------------------------------------------===// -import org.swift.build.utils.resolveSwiftKitVersion - plugins { id("build-logic.java-application-conventions") - `maven-publish` + id("build-logic.java-publishing-conventions") + `java-library` } -group = "org.swift.swiftkit" - -version = resolveSwiftKitVersion() +description = "SwiftKit FFM: Swift/Java interop using java.lang.foreign (Panama). Requires JDK 22+." base { archivesName = "swiftkit-ffm" @@ -32,16 +29,6 @@ repositories { mavenCentral() } -publishing { - publications { - create("maven") { - groupId = group as? String - artifactId = "swiftkit-ffm" - from(components["java"]) - } - } -} - java { toolchain { languageVersion.set(JavaLanguageVersion.of((gradle.extra.properties["swiftJavaJdk"] as? Int) ?: 25)) @@ -49,7 +36,9 @@ java { } dependencies { - implementation(projects.swiftKitCore) + // `api`: the public API exposes SwiftKitCore types (e.g. AllocatingSwiftArena extends SwiftArena), + // so consumers of swiftkit-ffm need swiftkit-core on their compile classpath. + api(projects.swiftKitCore) testRuntimeOnly(libs.junit.platform.launcher) // TODO: workaround for not finding junit: https://github.com/gradle/gradle/issues/34512 testImplementation(platform(libs.junit.bom)) @@ -111,4 +100,4 @@ tasks.build { dependsOn(compileSwift) } -registerCleanSwift(rootDir) \ No newline at end of file +registerCleanSwift(rootDir) diff --git a/SwiftKitNative/build.gradle.kts b/SwiftKitNative/build.gradle.kts new file mode 100644 index 000000000..1e4939495 --- /dev/null +++ b/SwiftKitNative/build.gradle.kts @@ -0,0 +1,110 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2026 Apple Inc. and the Swift.org project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of Swift.org project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +// The Swift libraries that swiftkit-core and swiftkit-ffm load at runtime +// (libSwiftJava, libSwiftRuntimeFunctions), published as `swiftkit-native` with +// one classifier jar per platform, e.g. `swiftkit-native--osx-aarch_64.jar`. +// +// The libraries sit at the root of each classifier jar, which is where +// `SwiftLibraries.loadResourceLibrary` looks for them. +// +// Where the libraries come from: +// -PnativeLibsDir= one sub-directory per classifier, holding the libraries +// built on that platform (CI, see .github/workflows/publish.yml) +// otherwise built for this machine with `swift build -c release`, +// with a classifier like `osx-aarch_64` or `linux-x86_64` + +plugins { + id("build-logic.java-publishing-conventions") +} + +base { + archivesName = "swiftkit-native" +} +description = "Swift native libraries needed at runtime by swiftkit-core and swiftkit-ffm, one classifier jar per platform." + +val nativeLibraries = listOf("SwiftRuntimeFunctions", "SwiftJava") + +// ==== ----------------------------------------------------------------------- +// MARK: Native libraries for this machine + +// One invocation per product: `swift build` with several `--product` flags only +// builds the last one. +val swiftBuildTasks = nativeLibraries.map { product -> + tasks.register("swiftBuild$product") { + group = "swift" + description = "Build lib$product in release mode" + workingDir = rootDir + commandLine("swift", "build", "--disable-experimental-prebuilts", "-c", "release", "--product", product) + } +} + +fun hostClassifier(): String { + val os = System.getProperty("os.name").lowercase() + val osPart = when { + os.contains("mac") -> "osx" + os.contains("linux") -> "linux" + else -> os.substringBefore(' ') + } + val arch = when (val arch = System.getProperty("os.arch")) { + "aarch64", "arm64" -> "aarch_64" + "amd64", "x86_64" -> "x86_64" + else -> arch + } + return "$osPart-$arch" +} + +// ==== ----------------------------------------------------------------------- +// MARK: Classifier jars + +// classifier -> directory containing that platform's libraries +val platformLibraries: Map = + when (val nativeLibsDir = providers.gradleProperty("nativeLibsDir").orNull?.let { rootProject.file(it) }) { + null -> mapOf(hostClassifier() to files(rootDir.resolve(".build/release")).builtBy(swiftBuildTasks)) + else -> { + val dirs = nativeLibsDir.listFiles { file -> file.isDirectory }.orEmpty().sortedBy { it.name } + require(dirs.isNotEmpty()) { "-PnativeLibsDir=$nativeLibsDir has no per-classifier sub-directories" } + dirs.forEach { dir -> + val missing = nativeLibraries.filter { lib -> listOf("dylib", "so").none { dir.resolve("lib$lib.$it").isFile } } + require(missing.isEmpty()) { "$dir is missing native libraries: $missing" } + } + dirs.associate { it.name to files(it) } + } + } + +val swiftVersion: String? = providers.gradleProperty("swiftVersion").orNull + +val nativeJars = platformLibraries.map { (classifier, libraries) -> + tasks.register("nativeJar_" + classifier.replace(Regex("[^A-Za-z0-9_]"), "_")) { + description = "Assemble the $classifier native libraries jar" + archiveClassifier = classifier + from(libraries) { + include(nativeLibraries.flatMap { listOf("lib$it.dylib", "lib$it.so") }) + } + manifest { + attributes("Implementation-Title" to "swiftkit-native", "Implementation-Version" to project.version) + swiftVersion?.let { attributes("Swift-Version" to it) } + } + } +} + +publishing.publications.named("maven") { + nativeJars.forEach { artifact(it) } +} + +// The main jar is empty and consumers must pick a classifier, which plain POM +// resolution handles directly. Gradle module metadata would only list the empty jar. +tasks.withType().configureEach { + enabled = false +} diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 000000000..c2695f3b5 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,86 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2024-2026 Apple Inc. and the Swift.org project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of Swift.org project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +plugins { + base +} + +// ==== ----------------------------------------------------------------------- +// MARK: Version +// +// Derived from git tags, so CI checkouts need the tag history (`fetch-depth: 0`): +// - HEAD is exactly at an `N.N.N` tag -> that version (a release) +// - otherwise -> the latest tag with patch + 1, plus `-SNAPSHOT` +// - no tags at all -> `0.0.1-SNAPSHOT` +// +// `-PswiftkitVersion=` overrides the derived version. + +val tagPattern = Regex("""^\d+\.\d+\.\d+$""") +val releaseTagGlob = "[0-9]*.[0-9]*.[0-9]*" // only consider release tags + +fun runGit(vararg args: String): String? = try { + val process = ProcessBuilder("git", *args) + .directory(rootDir) + .redirectErrorStream(false) + .start() + val out = process.inputStream.bufferedReader().readText().trim() + process.errorStream.bufferedReader().readText() // drain + if (process.waitFor() == 0 && out.isNotEmpty()) out else null +} catch (_: Exception) { + null +} + +fun computeVersion(): String { + val exact = runGit("describe", "--exact-match", "--tags", "--match", releaseTagGlob, "HEAD") + if (exact != null && tagPattern.matches(exact)) { + return exact + } + val latest = runGit("describe", "--tags", "--abbrev=0", "--match", releaseTagGlob) + val (major, minor, patch) = if (latest != null && tagPattern.matches(latest)) { + latest.split(".").map { it.toInt() } + } else { + listOf(0, 0, 0) + } + return "$major.$minor.${patch + 1}-SNAPSHOT" +} + +val computedVersion: String = providers.gradleProperty("swiftkitVersion").orNull + ?.takeIf { it.isNotBlank() } + ?: computeVersion() + +allprojects { + version = computedVersion +} + +// `./gradlew -q printVersion` prints the resolved version +tasks.register("printVersion") { + doLast { println(computedVersion) } +} + +// ==== ----------------------------------------------------------------------- +// MARK: Publishing +// +// The published modules (SwiftKitCore, SwiftKitFFM, SwiftKitNative) apply +// build-logic.java-publishing-conventions, which gives them two repositories: +// +// ./gradlew publishAllPublicationsToStagingRepository # to build/staging-deploy +// ./gradlew publishAllPublicationsToSonatypeRepository # to Maven Central +// +// The version decides where `sonatype` uploads to: +// - `X.Y.Z` -> the Central Portal's OSSRH Staging API. publish.yml then +// turns the upload into a deployment, which Central +// publishes as soon as it has validated it. +// - `X.Y.Z-SNAPSHOT` -> https://central.sonatype.com/repository/maven-snapshots/ +// +// Credentials and the signing key come from the environment, see RELEASING.md. diff --git a/gradle.properties b/gradle.properties index 018c38280..e2bff131c 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1 +1,14 @@ -org.gradle.java.installations.fromEnv=JAVA_HOME_25,JAVA_HOME_25_X64,JAVA_HOME_25_ARM64,JAVA_HOME_21,JAVA_HOME_21_X64,JAVA_HOME_21_ARM64,JAVA_HOME_17,JAVA_HOME_17_X64,JAVA_HOME_17_ARM64 \ No newline at end of file +org.gradle.java.installations.fromEnv=JAVA_HOME_25,JAVA_HOME_25_X64,JAVA_HOME_25_ARM64,JAVA_HOME_21,JAVA_HOME_21_X64,JAVA_HOME_21_ARM64,JAVA_HOME_17,JAVA_HOME_17_X64,JAVA_HOME_17_ARM64 + +# ==== ----------------------------------------------------------------------- +# MARK: Maven metadata +group=org.swift.swiftjava + +projectUrl=https://github.com/swiftlang/swift-java +scmHost=github.com +scmPath=swiftlang/swift-java +issueManagementUrl=https://github.com/swiftlang/swift-java/issues +ciManagementUrl=https://github.com/swiftlang/swift-java/actions + +licenseName=Apache License, Version 2.0 +licenseUrl=https://www.apache.org/licenses/LICENSE-2.0.txt diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 8bdaf60c7..d997cfc60 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/scripts/release.sh b/scripts/release.sh index d9ef3eae3..0d60ad9f1 100755 --- a/scripts/release.sh +++ b/scripts/release.sh @@ -182,11 +182,17 @@ info "Package.swift updated." # ==== ----------------------------------------------------------------------- # MARK: Verify build -info "Verifying build..." +info "Verifying Swift build..." if ! xcrun swift build --package-path "$REPO_ROOT" 2>&1; then error "Build failed! Please fix the issues before releasing." fi +info "Verifying Gradle build..." +if ! "$REPO_ROOT/gradlew" -p "$REPO_ROOT" \ + :SwiftKitCore:build :SwiftKitFFM:build -x test 2>&1; then + error "Gradle build failed! Please fix the issues before releasing." +fi + info "Build succeeded." # ==== ----------------------------------------------------------------------- @@ -213,6 +219,8 @@ echo -e " 3. Merge the pull request" echo -e " 4. Tag the merge commit on main:" echo -e " ${BOLD}git tag -s $RELEASE_VERSION -m $RELEASE_VERSION${NC}" echo -e " ${BOLD}git push origin $RELEASE_VERSION${NC}" +echo -e " Pushing the tag publishes the release to Maven Central (.github/workflows/publish.yml)," +echo -e " or only dry-runs it while publishing is not enabled (see RELEASING.md)" echo -e " 5. Create a GitHub release for the tag" echo -e " 6. Come back here and press Enter to prepare the next development snapshot" echo -e " Or run: ${BOLD}./scripts/release.sh --next${NC}" diff --git a/settings.gradle.kts b/settings.gradle.kts index 1877b848e..9979ef87d 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -69,6 +69,7 @@ val ffmModules = setOf( val skipped = mutableListOf() include("SwiftKitCore") +include("SwiftKitNative") if (ffmCapable) { include("SwiftKitFFM") } else {