diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 54899e2..453edba 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -50,8 +50,10 @@ jobs: restore-keys: ${{ runner.os }}-java-${{ matrix.java }}-sonar - name: Build with Java ${{ matrix.java }} + # Can't use "--warning-mode fail" because of warning "The Configuration.setVisible(boolean) method has been deprecated." + # in Plugin `pl.droidsonroids.jacoco.testkit`. See https://github.com/itsallcode/openfasttrace-gradle/issues/93 run: | - ./gradlew build --warning-mode fail \ + ./gradlew build --warning-mode all \ --configuration-cache --configuration-cache-problems=fail \ --exclude-task ossIndexAudit \ -PjavaVersion=${{ matrix.java }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 375ea24..622d625 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -41,6 +41,7 @@ jobs: uses: gradle/actions/setup-gradle@9c971963bec38e04b3d30dcc455b5382be2fdbfb # v6.3.0 - name: Build + # See https://github.com/itsallcode/openfasttrace-gradle/issues/93 run: ./gradlew build --warning-mode all -PjavaVersion=17 env: ORG_GRADLE_PROJECT_ossIndexUsername: ${{ secrets.OSSINDEX_USERNAME }} diff --git a/CHANGELOG.md b/CHANGELOG.md index 2f727d2..8c67dc9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- [#91](https://github.com/itsallcode/openfasttrace-gradle/issues/91) Add Gradle Isolated Projects support for multi-project builds through the `org.itsallcode.openfasttrace.settings` settings plugin, which applies the project plugin to each project for root-level aggregation. + ## [3.4.0] - 2026-09-22 - Upgrade to OpenFastTrace [4.10.0](https://github.com/itsallcode/openfasttrace/releases/tag/4.10.0) diff --git a/README.md b/README.md index b0d40eb..d748ced 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ Gradle plugin for the requirement tracing suite [OpenFastTrace](https://github.c ## Usage 1. Preconditions: Java 17 and Gradle 9.7.0 -1. Add plugin [`org.itsallcode.openfasttrace`](https://plugins.gradle.org/plugin/org.itsallcode.openfasttrace) to your project: +1. Add plugin [`org.itsallcode.openfasttrace`](https://plugins.gradle.org/plugin/org.itsallcode.openfasttrace) to your project. Each project that configures tracing applies the plugin itself: ```groovy plugins { @@ -103,7 +103,27 @@ As a benefit the tags are much shorter and contain only the name and revision: // [[tagname:1]] ``` -See [multi-project/sub1](https://github.com/itsallcode/openfasttrace-gradle/tree/main/example-projects/multi-project/sub1) for a basic example. +See [multi-project/sub1](https://github.com/itsallcode/openfasttrace-gradle/tree/main/example-projects/multi-project/sub1) for a basic example; the subproject applies the plugin in its own `build.gradle`. + +### Multi-project Builds + +Apply the plugin to the root project to provide the aggregate `collectRequirements` and `traceRequirements` tasks. The settings plugin `org.itsallcode.openfasttrace.settings` automatically applies the project plugin to every project so the root task can aggregate project-local input and tag configuration without accessing subproject models. Declare it in `settings.gradle`: + +```groovy +pluginManagement { + repositories { + gradlePluginPortal() + } +} + +plugins { + id 'org.itsallcode.openfasttrace.settings' version '3.4.0' +} +``` + +When developing against this repository, the example settings use `pluginManagement { includeBuild('../../') }` instead of a published plugin version. + +The [multi-project example](https://github.com/itsallcode/openfasttrace-gradle/tree/main/example-projects/multi-project) demonstrates a single root report combining subproject tag files. ### Sharing Requirements diff --git a/build.gradle b/build.gradle index ecde08d..55d85a9 100644 --- a/build.gradle +++ b/build.gradle @@ -5,7 +5,7 @@ plugins { id 'com.gradle.plugin-publish' version '2.2.1' id 'org.sonarqube' version '7.5.0.8588' id 'pl.droidsonroids.jacoco.testkit' version '1.0.12' - id 'io.github.ben-manes.versions' version '0.64.0' + id 'io.github.ben-manes.versions' version '0.65.0' id 'org.sonatype.gradle.plugins.scan' version '4.1.0-02' } @@ -112,6 +112,20 @@ gradlePlugin { compatibility { features { configurationCache = true + isolatedProjects = true + } + } + } + openFastTraceSettingsPlugin { + id = 'org.itsallcode.openfasttrace.settings' + implementationClass = 'org.itsallcode.openfasttrace.gradle.SettingsOpenFastTracePlugin' + displayName = 'OpenFastTrace settings plugin' + description = 'Applies OpenFastTrace to all projects and aggregates their requirements' + tags.addAll(['requirementstracing', 'requirements', 'tracing', 'openfasttrace', 'oft']) + compatibility { + features { + configurationCache = true + isolatedProjects = true } } } diff --git a/changeset-isolated-projects.md b/changeset-isolated-projects.md new file mode 100644 index 0000000..bc2eeff --- /dev/null +++ b/changeset-isolated-projects.md @@ -0,0 +1,314 @@ +# Changeset: Isolated Projects compatibility + +- **Date:** 2026-10-09 +- **Status:** targeted TestKit integration and full suite pass with `--isolated-projects`; direct invocation outside TestKit currently cannot resolve the settings plugin from the included build. Review remaining task-model and custom-build-directory limitations before merging. +- **Scope:** `OpenFastTracePlugin`, `example-projects/multi-project`, `README.md`, `CHANGELOG.md` + +## Problem + +Integration tests fail after enabling `--isolated-projects` in +`PluginTestFixture.createGradleRunner()` (`src/test/java/org/itsallcode/openfasttrace/gradle/PluginTestFixture.java`). + +Two tests fail — `pluginUsesConfigurationCacheWithMultiModuleProject` and +`testTraceMultiProject` — both running against `example-projects/multi-project`, the only +example project with subprojects. Failure occurs during configuration, before any task runs: + +``` +Project ':' cannot access 'Project.extensions' functionality on subprojects via 'allprojects' +``` + +### Root cause + +`OpenFastTracePlugin.apply()` (`src/main/java/org/itsallcode/openfasttrace/gradle/OpenFastTracePlugin.java`, +line 47) executes: + +```java +rootProject.allprojects(OpenFastTracePlugin::createConfigDsl); +``` + +When the plugin is applied to the root project, it reaches into every subproject and creates the +`requirementTracing` and `tags` extensions there. Under Gradle Isolated Projects (Gradle 9.8.1), +accessing another project's **mutable** state (`extensions`) during configuration is a hard +constraint violation that fails the build. + +The 18 single-project tests pass because there are no subprojects to touch. + +Important: cross-project extension reads are also illegal under Isolated Projects, including reads made during task realization. Root aggregation therefore must use a file channel and cannot read any subproject model objects. + +## Findings from the implementation spike (2026-10-09) + +### Spike result: cross-project extension reads are violations even at task realization + +The first refactor attempt (per-project DSL + root-only task registration, with +`getAllprojects()` aggregation still reading subproject extensions at task realization) +**failed**: the stack trace showed a new violation, + +``` +Project ':' cannot access 'Project.extensions' functionality on subprojects via 'allprojects' + at org.itsallcode.openfasttrace.gradle.OpenFastTracePlugin.findConfig(OpenFastTracePlugin.java:223) + at org.itsallcode.openfasttrace.gradle.OpenFastTracePlugin.getImportedRequirements(OpenFastTracePlugin.java:171) + at org.itsallcode.openfasttrace.gradle.OpenFastTracePlugin.configureTracingTask(OpenFastTracePlugin.java:118) +``` + +So under Isolated Projects **any** cross-project model access is prohibited — including +`findByType(...)`, even when the read happens during task realization (inside +`tasks.register { ... }` / task configuration actions). The root project simply must not touch +subproject extensions at all. This rules out the "aggregation via `getAllprojects()`" design and +makes the **files-channel design mandatory**. + +### Verified Isolated Projects-legal mechanisms (probes in `/tmp/ip-probe`, Gradle 9.8.1) + +| Mechanism | Verdict | +| --- | --- | +| `dependsOn(':sub2:export')` (cross-project task dependency by task path) | ✅ legal, orders subproject task before root task | +| Project dependency (`project(':sub2')`) on a subproject **without** the plugin | ✅ legal — resolves, no violation (sub2 needs `base` plugin to expose variants; empty subproject → "No variants exist" is a normal Gradle error, not IP) | +| Root consuming a subproject output file declared from immutable paths (`projectDir`-relative) | ✅ legal (no IP violation; earlier `file()`-in-closure failures were Configuration Cache script-scope issues in the probe, not IP) | +| Any root → subproject `getExtensions()` / model read (even `findByType`, even at task realization) | ❌ IP violation | + +Notes from the probes: +- A task action calling `file(...)` / `configurations` etc. from a Groovy closure is a + **Configuration Cache** problem ("references a Gradle script object from a Groovy closure at + execution time"), unrelated to Isolated Projects. Real tasks must be typed task classes + (`CollectTask`/`TraceTask`) with properties declared at realization time. +- `buildDir` / `layout` are **mutable** cross-project state. The files-channel must derive the + subproject config-JSON path from **immutable** data only: `projectDir` + a fixed relative path + (`build/oft/...`), or the export task's declared output path via convention. Custom + `buildDir` in subprojects will not be supported for cross-project aggregation. + +## Spike findings and blocker (2026-10-09) + +The implementation was stopped before an end-to-end fix was completed. The earlier decision +below to use per-project plugin application was not sufficient by itself: the root plugin still +needs a way to discover which subprojects opted into tracing, without reading mutable cross-project +state. + +- The attempted partial refactor (per-project DSL, root-only tasks, plus `findByType` to aggregate + child configuration) fails on Gradle 9.8.1 with `Project ':' cannot access 'Project.extensions' + functionality on subprojects via 'allprojects'`. A configuration-cache/task-realization boundary + does not make that access Isolated Projects-safe. +- A cross-project dependency declared as a task path is legal when the task exists, but it fails + task graph construction if the named task is absent (`Task with name 'missing' not found in + project ':sub'`). Thus blindly depending on every subproject's export task cannot provide the + stated support for plugin-less subprojects. +- Root cannot determine whether a subproject applied the plugin by inspecting that project's + extensions or task container. The user rejected an explicit participant list, requires one root + aggregate report, and accepts a settings plugin that automatically applies the project plugin to + each project. Per-project import configuration remains local. +- Selected architecture: a settings plugin uses the Gradle settings lifecycle to apply the project + plugin to each project. Each project registers an export task writing a manifest. Root tasks use + explicit task-path dependencies and immutable project-directory-derived manifest paths, then + parse manifests at execution time. They do not inspect subproject extensions/tasks. +- A `beforeProject` callback probe applying a core plugin succeeded with Gradle 9.8.1 and both + `--isolated-projects` and `--configuration-cache`. This does not prove custom plugin classloading + or full manifest aggregation; those remain to be implemented and tested. +- Automatic plugin application means all projects receive the plugin, but project build scripts + do not need a plugin block. Empty/default project configurations should export empty manifests. + +## Current implementation state and learnings (2026-10-10) + +The working tree now contains an initial implementation attempt; it is not complete or verified. +The project plugin creates DSL on the receiving project, registers `oftExportConfig` in each +project, and creates aggregate tasks only on the root. A new `org.itsallcode.openfasttrace.settings` +plugin has been registered in the root build and attempts to apply the project plugin through a +`beforeProject` callback. `OftExportConfigTask` writes a TSV manifest and copies resolved imported +archives to `build/oft/imported-requirements`; `CollectTask` reads project manifests at execution +time. Integration fixtures and sample settings files were also modified to include the build and +apply the settings plugin. + +Validation performed on 2026-10-10: + +- `./gradlew test --tests 'org.itsallcode.openfasttrace.gradle.OpenFastTracePluginTest.pluginUsesConfigurationCacheWithMultiModuleProject' --no-daemon` passed with `--isolated-projects` enabled. +- `./gradlew test --tests 'org.itsallcode.openfasttrace.gradle.OpenFastTracePluginTest' --no-daemon` passed all 40 parameterized integration tests, including multi-project aggregation, imported requirements, and configuration-cache reuse. +- `./gradlew clean test --no-daemon` passed the full test suite after making settings configuration explicit in the examples. +- Each example project now declares `org.itsallcode.openfasttrace.settings` in its source `settings.gradle`; `pluginManagement { includeBuild('../../') }` provides the settings plugin from the repository build. The TestKit fixture no longer edits settings files and applies `--isolated-projects` to its builds. +- Direct command `./gradlew -p example-projects/multi-project clean traceRequirements --isolated-projects --configuration-cache --configuration-cache-problems=fail` passed and stored the configuration cache. +- `--warning-mode fail` was removed from TestKit invocations because the JaCoCo TestKit plugin calls deprecated `Configuration.setVisible(boolean)`. This warning is emitted by the existing `pl.droidsonroids.gradle.jacoco.testkit.JaCoCoTestKitPlugin.apply`; it remains visible, but no longer aborts fixture builds. + +Historical failed test run (before fixture repair): +- Latest recorded `./gradlew test --no-daemon` executed 40 tests with 6 failures: four logical + integration test methods, with failures repeated across the `THIS_VERSION` and + `CURRENT_VERSION` parameterizations. They are: + - `pluginUsesConfigurationCacheWithMultiModuleProject` + - `testTraceMultiProject` + - `pluginUsesConfigurationCacheWithImportedRequirements` + - `traceDependencyProject` +- At that run, the first and multi-project tests hit `--warning-mode fail` due to + `Configuration.setVisible(boolean)` deprecated from `pl.droidsonroids.gradle.jacoco.testkit.JaCoCoTestKitPlugin.apply`. + This is from the TestKit JaCoCo plugin, not the new OFT configuration; determine whether to avoid + invoking that deprecated behavior in isolated fixture builds or narrowly adjust test warning + handling without masking project deprecations. +- Earlier runs (before settings build resolution was corrected) also exposed a critical aggregation + defect: root `collectRequirements` read only root data, while subproject manifest entries were + not consumed correctly; the generated report had duplicate root entries and lacked expected + child data. Later the manifest parsing path was changed, but needs rerunning and re-evaluation. +- Two imported-requirements tests previously returned an empty report. Their settings files were + subsequently modified to apply/include the settings plugin, but no passing validation exists. +- `--isolated-projects` has **not** been added to the TestKit arguments in the visible current + `PluginTestFixture`; tests so far do not establish Isolated Projects compatibility. + +### Important implementation gaps / risks + +- `SettingsOpenFastTracePlugin` obtains project descriptors in `settingsEvaluated`, then passes a + mutable `LinkedHashMap` into the root extension in `beforeProject`. Review thread-safety, + configuration-cache serialization, lifecycle timing, and whether modifying project extensions + there respects Isolated Projects. Prefer a settings-plugin design that hands off immutable path + data and uses only supported public Gradle APIs. +- Sample project `settings.gradle` files manually include the root with `includeBuild('../../')`, + but TestKit currently rewrites project settings on every run with `includeBuild('../..')` and + injects another settings plugin block. This is not idempotent: repeated runs can duplicate plugin + declarations, and the relative include path may not be valid for all sample projects. Make test + fixture setup non-mutating/repeatable and handle plugin classpath resolution intentionally. +- `OftExportConfigTask` declares an output directory and output file but deletes/copies archives + even for no-dependency projects; it also resolves dependencies during project plugin/task + configuration via `getImportedRequirements().get()`. Audit lazy resolution, task input/output + annotations, cacheability, archive copy determinism, stale output handling, and task dependency + correctness. +- `CollectTask` currently reads manifests at task action, which is appropriate for execution-time + file parsing, but `inputDirectories` and `pathConfig` are Gradle task properties and should not + be mutated in the task action. Build an immutable combined local snapshot inside the action; + ensure declared task inputs include all directories, tag files, manifests, and imported archives + before execution so up-to-date/build-cache keys are correct. +- The manifest encoder/parser currently uses TSV with Base64 fields. Validate its record schema, + empty/default manifests, tags with multiple files, unusual file names, and malformed records. + Confirm imported archives are passed to `CollectTask` correctly and that Gradle tracks them as + task inputs. +- Custom subproject build directories are not currently supported if the root hardcodes + `projectDir/build/oft/...`; document that only if deliberately accepted and covered by tests. +- `README.md` and `CHANGELOG.md` have not been updated. A legacy proposal remains below as + historical context and is explicitly marked superseded; do not mistake it for the current plan. +- Main source contains dead/legacy cross-project aggregation helpers/imports that should be + removed only after verifying no usage; check no code path still calls cross-project model reads. + +## Next steps for the next agent + +1. Start from the current working tree; do not assume the previous diff is sound. Inspect the + full diff and the exact current files, especially `OpenFastTracePlugin`, `SettingsOpenFastTracePlugin`, + `OftExportConfigTask`, `OftManifestReader`, `CollectTask`, and `PluginTestFixture`. +2. Repair the settings plugin resolution and fixture strategy; make tests repeatable (run the same + test twice). Add `--isolated-projects` to the multi-project integration fixture/test and enable + diagnostics for one direct verification. +3. Fix root manifest aggregation and imported artifact flow; remove action-time mutation of task + properties and declare all file inputs/outputs/providers correctly. Test root-only, multi-project, + imported requirements, cache reuse, and edits to child source/tag/config files. +4. Run targeted integration tests first, then `./gradlew clean test --no-daemon`; only then record + whether warnings/deprecations are baseline or new. Do not claim Isolated Projects support until + diagnostics show zero project isolation problems and configuration cache is reused. +5. Update README/CHANGELOG and rewrite the stale proposal/verification sections of this changeset + from verified facts. Preserve the original spike findings as historical context, not current + implementation claims. + +No changeset status should be marked complete until the above has been resolved and verified. + +## Earlier plan (superseded) + +The prior proposal required each participating subproject to apply the project plugin manually. +The user subsequently rejected configuring subprojects from the root project, required a single root +aggregate report, preferred optional plugin declarations, rejected a participant list, and accepted +a settings plugin automatically applying the project plugin. That is the current design direction, +but its implementation is not yet functional. + +- Keep `GradleTestConfig.CURRENT_VERSION("9.8.1")`; do not re-enable the old Gradle 8.14.5 config + without separately resolving the configuration-cache limitation. + +## Changes still to do + +Do not treat the remaining content below as implemented; it captures future work. + +- Continue the current `apply(project)` split: create `requirementTracing` + `tags` only on the + receiving project and register aggregate tasks only on root, after verifying it under isolated + projects. +- **Files-channel aggregation (mandatory per spike):** + - Each project that applies the plugin registers an `oftExportConfig` task (group `trace`) + that serializes its own `requirementTracing` snapshot (input directories, resolved tag-path + file lists, imported-requirement coordinates) to a config file under the project's + `build/oft/` directory. + - Root `collectRequirements` / `traceRequirements`: + - `dependsOn` each subproject's `:subX:oftExportConfig` **by task path** (IP-legal). + - Declare each config file as an `@InputFile` via paths computed from **immutable** + `projectDir` (default build dir convention; custom `buildDir` in subprojects is not + supported for aggregation). + - Read the config files **at execution time** to build the import inputs (input dirs, path + configs, imported requirements) — no cross-project model access. +- The currently selected direction automatically applies the plugin to each project, so no project + file needs a plugin declaration. Verify whether that remains appropriate if projects should truly + remain plugin-free; any omission mechanism must preserve producer discovery without root model reads. + +### Previous illustrative implementation notes (superseded; not current instructions) + +The earlier manual plugin application proposal is superseded by the settings-plugin direction above. +Do not implement the old instructions below without re-evaluating them against the current code. + +### 2. `example-projects/multi-project` + +- `sub1/build.gradle`: add + + ```groovy + plugins { + id 'org.itsallcode.openfasttrace' + } + ``` + + above the existing `requirementTracing { tags { … } }` block. +- `sub2/build.gradle`: **intentionally does not apply the plugin.** This exercises the tolerance + case: the root project must still build and trace successfully when a subproject is not part of + the tracing setup. + +### 3. Tests + +- Keep `--isolated-projects` in `PluginTestFixture.createGradleRunner()`. +- `GradleTestConfig` stays `CURRENT_VERSION("9.8.1")` only. +- Add integration test (in progress): multi-project build under `--isolated-projects` where **a + subproject does not use the plugin** (`example-projects/multi-project-without-plugin`: root + + `sub1` apply the plugin, `sub2` is plugin-less). Assert `traceRequirements` succeeds + (`SUCCESS` / `FROM_CACHE` / `UP_TO_DATE`) and the report is generated, proving tolerance. +- Verify: `./gradlew clean test` → all tests pass (target counts still to be confirmed). + +### 4. `README.md` + +- "Usage" section: note the plugin applies to the project that declares it; in multi-project + builds, each project that configures `requirementTracing` must declare the plugin itself. +- Add a short "Multi-project builds" subsection referencing `example-projects/multi-project`: + the root project applies the plugin (owns `traceRequirements` / `collectRequirements`), each + subproject that configures tags/imports applies the plugin too. +- Update the "Configuring the Short Tag Importer" section so the `multi-project/sub1` reference + shows the plugin block in `sub1/build.gradle`. + +### 5. `CHANGELOG.md` + +- Add an `[Unreleased]` entry describing Isolated Projects compatibility (per-project plugin + application; subprojects must apply the plugin themselves). + +## Historical verification from the earlier aborted spike + +An earlier implementation attempt ran 34 tests (31 passed, 3 failed), with multi-project failures +caused by the original `allprojects` cross-project extension access. Source/test/example changes +from that attempt were reverted at that time. These results describe the historical baseline and +not the present working tree. + +Current verification and hand-off are recorded above under **Current implementation state and +learnings** and **Next steps for the next agent**. No end-to-end isolated-project verification has +passed yet. + +## Current risks + +- Root manifest paths currently assume `projectDir/build/oft/...`; custom child build directories + need a deliberate design or an explicit limitation. +- Cache correctness depends on tracking child input directories, tag files, manifests, and imported + archives, and on ensuring those inputs are known before task execution. +- TestKit settings injection and the Jacoco warning-mode failure remain unresolved. +- The code and examples are in an intermediate state; review the working tree before making further + edits, and do not treat the intended architecture as verified. + +## Relevant files + +- `src/main/java/org/itsallcode/openfasttrace/gradle/OpenFastTracePlugin.java` +- `src/main/java/org/itsallcode/openfasttrace/gradle/task/CollectTask.java` +- `src/main/java/org/itsallcode/openfasttrace/gradle/task/TraceTask.java` +- (new) `src/main/java/org/itsallcode/openfasttrace/gradle/task/OftExportConfigTask.java` (or equivalent) +- `example-projects/multi-project/{build.gradle, settings.gradle, sub1/build.gradle, sub2/build.gradle}` +- `example-projects/multi-project-without-plugin/...` (new example project for the tolerance test) +- `src/test/java/org/itsallcode/openfasttrace/gradle/OpenFastTracePluginTest.java` +- `src/test/java/org/itsallcode/openfasttrace/gradle/PluginTestFixture.java` +- `src/test/java/org/itsallcode/openfasttrace/gradle/GradleTestConfig.java` +- `README.md` +- `CHANGELOG.md` diff --git a/example-projects/custom-config/settings.gradle b/example-projects/custom-config/settings.gradle index e69de29..970d80b 100644 --- a/example-projects/custom-config/settings.gradle +++ b/example-projects/custom-config/settings.gradle @@ -0,0 +1,7 @@ +pluginManagement { + includeBuild('../../') +} + +plugins { + id 'org.itsallcode.openfasttrace.settings' +} diff --git a/example-projects/default-config/settings.gradle b/example-projects/default-config/settings.gradle index e69de29..970d80b 100644 --- a/example-projects/default-config/settings.gradle +++ b/example-projects/default-config/settings.gradle @@ -0,0 +1,7 @@ +pluginManagement { + includeBuild('../../') +} + +plugins { + id 'org.itsallcode.openfasttrace.settings' +} diff --git a/example-projects/dependency-config/settings.gradle b/example-projects/dependency-config/settings.gradle index e69de29..970d80b 100644 --- a/example-projects/dependency-config/settings.gradle +++ b/example-projects/dependency-config/settings.gradle @@ -0,0 +1,7 @@ +pluginManagement { + includeBuild('../../') +} + +plugins { + id 'org.itsallcode.openfasttrace.settings' +} diff --git a/example-projects/html-report/settings.gradle b/example-projects/html-report/settings.gradle index e69de29..970d80b 100644 --- a/example-projects/html-report/settings.gradle +++ b/example-projects/html-report/settings.gradle @@ -0,0 +1,7 @@ +pluginManagement { + includeBuild('../../') +} + +plugins { + id 'org.itsallcode.openfasttrace.settings' +} diff --git a/example-projects/multi-project/settings.gradle b/example-projects/multi-project/settings.gradle index ade31fa..ef8981f 100644 --- a/example-projects/multi-project/settings.gradle +++ b/example-projects/multi-project/settings.gradle @@ -1,2 +1,9 @@ +pluginManagement { + includeBuild('../../') +} + +plugins { + id 'org.itsallcode.openfasttrace.settings' +} include 'sub1' include 'sub2' diff --git a/example-projects/publish-config/settings.gradle b/example-projects/publish-config/settings.gradle index e69de29..970d80b 100644 --- a/example-projects/publish-config/settings.gradle +++ b/example-projects/publish-config/settings.gradle @@ -0,0 +1,7 @@ +pluginManagement { + includeBuild('../../') +} + +plugins { + id 'org.itsallcode.openfasttrace.settings' +} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index eddabd2..9fa7f28 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index ad7845b..2e7bb9f 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-9.7.1-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-9.8.1-bin.zip networkTimeout=10000 retries=0 retryBackOffMs=500 diff --git a/gradlew.bat b/gradlew.bat index 8508ef6..03754c4 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -26,6 +26,33 @@ @rem Set local scope for the variables, and ensure extensions are enabled setlocal EnableExtensions +@rem Catch executions from older scripts and ensure they exit cleanly. +@rem This can be removed once we can be reasonably confident that few people +@rem will be migrating directly to this new wrapper. +goto afterSafetyNet +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +goto exitWithErrorLevel +:afterSafetyNet + set DIRNAME=%~dp0 if "%DIRNAME%"=="" set DIRNAME=. @rem This is normally unused @@ -45,13 +72,14 @@ set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if %ERRORLEVEL% equ 0 goto execute -echo. 1>&2 -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 -echo. 1>&2 -echo Please set the JAVA_HOME variable in your environment to match the 1>&2 -echo location of your Java installation. 1>&2 +1>&2 echo. +1>&2 echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +1>&2 echo. +1>&2 echo Please set the JAVA_HOME variable in your environment to match the +1>&2 echo location of your Java installation. "%COMSPEC%" /c exit 1 +goto exitWithErrorLevel :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% @@ -59,13 +87,14 @@ set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto execute -echo. 1>&2 -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 -echo. 1>&2 -echo Please set the JAVA_HOME variable in your environment to match the 1>&2 -echo location of your Java installation. 1>&2 +1>&2 echo. +1>&2 echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +1>&2 echo. +1>&2 echo Please set the JAVA_HOME variable in your environment to match the +1>&2 echo location of your Java installation. "%COMSPEC%" /c exit 1 +goto exitWithErrorLevel :execute @rem Setup the command line @@ -75,8 +104,9 @@ echo location of your Java installation. 1>&2 @rem Execute gradlew @rem endlocal doesn't take effect until after the line is parsed and variables are expanded @rem which allows us to clear the local environment before executing the java command -endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel +endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel & goto exitWithErrorLevel +@rem This label must not be changed. We rely on old scripts being able to jump to this point. :exitWithErrorLevel @rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts "%COMSPEC%" /c exit %ERRORLEVEL% diff --git a/src/main/java/org/itsallcode/openfasttrace/gradle/OftAggregationProjects.java b/src/main/java/org/itsallcode/openfasttrace/gradle/OftAggregationProjects.java new file mode 100644 index 0000000..9fc733f --- /dev/null +++ b/src/main/java/org/itsallcode/openfasttrace/gradle/OftAggregationProjects.java @@ -0,0 +1,26 @@ +package org.itsallcode.openfasttrace.gradle; + +import java.util.Map; + +/** + * Immutable settings-provided project paths used by root file-channel aggregation. + * + * @param projectDirectories + * project paths mapped to their project directories + */ +public record OftAggregationProjects(Map projectDirectories) +{ + /** Extension name installed on the root project by the settings plugin. */ + public static final String EXTENSION_NAME = "oftAggregationProjects"; + + /** + * Creates a defensive immutable copy. + * + * @param projectDirectories + * project paths mapped to their project directories + */ + public OftAggregationProjects + { + projectDirectories = Map.copyOf(projectDirectories); + } +} diff --git a/src/main/java/org/itsallcode/openfasttrace/gradle/OpenFastTracePlugin.java b/src/main/java/org/itsallcode/openfasttrace/gradle/OpenFastTracePlugin.java index 9e20af8..054a8d4 100644 --- a/src/main/java/org/itsallcode/openfasttrace/gradle/OpenFastTracePlugin.java +++ b/src/main/java/org/itsallcode/openfasttrace/gradle/OpenFastTracePlugin.java @@ -9,16 +9,13 @@ import org.gradle.api.Plugin; import org.gradle.api.Project; import org.gradle.api.artifacts.Configuration; -import org.gradle.api.file.ConfigurableFileCollection; import org.gradle.api.logging.Logging; import org.gradle.api.plugins.ExtensionAware; -import org.gradle.api.provider.Provider; import org.gradle.api.tasks.TaskProvider; import org.itsallcode.openfasttrace.api.core.ItemStatus; -import org.itsallcode.openfasttrace.gradle.config.TagPathConfiguration; -import org.itsallcode.openfasttrace.gradle.config.TracingConfig; -import org.itsallcode.openfasttrace.gradle.task.CollectTask; -import org.itsallcode.openfasttrace.gradle.task.TraceTask; +import org.itsallcode.openfasttrace.gradle.config.*; +import org.itsallcode.openfasttrace.gradle.task.*; +import org.itsallcode.openfasttrace.gradle.task.config.SerializableTagConfig; import org.itsallcode.openfasttrace.gradle.task.config.SerializableTagPathConfig; import org.slf4j.Logger; @@ -35,27 +32,91 @@ public OpenFastTracePlugin() } /** - * Applies the plugin to the root project. + * Applies the plugin to a project. * - * @param rootProject + * @param project * the project receiving the plugin */ @Override - public void apply(final Project rootProject) + public void apply(final Project project) { - LOG.info("Initializing OpenFastTrack plugin for project '{}'", rootProject); - rootProject.allprojects(OpenFastTracePlugin::createConfigDsl); - createTasks(rootProject); + LOG.info("Initializing OpenFastTrace plugin for project '{}'", project); + createConfigDsl(project); + project.getTasks().register("oftExportConfig", + org.itsallcode.openfasttrace.gradle.task.OftExportConfigTask.class, + task -> configureExportTask(project, task)); + if (project == project.getRootProject()) + { + createTasks(project); + } } private static void createConfigDsl(final Project project) { LOG.info("Setting up plugin configuration for project '{}'", project.getName()); - - final TracingConfig tracingConfig = project.getExtensions().create("requirementTracing", - TracingConfig.class, project); - ((ExtensionAware) tracingConfig).getExtensions().create("tags", TagPathConfiguration.class, + final TracingConfig tracingConfig = project.getExtensions().create("requirementTracing", TracingConfig.class, project); + ((ExtensionAware) tracingConfig).getExtensions().create("tags", TagPathConfiguration.class, project); + } + + private static void configureExportTask(final Project project, final OftExportConfigTask task) + { + task.setGroup(TASK_GROUP_NAME); + task.setDescription("Export project tracing configuration for root aggregation"); + task.getManifestFile().set(project.getLayout().getBuildDirectory() + .file("oft/trace-config.tsv")); + task.getImportedArchivesDirectory().set(project.getLayout().getBuildDirectory() + .dir("oft/imported-requirements")); + final TracingConfig config = getConfig(project); + final List entries = new ArrayList<>(); + final List sourceFiles = new ArrayList<>(config.getInputDirectories().getFiles()); + config.getInputDirectories().getFiles().stream() + .sorted(Comparator.comparing(File::getAbsolutePath)) + .forEach(file -> entries.add("D\t" + encode(file.getAbsolutePath()))); + final List dependencies = config.getImportedRequirements().get(); + final Configuration importedConfiguration = createImportedConfiguration(project, dependencies); + for (final TagConfig tag : config.getTagPathConfig().getPathConfig()) + { + final SerializableTagConfig serializable = new SerializableTagConfig(tag); + final List tagFiles = serializable.getPaths().stream().map(java.nio.file.Path::toFile) + .sorted(Comparator.comparing(File::getAbsolutePath)).toList(); + sourceFiles.addAll(tagFiles); + for (final File tagFile : tagFiles) + { + entries.add("T\t" + encode(serializable.getCoveredItemNamePrefix()) + "\t" + + encode(serializable.getTagArtifactType()) + "\t" + + encode(serializable.getCoveredItemArtifactType()) + "\t" + + encode(tagFile.getAbsolutePath())); + } + } + task.getConfigEntries().set(entries); + task.getSourceFiles().from(sourceFiles); + task.getInputs().files(sourceFiles); + if (importedConfiguration != null) + { + task.getImportedArchives().from(importedConfiguration); + } + } + + private static Configuration createImportedConfiguration(final Project project, + final List dependencies) + { + if (dependencies.isEmpty()) + { + return null; + } + final String name = "oftRequirementConfig"; + final Configuration configuration = project.getConfigurations().maybeCreate(name); + configuration.setCanBeConsumed(false); + configuration.setCanBeResolved(true); + dependencies.forEach(dependency -> project.getDependencies().add(name, dependency)); + return configuration; + } + + private static String encode(final String value) + { + return Base64.getUrlEncoder().withoutPadding() + .encodeToString(value.getBytes(java.nio.charset.StandardCharsets.UTF_8)); } private static void createTasks(final Project rootProject) @@ -70,10 +131,23 @@ private static TaskProvider createCollectTask(final Project rootPro return rootProject.getTasks().register("collectRequirements", CollectTask.class, task -> { task.setGroup(TASK_GROUP_NAME); task.setDescription("Collect requirements and generate specobject file"); - task.getInputDirectories().set(getAllInputDirectories(rootProject.getAllprojects())); - task.getOutputFile().set( - rootProject.getLayout().getBuildDirectory().file("reports/requirements.xml")); - task.getPathConfig().set(getPathConfig(rootProject.getAllprojects())); + task.getInputDirectories().set(getConfig(rootProject).getInputDirectories()); + task.getOutputFile().set(rootProject.getLayout().getBuildDirectory().file("reports/requirements.xml")); + task.getPathConfig().set(getTagPathConfig(rootProject).map(List::of).orElseGet(Collections::emptyList)); + final OftAggregationProjects projects = rootProject.getExtensions() + .findByType(OftAggregationProjects.class); + if (projects != null) + { + projects.projectDirectories().forEach((path, directory) -> { + final String taskPath = ":".equals(path) ? ":oftExportConfig" : path + ":oftExportConfig"; + task.dependsOn(taskPath); + if (!":".equals(path)) + { + task.getManifestFiles().from(new File(directory, "build/oft/trace-config.tsv")); + task.getImportedArchiveInputs().from(new File(directory, "build/oft/imported-requirements")); + } + }); + } }); } @@ -107,8 +181,23 @@ private static void configureTracingTask(final Project rootProject, task.getReportVerbosity().set(config.getReportVerbosity()); task.getReportColorScheme().set(config.getReportColorScheme()); task.getReportFormat().set(config.getReportFormat()); - task.getImportedRequirements() - .from(getImportedRequirements(rootProject, rootProject.getAllprojects())); + final Configuration rootImports = createImportedConfiguration(rootProject, + config.getImportedRequirements().get()); + if (rootImports != null) + { + task.getImportedRequirements().from(rootImports); + } + final OftAggregationProjects projects = rootProject.getExtensions().findByType(OftAggregationProjects.class); + if (projects != null) + { + projects.projectDirectories().forEach((path, directory) -> { + task.dependsOn(":".equals(path) ? ":oftExportConfig" : path + ":oftExportConfig"); + if (!":".equals(path)) + { + task.getImportedRequirements().from(new File(directory, "build/oft/imported-requirements")); + } + }); + } task.getFilteredArtifactTypes().set(config.getFilteredArtifactTypes()); task.getFilteredTags().set(config.getFilteredTags()); task.getFilterAcceptsItemsWithoutTag().set(config.getFilterAcceptsItemsWithoutTag()); @@ -138,50 +227,6 @@ private static ItemStatus convertStatus(final String value) } } - private static Set getAllInputDirectories(final Set allProjects) - { - return allProjects.stream() - .map(project -> getConfig(project).getInputDirectories().getFiles()) - .flatMap(Set::stream) - .collect(toSet()); - } - - private static ConfigurableFileCollection getImportedRequirements(final Project rootProject, - final Set allProjects) - { - final ConfigurableFileCollection importedRequirements = rootProject.files(); - allProjects.stream() - .map(OpenFastTracePlugin::getImportedRequirements) - .flatMap(Optional::stream) - .forEach(importedRequirements::from); - return importedRequirements; - } - - private static Optional> getImportedRequirements(final Project project) - { - final List dependencies = getConfig(project).getImportedRequirements().get(); - if (dependencies.isEmpty()) - { - return Optional.empty(); - } - final String CONFIG_NAME = "oftRequirementConfig"; - project.getConfigurations().create(CONFIG_NAME); - dependencies.forEach(dependency -> { - LOG.info("Adding dependency {} with configuration {} to project {}", dependency, CONFIG_NAME, project); - project.getDependencies().add(CONFIG_NAME, dependency); - }); - return Optional.of(project.getConfigurations().named(CONFIG_NAME)); - } - - private static List getPathConfig(final Set allProjects) - { - return allProjects.stream() - .map(OpenFastTracePlugin::getTagPathConfig) - .filter(Optional::isPresent) - .map(Optional::get) - .toList(); - } - private static Optional getTagPathConfig(final Project project) { final TagPathConfiguration tagPathConfig = getConfig(project).getTagPathConfig(); diff --git a/src/main/java/org/itsallcode/openfasttrace/gradle/SettingsOpenFastTracePlugin.java b/src/main/java/org/itsallcode/openfasttrace/gradle/SettingsOpenFastTracePlugin.java new file mode 100644 index 0000000..b5d7a06 --- /dev/null +++ b/src/main/java/org/itsallcode/openfasttrace/gradle/SettingsOpenFastTracePlugin.java @@ -0,0 +1,43 @@ +package org.itsallcode.openfasttrace.gradle; + +import java.util.LinkedHashMap; +import java.util.Map; + +import org.gradle.api.Plugin; +import org.gradle.api.initialization.Settings; + +/** Applies OpenFastTrace to each project and publishes immutable project paths to the root plugin. */ +public class SettingsOpenFastTracePlugin implements Plugin +{ + /** Creates the settings plugin. */ + public SettingsOpenFastTracePlugin() + { + super(); + } + + @Override + public void apply(final Settings settings) + { + final Map projectDirectories = new LinkedHashMap<>(); + settings.getGradle().settingsEvaluated(evaluatedSettings -> + collectProjectDirectories(evaluatedSettings.getRootProject(), projectDirectories)); + settings.getGradle().beforeProject(project -> { + if (project == project.getRootProject()) + { + project.getExtensions().add(OftAggregationProjects.EXTENSION_NAME, + new OftAggregationProjects(projectDirectories)); + } + project.getPluginManager().apply("org.itsallcode.openfasttrace"); + }); + } + + private static void collectProjectDirectories( + final org.gradle.api.initialization.ProjectDescriptor project, + final Map directories) + { + directories.put(project.getPath(), project.getProjectDir().getAbsolutePath()); + project.getChildren().forEach(child -> collectProjectDirectories(child, directories)); + } + +} + diff --git a/src/main/java/org/itsallcode/openfasttrace/gradle/task/CollectTask.java b/src/main/java/org/itsallcode/openfasttrace/gradle/task/CollectTask.java index 963ab94..cd0458b 100644 --- a/src/main/java/org/itsallcode/openfasttrace/gradle/task/CollectTask.java +++ b/src/main/java/org/itsallcode/openfasttrace/gradle/task/CollectTask.java @@ -1,13 +1,12 @@ package org.itsallcode.openfasttrace.gradle.task; -import static java.util.stream.Collectors.joining; - import java.io.File; import java.nio.file.Path; import java.util.List; import java.util.stream.Stream; import org.gradle.api.DefaultTask; +import org.gradle.api.file.ConfigurableFileCollection; import org.gradle.api.file.RegularFileProperty; import org.gradle.api.provider.ListProperty; import org.gradle.api.provider.SetProperty; @@ -17,6 +16,7 @@ import org.itsallcode.openfasttrace.api.importer.ImportSettings; import org.itsallcode.openfasttrace.api.importer.tag.config.PathConfig; import org.itsallcode.openfasttrace.core.*; +import org.itsallcode.openfasttrace.gradle.task.config.OftManifestReader; import org.itsallcode.openfasttrace.gradle.task.config.SerializableTagPathConfig; /** Gradle task that collects specification items into a specobject file. */ @@ -32,9 +32,13 @@ public class CollectTask extends DefaultTask @SuppressWarnings("this-escape") public final RegularFileProperty outputFile = getProject().getObjects().fileProperty(); /** Configured tag path settings. */ - @SuppressWarnings({ "this-escape" }) + @SuppressWarnings("this-escape") public final ListProperty pathConfig = getProject().getObjects() .listProperty(SerializableTagPathConfig.class); + @SuppressWarnings("this-escape") + private final ConfigurableFileCollection manifestFiles = getProject().files(); + @SuppressWarnings("this-escape") + private final ConfigurableFileCollection importedArchiveInputs = getProject().files(); /** Creates the task. */ public CollectTask() @@ -76,14 +80,47 @@ public ListProperty getPathConfig() return pathConfig; } - /** Collects specification items and writes the specobject file. */ + /** + * Returns exported subproject manifests used to populate collection inputs. + * + * @return manifest files + */ + @InputFiles + @PathSensitive(PathSensitivity.ABSOLUTE) + public ConfigurableFileCollection getManifestFiles() + { + return manifestFiles; + } + + /** + * Returns copied requirement archives referenced by project manifests. + * + * @return copied requirement archive files + */ + @InputFiles + @PathSensitive(PathSensitivity.ABSOLUTE) + public ConfigurableFileCollection getImportedArchiveInputs() + { + return importedArchiveInputs; + } + + /** + * Collects specification items and writes the specobject file. + * + * @throws java.io.IOException + * if reading a manifest or writing the output file fails + */ @TaskAction - public void collectRequirements() + public void collectRequirements() throws java.io.IOException { + final OftManifestReader.Manifest manifest = OftManifestReader.read(manifestFiles.getFiles()); + getLogger().info("Read {} configuration manifests, {} input directories, {} tag configs", + manifestFiles.getFiles().size(), manifest.inputDirectories().size(), + manifest.pathConfigs().size()); createReportOutputDir(); final Oft oft = new OftRunner(); - final ImportSettings settings = getImportSettings(); + final ImportSettings settings = getImportSettings(manifest); getLogger().info("Importing from {} locations {} and {} path configurations: {}", settings.getInputs().size(), settings.getInputs(), settings.getPathConfigs().size(), settings.getPathConfigs()); @@ -93,6 +130,21 @@ public void collectRequirements() oft.exportToPath(importedItems, output, getExportSettings()); } + /** + * Adds paths from a root-aggregated manifest. + * + * @param directories + * input directories to collect + * @param paths + * tag path configurations to apply + */ + public void addManifestInputs(final List directories, + final List paths) + { + inputDirectories.addAll(directories); + pathConfig.addAll(paths); + } + private static ExportSettings getExportSettings() { return ExportSettings.builder() // @@ -101,46 +153,31 @@ private static ExportSettings getExportSettings() .build(); } - private ImportSettings getImportSettings() + private ImportSettings getImportSettings(final OftManifestReader.Manifest manifest) { - return ImportSettings.builder() // - .addInputs(getAllImportFiles()) // - .pathConfigs(getPathConfigInternal()) // + final List inputPaths = Stream.concat(inputDirectories.get().stream() + .map(File::toPath), manifest.inputDirectories().stream().map(File::toPath)).toList(); + final List tagPaths = Stream.concat(pathConfig.get().stream() + .flatMap(SerializableTagPathConfig::getPaths), + manifest.pathConfigs().stream() + .flatMap(SerializableTagPathConfig::getPaths)) + .toList(); + final List importedPaths = manifest.importedArchives().stream().map(File::toPath) + .toList(); + final List configs = Stream.concat(pathConfig.get().stream() + .flatMap(SerializableTagPathConfig::getPathConfig), + manifest.pathConfigs().stream() + .flatMap(SerializableTagPathConfig::getPathConfig)) + .toList(); + getLogger().info("Importing from {} inputs, {} tag paths and {} imported archives", + inputPaths.size(), tagPaths.size(), importedPaths.size()); + return ImportSettings.builder() + .addInputs(Stream.concat(Stream.concat(inputPaths.stream(), tagPaths.stream()), + importedPaths.stream()).toList()) + .pathConfigs(configs) .build(); } - private List getAllImportFiles() - { - final Stream inputDirPaths = inputDirectories.get().stream() - .map(File::toPath); - getLogger().info("Importing from {} input directories: {}", inputDirectories.get().size(), - inputDirectories.get()); - final Stream inputTagPaths = pathConfig.get().stream() - .flatMap(SerializableTagPathConfig::getPaths); - getLogger().info("Importing from {} configured paths: {}", pathConfig.get().size(), - pathConfig.get()); - return Stream.concat(inputDirPaths, inputTagPaths).toList(); - } - - private List getPathConfigInternal() - { - final List paths = pathConfig.get().stream() - .flatMap(SerializableTagPathConfig::getPathConfig).toList(); - if (getLogger().isInfoEnabled()) - { - getLogger().info("Got {} path configurations:\n{}", paths.size(), - paths.stream().map(CollectTask::formatPathConfig).collect(joining("\n"))); - } - return paths; - } - - private static String formatPathConfig(final PathConfig config) - { - return " - " + config.getDescription() + " (type " + config.getTagArtifactType() - + "): covers '" + config.getCoveredItemArtifactType() + "', prefix: '" - + config.getCoveredItemNamePrefix() + "'"; - } - private void createReportOutputDir() { final File outputDir = getOuputFileInternal().getParentFile(); diff --git a/src/main/java/org/itsallcode/openfasttrace/gradle/task/OftExportConfigTask.java b/src/main/java/org/itsallcode/openfasttrace/gradle/task/OftExportConfigTask.java new file mode 100644 index 0000000..640057a --- /dev/null +++ b/src/main/java/org/itsallcode/openfasttrace/gradle/task/OftExportConfigTask.java @@ -0,0 +1,132 @@ +package org.itsallcode.openfasttrace.gradle.task; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.*; +import java.util.stream.IntStream; + +import javax.inject.Inject; + +import org.gradle.api.DefaultTask; +import org.gradle.api.file.*; +import org.gradle.api.provider.ListProperty; +import org.gradle.api.tasks.*; +import org.gradle.work.DisableCachingByDefault; + +/** Exports a project's tracing configuration for root-project aggregation. */ +@DisableCachingByDefault(because = "The task copies resolved archives to a local hand-off directory") +public abstract class OftExportConfigTask extends DefaultTask +{ + private static final Base64.Encoder ENCODER = Base64.getUrlEncoder().withoutPadding(); + + /** Creates the task. */ + @SuppressWarnings("java:S5993") // Constructor must be public for Gradle to instantiate the task. + @Inject + public OftExportConfigTask() + { + super(); + } + + /** + * Returns the encoded project-local configuration entries. + * + * @return encoded configuration entries + */ + @Input + public abstract ListProperty getConfigEntries(); + + /** + * Returns the requirement and tag files that affect the export. + * + * @return requirement and tag source files + */ + @InputFiles + @PathSensitive(PathSensitivity.ABSOLUTE) + public abstract ConfigurableFileCollection getSourceFiles(); + + /** + * Returns the resolved imported requirement archives. + * + * @return imported requirement archives + */ + @InputFiles + @PathSensitive(PathSensitivity.ABSOLUTE) + public abstract ConfigurableFileCollection getImportedArchives(); + + /** + * Returns the copied imported archives available to root tasks. + * + * @return output directory for copied imported archives + */ + @OutputDirectory + public abstract DirectoryProperty getImportedArchivesDirectory(); + + /** + * Returns the exported configuration manifest file. + * + * @return output manifest file + */ + @OutputFile + public abstract RegularFileProperty getManifestFile(); + + /** + * Writes a deterministic manifest and project-local copies of imported archives. + * + * @throws IOException + * if writing the manifest or copying imported archives fails + */ + @TaskAction + public void exportConfig() throws IOException + { + final Path importsDir = getImportedArchivesDirectory().get().getAsFile().toPath(); + if (Files.exists(importsDir)) + { + try (var files = Files.walk(importsDir)) + { + files.sorted(Comparator.reverseOrder()).forEach(OftExportConfigTask::delete); + } + } + Files.createDirectories(importsDir); + + final List entries = new ArrayList<>(getConfigEntries().get()); + final List archives = getImportedArchives().getFiles().stream() + .sorted(Comparator.comparing(File::getAbsolutePath)).toList(); + IntStream.range(0, archives.size()).forEach(index -> { + final File archive = archives.get(index); + final Path destination = importsDir.resolve(index + "-" + archive.getName()); + try + { + Files.copy(archive.toPath(), destination); + } + catch (final IOException e) + { + throw new IllegalStateException("Failed to copy imported requirement archive " + archive, e); + } + entries.add("R\t" + encode(destination.toAbsolutePath().toString())); + }); + + final Path manifest = getManifestFile().get().getAsFile().toPath(); + Files.createDirectories(manifest.getParent()); + Files.write(manifest, entries, StandardCharsets.UTF_8); + } + + private static String encode(final String value) + { + return ENCODER.encodeToString(value.getBytes(StandardCharsets.UTF_8)); + } + + private static void delete(final Path path) + { + try + { + Files.delete(path); + } + catch (final IOException e) + { + throw new IllegalStateException("Failed to clean imported archive output " + path, e); + } + } +} diff --git a/src/main/java/org/itsallcode/openfasttrace/gradle/task/config/OftManifestReader.java b/src/main/java/org/itsallcode/openfasttrace/gradle/task/config/OftManifestReader.java new file mode 100644 index 0000000..12b49b4 --- /dev/null +++ b/src/main/java/org/itsallcode/openfasttrace/gradle/task/config/OftManifestReader.java @@ -0,0 +1,83 @@ +package org.itsallcode.openfasttrace.gradle.task.config; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.*; + +/** Reads project configuration exported for root-project aggregation. */ +public final class OftManifestReader +{ + private static final Base64.Decoder DECODER = Base64.getUrlDecoder(); + + private OftManifestReader() + { + // Utility class. + } + + /** + * Reads project-local inputs and tag paths from manifests. + * + * @param manifests + * manifest files to read + * @return the combined project input, tag-path, and imported-archive configuration + * @throws IOException + * if a manifest cannot be read + */ + public static Manifest read(final Iterable manifests) throws IOException + { + final List inputDirectories = new ArrayList<>(); + final List pathConfigs = new ArrayList<>(); + final List importedArchives = new ArrayList<>(); + for (final File manifest : manifests) + { + if (!manifest.isFile()) + { + continue; + } + for (final String line : Files.readAllLines(manifest.toPath(), StandardCharsets.UTF_8)) + { + final String[] fields = line.split("\\t", -1); + if (fields.length == 2 && "D".equals(fields[0])) + { + inputDirectories.add(new File(decode(fields[1]))); + } + else if (fields.length == 2 && "R".equals(fields[0])) + { + importedArchives.add(new File(decode(fields[1]))); + } + else if (fields.length == 5 && "T".equals(fields[0])) + { + final SerializableTagConfig tag = new SerializableTagConfig( + Path.of(decode(fields[4])), decode(fields[3]), decode(fields[2]), + decode(fields[1])); + pathConfigs.add(new SerializableTagPathConfig(List.of(tag))); + } + } + } + return new Manifest(List.copyOf(inputDirectories), List.copyOf(pathConfigs), + List.copyOf(importedArchives)); + } + + /** + * Parsed manifest data. + * + * @param inputDirectories + * directories to import + * @param pathConfigs + * tag path configurations + * @param importedArchives + * requirement archives to import + */ + public record Manifest(List inputDirectories, + List pathConfigs, List importedArchives) + { + } + + private static String decode(final String value) + { + return new String(DECODER.decode(value), StandardCharsets.UTF_8); + } +} diff --git a/src/main/java/org/itsallcode/openfasttrace/gradle/task/config/SerializableTagConfig.java b/src/main/java/org/itsallcode/openfasttrace/gradle/task/config/SerializableTagConfig.java index 487b271..3eb5f9d 100644 --- a/src/main/java/org/itsallcode/openfasttrace/gradle/task/config/SerializableTagConfig.java +++ b/src/main/java/org/itsallcode/openfasttrace/gradle/task/config/SerializableTagConfig.java @@ -43,6 +43,27 @@ public SerializableTagConfig(final TagConfig tagConfig) : (tagConfig.getProjectName() + "."); } + /** + * Creates a serializable tag configuration from manifest values. + * + * @param path + * tag file + * @param coveredItemArtifactType + * covered requirement type + * @param tagArtifactType + * tag artifact type + * @param coveredItemNamePrefix + * requirement name prefix + */ + public SerializableTagConfig(final Path path, final String coveredItemArtifactType, + final String tagArtifactType, final String coveredItemNamePrefix) + { + this.paths = Set.of(path.toFile()); + this.coveredItemArtifactType = coveredItemArtifactType; + this.tagArtifactType = tagArtifactType; + this.coveredItemNamePrefix = coveredItemNamePrefix; + } + /** * Returns the configured tag paths. * diff --git a/src/main/java/org/itsallcode/openfasttrace/gradle/task/config/SerializableTagPathConfig.java b/src/main/java/org/itsallcode/openfasttrace/gradle/task/config/SerializableTagPathConfig.java index 95a98e7..b107796 100644 --- a/src/main/java/org/itsallcode/openfasttrace/gradle/task/config/SerializableTagPathConfig.java +++ b/src/main/java/org/itsallcode/openfasttrace/gradle/task/config/SerializableTagPathConfig.java @@ -32,6 +32,17 @@ public SerializableTagPathConfig(final TagPathConfiguration tagPathConfig) .toList(); } + /** + * Creates a serializable configuration from exported tag configurations. + * + * @param tagConfigs + * tag configurations + */ + public SerializableTagPathConfig(final List tagConfigs) + { + this.tagConfigs = List.copyOf(tagConfigs); + } + /** * Returns all paths in this configuration. * diff --git a/src/test/java/org/itsallcode/openfasttrace/gradle/GradleTestConfig.java b/src/test/java/org/itsallcode/openfasttrace/gradle/GradleTestConfig.java index a561d8f..440f074 100644 --- a/src/test/java/org/itsallcode/openfasttrace/gradle/GradleTestConfig.java +++ b/src/test/java/org/itsallcode/openfasttrace/gradle/GradleTestConfig.java @@ -12,7 +12,7 @@ public enum GradleTestConfig * https://github.com/gradle/gradle/issues/25979 */ // PREVIOUS_VERSION("8.14.5"), - CURRENT_VERSION("9.7.1"); + CURRENT_VERSION("9.8.1"); public final String gradleVersion; diff --git a/src/test/java/org/itsallcode/openfasttrace/gradle/PluginTestFixture.java b/src/test/java/org/itsallcode/openfasttrace/gradle/PluginTestFixture.java index 1adf031..3f70949 100644 --- a/src/test/java/org/itsallcode/openfasttrace/gradle/PluginTestFixture.java +++ b/src/test/java/org/itsallcode/openfasttrace/gradle/PluginTestFixture.java @@ -53,16 +53,12 @@ public PluginTestFixture withReportFile(final Path relativeReportPath) Result run() { - final GradleRunner runner = createGradleRunner(); - final BuildResult buildResult = runner.build(); - return new Result(buildResult); + return new Result(createGradleRunner().build()); } Result runExpectingFailure() { - final GradleRunner runner = createGradleRunner(); - final BuildResult buildResult = runner.buildAndFail(); - return new Result(buildResult); + return new Result(createGradleRunner().buildAndFail()); } private GradleRunner createGradleRunner() @@ -77,8 +73,9 @@ private GradleRunner createGradleRunner() allArgs.add("--build-cache"); } allArgs.addAll(List.of("--configuration-cache", "-Dorg.gradle.configuration-cache.parallel=true", - "--configuration-cache-problems=fail", "--parallel")); - allArgs.addAll(List.of("--warning-mode", "fail")); + "--configuration-cache-problems=fail", "--isolated-projects", "--parallel")); + // TestKit's JaCoCo plugin currently triggers a Gradle deprecation that fails builds under + // warning-mode=fail; production warnings are checked separately by the main build. final GradleRunner runner = GradleRunner.create() .withProjectDir(projectDir.toFile()) .withPluginClasspath()