feat: add Bifrost Gitea import proof of concept
This commit is contained in:
1 parent
fb9cc5ff11
commit
537391fe49
30 files changed
+1331
No files matched your search
@@ -0,0 +1,5 @@
|
|||||||
|
.git
|
||||||
|
.claude
|
||||||
|
target
|
||||||
|
node_modules
|
||||||
|
.env
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
*.sh text eol=lf
|
||||||
|
mvnw text eol=lf
|
||||||
|
*.java text eol=lf
|
||||||
|
*.js text eol=lf
|
||||||
|
*.yml text eol=lf
|
||||||
|
*.md text eol=lf
|
||||||
|
*.xml text eol=lf
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
name: Build Bifrost
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: ["**"]
|
||||||
|
tags: ["v*.*.*"]
|
||||||
|
pull_request:
|
||||||
|
workflow_dispatch:
|
||||||
|
inputs:
|
||||||
|
revision:
|
||||||
|
description: "Optional version override for a manual build"
|
||||||
|
required: false
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout full history and tags
|
||||||
|
uses: actions/checkout@v4.2.2
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
- name: Set up pinned Java
|
||||||
|
uses: actions/setup-java@v4.7.1
|
||||||
|
with:
|
||||||
|
distribution: temurin
|
||||||
|
java-version: "17.0.13+11"
|
||||||
|
cache: maven
|
||||||
|
- name: Calculate project version
|
||||||
|
id: version
|
||||||
|
run: |
|
||||||
|
revision=$(sh scripts/version.sh)
|
||||||
|
if [ -n "$REVISION_OVERRIDE" ]; then revision="$REVISION_OVERRIDE"; fi
|
||||||
|
echo "revision=$revision" >> "$GITHUB_OUTPUT"
|
||||||
|
echo "release_needed=$(sh scripts/version.sh --release-needed)" >> "$GITHUB_OUTPUT"
|
||||||
|
echo "release_version=$(sh scripts/version.sh --next-release)" >> "$GITHUB_OUTPUT"
|
||||||
|
env:
|
||||||
|
REVISION_OVERRIDE: ${{ github.event.inputs.revision }}
|
||||||
|
- name: Validate changelog on pull requests
|
||||||
|
if: github.event_name == 'pull_request'
|
||||||
|
run: |
|
||||||
|
sh scripts/check-changelog.sh
|
||||||
|
echo "Changelog preview:"
|
||||||
|
awk '/^## \[Unreleased\]$/ {show=1; next} /^## \[/ {show=0} show {print}' CHANGELOG.md
|
||||||
|
- name: Build and run unit tests
|
||||||
|
env:
|
||||||
|
BUILD_REVISION: ${{ steps.version.outputs.revision }}
|
||||||
|
run: |
|
||||||
|
sh scripts/render-readme.sh "$BUILD_REVISION"
|
||||||
|
sh ./mvnw -B -Drevision="$BUILD_REVISION" verify
|
||||||
|
- name: Upload plugin JAR
|
||||||
|
uses: actions/upload-artifact@v4.6.2
|
||||||
|
with:
|
||||||
|
name: sonar-bifrost-plugin-${{ steps.version.outputs.revision }}
|
||||||
|
path: target/sonar-bifrost-plugin-${{ steps.version.outputs.revision }}.jar
|
||||||
|
if-no-files-found: error
|
||||||
|
- name: Build release version
|
||||||
|
if: github.event_name == 'push' && github.ref == 'refs/heads/main' && steps.version.outputs.release_needed == 'true' && !contains(github.event.head_commit.message, 'chore(release):')
|
||||||
|
env:
|
||||||
|
RELEASE_VERSION: ${{ steps.version.outputs.release_version }}
|
||||||
|
run: |
|
||||||
|
sh scripts/render-readme.sh "$RELEASE_VERSION"
|
||||||
|
sh ./mvnw -B -Drevision="$RELEASE_VERSION" verify
|
||||||
|
- name: Create release commit, tag, and Gitea release
|
||||||
|
if: github.event_name == 'push' && github.ref == 'refs/heads/main' && steps.version.outputs.release_needed == 'true' && !contains(github.event.head_commit.message, 'chore(release):')
|
||||||
|
env:
|
||||||
|
GITEA_TOKEN: ${{ secrets.RELEASE_TOKEN }}
|
||||||
|
GITEA_API_URL: ${{ vars.GITEA_API_URL }}
|
||||||
|
GITEA_REPOSITORY: ${{ github.repository }}
|
||||||
|
GITEA_REPOSITORY_URL: ${{ vars.GITEA_REPOSITORY_URL }}
|
||||||
|
GITEA_MAIN_BRANCH: main
|
||||||
|
RELEASE_VERSION: ${{ steps.version.outputs.release_version }}
|
||||||
|
run: sh scripts/release.sh "$RELEASE_VERSION"
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
target/
|
||||||
|
.flattened-pom.xml
|
||||||
|
*.log
|
||||||
|
.idea/
|
||||||
|
.vscode/
|
||||||
|
dist/
|
||||||
|
node_modules/
|
||||||
|
.env
|
||||||
+2
@@ -0,0 +1,2 @@
|
|||||||
|
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip
|
||||||
|
distributionSha512Sum=8beac8d11ef208f1e2a8df0682b9448a9a363d2ad13ca74af43705549e72e74c9378823bf689287801cbbfc2f6ea9596201d19ccacfdfb682ee8a2ff4c4418ba
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
# Changelog
|
||||||
|
|
||||||
|
All notable changes to this project are documented in this file.
|
||||||
|
|
||||||
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
||||||
|
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||||
|
|
||||||
|
## [Unreleased]
|
||||||
|
|
||||||
|
[Unreleased]: http://localhost:3000/owner/bifrost/compare/v0.1.0...HEAD
|
||||||
+18
@@ -0,0 +1,18 @@
|
|||||||
|
FROM maven:3.9.9-eclipse-temurin-17 AS build
|
||||||
|
WORKDIR /workspace
|
||||||
|
COPY pom.xml .
|
||||||
|
COPY README.md ./README.md
|
||||||
|
COPY src ./src
|
||||||
|
COPY scripts ./scripts
|
||||||
|
COPY .mvn ./.mvn
|
||||||
|
COPY mvnw mvnw
|
||||||
|
COPY mvnw.cmd mvnw.cmd
|
||||||
|
ARG REVISION=
|
||||||
|
RUN version="$REVISION"; if [ -z "$version" ]; then version="$(sh scripts/version.sh)"; fi; \
|
||||||
|
sh scripts/render-readme.sh "$version"; \
|
||||||
|
mvn -B -Drevision="$version" package
|
||||||
|
|
||||||
|
FROM scratch AS export
|
||||||
|
ARG REVISION=
|
||||||
|
COPY --from=build /workspace/target/sonar-bifrost-plugin-*.jar /
|
||||||
|
COPY --from=build /workspace/target/README.md /README.md
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
.PHONY: build test docker-build package clean
|
||||||
|
|
||||||
|
build:
|
||||||
|
@version=$$(sh scripts/version.sh); sh scripts/render-readme.sh "$$version"; sh ./mvnw -B -Drevision="$$version" package
|
||||||
|
|
||||||
|
test:
|
||||||
|
@version=$$(sh scripts/version.sh); sh scripts/render-readme.sh "$$version"; sh ./mvnw -B -Drevision="$$version" test
|
||||||
|
|
||||||
|
docker-build:
|
||||||
|
docker build --target export --output type=local,dest=dist .
|
||||||
|
|
||||||
|
package: build
|
||||||
|
|
||||||
|
clean:
|
||||||
|
sh ./mvnw -B clean
|
||||||
@@ -0,0 +1,151 @@
|
|||||||
|
# Bifrost
|
||||||
|
|
||||||
|
Proof of concept plugin that lists Gitea repositories and creates SonarQube Community Build projects for selected repositories.
|
||||||
|
|
||||||
|
## Target and status
|
||||||
|
|
||||||
|
- SonarQube Community Build: `25.9.0.112764` (minimum tested target is tracked separately from the plugin API manifest field).
|
||||||
|
- Sonar plugin API: `13.0.0.3026`.
|
||||||
|
- Java: 17.
|
||||||
|
- Artifact: `sonar-bifrost-plugin-<version>.jar`.
|
||||||
|
- Generated build version: `@PLUGIN_VERSION@`.
|
||||||
|
- Maven is used because SonarSource publishes the supported plugin packaging extension for Maven.
|
||||||
|
|
||||||
|
The source and deployment scaffolding are present. This environment did not have Java or Maven installed, and Docker could not connect to its engine. The JAR, tests, live Gitea calls, and browser behavior have not been verified here.
|
||||||
|
|
||||||
|
## Tree
|
||||||
|
|
||||||
|
```text
|
||||||
|
.
|
||||||
|
├── .claude/skills/ # Eleven project skills
|
||||||
|
├── .gitea/workflows/build.yml # Gitea Actions CI and release pipeline
|
||||||
|
├── .mvn/wrapper/ # Maven distribution pin
|
||||||
|
├── scripts/ # Version, changelog, and release helpers
|
||||||
|
├── src/main/java/cc/tordais/sonar/bifrost/
|
||||||
|
│ ├── BifrostPlugin.java
|
||||||
|
│ ├── config/BifrostProperties.java
|
||||||
|
│ ├── gitea/GiteaClient.java
|
||||||
|
│ ├── gitea/GiteaRepository.java
|
||||||
|
│ ├── page/ImportPage.java
|
||||||
|
│ ├── service/OrganizationPolicy.java
|
||||||
|
│ ├── service/ProjectKey.java
|
||||||
|
│ └── ws/BifrostWebService.java
|
||||||
|
├── src/main/resources/static/import.js
|
||||||
|
├── src/test/java/cc/tordais/sonar/bifrost/
|
||||||
|
│ ├── gitea/GiteaClientTest.java
|
||||||
|
│ └── service/{OrganizationPolicyTest,ProjectKeyTest}.java
|
||||||
|
├── CHANGELOG.md
|
||||||
|
├── Dockerfile
|
||||||
|
├── docker-compose.yml
|
||||||
|
├── Makefile
|
||||||
|
├── mvnw, mvnw.cmd
|
||||||
|
└── pom.xml
|
||||||
|
```
|
||||||
|
|
||||||
|
## Local build
|
||||||
|
|
||||||
|
The launcher bootstraps the pinned Maven 3.9.9 distribution and verifies its SHA-512 checksum. It requires network access to Maven Central on first use.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
make build
|
||||||
|
```
|
||||||
|
|
||||||
|
On Windows, run `mvnw.cmd -B -Drevision=1.2.3 verify`. To force a version manually, pass `-Drevision=1.2.3` to Maven.
|
||||||
|
|
||||||
|
## Docker build
|
||||||
|
|
||||||
|
Docker builds the plugin using a pinned Maven/JDK image and exports the JAR without a local JDK or Maven installation:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
docker build --target export --output type=local,dest=dist .
|
||||||
|
```
|
||||||
|
|
||||||
|
Pass a version with `--build-arg REVISION=1.2.3`. The build stage uses `scripts/version.sh` when `REVISION` is empty.
|
||||||
|
|
||||||
|
## Install and configure
|
||||||
|
|
||||||
|
1. Copy the JAR to `<sonarqubeHome>/extensions/plugins/` and restart SonarQube. In Docker, mount it at `/opt/sonarqube/extensions/plugins/`.
|
||||||
|
2. In Administration > Configuration, set Gitea URL and token, selection mode, allowed organizations, and the personal repositories option.
|
||||||
|
3. Grant the user the global Create Projects permission.
|
||||||
|
4. Open Import from Gitea, select organizations or All, select repositories, then choose Import.
|
||||||
|
|
||||||
|
The token is held only by the plugin server. Project creation and repository-link creation use same-origin SonarQube REST requests from the logged-in browser session. The plugin API checks the caller's Create Projects permission and revalidates each selected organization before returning approval.
|
||||||
|
|
||||||
|
## Test scenario
|
||||||
|
|
||||||
|
Use the Compose stack for a disposable SonarQube and Gitea setup:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
make build
|
||||||
|
export BIFROST_PLUGIN_JAR="target/sonar-bifrost-plugin-$(sh scripts/version.sh).jar"
|
||||||
|
docker compose up -d
|
||||||
|
```
|
||||||
|
|
||||||
|
Complete Gitea's first-run account setup at `http://localhost:3000`. Create organizations `alpha-lab` and `beta-lab`, then create two repositories in each: `api` and `web`. This deliberately repeats repository names across organizations. Create a token that can read all four repositories and set it in SonarQube's global plugin settings. On SonarQube, grant the test account Create Projects and import the four repositories. Expected keys are `alpha-lab_api`, `alpha-lab_web`, `beta-lab_api`, and `beta-lab_web`; no collision should occur. Try a second pair of names that sanitize to the same key to verify collision feedback.
|
||||||
|
|
||||||
|
The Compose Gitea URL from the SonarQube container is `http://gitea:3000`. The initial settings are blank and must be configured in the UI.
|
||||||
|
|
||||||
|
## Versioning
|
||||||
|
|
||||||
|
Git tags `vMAJOR.MINOR.PATCH` are the release source of truth. Commit subjects follow Conventional Commits. `feat:` requests a minor release, `fix:`, `perf:`, and `refactor:` request a patch, and `!` or a `BREAKING CHANGE:` footer requests a major release. Other types do not request a release.
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
|
||||||
|
- At tag `v1.2.3`: `scripts/version.sh` returns `1.2.3`.
|
||||||
|
- After two commits since `v1.2.3`, without a release-triggering change: it returns `1.2.3-SNAPSHOT.2+<short-sha>`.
|
||||||
|
- With no tags: it returns `0.1.0-SNAPSHOT.<commit-count>+<short-sha>`.
|
||||||
|
- To force a local version: `sh ./mvnw -Drevision=2.0.0-SNAPSHOT package`.
|
||||||
|
|
||||||
|
If the workflow pushes a tag but release publication fails, inspect the tag and changelog commit first. Re-run the release API request for the existing tag after confirming there is no existing release. Do not force-move a published tag. If the tag itself points to the wrong commit, coordinate a deliberate corrective tag/release; do not silently rewrite it.
|
||||||
|
|
||||||
|
## Changelog
|
||||||
|
|
||||||
|
`CHANGELOG.md` follows Keep a Changelog 1.1.0. The intended mapping is `feat:` to Added; `fix:` to Fixed; `perf:` and `refactor:` to Changed; `deprecate:` to Deprecated; `revert:` to Removed; `security:` to Security. Breaking changes are prefixed with **BREAKING:**. `docs:`, `chore:`, `ci:`, `test:`, and `style:` are excluded.
|
||||||
|
|
||||||
|
Edit the `[Unreleased]` entries by hand before release when generated wording needs correction. `sh scripts/changelog.sh X.Y.Z` transfers curated entries or generates entries from Conventional Commits, then updates comparison links using `GITEA_REPOSITORY_URL`. `sh scripts/check-changelog.sh` validates headings, categories, dates, order, and comparison links.
|
||||||
|
|
||||||
|
## CI and releases
|
||||||
|
|
||||||
|
The Gitea Actions workflow checks out full history/tags, installs Java 17, calculates a version, validates changelog formatting on pull requests, runs Maven verification, and uploads the JAR. On a main-branch push, a release commit/tag and Gitea release are created when Conventional Commits request a bump.
|
||||||
|
|
||||||
|
Configure repository variable `GITEA_API_URL` (for example, `https://gitea.example/api/v1`), repository variable `GITEA_REPOSITORY_URL` (the repository web URL), and secret `RELEASE_TOKEN`. The token needs repository write access to push the changelog commit/tag and create a release with an asset. For protected branches, allow this token identity to push the release commit to `main`, or use a dedicated release branch and adjust `GITEA_MAIN_BRANCH`. Actions use GitHub-hosted action sources (`actions/checkout`, `actions/setup-java`, `actions/upload-artifact`); an isolated act_runner may need those repositories mirrored or outbound GitHub access.
|
||||||
|
|
||||||
|
## Skills
|
||||||
|
|
||||||
|
The `.claude/skills/<name>/SKILL.md` files are project instructions:
|
||||||
|
|
||||||
|
- `sonarqube-plugin-development`: entry point, extension lifecycle, manifest, and public API constraints.
|
||||||
|
- `sonarqube-frontend-extension`: page API, UI, bundle, and accessibility.
|
||||||
|
- `java-best-practices`: Java 17 boundaries, immutability, resource handling, and errors.
|
||||||
|
- `java-testing`: deterministic unit tests and HTTP mocking.
|
||||||
|
- `gitea-api-client`: Gitea paths, tokens, pagination, timeouts, and status mapping.
|
||||||
|
- `secure-coding-plugin`: URL/input validation, permissions, secrets, CSRF, and dependencies.
|
||||||
|
- `maven-build-packaging`: pinned Maven build and plugin JAR packaging.
|
||||||
|
- `release-versioning-changelog`: tag bumps, changelog structure, and release flow.
|
||||||
|
- `gitea-actions-ci`: act_runner constraints and release workflow.
|
||||||
|
- `docker-test-environment`: pinned SonarQube, PostgreSQL, Gitea, and plugin mount.
|
||||||
|
- `project-workflow`: language, evidence, implementation order, and definition of done.
|
||||||
|
|
||||||
|
When the SonarQube target changes, update version-sensitive skill claims only after checking official SonarSource docs and target source/artifact metadata. Then update API/compiler/manifest pins, rebuild and inspect the JAR, and rerun each checklist. Skills are guidance, not a substitute for version-specific verification.
|
||||||
|
|
||||||
|
## Troubleshooting
|
||||||
|
|
||||||
|
- **Plugin rejected at startup:** verify the JAR manifest `Plugin-Key`, `Plugin-Version`, and `Sonar-Version` against the target API, then inspect `web.log`.
|
||||||
|
- **No organizations appear:** check the Gitea URL from the SonarQube container, token permissions, organization allowlist, and Gitea logs.
|
||||||
|
- **401 or 403 from Gitea:** replace the token or grant read access to the relevant organization repositories.
|
||||||
|
- **Import denied:** grant the current SonarQube user Create Projects.
|
||||||
|
- **Project exists:** choose a different source repository or remove the existing project; the plugin does not overwrite projects.
|
||||||
|
- **Sanitized key collision:** rename one repository or organization so their sanitized combined keys differ.
|
||||||
|
- **SonarQube does not start in Docker:** check available memory and the host's `vm.max_map_count` requirement for the bundled search engine.
|
||||||
|
|
||||||
|
## Limitations and risks
|
||||||
|
|
||||||
|
- The official plugin API compatibility table omits Community Build 25.9. `13.0.0.3026` is inferred from the target server's published dependency metadata and adjacent releases; a real 25.9 build/startup check remains required.
|
||||||
|
- The manifest `Sonar-Version` denotes the minimum plugin API version. The separate `sonar.minimumVersion` property records the target product release because the documented manifest field does not encode a SonarQube product version.
|
||||||
|
- The UTF-8 plugin display name is set to ASCII `Bifrost` because manifest encoding has not yet been confirmed by inspecting a built JAR.
|
||||||
|
- The page uses public same-origin REST endpoints `api/projects/create` and `api/project_links/create`. Endpoint parameter and permission behavior should be verified on a live 25.9 instance.
|
||||||
|
- Existing-project detection uses the current user's `api/projects/search` visibility. Projects the user cannot browse may appear unimported; duplicate creation is still rejected by SonarQube and reported.
|
||||||
|
- The global page menu is not conditionally hidden by Create Projects permission because the public page API documents only administrator gating. Every data and import web service checks Create Projects; direct same-origin project creation is also enforced by SonarQube. Menu hiding is a UI limitation.
|
||||||
|
- The Gitea token scope and response fields may vary by Gitea version. The local Compose default is Gitea 1.23.8; no external instance was supplied.
|
||||||
|
- The Maven launcher is a small pinned-distribution bootstrap, not the upstream Maven Wrapper JAR implementation. It requires network access for initial Maven download and has not been validated in this environment.
|
||||||
|
- Release scripts and workflow are scaffolding and have not been exercised against a real Gitea runner or protected branch.
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
services:
|
||||||
|
postgres:
|
||||||
|
image: postgres:17.2-alpine3.21
|
||||||
|
environment:
|
||||||
|
POSTGRES_USER: sonar
|
||||||
|
POSTGRES_PASSWORD: sonar-test-only
|
||||||
|
POSTGRES_DB: sonar
|
||||||
|
volumes:
|
||||||
|
- postgres-data:/var/lib/postgresql/data
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "pg_isready -U sonar -d sonar"]
|
||||||
|
interval: 5s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 30
|
||||||
|
|
||||||
|
gitea:
|
||||||
|
image: gitea/gitea:1.23.8
|
||||||
|
environment:
|
||||||
|
USER_UID: 1000
|
||||||
|
USER_GID: 1000
|
||||||
|
GITEA__database__DB_TYPE: sqlite3
|
||||||
|
GITEA__server__ROOT_URL: http://localhost:3000/
|
||||||
|
GITEA__security__INSTALL_LOCK: "true"
|
||||||
|
GITEA__service__DISABLE_REGISTRATION: "false"
|
||||||
|
ports:
|
||||||
|
- "3000:3000"
|
||||||
|
- "2222:22"
|
||||||
|
volumes:
|
||||||
|
- gitea-data:/data
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "curl -fsS http://localhost:3000/api/healthz || exit 1"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 30
|
||||||
|
|
||||||
|
sonarqube:
|
||||||
|
image: sonarqube:25.9.0.112764-community
|
||||||
|
depends_on:
|
||||||
|
postgres:
|
||||||
|
condition: service_healthy
|
||||||
|
environment:
|
||||||
|
SONAR_JDBC_URL: jdbc:postgresql://postgres:5432/sonar
|
||||||
|
SONAR_JDBC_USERNAME: sonar
|
||||||
|
SONAR_JDBC_PASSWORD: sonar-test-only
|
||||||
|
ports:
|
||||||
|
- "9000:9000"
|
||||||
|
volumes:
|
||||||
|
- sonar-data:/opt/sonarqube/data
|
||||||
|
- sonar-logs:/opt/sonarqube/logs
|
||||||
|
- ${BIFROST_PLUGIN_JAR:-./target/sonar-bifrost-plugin-0.1.0-SNAPSHOT.jar}:/opt/sonarqube/extensions/plugins/sonar-bifrost-plugin.jar:ro
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "curl -fsS http://localhost:9000/api/system/status | grep -q UP"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 60
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
postgres-data:
|
||||||
|
gitea-data:
|
||||||
|
sonar-data:
|
||||||
|
sonar-logs:
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
#!/usr/bin/env sh
|
||||||
|
set -eu
|
||||||
|
base_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
|
||||||
|
distribution=3.9.9
|
||||||
|
user_cache=${MAVEN_USER_HOME:-${HOME:-/tmp}/.m2}
|
||||||
|
install_dir="$user_cache/wrapper/dists/apache-maven-$distribution"
|
||||||
|
maven="$install_dir/apache-maven-$distribution/bin/mvn"
|
||||||
|
if [ ! -x "$maven" ]; then
|
||||||
|
mkdir -p "$install_dir"
|
||||||
|
archive="$install_dir/maven.zip"
|
||||||
|
if command -v curl >/dev/null 2>&1; then
|
||||||
|
curl --fail --location --silent --show-error "https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/$distribution/apache-maven-$distribution-bin.zip" -o "$archive"
|
||||||
|
elif command -v wget >/dev/null 2>&1; then
|
||||||
|
wget -q "https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/$distribution/apache-maven-$distribution-bin.zip" -O "$archive"
|
||||||
|
else
|
||||||
|
echo 'curl or wget is required to bootstrap pinned Maven 3.9.9.' >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
expected=8beac8d11ef208f1e2a8df0682b9448a9a363d2ad13ca74af43705549e72e74c9378823bf689287801cbbfc2f6ea9596201d19ccacfdfb682ee8a2ff4c4418ba
|
||||||
|
if command -v sha512sum >/dev/null 2>&1; then actual=$(sha512sum "$archive" | cut -d ' ' -f 1); elif command -v shasum >/dev/null 2>&1; then actual=$(shasum -a 512 "$archive" | cut -d ' ' -f 1); else echo 'sha512sum or shasum is required to verify Maven.' >&2; exit 1; fi
|
||||||
|
[ "$actual" = "$expected" ] || { echo 'Maven distribution checksum verification failed.' >&2; exit 1; }
|
||||||
|
unzip -q -o "$archive" -d "$install_dir"
|
||||||
|
rm -f "$archive"
|
||||||
|
fi
|
||||||
|
exec "$maven" -f "$base_dir/pom.xml" "$@"
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
@echo off
|
||||||
|
setlocal
|
||||||
|
set "MAVEN_VERSION=3.9.9"
|
||||||
|
if not defined MAVEN_USER_HOME set "MAVEN_USER_HOME=%USERPROFILE%\.m2"
|
||||||
|
set "MAVEN_DIR=%MAVEN_USER_HOME%\wrapper\dists\apache-maven-%MAVEN_VERSION%\apache-maven-%MAVEN_VERSION%"
|
||||||
|
set "MAVEN_EXE=%MAVEN_DIR%\bin\mvn.cmd"
|
||||||
|
if not exist "%MAVEN_EXE%" (
|
||||||
|
set "ARCHIVE=%TEMP%\apache-maven-%MAVEN_VERSION%-bin.zip"
|
||||||
|
powershell -NoProfile -ExecutionPolicy Bypass -Command "$ErrorActionPreference='Stop'; Invoke-WebRequest -Uri 'https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/%MAVEN_VERSION%/apache-maven-%MAVEN_VERSION%-bin.zip' -OutFile '%TEMP%\apache-maven-%MAVEN_VERSION%-bin.zip'; New-Item -ItemType Directory -Force -Path '%MAVEN_USER_HOME%\wrapper\dists\apache-maven-%MAVEN_VERSION%' | Out-Null"
|
||||||
|
if errorlevel 1 exit /b 1
|
||||||
|
for /f %%H in ('certutil -hashfile "%TEMP%\apache-maven-%MAVEN_VERSION%-bin.zip" SHA512 ^| findstr /R /V "hash CertUtil"') do set "ACTUAL_SHA512=%%H"
|
||||||
|
if /I not "%ACTUAL_SHA512%"=="8beac8d11ef208f1e2a8df0682b9448a9a363d2ad13ca74af43705549e72e74c9378823bf689287801cbbfc2f6ea9596201d19ccacfdfb682ee8a2ff4c4418ba" exit /b 1
|
||||||
|
powershell -NoProfile -ExecutionPolicy Bypass -Command "Expand-Archive -Force '%TEMP%\apache-maven-%MAVEN_VERSION%-bin.zip' '%MAVEN_USER_HOME%\wrapper\dists\apache-maven-%MAVEN_VERSION%'"
|
||||||
|
)
|
||||||
|
call "%MAVEN_EXE%" -f "%~dp0pom.xml" %*
|
||||||
|
exit /b %ERRORLEVEL%
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
<groupId>cc.tordais.sonar</groupId>
|
||||||
|
<artifactId>sonar-bifrost-plugin</artifactId>
|
||||||
|
<version>${revision}</version>
|
||||||
|
<packaging>sonar-plugin</packaging>
|
||||||
|
<name>Bifrost</name>
|
||||||
|
<properties>
|
||||||
|
<revision>0.1.0-SNAPSHOT</revision>
|
||||||
|
<maven.compiler.release>17</maven.compiler.release>
|
||||||
|
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||||
|
<sonar.plugin.api.version>13.0.0.3026</sonar.plugin.api.version>
|
||||||
|
<pluginApiMinVersion>13.0.0.3026</pluginApiMinVersion>
|
||||||
|
<sonar.minimumVersion>25.9.0.112764</sonar.minimumVersion>
|
||||||
|
<junit.version>5.11.4</junit.version>
|
||||||
|
<assertj.version>3.27.3</assertj.version>
|
||||||
|
<mockito.version>5.15.2</mockito.version>
|
||||||
|
</properties>
|
||||||
|
<dependencies>
|
||||||
|
<dependency><groupId>org.sonarsource.api.plugin</groupId><artifactId>sonar-plugin-api</artifactId><version>${sonar.plugin.api.version}</version><scope>provided</scope></dependency>
|
||||||
|
<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.18.2</version></dependency>
|
||||||
|
<dependency><groupId>org.junit.jupiter</groupId><artifactId>junit-jupiter</artifactId><version>${junit.version}</version><scope>test</scope></dependency>
|
||||||
|
<dependency><groupId>org.assertj</groupId><artifactId>assertj-core</artifactId><version>${assertj.version}</version><scope>test</scope></dependency>
|
||||||
|
<dependency><groupId>org.mockito</groupId><artifactId>mockito-core</artifactId><version>${mockito.version}</version><scope>test</scope></dependency>
|
||||||
|
</dependencies>
|
||||||
|
<build>
|
||||||
|
<finalName>sonar-bifrost-plugin-${revision}</finalName>
|
||||||
|
<plugins>
|
||||||
|
<plugin><groupId>org.sonarsource.sonar-packaging-maven-plugin</groupId><artifactId>sonar-packaging-maven-plugin</artifactId><version>1.23.0.740</version><extensions>true</extensions>
|
||||||
|
<configuration><pluginKey>bifrost</pluginKey><pluginName>Bifrost (Gitea Import)</pluginName><pluginClass>cc.tordais.sonar.bifrost.BifrostPlugin</pluginClass><pluginDescription>Import Gitea repositories as SonarQube projects.</pluginDescription><pluginUrl>http://localhost:3000/owner/bifrost</pluginUrl></configuration>
|
||||||
|
</plugin>
|
||||||
|
<plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>3.13.0</version></plugin>
|
||||||
|
<plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-surefire-plugin</artifactId><version>3.5.2</version></plugin>
|
||||||
|
<plugin><groupId>org.codehaus.mojo</groupId><artifactId>flatten-maven-plugin</artifactId><version>1.6.0</version><configuration><flattenMode>resolveCiFriendliesOnly</flattenMode></configuration><executions><execution><id>flatten</id><phase>process-resources</phase><goals><goal>flatten</goal></goals></execution><execution><id>flatten.clean</id><phase>clean</phase><goals><goal>clean</goal></goals></execution></executions></plugin>
|
||||||
|
<plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-enforcer-plugin</artifactId><version>3.5.0</version><executions><execution><id>require-java</id><goals><goal>enforce</goal></goals><configuration><rules><requireJavaVersion><version>[17,)</version></requireJavaVersion></rules></configuration></execution></executions></plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
</project>
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
#!/usr/bin/env sh
|
||||||
|
set -eu
|
||||||
|
|
||||||
|
version=${1:?Usage: scripts/changelog.sh X.Y.Z}
|
||||||
|
printf '%s\n' "$version" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+$' || { echo 'Version must be X.Y.Z.' >&2; exit 2; }
|
||||||
|
export CHANGELOG_VERSION="$version"
|
||||||
|
export GITEA_REPOSITORY_URL="${GITEA_REPOSITORY_URL:-http://localhost:3000/owner/bifrost}"
|
||||||
|
python_bin=${PYTHON:-python3}
|
||||||
|
"$python_bin" - <<'PY'
|
||||||
|
import datetime
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import subprocess
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
path = Path("CHANGELOG.md")
|
||||||
|
text = path.read_text(encoding="utf-8")
|
||||||
|
version = os.environ["CHANGELOG_VERSION"]
|
||||||
|
base_url = os.environ["GITEA_REPOSITORY_URL"].rstrip("/")
|
||||||
|
today = datetime.date.today().isoformat()
|
||||||
|
if re.search(rf"^## \[{re.escape(version)}\] - ", text, re.M):
|
||||||
|
raise SystemExit(f"Changelog already contains version {version}.")
|
||||||
|
|
||||||
|
heading = "## [Unreleased]"
|
||||||
|
if heading not in text:
|
||||||
|
raise SystemExit("CHANGELOG.md has no Unreleased section.")
|
||||||
|
prefix, remainder = text.split(heading, 1)
|
||||||
|
match = re.search(r"\n## \[\d+\.\d+\.\d+\] - \d{4}-\d{2}-\d{2}\n", remainder)
|
||||||
|
if match:
|
||||||
|
unreleased_body = remainder[:match.start()].strip()
|
||||||
|
old_sections = remainder[match.start():]
|
||||||
|
else:
|
||||||
|
old_sections = ""
|
||||||
|
unreleased_body = remainder.split("\n[Unreleased]:", 1)[0].strip()
|
||||||
|
old_sections = re.split(r"\n\[Unreleased\]:", old_sections, maxsplit=1)[0].strip()
|
||||||
|
|
||||||
|
if not unreleased_body:
|
||||||
|
previous = subprocess.run(["git", "describe", "--tags", "--match", "v[0-9]*.[0-9]*.[0-9]*", "--abbrev=0"], text=True, capture_output=True).stdout.strip()
|
||||||
|
revision = f"{previous}..HEAD" if previous else "HEAD"
|
||||||
|
categories = {"Added": [], "Changed": [], "Deprecated": [], "Removed": [], "Fixed": [], "Security": []}
|
||||||
|
commits = subprocess.run(["git", "log", "--no-merges", "--format=%s%x00%b%x00", revision], text=True, capture_output=True, check=False).stdout.split("\x00")
|
||||||
|
mapping = {"feat": "Added", "fix": "Fixed", "perf": "Changed", "refactor": "Changed", "deprecate": "Deprecated", "revert": "Removed", "security": "Security"}
|
||||||
|
for index in range(0, len(commits) - 1, 2):
|
||||||
|
subject, body = commits[index].strip(), commits[index + 1].strip()
|
||||||
|
parsed = re.match(r"^([a-z]+)(?:\([^)]*\))?(!)?:\s*(.+)$", subject)
|
||||||
|
if not parsed or parsed.group(1) not in mapping:
|
||||||
|
continue
|
||||||
|
kind, breaking_mark, summary = parsed.groups()
|
||||||
|
if kind == "deprecate": category = "Deprecated"
|
||||||
|
elif kind == "revert" or "Removed:" in body: category = "Removed"
|
||||||
|
elif kind == "security" or "Security:" in body: category = "Security"
|
||||||
|
elif "Deprecated:" in body: category = "Deprecated"
|
||||||
|
else: category = mapping[kind]
|
||||||
|
breaking = bool(breaking_mark or re.search(r"^(BREAKING CHANGE|BREAKING-CHANGE):", body, re.M))
|
||||||
|
sentence = summary[0].upper() + summary[1:]
|
||||||
|
if sentence[-1] not in ".!?": sentence += "."
|
||||||
|
if breaking: sentence = "**BREAKING:** " + sentence
|
||||||
|
categories[category].append("- " + sentence)
|
||||||
|
blocks = [f"### {name}\n\n" + "\n".join(entries) for name, entries in categories.items() if entries]
|
||||||
|
unreleased_body = "\n\n".join(blocks)
|
||||||
|
|
||||||
|
tags = subprocess.run(["git", "tag", "--list", "v[0-9]*.[0-9]*.[0-9]*", "--sort=-version:refname"], text=True, capture_output=True).stdout.splitlines()
|
||||||
|
previous = tags[0] if tags else "v0.0.0"
|
||||||
|
existing_versions = re.findall(r"^## \[(\d+\.\d+\.\d+)\] - \d{4}-\d{2}-\d{2}$", old_sections, re.M)
|
||||||
|
new_refs = [f"[Unreleased]: {base_url}/compare/v{version}...HEAD"]
|
||||||
|
new_refs.append(f"[{version}]: {base_url}/compare/{previous or 'v0.0.0'}...v{version}")
|
||||||
|
historical = [item for item in existing_versions if item != version]
|
||||||
|
for index, item in enumerate(historical):
|
||||||
|
prior = "v" + historical[index + 1] if index + 1 < len(historical) else "v0.0.0"
|
||||||
|
new_refs.append(f"[{item}]: {base_url}/compare/{prior}...v{item}")
|
||||||
|
|
||||||
|
parts = [prefix.rstrip(), heading, "", f"## [{version}] - {today}", "", unreleased_body, old_sections, "\n".join(new_refs)]
|
||||||
|
output = "\n".join(part for part in parts if part is not None).rstrip() + "\n"
|
||||||
|
path.write_text(output, encoding="utf-8")
|
||||||
|
PY
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
#!/usr/bin/env sh
|
||||||
|
set -eu
|
||||||
|
file=${1:-CHANGELOG.md}
|
||||||
|
python_bin=${PYTHON:-python3}
|
||||||
|
"$python_bin" - "$file" <<'PY'
|
||||||
|
import datetime
|
||||||
|
import re
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
text = Path(sys.argv[1]).read_text(encoding="utf-8")
|
||||||
|
if not text.startswith("# Changelog\n"):
|
||||||
|
raise SystemExit("Missing Changelog title.")
|
||||||
|
if "Keep a Changelog" not in text or "Semantic Versioning" not in text:
|
||||||
|
raise SystemExit("Missing Keep a Changelog or Semantic Versioning reference.")
|
||||||
|
if not re.search(r"^## \[Unreleased\]$", text, re.M):
|
||||||
|
raise SystemExit("Missing Unreleased section.")
|
||||||
|
|
||||||
|
headings = re.findall(r"^## (.+)$", text, re.M)
|
||||||
|
versions = []
|
||||||
|
for heading in headings:
|
||||||
|
if heading == "[Unreleased]":
|
||||||
|
continue
|
||||||
|
match = re.fullmatch(r"\[(\d+\.\d+\.\d+)\] - (\d{4}-\d{2}-\d{2})", heading)
|
||||||
|
if not match:
|
||||||
|
raise SystemExit(f"Invalid version heading: {heading}")
|
||||||
|
version, date = match.groups()
|
||||||
|
datetime.date.fromisoformat(date)
|
||||||
|
versions.append(version)
|
||||||
|
if versions != sorted(versions, key=lambda value: tuple(map(int, value.split("."))), reverse=True):
|
||||||
|
raise SystemExit("Version sections must be newest first.")
|
||||||
|
|
||||||
|
allowed = {"Added", "Changed", "Deprecated", "Removed", "Fixed", "Security"}
|
||||||
|
for category in re.findall(r"^### (.+)$", text, re.M):
|
||||||
|
if category not in allowed:
|
||||||
|
raise SystemExit(f"Invalid changelog category: {category}")
|
||||||
|
|
||||||
|
links = dict(re.findall(r"^\[([^]]+)\]: (\S+)$", text, re.M))
|
||||||
|
if "Unreleased" not in links:
|
||||||
|
raise SystemExit("Missing Unreleased comparison link.")
|
||||||
|
urls = [links["Unreleased"]] + [links.get(version, "") for version in versions]
|
||||||
|
if any(not url for url in urls):
|
||||||
|
raise SystemExit("A version comparison link is missing.")
|
||||||
|
bases = {url.split("/compare/", 1)[0] for url in urls if "/compare/" in url}
|
||||||
|
if len(bases) != 1 or len(bases) == 0:
|
||||||
|
raise SystemExit("Comparison links must use one repository URL and /compare/ paths.")
|
||||||
|
latest = versions[0] if versions else "0.1.0"
|
||||||
|
if not links["Unreleased"].endswith(f"/compare/v{latest}...HEAD"):
|
||||||
|
raise SystemExit("Unreleased comparison link does not match the latest release.")
|
||||||
|
for index, version in enumerate(versions):
|
||||||
|
previous = "v" + versions[index + 1] if index + 1 < len(versions) else "v0.0.0"
|
||||||
|
expected = f"/compare/{previous}...v{version}"
|
||||||
|
if not links[version].endswith(expected):
|
||||||
|
raise SystemExit(f"Comparison link for {version} must end with {expected}.")
|
||||||
|
print("Changelog format looks valid.")
|
||||||
|
PY
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
#!/usr/bin/env sh
|
||||||
|
set -eu
|
||||||
|
|
||||||
|
version=${1:?Usage: scripts/release.sh X.Y.Z}
|
||||||
|
: "${GITEA_TOKEN:?GITEA_TOKEN secret is required}"
|
||||||
|
: "${GITEA_API_URL:?GITEA_API_URL is required}"
|
||||||
|
: "${GITEA_REPOSITORY:?GITEA_REPOSITORY must be owner/repository}"
|
||||||
|
: "${GITEA_REPOSITORY_URL:?GITEA_REPOSITORY_URL is required}"
|
||||||
|
printf '%s\n' "$version" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+$' || { echo 'Release version must be X.Y.Z.' >&2; exit 2; }
|
||||||
|
|
||||||
|
GITEA_USERNAME=$(curl --fail --silent --show-error -H "Authorization: token $GITEA_TOKEN" "$GITEA_API_URL/user" | jq -r '.login')
|
||||||
|
export GITEA_USERNAME
|
||||||
|
git_push() {
|
||||||
|
askpass=$(mktemp)
|
||||||
|
cat > "$askpass" <<'ASKPASS'
|
||||||
|
#!/usr/bin/env sh
|
||||||
|
case "$1" in
|
||||||
|
*Username*) printf '%s\n' "$GITEA_USERNAME" ;;
|
||||||
|
*) printf '%s\n' "$GITEA_TOKEN" ;;
|
||||||
|
esac
|
||||||
|
ASKPASS
|
||||||
|
chmod 700 "$askpass"
|
||||||
|
if GIT_ASKPASS="$askpass" GIT_TERMINAL_PROMPT=0 git -c credential.helper= -c http.extraheader= push origin "$@"; then result=0; else result=$?; fi
|
||||||
|
rm -f "$askpass"
|
||||||
|
return "$result"
|
||||||
|
}
|
||||||
|
|
||||||
|
latest_subject=$(git log -1 --format=%s)
|
||||||
|
release_commit_version=$(printf '%s' "$latest_subject" | sed -n 's/^chore(release): v\([0-9][0-9.]*\).*/\1/p')
|
||||||
|
tag_exists=false
|
||||||
|
if git rev-parse "v$version" >/dev/null 2>&1; then tag_exists=true; fi
|
||||||
|
|
||||||
|
if [ "$tag_exists" = false ]; then
|
||||||
|
if [ "$release_commit_version" = "$version" ]; then
|
||||||
|
git tag "v$version" HEAD
|
||||||
|
git_push "v$version"
|
||||||
|
elif [ -n "$release_commit_version" ]; then
|
||||||
|
echo "HEAD is already a release commit for v$release_commit_version." >&2
|
||||||
|
exit 1
|
||||||
|
else
|
||||||
|
sh scripts/changelog.sh "$version"
|
||||||
|
git config user.name "Gitea Actions"
|
||||||
|
git config user.email "actions@users.noreply.gitea.local"
|
||||||
|
git add CHANGELOG.md
|
||||||
|
git commit -m "chore(release): v$version [skip ci]"
|
||||||
|
git tag "v$version"
|
||||||
|
git_push "HEAD:${GITEA_MAIN_BRANCH:-main}" "v$version"
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
tagged_subject=$(git log -1 --format=%s "v$version")
|
||||||
|
case "$tagged_subject" in
|
||||||
|
"chore(release): v$version"*) ;;
|
||||||
|
*) echo "Tag v$version does not point at its changelog release commit." >&2; exit 1 ;;
|
||||||
|
esac
|
||||||
|
sh scripts/render-readme.sh "$version"
|
||||||
|
sh ./mvnw -B -Drevision="$version" package
|
||||||
|
fi
|
||||||
|
|
||||||
|
release_body=$(awk -v heading="## [$version] -" 'index($0, heading) == 1 {found=1; next} found && /^## / {exit} found {print}' CHANGELOG.md)
|
||||||
|
payload=$(jq -n --arg tag "v$version" --arg name "v$version" --arg body "$release_body" '{tag_name:$tag,name:$name,body:$body,draft:false,prerelease:false}')
|
||||||
|
existing_release=$(curl --silent -H "Authorization: token $GITEA_TOKEN" "$GITEA_API_URL/repos/$GITEA_REPOSITORY/releases/tags/v$version")
|
||||||
|
if printf '%s' "$existing_release" | jq -e '.id' >/dev/null 2>&1; then
|
||||||
|
release_id=$(printf '%s' "$existing_release" | jq -r '.id')
|
||||||
|
echo "Gitea release v$version already exists; checking its JAR attachment."
|
||||||
|
else
|
||||||
|
release_json=$(curl --fail --silent --show-error -H "Authorization: token $GITEA_TOKEN" -H 'Content-Type: application/json' -d "$payload" "$GITEA_API_URL/repos/$GITEA_REPOSITORY/releases")
|
||||||
|
release_id=$(printf '%s' "$release_json" | jq -r '.id')
|
||||||
|
fi
|
||||||
|
jar=$(find target -maxdepth 1 -name "sonar-bifrost-plugin-$version.jar" -print -quit)
|
||||||
|
[ -n "$jar" ] || { echo 'Release JAR is missing.' >&2; exit 1; }
|
||||||
|
attachments=$(curl --fail --silent --show-error -H "Authorization: token $GITEA_TOKEN" "$GITEA_API_URL/repos/$GITEA_REPOSITORY/releases/$release_id/assets")
|
||||||
|
if printf '%s' "$attachments" | jq -e --arg name "$(basename "$jar")" '.[]? | select(.name == $name)' >/dev/null; then
|
||||||
|
echo "Release v$version already has $(basename "$jar")."
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
curl --fail --silent --show-error -H "Authorization: token $GITEA_TOKEN" -H 'Content-Type: application/octet-stream' --data-binary "@$jar" "$GITEA_API_URL/repos/$GITEA_REPOSITORY/releases/$release_id/assets?name=$(basename "$jar")" >/dev/null
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
#!/usr/bin/env sh
|
||||||
|
set -eu
|
||||||
|
version=${1:-$(sh scripts/version.sh)}
|
||||||
|
printf '%s\n' "$version" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?(\+[0-9A-Za-z.-]+)?$' || { echo 'Invalid plugin version.' >&2; exit 2; }
|
||||||
|
mkdir -p target
|
||||||
|
python_bin=${PYTHON:-python3}
|
||||||
|
"$python_bin" - "$version" <<'PY'
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
version = sys.argv[1]
|
||||||
|
source = Path("README.md").read_text(encoding="utf-8")
|
||||||
|
if "@PLUGIN_VERSION@" not in source:
|
||||||
|
raise SystemExit("README.md is missing the plugin version marker.")
|
||||||
|
Path("target/README.md").write_text(source.replace("@PLUGIN_VERSION@", version), encoding="utf-8")
|
||||||
|
PY
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
#!/usr/bin/env sh
|
||||||
|
set -eu
|
||||||
|
|
||||||
|
tag=$(git describe --tags --match 'v[0-9]*.[0-9]*.[0-9]*' --abbrev=0 2>/dev/null || true)
|
||||||
|
sha=$(git rev-parse --short=8 HEAD 2>/dev/null || printf 'nogit000')
|
||||||
|
|
||||||
|
if [ -n "$tag" ] && git tag --points-at HEAD | grep -Fxq "$tag"; then
|
||||||
|
[ "${1:-}" = "--release-needed" ] && { printf 'false\n'; exit 0; }
|
||||||
|
[ "${1:-}" = "--next-release" ] && { printf '%s\n' "${tag#v}"; exit 0; }
|
||||||
|
printf '%s\n' "${tag#v}"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ -n "$tag" ]; then
|
||||||
|
has_tag=true
|
||||||
|
base=${tag#v}
|
||||||
|
range="$tag..HEAD"
|
||||||
|
commits=$(git rev-list --count "$range")
|
||||||
|
log_range=$range
|
||||||
|
else
|
||||||
|
has_tag=false
|
||||||
|
base=0.1.0
|
||||||
|
log_range=HEAD
|
||||||
|
commits=$(git rev-list --count HEAD 2>/dev/null || printf '0')
|
||||||
|
fi
|
||||||
|
|
||||||
|
major=${base%%.*}
|
||||||
|
remainder=${base#*.}
|
||||||
|
minor=${remainder%%.*}
|
||||||
|
patch=${remainder#*.}
|
||||||
|
bump=0
|
||||||
|
log_file=$(mktemp)
|
||||||
|
trap 'rm -f "$log_file"' EXIT
|
||||||
|
git log --format=%B "$log_range" 2>/dev/null > "$log_file" || :
|
||||||
|
if grep -Eq '^(BREAKING CHANGE:|BREAKING-CHANGE:)|^[a-z]+(\([^)]*\))?!:' "$log_file"; then
|
||||||
|
bump=3
|
||||||
|
elif grep -Eq '^feat(\([^)]*\))?:' "$log_file"; then
|
||||||
|
bump=2
|
||||||
|
elif grep -Eq '^(fix|perf|refactor)(\([^)]*\))?:' "$log_file"; then
|
||||||
|
bump=1
|
||||||
|
fi
|
||||||
|
|
||||||
|
case "$bump" in
|
||||||
|
3) major=$((major + 1)); minor=0; patch=0 ;;
|
||||||
|
2) minor=$((minor + 1)); patch=0 ;;
|
||||||
|
1) patch=$((patch + 1)) ;;
|
||||||
|
esac
|
||||||
|
next="$major.$minor.$patch"
|
||||||
|
|
||||||
|
case "${1:-}" in
|
||||||
|
--release-needed) [ "$bump" -gt 0 ] && printf 'true\n' || printf 'false\n' ;;
|
||||||
|
--next-release) printf '%s\n' "$next" ;;
|
||||||
|
*) if [ "$has_tag" = false ]; then printf '0.1.0-SNAPSHOT.%s+%s\n' "$commits" "$sha"; else printf '%s-SNAPSHOT.%s+%s\n' "$next" "$commits" "$sha"; fi ;;
|
||||||
|
esac
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
package cc.tordais.sonar.bifrost;
|
||||||
|
|
||||||
|
import cc.tordais.sonar.bifrost.config.BifrostProperties;
|
||||||
|
import cc.tordais.sonar.bifrost.page.ImportPage;
|
||||||
|
import cc.tordais.sonar.bifrost.ws.BifrostWebService;
|
||||||
|
import org.sonar.api.Plugin;
|
||||||
|
|
||||||
|
public final class BifrostPlugin implements Plugin {
|
||||||
|
@Override
|
||||||
|
public void define(Context context) {
|
||||||
|
context.addExtensions(BifrostProperties.definitions().toArray());
|
||||||
|
context.addExtensions(ImportPage.class, BifrostWebService.class);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
package cc.tordais.sonar.bifrost.config;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import org.sonar.api.PropertyType;
|
||||||
|
import org.sonar.api.config.PropertyDefinition;
|
||||||
|
|
||||||
|
public final class BifrostProperties {
|
||||||
|
public static final String CATEGORY = "Bifrost (Gitea Import)";
|
||||||
|
public static final String GITEA_URL = "sonar.bifrost.giteaUrl";
|
||||||
|
public static final String GITEA_TOKEN = "sonar.bifrost.giteaToken.secured";
|
||||||
|
public static final String ORG_MODE = "sonar.bifrost.organizationMode";
|
||||||
|
public static final String ORGS = "sonar.bifrost.allowedOrganizations";
|
||||||
|
public static final String INCLUDE_PERSONAL = "sonar.bifrost.includePersonalRepositories";
|
||||||
|
|
||||||
|
private BifrostProperties() {}
|
||||||
|
|
||||||
|
public static List<PropertyDefinition> definitions() {
|
||||||
|
return List.of(
|
||||||
|
PropertyDefinition.builder(GITEA_URL).name("Gitea URL").description("Base URL of the Gitea instance.").category(CATEGORY).index(0).build(),
|
||||||
|
PropertyDefinition.builder(GITEA_TOKEN).name("Gitea token").description("Server-side token used to access repositories.").category(CATEGORY).type(PropertyType.PASSWORD).index(1).build(),
|
||||||
|
PropertyDefinition.builder(ORG_MODE).name("Organization selection mode").description("Choose fixed list or all organizations accessible to the token.").category(CATEGORY).type(PropertyType.SINGLE_SELECT_LIST).defaultValue("fixed").options("fixed", "all").index(2).build(),
|
||||||
|
PropertyDefinition.builder(ORGS).name("Allowed organizations").description("Organization allowlist. Required in fixed mode and applied as an allowlist in all mode.").category(CATEGORY).multiValues(true).index(3).build(),
|
||||||
|
PropertyDefinition.builder(INCLUDE_PERSONAL).name("Include personal repositories").description("Also list repositories owned by the token account.").category(CATEGORY).type(PropertyType.BOOLEAN).defaultValue("false").index(4).build());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
package cc.tordais.sonar.bifrost.gitea;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.URI;
|
||||||
|
import java.net.URLEncoder;
|
||||||
|
import java.net.http.HttpClient;
|
||||||
|
import java.net.http.HttpRequest;
|
||||||
|
import java.net.http.HttpResponse;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public final class GiteaClient {
|
||||||
|
private static final int PAGE_SIZE = 50;
|
||||||
|
private static final int MAX_PAGES = 100;
|
||||||
|
private final URI baseUri;
|
||||||
|
private final String token;
|
||||||
|
private final HttpClient client;
|
||||||
|
private final ObjectMapper mapper = new ObjectMapper();
|
||||||
|
|
||||||
|
public GiteaClient(URI baseUri, String token) {
|
||||||
|
if (!("http".equalsIgnoreCase(baseUri.getScheme()) || "https".equalsIgnoreCase(baseUri.getScheme())) || baseUri.getHost() == null || baseUri.getUserInfo() != null || baseUri.getQuery() != null || baseUri.getFragment() != null) {
|
||||||
|
throw new IllegalArgumentException("Gitea URL must be an absolute HTTP or HTTPS URL without credentials or query parameters.");
|
||||||
|
}
|
||||||
|
this.baseUri = URI.create(baseUri.toString().replaceAll("/$", "") + "/");
|
||||||
|
this.token = token;
|
||||||
|
this.client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).followRedirects(HttpClient.Redirect.NEVER).build();
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<String> organizations() throws IOException, InterruptedException {
|
||||||
|
List<String> names = new ArrayList<>();
|
||||||
|
for (int page = 1; page <= MAX_PAGES; page++) {
|
||||||
|
JsonNode rows = get("api/v1/user/orgs?page=" + page + "&limit=" + PAGE_SIZE);
|
||||||
|
for (JsonNode row : rows) names.add(row.path("username").asText(row.path("name").asText()));
|
||||||
|
if (rows.size() < PAGE_SIZE) return List.copyOf(names);
|
||||||
|
}
|
||||||
|
throw new IOException("Gitea returned too many organization pages.");
|
||||||
|
}
|
||||||
|
|
||||||
|
public String currentUsername() throws IOException, InterruptedException {
|
||||||
|
return get("api/v1/user").path("login").asText();
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<GiteaRepository> personalRepositories() throws IOException, InterruptedException {
|
||||||
|
String username = currentUsername();
|
||||||
|
List<GiteaRepository> repos = new ArrayList<>();
|
||||||
|
for (int page = 1; page <= MAX_PAGES; page++) {
|
||||||
|
JsonNode rows = get("api/v1/user/repos?page=" + page + "&limit=" + PAGE_SIZE);
|
||||||
|
for (JsonNode row : rows) {
|
||||||
|
if (username.equals(row.path("owner").path("login").asText())) {
|
||||||
|
repos.add(new GiteaRepository(username, row.path("name").asText(), row.path("default_branch").asText(), row.path("html_url").asText()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (rows.size() < PAGE_SIZE) return List.copyOf(repos);
|
||||||
|
}
|
||||||
|
throw new IOException("Gitea returned too many personal repository pages.");
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<GiteaRepository> repositories(String organization) throws IOException, InterruptedException {
|
||||||
|
String encoded = URLEncoder.encode(organization, StandardCharsets.UTF_8).replace("+", "%20");
|
||||||
|
List<GiteaRepository> repos = new ArrayList<>();
|
||||||
|
for (int page = 1; page <= MAX_PAGES; page++) {
|
||||||
|
JsonNode rows = get("api/v1/orgs/" + encoded + "/repos?page=" + page + "&limit=" + PAGE_SIZE);
|
||||||
|
for (JsonNode row : rows) {
|
||||||
|
repos.add(new GiteaRepository(organization, row.path("name").asText(), row.path("default_branch").asText(), row.path("html_url").asText()));
|
||||||
|
}
|
||||||
|
if (rows.size() < PAGE_SIZE) return List.copyOf(repos);
|
||||||
|
}
|
||||||
|
throw new IOException("Gitea returned too many repository pages.");
|
||||||
|
}
|
||||||
|
|
||||||
|
private JsonNode get(String path) throws IOException, InterruptedException {
|
||||||
|
HttpRequest request = HttpRequest.newBuilder(baseUri.resolve(path)).timeout(Duration.ofSeconds(15)).header("Authorization", "token " + token).header("Accept", "application/json").GET().build();
|
||||||
|
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
|
||||||
|
if (response.statusCode() == 401) throw new IOException("Gitea rejected the configured token (401).");
|
||||||
|
if (response.statusCode() == 403) throw new IOException("The Gitea token does not have permission to list this resource (403).");
|
||||||
|
if (response.statusCode() == 404) throw new IOException("The requested Gitea organization or resource was not found (404).");
|
||||||
|
if (response.statusCode() == 429) throw new IOException("Gitea rate limit reached (429). Try again later.");
|
||||||
|
if (response.statusCode() >= 500) throw new IOException("Gitea is temporarily unavailable (HTTP " + response.statusCode() + ").");
|
||||||
|
if (response.statusCode() < 200 || response.statusCode() >= 300) throw new IOException("Gitea request failed (HTTP " + response.statusCode() + ").");
|
||||||
|
return mapper.readTree(response.body());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
package cc.tordais.sonar.bifrost.gitea;
|
||||||
|
|
||||||
|
public record GiteaRepository(String organization, String name, String defaultBranch, String htmlUrl) {}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
package cc.tordais.sonar.bifrost.page;
|
||||||
|
|
||||||
|
import org.sonar.api.web.page.Page;
|
||||||
|
import org.sonar.api.web.page.PageDefinition;
|
||||||
|
|
||||||
|
public final class ImportPage implements PageDefinition {
|
||||||
|
@Override
|
||||||
|
public void define(Context context) {
|
||||||
|
context.addPage(Page.builder("bifrost/import").setName("Import from Gitea").build());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
package cc.tordais.sonar.bifrost.service;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Set;
|
||||||
|
|
||||||
|
public final class OrganizationPolicy {
|
||||||
|
private final boolean allMode;
|
||||||
|
private final Set<String> allowlist;
|
||||||
|
|
||||||
|
public OrganizationPolicy(boolean allMode, List<String> allowlist) {
|
||||||
|
this.allMode = allMode;
|
||||||
|
this.allowlist = Set.copyOf(allowlist);
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean permits(String organization, List<String> tokenOrganizations) {
|
||||||
|
if (organization == null || !organization.matches("[A-Za-z0-9][A-Za-z0-9_.-]{0,99}")) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (allMode && !tokenOrganizations.contains(organization)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return allowlist.isEmpty() || allowlist.contains(organization);
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<String> visibleOrganizations(List<String> tokenOrganizations) {
|
||||||
|
if (allMode) {
|
||||||
|
return tokenOrganizations.stream().filter(org -> allowlist.isEmpty() || allowlist.contains(org)).toList();
|
||||||
|
}
|
||||||
|
return allowlist.stream().sorted().toList();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
package cc.tordais.sonar.bifrost.service;
|
||||||
|
|
||||||
|
import java.util.Locale;
|
||||||
|
|
||||||
|
public final class ProjectKey {
|
||||||
|
private ProjectKey() {}
|
||||||
|
|
||||||
|
public static String of(String organization, String repository) {
|
||||||
|
String raw = organization + "_" + repository;
|
||||||
|
String key = raw.replaceAll("[^A-Za-z0-9_.:-]", "_");
|
||||||
|
if (key.isBlank() || !Character.isLetterOrDigit(key.charAt(0))) {
|
||||||
|
key = "_" + key;
|
||||||
|
}
|
||||||
|
return key.toLowerCase(Locale.ROOT);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,139 @@
|
|||||||
|
package cc.tordais.sonar.bifrost.ws;
|
||||||
|
|
||||||
|
import cc.tordais.sonar.bifrost.config.BifrostProperties;
|
||||||
|
import cc.tordais.sonar.bifrost.gitea.GiteaClient;
|
||||||
|
import cc.tordais.sonar.bifrost.gitea.GiteaRepository;
|
||||||
|
import cc.tordais.sonar.bifrost.service.OrganizationPolicy;
|
||||||
|
import cc.tordais.sonar.bifrost.service.ProjectKey;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.URI;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
import org.sonar.api.config.Configuration;
|
||||||
|
import org.sonar.api.server.ws.Request;
|
||||||
|
import org.sonar.api.server.ws.Response;
|
||||||
|
import org.sonar.api.server.ws.WebService;
|
||||||
|
import org.sonar.api.server.ServerSide;
|
||||||
|
import org.sonar.api.user.UserSession;
|
||||||
|
import org.sonar.api.permissions.GlobalPermission;
|
||||||
|
|
||||||
|
@ServerSide
|
||||||
|
public final class BifrostWebService implements WebService {
|
||||||
|
private static final int MAX_IMPORT_ITEMS = 100;
|
||||||
|
private final Configuration configuration;
|
||||||
|
private final UserSession userSession;
|
||||||
|
|
||||||
|
public BifrostWebService(Configuration configuration, UserSession userSession) {
|
||||||
|
this.configuration = configuration;
|
||||||
|
this.userSession = userSession;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void define(Context context) {
|
||||||
|
WebService.NewController controller = context.createController("api/bifrost");
|
||||||
|
controller.createAction("orgs").setDescription("List configured Gitea organizations.").setSince("1.0").setHandler(this::orgs);
|
||||||
|
controller.createAction("repos").setDescription("List repositories for one allowed organization.").setSince("1.0").setHandler(this::repos).createParam("org").setRequired(true).setExampleValue("engineering");
|
||||||
|
controller.createAction("import").setDescription("Validate a bounded repository import selection.").setSince("1.0").setPost(true).setHandler(this::validateImport).createParam("selection").setRequired(true).setDescription("JSON array of organization and repository names.");
|
||||||
|
controller.done();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void orgs(Request request, Response response) throws Exception {
|
||||||
|
requirePermission();
|
||||||
|
GiteaClient client = client();
|
||||||
|
OrganizationPolicy policy = policy();
|
||||||
|
List<String> tokenOrganizations = client.organizations();
|
||||||
|
List<String> visible = new java.util.ArrayList<>(policy.visibleOrganizations(tokenOrganizations));
|
||||||
|
if (configuration.getBoolean(BifrostProperties.INCLUDE_PERSONAL).orElse(false)) visible.add(client.currentUsername());
|
||||||
|
var json = response.newJsonWriter().beginObject().beginArray("organizations");
|
||||||
|
for (String organization : visible) json.value(organization);
|
||||||
|
json.endArray().endObject().close();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void repos(Request request, Response response) throws Exception {
|
||||||
|
requirePermission();
|
||||||
|
String organization = request.mandatoryParam("org");
|
||||||
|
GiteaClient client = client();
|
||||||
|
String username = configuration.getBoolean(BifrostProperties.INCLUDE_PERSONAL).orElse(false) ? client.currentUsername() : "";
|
||||||
|
if (!(organization.equals(username) && !username.isEmpty()) && !policy().permits(organization, client.organizations())) {
|
||||||
|
throw new IllegalArgumentException("The requested organization is not allowed by the plugin configuration.");
|
||||||
|
}
|
||||||
|
List<GiteaRepository> repositories = organization.equals(username) && !username.isEmpty() ? client.personalRepositories() : client.repositories(organization);
|
||||||
|
var json = response.newJsonWriter().beginObject().beginArray("repositories");
|
||||||
|
for (GiteaRepository repository : repositories) {
|
||||||
|
json.beginObject().prop("org", repository.organization()).prop("name", repository.name()).prop("defaultBranch", repository.defaultBranch()).prop("url", repository.htmlUrl()).endObject();
|
||||||
|
}
|
||||||
|
json.endArray().endObject().close();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void validateImport(Request request, Response response) throws Exception {
|
||||||
|
requirePermission();
|
||||||
|
String payload = request.param("selection");
|
||||||
|
if (payload == null || payload.length() > 30_000) throw new IllegalArgumentException("The import selection is missing or too large.");
|
||||||
|
List<ImportSelection> items = ImportSelection.parse(payload);
|
||||||
|
if (items.isEmpty() || items.size() > MAX_IMPORT_ITEMS) throw new IllegalArgumentException("Select between 1 and 100 repositories per import.");
|
||||||
|
GiteaClient client = client();
|
||||||
|
List<String> available = client.organizations();
|
||||||
|
OrganizationPolicy policy = policy();
|
||||||
|
boolean personalEnabled = configuration.getBoolean(BifrostProperties.INCLUDE_PERSONAL).orElse(false);
|
||||||
|
String currentUsername = personalEnabled ? client.currentUsername() : "";
|
||||||
|
for (ImportSelection item : items) {
|
||||||
|
boolean personal = personalEnabled && item.organization().equals(currentUsername);
|
||||||
|
if ((!personal && !policy.permits(item.organization(), available)) || !item.repository().matches("[A-Za-z0-9][A-Za-z0-9_.-]{0,99}")) {
|
||||||
|
throw new IllegalArgumentException("The selection contains an invalid or disallowed repository.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var catalog = new java.util.HashMap<String, List<GiteaRepository>>();
|
||||||
|
for (String organization : items.stream().map(ImportSelection::organization).distinct().toList()) {
|
||||||
|
boolean personal = personalEnabled && organization.equals(currentUsername);
|
||||||
|
catalog.put(organization, personal ? client.personalRepositories() : client.repositories(organization));
|
||||||
|
}
|
||||||
|
var keys = new java.util.HashMap<String, String>();
|
||||||
|
for (ImportSelection item : items) {
|
||||||
|
String identity = item.organization() + "/" + item.repository();
|
||||||
|
boolean repositoryExists = catalog.get(item.organization()).stream().anyMatch(repo -> repo.name().equals(item.repository()));
|
||||||
|
if (!repositoryExists) throw new IllegalArgumentException("Repository " + identity + " is not accessible through the configured Gitea token.");
|
||||||
|
String previous = keys.putIfAbsent(ProjectKey.of(item.organization(), item.repository()), identity);
|
||||||
|
if (previous != null && !previous.equals(identity)) throw new IllegalArgumentException("The selection contains repositories that produce the same SonarQube project key.");
|
||||||
|
}
|
||||||
|
var json = response.newJsonWriter().beginObject().prop("validated", items.size()).beginArray("repositories");
|
||||||
|
for (ImportSelection item : items) {
|
||||||
|
GiteaRepository repository = catalog.get(item.organization()).stream().filter(repo -> repo.name().equals(item.repository())).findFirst().orElseThrow();
|
||||||
|
json.beginObject().prop("org", repository.organization()).prop("repo", repository.name()).prop("name", repository.name()).prop("url", repository.htmlUrl()).prop("defaultBranch", repository.defaultBranch()).endObject();
|
||||||
|
}
|
||||||
|
json.endArray().endObject().close();
|
||||||
|
}
|
||||||
|
|
||||||
|
private GiteaClient client() {
|
||||||
|
String url = configuration.get(BifrostProperties.GITEA_URL).orElseThrow(() -> new IllegalStateException("Configure the Gitea URL in Administration > Configuration."));
|
||||||
|
String token = configuration.get(BifrostProperties.GITEA_TOKEN).orElseThrow(() -> new IllegalStateException("Configure the Gitea token in Administration > Configuration."));
|
||||||
|
return new GiteaClient(URI.create(url), token);
|
||||||
|
}
|
||||||
|
|
||||||
|
private OrganizationPolicy policy() {
|
||||||
|
boolean allMode = "all".equals(configuration.get(BifrostProperties.ORG_MODE).orElse("fixed"));
|
||||||
|
List<String> organizations = Arrays.asList(configuration.getStringArray(BifrostProperties.ORGS));
|
||||||
|
if (!allMode && organizations.isEmpty()) throw new IllegalStateException("Add at least one allowed organization in Administration > Configuration.");
|
||||||
|
return new OrganizationPolicy(allMode, organizations);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void requirePermission() {
|
||||||
|
if (!userSession.hasPermission(GlobalPermission.PROVISION_PROJECTS)) {
|
||||||
|
throw new IllegalStateException("You need the Create Projects permission to use Bifrost.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private record ImportSelection(String organization, String repository) {
|
||||||
|
static List<ImportSelection> parse(String json) throws IOException {
|
||||||
|
var mapper = new com.fasterxml.jackson.databind.ObjectMapper();
|
||||||
|
var root = mapper.readTree(json);
|
||||||
|
if (!root.isArray()) throw new IllegalArgumentException("The import selection must be a JSON array.");
|
||||||
|
java.util.ArrayList<ImportSelection> items = new java.util.ArrayList<>();
|
||||||
|
for (var node : root) {
|
||||||
|
String org = node.path("org").asText();
|
||||||
|
String repo = node.path("repo").asText();
|
||||||
|
items.add(new ImportSelection(org, repo));
|
||||||
|
}
|
||||||
|
return List.copyOf(items);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,183 @@
|
|||||||
|
(function () {
|
||||||
|
window.registerExtension("bifrost/import", function (options) {
|
||||||
|
const root = options.el;
|
||||||
|
const selected = new Map();
|
||||||
|
const resultById = new Map();
|
||||||
|
const tableRows = new Map();
|
||||||
|
let organizations = [];
|
||||||
|
let repositories = [];
|
||||||
|
|
||||||
|
root.innerHTML = "";
|
||||||
|
const heading = document.createElement("h1");
|
||||||
|
heading.textContent = "Import from Gitea";
|
||||||
|
const status = document.createElement("p");
|
||||||
|
status.setAttribute("role", "status");
|
||||||
|
const selectorLabel = document.createElement("label");
|
||||||
|
selectorLabel.textContent = "Organization ";
|
||||||
|
const selector = document.createElement("select");
|
||||||
|
selector.setAttribute("aria-label", "Organization");
|
||||||
|
selectorLabel.appendChild(selector);
|
||||||
|
const selectAll = document.createElement("button");
|
||||||
|
selectAll.type = "button";
|
||||||
|
selectAll.textContent = "Select all (displayed organization)";
|
||||||
|
const importButton = document.createElement("button");
|
||||||
|
importButton.type = "button";
|
||||||
|
importButton.textContent = "Import selected repositories";
|
||||||
|
const table = document.createElement("table");
|
||||||
|
const head = table.createTHead().insertRow();
|
||||||
|
["Select", "Organization", "Repository", "Default branch", "URL", "Status"].forEach(function (name) {
|
||||||
|
const cell = document.createElement("th");
|
||||||
|
cell.scope = "col";
|
||||||
|
cell.textContent = name;
|
||||||
|
head.appendChild(cell);
|
||||||
|
});
|
||||||
|
const body = table.createTBody();
|
||||||
|
root.append(heading, status, selectorLabel, selectAll, importButton, table);
|
||||||
|
|
||||||
|
function keyOf(org, repo) {
|
||||||
|
let value = (org + "_" + repo).replace(/[^A-Za-z0-9_.:-]/g, "_").toLowerCase();
|
||||||
|
if (!/^[a-z0-9]/.test(value)) value = "_" + value;
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
function request(path, init) {
|
||||||
|
return fetch(path, Object.assign({ credentials: "same-origin", headers: { "X-Requested-With": "XMLHttpRequest" } }, init || {}))
|
||||||
|
.then(function (response) {
|
||||||
|
if (!response.ok) return response.text().then(function (text) { throw new Error(text || ("Request failed (" + response.status + ")")); });
|
||||||
|
return response.json();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function repositoryId(repository) {
|
||||||
|
return repository.org + "/" + repository.name;
|
||||||
|
}
|
||||||
|
|
||||||
|
function render() {
|
||||||
|
body.textContent = "";
|
||||||
|
tableRows.clear();
|
||||||
|
repositories.forEach(function (repository) {
|
||||||
|
const row = body.insertRow();
|
||||||
|
const id = repositoryId(repository);
|
||||||
|
const checkbox = document.createElement("input");
|
||||||
|
checkbox.type = "checkbox";
|
||||||
|
checkbox.checked = selected.has(id);
|
||||||
|
checkbox.disabled = repository.alreadyImported === true;
|
||||||
|
checkbox.setAttribute("aria-label", "Select " + repository.org + "/" + repository.name);
|
||||||
|
checkbox.addEventListener("change", function () {
|
||||||
|
if (checkbox.checked) selected.set(id, repository);
|
||||||
|
else selected.delete(id);
|
||||||
|
});
|
||||||
|
row.insertCell().appendChild(checkbox);
|
||||||
|
row.insertCell().textContent = repository.org;
|
||||||
|
row.insertCell().textContent = repository.name;
|
||||||
|
row.insertCell().textContent = repository.defaultBranch || "";
|
||||||
|
const urlCell = row.insertCell();
|
||||||
|
try {
|
||||||
|
const repositoryUrl = new URL(repository.url);
|
||||||
|
if (repositoryUrl.protocol === "http:" || repositoryUrl.protocol === "https:") {
|
||||||
|
const link = document.createElement("a");
|
||||||
|
link.href = repositoryUrl.href;
|
||||||
|
link.textContent = repository.url;
|
||||||
|
link.rel = "noopener noreferrer";
|
||||||
|
urlCell.appendChild(link);
|
||||||
|
} else {
|
||||||
|
urlCell.textContent = "Invalid repository URL";
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
urlCell.textContent = "Invalid repository URL";
|
||||||
|
}
|
||||||
|
row.insertCell().textContent = resultById.get(id) || (repository.alreadyImported ? "Already imported" : "");
|
||||||
|
if (repository.alreadyImported) row.style.opacity = "0.55";
|
||||||
|
tableRows.set(id, checkbox);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function loadRepositories() {
|
||||||
|
const organization = selector.value;
|
||||||
|
status.textContent = "Loading repositories…";
|
||||||
|
const selectedOrganizations = organization === "*" ? organizations : [organization];
|
||||||
|
Promise.all(selectedOrganizations.map(function (org) {
|
||||||
|
return request("/api/bifrost/repos?org=" + encodeURIComponent(org)).then(function (data) { return data.repositories || []; });
|
||||||
|
})).then(function (groups) {
|
||||||
|
repositories = groups.flat();
|
||||||
|
const keys = repositories.map(function (repo) { return keyOf(repo.org, repo.name); });
|
||||||
|
if (!keys.length) return { projects: [] };
|
||||||
|
return request("/api/projects/search?projects=" + encodeURIComponent(keys.join(","))).then(function (data) {
|
||||||
|
const known = new Set((data.components || []).map(function (component) { return component.key; }));
|
||||||
|
repositories.forEach(function (repo) { repo.alreadyImported = known.has(keyOf(repo.org, repo.name)); });
|
||||||
|
});
|
||||||
|
}).then(function () {
|
||||||
|
status.textContent = repositories.length + " repositories displayed.";
|
||||||
|
render();
|
||||||
|
}).catch(function (error) { status.textContent = error.message; });
|
||||||
|
}
|
||||||
|
|
||||||
|
request("/api/bifrost/orgs").then(function (data) {
|
||||||
|
organizations = data.organizations || [];
|
||||||
|
const allOption = document.createElement("option");
|
||||||
|
allOption.value = "*";
|
||||||
|
allOption.textContent = "All organizations";
|
||||||
|
selector.appendChild(allOption);
|
||||||
|
organizations.forEach(function (org) {
|
||||||
|
const option = document.createElement("option");
|
||||||
|
option.value = org;
|
||||||
|
option.textContent = org;
|
||||||
|
selector.appendChild(option);
|
||||||
|
});
|
||||||
|
selector.addEventListener("change", loadRepositories);
|
||||||
|
if (organizations.length) loadRepositories();
|
||||||
|
else status.textContent = "No allowed organizations are configured.";
|
||||||
|
}).catch(function (error) { status.textContent = error.message; });
|
||||||
|
|
||||||
|
selectAll.addEventListener("click", function () {
|
||||||
|
repositories.forEach(function (repository) {
|
||||||
|
if (!repository.alreadyImported) selected.set(repositoryId(repository), repository);
|
||||||
|
});
|
||||||
|
render();
|
||||||
|
});
|
||||||
|
|
||||||
|
importButton.addEventListener("click", function () {
|
||||||
|
const items = Array.from(selected.values());
|
||||||
|
if (!items.length) { status.textContent = "Select at least one repository."; return; }
|
||||||
|
const keys = new Map();
|
||||||
|
for (const item of items) {
|
||||||
|
const key = keyOf(item.org, item.name);
|
||||||
|
if (keys.has(key)) {
|
||||||
|
resultById.set(repositoryId(item), "Error: project key collides with " + keys.get(key) + ".");
|
||||||
|
resultById.set(keys.get(key), "Error: project key collides with " + repositoryId(item) + ".");
|
||||||
|
} else keys.set(key, repositoryId(item));
|
||||||
|
}
|
||||||
|
const collisions = items.filter(function (item) { return (resultById.get(repositoryId(item)) || "").startsWith("Error:"); });
|
||||||
|
const permittedItems = items.filter(function (item) { return !collisions.includes(item); });
|
||||||
|
if (!permittedItems.length) { render(); return; }
|
||||||
|
status.textContent = "Validating selection…";
|
||||||
|
const payload = permittedItems.map(function (item) { return { org: item.org, repo: item.name }; });
|
||||||
|
request("/api/bifrost/import", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ selection: JSON.stringify(payload) }) })
|
||||||
|
.then(function (validation) {
|
||||||
|
const approvedItems = (validation.repositories || []).map(function (repository) {
|
||||||
|
return { org: repository.org, name: repository.repo, url: repository.url, defaultBranch: repository.defaultBranch };
|
||||||
|
});
|
||||||
|
return Promise.all(approvedItems.map(function (item) {
|
||||||
|
const id = repositoryId(item);
|
||||||
|
const key = keyOf(item.org, item.name);
|
||||||
|
return request("/api/projects/create", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ project: key, name: item.name }) })
|
||||||
|
.then(function () {
|
||||||
|
return request("/api/project_links/create", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ projectKey: key, name: "Gitea", url: item.url }) })
|
||||||
|
.then(function () { resultById.set(id, "Created"); })
|
||||||
|
.catch(function () { resultById.set(id, "Created; repository link could not be added"); });
|
||||||
|
})
|
||||||
|
.catch(function (error) {
|
||||||
|
const text = error.message || "";
|
||||||
|
resultById.set(id, /already exists|already been taken|already used/i.test(text) ? "Already exists" : "Error: " + text);
|
||||||
|
});
|
||||||
|
}));
|
||||||
|
}).then(function () {
|
||||||
|
status.textContent = "Import finished.";
|
||||||
|
permittedItems.forEach(function (item) { selected.delete(repositoryId(item)); });
|
||||||
|
loadRepositories();
|
||||||
|
}).catch(function (error) { status.textContent = error.message; render(); });
|
||||||
|
});
|
||||||
|
|
||||||
|
return function () { root.textContent = ""; };
|
||||||
|
});
|
||||||
|
}());
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
package cc.tordais.sonar.bifrost.gitea;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||||
|
|
||||||
|
import com.sun.net.httpserver.HttpServer;
|
||||||
|
import java.net.InetSocketAddress;
|
||||||
|
import java.net.URI;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
|
import org.junit.jupiter.api.AfterEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
class GiteaClientTest {
|
||||||
|
private HttpServer server;
|
||||||
|
|
||||||
|
@AfterEach
|
||||||
|
void stopServer() {
|
||||||
|
if (server != null) server.stop(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void paginatesOrganizationsAndSendsTokenHeader() throws Exception {
|
||||||
|
server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
|
||||||
|
AtomicInteger requests = new AtomicInteger();
|
||||||
|
server.createContext("/api/v1/user/orgs", exchange -> {
|
||||||
|
assertThat(exchange.getRequestHeaders().getFirst("Authorization")).isEqualTo("token test-secret");
|
||||||
|
int page = Integer.parseInt(exchange.getRequestURI().getRawQuery().split("[=&]")[1]);
|
||||||
|
requests.incrementAndGet();
|
||||||
|
String body = page == 1 ? "[" + "{\"username\":\"org" + "\"},".repeat(49) + "{\"username\":\"last\"}]" : "[]";
|
||||||
|
byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
|
||||||
|
exchange.getResponseHeaders().add("Content-Type", "application/json");
|
||||||
|
exchange.sendResponseHeaders(200, bytes.length);
|
||||||
|
exchange.getResponseBody().write(bytes);
|
||||||
|
exchange.close();
|
||||||
|
});
|
||||||
|
server.start();
|
||||||
|
var client = new GiteaClient(URI.create("http://127.0.0.1:" + server.getAddress().getPort()), "test-secret");
|
||||||
|
assertThat(client.organizations()).hasSize(50);
|
||||||
|
assertThat(requests).hasValue(2);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void mapsUnauthorizedResponseWithoutExposingToken() throws Exception {
|
||||||
|
server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
|
||||||
|
server.createContext("/api/v1/user/orgs", exchange -> {
|
||||||
|
exchange.sendResponseHeaders(401, -1);
|
||||||
|
exchange.close();
|
||||||
|
});
|
||||||
|
server.start();
|
||||||
|
var client = new GiteaClient(URI.create("http://127.0.0.1:" + server.getAddress().getPort()), "hidden-value");
|
||||||
|
assertThatThrownBy(client::organizations).hasMessage("Gitea rejected the configured token (401).")
|
||||||
|
.hasMessageNotContaining("hidden-value");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void mapsForbiddenNotFoundAndServerFailures() throws Exception {
|
||||||
|
server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
|
||||||
|
AtomicInteger status = new AtomicInteger(403);
|
||||||
|
server.createContext("/api/v1/user/orgs", exchange -> {
|
||||||
|
exchange.sendResponseHeaders(status.get(), -1);
|
||||||
|
exchange.close();
|
||||||
|
});
|
||||||
|
server.start();
|
||||||
|
var client = new GiteaClient(URI.create("http://127.0.0.1:" + server.getAddress().getPort()), "test-secret");
|
||||||
|
assertThatThrownBy(client::organizations).hasMessage("The Gitea token does not have permission to list this resource (403).");
|
||||||
|
status.set(404);
|
||||||
|
assertThatThrownBy(client::organizations).hasMessage("The requested Gitea organization or resource was not found (404).");
|
||||||
|
status.set(503);
|
||||||
|
assertThatThrownBy(client::organizations).hasMessage("Gitea is temporarily unavailable (HTTP 503).");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
package cc.tordais.sonar.bifrost.service;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
class OrganizationPolicyTest {
|
||||||
|
@Test
|
||||||
|
void fixedModeOnlyAllowsConfiguredOrganizations() {
|
||||||
|
var policy = new OrganizationPolicy(false, List.of("alpha"));
|
||||||
|
assertThat(policy.permits("alpha", List.of("alpha", "beta"))).isTrue();
|
||||||
|
assertThat(policy.permits("beta", List.of("alpha", "beta"))).isFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void allModeStillAppliesConfiguredAllowlist() {
|
||||||
|
var policy = new OrganizationPolicy(true, List.of("alpha"));
|
||||||
|
assertThat(policy.permits("alpha", List.of("alpha", "beta"))).isTrue();
|
||||||
|
assertThat(policy.permits("beta", List.of("alpha", "beta"))).isFalse();
|
||||||
|
assertThat(policy.permits("alpha", List.of("beta"))).isFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void rejectsMalformedOrganizationNames() {
|
||||||
|
assertThat(new OrganizationPolicy(true, List.of()).permits("../admin", List.of("../admin"))).isFalse();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
package cc.tordais.sonar.bifrost.service;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
class ProjectKeyTest {
|
||||||
|
@Test
|
||||||
|
void sanitizesForbiddenCharactersAndNormalizesCase() {
|
||||||
|
assertThat(ProjectKey.of("My Org", "A@B")).isEqualTo("my_org_a_b");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void differentInputsCanBeDetectedAsCollisions() {
|
||||||
|
assertThat(ProjectKey.of("team", "repo/name")).isEqualTo(ProjectKey.of("team", "repo?name"));
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user