Compare commits

..

154 Commits

Author SHA1 Message Date
Daz DeBoer
6c7537229b Merge pull request #1026 from gradle/dd/java-toolchains
Use Maven toolchains.xml to register pre-installed JDKs as java toolchains
2024-01-04 05:34:34 +01:00
daz
650620f9f9 Build outputs 2024-01-03 21:12:13 -07:00
daz
d4e24dfc10 Register pre-installed JDKs in .m2/toolchains.xml
Since adding these to the `org.gradle.java.installations.fromEnv` property
is problematic (#1024), this mechanism allows the default toolchains to
be discovered by Gradle via a different mechanism.

The default JDK installations are added to `~/.m2/toolchains.xml` such that
they are discoverable by Gradle toolchain support.
The `setup-java` action also writes to this file, so we merge with any existing
content: this allows both pre-installed and "setup" JDKs to be automatically
detected by Gradle.
2024-01-03 21:08:40 -07:00
daz
7c57ba1136 Remove writing value to gradle.properties in setup
The written property will override any project-level setting, which
can lead to confusing behaviour.

Fixes #1024
2024-01-03 18:49:57 -07:00
Daz DeBoer
32bab5b15a Allow entries with same Job ID to match in different workflows
Previously, the workflow name was always included when matching a cache entry for the current job.
This can be overly restrictive when job definitions are shared between different workflows. 
The workflow name is still encoded in the cache entry key, but not in the restore key searching for entries with a matching job.

Fixes #1017
2024-01-03 18:38:36 -07:00
daz
270f30ba56 Always initialize encryption key 2024-01-02 14:28:29 -07:00
daz
c00a847f3f Enable config-cache tests
- Enable in full-build
- Pass encryption key secret to test workflow
2024-01-02 11:31:06 -07:00
daz
e2aa3f332c Test with Gradle 8.6-rc-1 2024-01-01 19:29:46 -07:00
dependabot[bot]
ff5d63e9dc Bump the npm-dependencies group with 3 updates
Bumps the npm-dependencies group with 3 updates: [@typescript-eslint/parser](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/parser), [eslint-plugin-jest](https://github.com/jest-community/eslint-plugin-jest) and [eslint-plugin-prettier](https://github.com/prettier/eslint-plugin-prettier).

Updates `@typescript-eslint/parser` from 6.15.0 to 6.17.0
- [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases)
- [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/parser/CHANGELOG.md)
- [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v6.17.0/packages/parser)

Updates `eslint-plugin-jest` from 27.6.0 to 27.6.1
- [Release notes](https://github.com/jest-community/eslint-plugin-jest/releases)
- [Changelog](https://github.com/jest-community/eslint-plugin-jest/blob/main/CHANGELOG.md)
- [Commits](https://github.com/jest-community/eslint-plugin-jest/compare/v27.6.0...v27.6.1)

Updates `eslint-plugin-prettier` from 5.1.1 to 5.1.2
- [Release notes](https://github.com/prettier/eslint-plugin-prettier/releases)
- [Changelog](https://github.com/prettier/eslint-plugin-prettier/blob/master/CHANGELOG.md)
- [Commits](https://github.com/prettier/eslint-plugin-prettier/compare/v5.1.1...v5.1.2)

---
updated-dependencies:
- dependency-name: "@typescript-eslint/parser"
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: npm-dependencies
- dependency-name: eslint-plugin-jest
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: npm-dependencies
- dependency-name: eslint-plugin-prettier
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: npm-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-01-01 17:54:53 -07:00
Daz DeBoer
4faac45dc8 Merge pull request #1021 from gradle/dd/pr-comment
Automatically add Job Summary as PR comment
2024-01-02 01:51:30 +01:00
daz
45ed60450e Build outputs 2024-01-01 17:50:40 -07:00
daz
72abd931ce Set workflow permissions where required 2024-01-01 17:50:40 -07:00
daz
a4107da76d Warn when permissions not set for PR comment 2024-01-01 17:50:40 -07:00
daz
d16a3f4093 Update docs for PR comment 2024-01-01 17:50:40 -07:00
daz
333078158e Allow job-summary only on failure
Instead of a binary true/false option, it is now possible to only add
a Job Summary when the build failed. This applies both to the overall
Job Summary added to the workflow run, and to the new PR comment feature.
2024-01-01 17:50:40 -07:00
daz
34a07dced0 Automatically add Job Summary as PR comment
Rather than requiring a separate step to add a PR comment,
the `gradle-build-action` can now automatically add the Job Summary
as a PR comment

Fixes #1020
2024-01-01 17:50:15 -07:00
daz
24e9e9dc6b Refactor and simplify summary generation 2023-12-31 15:12:04 -07:00
Goooler
bc72ac9e9d Use actions/setup-java v4 in doc
https://github.com/actions/setup-java/releases/tag/v4.0.0

Signed-off-by: Goooler <wangzongler@gmail.com>
2023-12-31 21:18:55 +01:00
Daz DeBoer
c791d32284 Reference 8.6-rc-1 in docs 2023-12-31 13:17:35 -07:00
Daz DeBoer
ceb0c736c1 Document using secret for encryption key 2023-12-31 13:13:44 -07:00
Daz DeBoer
3f2ca32cb0 Document configuration-cache support 2023-12-26 18:29:50 -07:00
Daz DeBoer
5d2dd0dea4 Merge pull request #1012 from gradle/dd/artifact-lib-update
Update to actions/artifact v2.0.0
2023-12-24 05:35:16 +01:00
Daz DeBoer
e865911745 Merge pull request #1005 from gradle/dependabot/gradle/dot-github/workflow-samples/kotlin-dsl/com.google.guava-guava-33.0.0-jre
Bump com.google.guava:guava from 32.1.3-jre to 33.0.0-jre in /.github/workflow-samples/kotlin-dsl
2023-12-24 05:27:49 +01:00
daz
0538e78c32 Build outputs 2023-12-23 21:25:47 -07:00
daz
a4dabb3a70 Adapt dependency-graph support for new artifact API
- Don't upload artifacts when using 'generate-and-submit'
- New option 'generate-and-upload' to be used with 'download-and-submit'
- Use Artifact API for downloading in the same and different workflow
2023-12-23 21:24:11 -07:00
daz
51b7a82e8e Update to latest artifact lib 2023-12-23 21:23:57 -07:00
daz
92cb3fe7e8 Build outputs 2023-12-23 18:25:52 -07:00
daz
e843ea4565 Update NPM dependencies 2023-12-23 18:25:51 -07:00
dependabot[bot]
14b4921945 Bump the github-actions group with 3 updates
Bumps the github-actions group with 3 updates: [github/codeql-action](https://github.com/github/codeql-action), [gradle/gradle-build-action](https://github.com/gradle/gradle-build-action) and [actions/upload-artifact](https://github.com/actions/upload-artifact).


Updates `github/codeql-action` from 2 to 3
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/github/codeql-action/compare/v2...v3)

Updates `gradle/gradle-build-action` from 2.10.0 to 2.11.0
- [Release notes](https://github.com/gradle/gradle-build-action/releases)
- [Commits](https://github.com/gradle/gradle-build-action/compare/v2.10.0...v2.11.0)

Updates `actions/upload-artifact` from 3 to 4
- [Release notes](https://github.com/actions/upload-artifact/releases)
- [Commits](https://github.com/actions/upload-artifact/compare/v3...v4)

---
updated-dependencies:
- dependency-name: github/codeql-action
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: github-actions
- dependency-name: gradle/gradle-build-action
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: github-actions
- dependency-name: actions/upload-artifact
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: github-actions
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-12-23 18:25:51 -07:00
daz
9c7269b85b Update to latest Develocity plugins 2023-12-23 18:25:50 -07:00
Daz DeBoer
a7b743845f Merge pull request #968 : Prepare for version 3.x
Contains all functionality planned for the initial 3.x release.

- Fixes #726 
- Fixes #946 
- Fixes #966 
- Fixes #996
2023-12-23 20:43:34 +01:00
daz
e6566cde89 Build outputs 2023-12-23 12:31:17 -07:00
daz
89f8dcd819 Complete deprecation of direct Gradle execution
- Deprecate `build-root-directory` and `gradle-executable` parameters
- Remove examples from README
2023-12-23 12:22:44 -07:00
daz
93050d1483 Improvements to cache reporting
- Avoid "Entry not saved: reason unknown" when entry was not restored
- Avoid "Entry not saved: Encryption key not provided" when no config-cache data found
- Avoid spurious log message when no config-cache data found
2023-12-23 12:21:27 -07:00
daz
df38ec05e0 Use 'release-nightly' for config-cache test
Config-cache save/restore is dependent on Gradle 8.6.
Use of the release-nightly is temporary until 8.6 is released.
2023-12-23 12:21:19 -07:00
daz
b3f092e821 Avoid saving config-cache from Gradle < 8.6
Earlier versions of Gradle didn't support the `GRADLE_ENCRYPTION_KEY`
for the configuration-cache, and so are either not useful to save,
or are actually unsafe due to unencrypted secrets.

We use semver to compare the Gradle version used to produce the config-cache
entry with the minimum Gradle version required.
2023-12-23 09:13:46 -07:00
daz
63ce84df08 Don't create entry for non-existant directory
- Filter out config-cache directories that do not exist when constructing
  cache entry definitions
2023-12-23 09:12:30 -07:00
daz
57f3f23714 Improve non-restore behavior for config-cache
- Avoid logging "not restoring" message when no entries exist to restore
- Clear the entries from metadata when they are not restored. This ensures that
  the non-restored entries are correctly purged.
2023-12-23 09:08:40 -07:00
daz
38785d7d62 Update integ test for config-cache caching
- Rename test for clarity
- Use cache-encryption-key in config-cache test
2023-12-22 12:52:09 -07:00
daz
a738af78ea Provide cache-encryption-key as action input
This makes it easier for users to enable config-cache saving in their workflow.

Config-cache data will only be saved/restored when the key is provided,
and the key is exported as `GRADLE_ENCRYPTION_KEY` for use in subsequent steps.
2023-12-22 12:52:09 -07:00
daz
ae24bf6608 Log completion of post-action step 2023-12-20 19:46:02 -07:00
daz
334a4b8d4d Reinstate configuration-cache save/restore capability 2023-12-20 17:31:01 -07:00
daz
009bd36b91 Exclude cc-keystore from Gradle User Home 2023-12-20 17:31:01 -07:00
daz
9d6738618d Support wildcards in cache-excludes 2023-12-20 10:05:25 -07:00
daz
f053e6b7e7 Deprecate the arguments parameter
Fixes #996
2023-12-20 09:57:20 -07:00
daz
c821b7c4f1 Update to run on Node 20 2023-12-20 09:57:18 -07:00
daz
982da8e78c Attempt to make init-script compatible with Gradle 1.12
The `PluginManager` type wasn't introduced until Gradle 2.x.
Remove this type from the method signature in an attempt to allow this
file to be parsed with Gradle 1.12.
2023-12-19 14:12:27 -07:00
daz
a0fc8606d2 Build outputs 2023-12-19 14:08:34 -07:00
daz
a1980784de Improve reporting for dependency-graph failure
The previous message was assuming a permissions issue, and was not
including the underlying error message in the response.
2023-12-19 14:05:20 -07:00
dependabot[bot]
89e46180c6 Bump com.google.guava:guava in /.github/workflow-samples/kotlin-dsl
Bumps [com.google.guava:guava](https://github.com/google/guava) from 32.1.3-jre to 33.0.0-jre.
- [Release notes](https://github.com/google/guava/releases)
- [Commits](https://github.com/google/guava/commits)

---
updated-dependencies:
- dependency-name: com.google.guava:guava
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-12-18 22:30:59 +00:00
Daz DeBoer
f95e9c7459 Clarify dependency-graph example 2023-12-12 10:48:54 -07:00
daz
8cbcb9948b Plugin repository URL is configurable
The repository URL used to resolve the `github-dependency-graph-gradle-plugin` is now
configurable, allowing a user to specify an internal proxy if the public portal is not available.

Specify a custom plugin repository using the `GRADLE_PLUGIN_REPOSITORY_URL` env var,
or the `gradle.plugin-repository.url` System property.

Fixes #933
2023-12-11 21:15:34 -07:00
daz
a71aff6a12 Handle failure in cache-cleanup
Do not abort the remainder of the post-action on failure in cache-cleanup.
Instead, just log a warning and continue.

Fixes #858
Fixes #990
2023-12-11 20:38:28 -07:00
daz
77699bae74 Handle failure writing build-results file
Fixes #866
2023-12-11 20:18:58 -07:00
daz
dc5927259f Merge branch 'dd/dependency-updates'
* dd/dependency-updates:
  Bumps the npm-dependencies group with 5 updates:
  Bump the github-actions group with 2 updates
  Bump from Gradle 8.4 to Gradle 8.5
2023-12-11 19:49:28 -07:00
daz
4f0075d967 Clarify docs for dedicated workflow
Fixes #976
2023-12-11 19:48:32 -07:00
daz
e1f9864a52 Bumps the npm-dependencies group with 5 updates:
| Package | From | To |
    | --- | --- | --- |
    | [@types/jest](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/jest) | `29.5.8` | `29.5.11` |
    | [@typescript-eslint/parser](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/parser) | `6.12.0` | `6.14.0` |
    | [eslint](https://github.com/eslint/eslint) | `8.54.0` | `8.55.0` |
    | [prettier](https://github.com/prettier/prettier) | `3.1.0` | `3.1.1` |
    | [typescript](https://github.com/Microsoft/TypeScript) | `5.3.2` | `5.3.3` |
2023-12-11 19:43:02 -07:00
dependabot[bot]
76d5a9b475 Bump the github-actions group with 2 updates
Bumps the github-actions group with 2 updates: [actions/setup-java](https://github.com/actions/setup-java) and [gradle/gradle-build-action](https://github.com/gradle/gradle-build-action).


Updates `actions/setup-java` from 3 to 4
- [Release notes](https://github.com/actions/setup-java/releases)
- [Commits](https://github.com/actions/setup-java/compare/v3...v4)

Updates `gradle/gradle-build-action` from 2.9.0 to 2.10.0
- [Release notes](https://github.com/gradle/gradle-build-action/releases)
- [Commits](https://github.com/gradle/gradle-build-action/compare/v2.9.0...v2.10.0)

---
updated-dependencies:
- dependency-name: actions/setup-java
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: github-actions
- dependency-name: gradle/gradle-build-action
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: github-actions
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-12-11 19:23:45 -07:00
daz
39d8c6d06e Bump from Gradle 8.4 to Gradle 8.5 2023-12-11 18:33:39 -07:00
Kengo TODA
0280eb7de5 docs: upload build reports even when build failed
Signed-off-by: Kengo TODA <skypencil@gmail.com>
2023-11-28 04:50:00 +01:00
daz
87a9a15658 Use 1.0.0 release of dependency graph plugin 2023-11-27 17:46:35 +10:00
Daz DeBoer
375481748b Document artifact-retention-days 2023-11-26 19:46:29 -07:00
daz
beff1c573c Update dev dependencies 2023-11-27 12:28:37 +10:00
dependabot[bot]
21a3ebb55f Bump com.fasterxml.jackson.dataformat:jackson-dataformat-smile
Bumps [com.fasterxml.jackson.dataformat:jackson-dataformat-smile](https://github.com/FasterXML/jackson-dataformats-binary) from 2.15.3 to 2.16.0.
- [Commits](https://github.com/FasterXML/jackson-dataformats-binary/compare/jackson-dataformats-binary-2.15.3...jackson-dataformats-binary-2.16.0)

---
updated-dependencies:
- dependency-name: com.fasterxml.jackson.dataformat:jackson-dataformat-smile
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-11-27 03:20:34 +01:00
dependabot[bot]
a5be560235 Bump the github-actions group with 2 updates
Bumps the github-actions group with 2 updates: [gradle/gradle-build-action](https://github.com/gradle/gradle-build-action) and [actions/github-script](https://github.com/actions/github-script).


Updates `gradle/gradle-build-action` from 2.8.1 to 2.9.0
- [Release notes](https://github.com/gradle/gradle-build-action/releases)
- [Commits](https://github.com/gradle/gradle-build-action/compare/v2.8.1...v2.9.0)

Updates `actions/github-script` from 6 to 7
- [Release notes](https://github.com/actions/github-script/releases)
- [Commits](https://github.com/actions/github-script/compare/v6...v7)

---
updated-dependencies:
- dependency-name: gradle/gradle-build-action
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: github-actions
- dependency-name: actions/github-script
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: github-actions
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-11-27 03:20:09 +01:00
Daz DeBoer
9bca466e27 Make artifact retention configurable
- Added a new `artifact-retention-days` input parameter to control retention of uploaded artifacts
- Artifacts retention will use repository settings if not overridden.
2023-11-09 00:06:31 -07:00
Daz DeBoer
f757bcfd86 Merge pull request #951 from gradle/dd/v2.9.1
Update dependencies
2023-11-09 06:19:22 +01:00
daz
8b6c211905 Bump to RC of github dependency graph plugin 2023-11-08 21:11:42 -08:00
daz
8db1c7621b Build outputs 2023-11-08 21:02:15 -08:00
daz
6eaacfc06c Update NPM dependencies 2023-11-08 21:02:15 -08:00
dependabot[bot]
750905c0ed Bump @babel/traverse from 7.21.3 to 7.23.2
Bumps [@babel/traverse](https://github.com/babel/babel/tree/HEAD/packages/babel-traverse) from 7.21.3 to 7.23.2.
- [Release notes](https://github.com/babel/babel/releases)
- [Changelog](https://github.com/babel/babel/blob/main/CHANGELOG.md)
- [Commits](https://github.com/babel/babel/commits/v7.23.2/packages/babel-traverse)

---
updated-dependencies:
- dependency-name: "@babel/traverse"
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-11-08 21:02:15 -08:00
daz
d5fbcc8361 Bump java dependency versions in tests 2023-11-08 21:02:15 -08:00
daz
0e761ca2b4 Bump to Gradle 8.4 for tests and samples 2023-11-08 21:02:15 -08:00
daz
6b7c087721 Bump version of Develocity plugins 2023-11-08 20:35:00 -08:00
Matthew Haughton
0bfe00a136 Fix typos in README
Signed-off-by: Matthew Haughton <3flex@users.noreply.github.com>
2023-10-12 21:33:54 +02:00
Daz DeBoer
62cce3c597 FIx dependency review example in README 2023-09-30 18:24:45 -06:00
Daz DeBoer
842c587ad8 Merge pull request #911 - Improve dependency review support 2023-10-01 02:01:56 +02:00
daz
4241e05054 Document configuration for dependency-review-action 2023-09-30 17:45:44 -06:00
daz
bfa3c0508e Build outputs 2023-09-30 08:49:10 -06:00
daz
c3bdce8205 Warn on dependency-graph-submit failure
A common issue when submitting a dependency graph is that the required
'contents: write' permission is not set.
We now catch any dependency submission failure and inform the user to check
that the required permissions are available.
2023-09-30 08:47:10 -06:00
daz
f92e7c3428 Improve compat with dependency-review-action
When using 'download-and-submit' for dependency graphs, we now run the
submission immediately instead of waiting until the post-action.
This allows a single job to both submit the graph and run the dependency
review action.
2023-09-29 20:36:16 -06:00
daz
d1b726d8c1 Do not generate dependency graph in cache-cleanup
- Allow environment variables to be overridden by system properties in dependency-graph initscript
- Set `GITHUB_DEPENDENCY_GRAPH_ENABLED=false` when executing Gradle for cache cleanup
2023-09-29 22:55:54 +02:00
Daz DeBoer
6fcc109efa Dependency updates (#904)
### Github Action updates

Updates `gradle/gradle-build-action` from 2.8.0 to 2.8.1

### NPM updates

Updates `@octokit/webhooks-types` from 7.3.0 to 7.3.1
- [Release notes](https://github.com/octokit/webhooks/releases)
- [Commits](https://github.com/octokit/webhooks/compare/v7.3.0...v7.3.1)

Updates `@typescript-eslint/parser` from 6.7.2 to 6.7.3
- [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases)
- [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/parser/CHANGELOG.md)
- [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v6.7.3/packages/parser)

Updates `eslint` from 8.49.0 to 8.50.0
- [Release notes](https://github.com/eslint/eslint/releases)
- [Changelog](https://github.com/eslint/eslint/blob/main/CHANGELOG.md)
- [Commits](https://github.com/eslint/eslint/compare/v8.49.0...v8.50.0)
2023-09-29 13:55:35 -06:00
Benoit Pierre
fde5b4fcde fix README.md internal references
Signed-off-by: Benoit Pierre <benoit.pierre@gmail.com>
2023-09-29 21:35:43 +02:00
daz
324fbdc804 Update to dep-graph plugin 0.4.1 2023-09-29 13:22:08 -06:00
daz
5658338fb0 Build outputs 2023-09-26 15:51:30 +02:00
daz
87ccc98a2a Use correct SHA for pull request events
In a pull request, GITHUB_SHA is set to the "last merge commit on the GITHUB_REF branch".
This isn't the correct value to use when generating a dependency graph.
This changes to use the value of `pull_request.head.sha`, which is the correct
value for a dependency graph.

Fixes #882
2023-09-26 15:51:30 +02:00
daz
4441c9f9bf Update to dep-graph plugin 0.4.0 2023-09-26 15:51:30 +02:00
Daz DeBoer
b5126f31db Use github.getOctokit() for compat with GitHub Enterprise
Thanks @nise-nabe for the inspiration

Fixes #885
2023-09-21 10:55:26 -06:00
Daz DeBoer
d8615ccc8b Document configuration to publish to scans.gradle.com
Fixes #870
2023-09-21 10:47:51 -06:00
Daz DeBoer
444c20baf7 Test multiple dependency graphs on all os's 2023-09-21 18:22:31 +02:00
daz
aea76e1766 Dependency updates 2023-09-21 10:01:33 -06:00
daz
103e3a7ba7 Build outputs 2023-09-21 08:47:55 -06:00
dependabot[bot]
73e3fc21c7 Bump the npm-dependencies group with 12 updates
Bumps the npm-dependencies group with 12 updates:

| Package | From | To |
| --- | --- | --- |
| [@actions/artifact](https://github.com/actions/toolkit/tree/HEAD/packages/artifact) | `1.1.1` | `1.1.2` |
| [@actions/core](https://github.com/actions/toolkit/tree/HEAD/packages/core) | `1.10.0` | `1.10.1` |
| [@types/unzipper](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/unzipper) | `0.10.6` | `0.10.7` |
| [@typescript-eslint/parser](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/parser) | `6.4.1` | `6.7.2` |
| [@vercel/ncc](https://github.com/vercel/ncc) | `0.36.1` | `0.38.0` |
| [eslint](https://github.com/eslint/eslint) | `8.47.0` | `8.49.0` |
| [eslint-plugin-github](https://github.com/github/eslint-plugin-github) | `4.9.2` | `4.10.0` |
| [eslint-plugin-jest](https://github.com/jest-community/eslint-plugin-jest) | `27.2.3` | `27.4.0` |
| [jest](https://github.com/jestjs/jest/tree/HEAD/packages/jest) | `29.6.3` | `29.7.0` |
| [@types/jest](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/jest) | `29.5.4` | `29.5.5` |
| [prettier](https://github.com/prettier/prettier) | `3.0.2` | `3.0.3` |
| [typescript](https://github.com/Microsoft/TypeScript) | `5.1.6` | `5.2.2` |


Updates `@actions/artifact` from 1.1.1 to 1.1.2
- [Changelog](https://github.com/actions/toolkit/blob/main/packages/artifact/RELEASES.md)
- [Commits](https://github.com/actions/toolkit/commits/HEAD/packages/artifact)

Updates `@actions/core` from 1.10.0 to 1.10.1
- [Changelog](https://github.com/actions/toolkit/blob/main/packages/core/RELEASES.md)
- [Commits](https://github.com/actions/toolkit/commits/HEAD/packages/core)

Updates `@types/unzipper` from 0.10.6 to 0.10.7
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/unzipper)

Updates `@typescript-eslint/parser` from 6.4.1 to 6.7.2
- [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases)
- [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/parser/CHANGELOG.md)
- [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v6.7.2/packages/parser)

Updates `@vercel/ncc` from 0.36.1 to 0.38.0
- [Release notes](https://github.com/vercel/ncc/releases)
- [Commits](https://github.com/vercel/ncc/compare/0.36.1...0.38.0)

Updates `eslint` from 8.47.0 to 8.49.0
- [Release notes](https://github.com/eslint/eslint/releases)
- [Changelog](https://github.com/eslint/eslint/blob/main/CHANGELOG.md)
- [Commits](https://github.com/eslint/eslint/compare/v8.47.0...v8.49.0)

Updates `eslint-plugin-github` from 4.9.2 to 4.10.0
- [Release notes](https://github.com/github/eslint-plugin-github/releases)
- [Commits](https://github.com/github/eslint-plugin-github/compare/v4.9.2...v4.10.0)

Updates `eslint-plugin-jest` from 27.2.3 to 27.4.0
- [Release notes](https://github.com/jest-community/eslint-plugin-jest/releases)
- [Changelog](https://github.com/jest-community/eslint-plugin-jest/blob/main/CHANGELOG.md)
- [Commits](https://github.com/jest-community/eslint-plugin-jest/compare/v27.2.3...v27.4.0)

Updates `jest` from 29.6.3 to 29.7.0
- [Release notes](https://github.com/jestjs/jest/releases)
- [Changelog](https://github.com/jestjs/jest/blob/main/CHANGELOG.md)
- [Commits](https://github.com/jestjs/jest/commits/v29.7.0/packages/jest)

Updates `@types/jest` from 29.5.4 to 29.5.5
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/jest)

Updates `prettier` from 3.0.2 to 3.0.3
- [Release notes](https://github.com/prettier/prettier/releases)
- [Changelog](https://github.com/prettier/prettier/blob/main/CHANGELOG.md)
- [Commits](https://github.com/prettier/prettier/compare/3.0.2...3.0.3)

Updates `typescript` from 5.1.6 to 5.2.2
- [Release notes](https://github.com/Microsoft/TypeScript/releases)
- [Commits](https://github.com/Microsoft/TypeScript/compare/v5.1.6...v5.2.2)

---
updated-dependencies:
- dependency-name: "@actions/artifact"
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: npm-dependencies
- dependency-name: "@actions/core"
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: npm-dependencies
- dependency-name: "@types/unzipper"
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: npm-dependencies
- dependency-name: "@typescript-eslint/parser"
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: npm-dependencies
- dependency-name: "@vercel/ncc"
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: npm-dependencies
- dependency-name: eslint
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: npm-dependencies
- dependency-name: eslint-plugin-github
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: npm-dependencies
- dependency-name: eslint-plugin-jest
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: npm-dependencies
- dependency-name: jest
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: npm-dependencies
- dependency-name: "@types/jest"
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: npm-dependencies
- dependency-name: prettier
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: npm-dependencies
- dependency-name: typescript
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: npm-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-09-21 08:44:23 -06:00
daz
b063df05a4 Bump GE plugin versions 2023-09-21 08:41:43 -06:00
dependabot[bot]
5e3952da92 Bump the github-actions group with 2 updates
Bumps the github-actions group with 2 updates: [actions/checkout](https://github.com/actions/checkout) and [gradle/gradle-build-action](https://github.com/gradle/gradle-build-action).


Updates `actions/checkout` from 3 to 4
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v3...v4)

Updates `gradle/gradle-build-action` from 2.7.1 to 2.8.0
- [Release notes](https://github.com/gradle/gradle-build-action/releases)
- [Commits](https://github.com/gradle/gradle-build-action/compare/v2.7.1...v2.8.0)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: github-actions
- dependency-name: gradle/gradle-build-action
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: github-actions
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-09-21 16:35:57 +02:00
Daz DeBoer
ed940a329a Fix name of test dependency-graph workflow 2023-09-21 08:19:49 -06:00
Daz DeBoer
3bfe3a4658 Clarify documentation
Fixes #867
2023-09-04 16:09:52 -06:00
daz
8f08e41675 Use unique cache key for workflow 2023-08-28 12:40:55 -06:00
Daz DeBoer
ef76a971e2 Simplify GE-inject config params (#863) 2023-08-28 11:59:09 -06:00
dependabot[bot]
98d77952ea Bump the npm-dependencies group with 1 update
Bumps the npm-dependencies group with 1 update: [@types/jest](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/jest).

- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/jest)

---
updated-dependencies:
- dependency-name: "@types/jest"
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: npm-dependencies
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-08-28 18:47:31 +02:00
Daz DeBoer
3122f2c659 Mention GE authentication with GE injection 2023-08-23 12:07:20 -06:00
Daz DeBoer
53c4cf6c4c Merge pull request #861 from gradle/dd/dependency-updates
Dependency updates
2023-08-23 15:59:29 +02:00
daz
f2d7085b02 Add octokit to dependabot ignores 2023-08-22 10:28:15 -06:00
dependabot[bot]
9124f04a83 Bump the npm-dependencies group with 3 updates
Updates `@typescript-eslint/parser` from 6.4.0 to 6.4.1
- [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases)
- [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/parser/CHANGELOG.md)
- [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v6.4.1/packages/parser)

Updates `jest` from 29.6.2 to 29.6.3
- [Release notes](https://github.com/jestjs/jest/releases)
- [Changelog](https://github.com/jestjs/jest/blob/main/CHANGELOG.md)
- [Commits](https://github.com/jestjs/jest/commits/v29.6.3/packages/jest)

Updates `prettier` from 3.0.1 to 3.0.2
- [Release notes](https://github.com/prettier/prettier/releases)
- [Changelog](https://github.com/prettier/prettier/blob/main/CHANGELOG.md)
- [Commits](https://github.com/prettier/prettier/compare/3.0.1...3.0.2)

---
updated-dependencies:
- dependency-name: "@typescript-eslint/parser"
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: npm-dependencies
- dependency-name: jest
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: npm-dependencies
- dependency-name: prettier
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: npm-dependencies
2023-08-22 09:13:40 -06:00
dependabot[bot]
c304f927c4 Bump the github-actions group with 1 update
Bumps the github-actions group with 1 update: [gradle/gradle-build-action](https://github.com/gradle/gradle-build-action).

- [Release notes](https://github.com/gradle/gradle-build-action/releases)
- [Commits](https://github.com/gradle/gradle-build-action/compare/v2.7.0...v2.7.1)

---
updated-dependencies:
- dependency-name: gradle/gradle-build-action
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: github-actions
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-08-21 22:36:46 +00:00
Daz DeBoer
e3426b1f20 Merge pull request #857 from gradle/dd/inject-ge
Add support for Gradle Enterprise injection into Gradle Builds
2023-08-21 01:38:14 +02:00
daz
d79398df06 Add docs for GE injection 2023-08-20 16:30:34 -06:00
daz
b9cd1d9e69 Build outputs 2023-08-20 16:29:23 -06:00
daz
d4db33d499 Add integ-test for GE injection 2023-08-20 16:29:23 -06:00
daz
05acc776e8 Wire new init-script into action
- Copy init-script to Gradle User Home
- Rename init-scripts for consistency and clarity
2023-08-20 16:29:23 -06:00
daz
33c9bfac14 Fix test for dependency graph with configuration cache 2023-08-20 16:29:23 -06:00
daz
97d9c134b7 Add init-script for Gradle Enterprise injection
Adds a new init-script which can enable and configure the Gradle Enterprise plugin(s)
for a build, without needing to modify the settings script for the project.
The functionality is enabled and configured via environment variables or system properties.

Not yet wired into `gradle-build-action`.
2023-08-20 16:29:23 -06:00
Daz DeBoer
a617adb316 Minor documentation updates 2023-08-20 15:56:45 -06:00
Daz DeBoer
b156d58cac Document the cache-overwrite-existing parameter 2023-08-20 14:14:54 -06:00
Daz DeBoer
b946c060aa Document the gradle-version output parameter 2023-08-20 14:05:33 -06:00
Daz DeBoer
96bed685e4 Merge pull request #855 from gradle/dd/installed-toolchains
Detect installed java toolchains
2023-08-20 05:27:22 +02:00
daz
800e5e1e62 Fix check 2023-08-19 20:42:08 -06:00
daz
ff3f4cfbf8 Build outputs 2023-08-19 20:14:11 -06:00
daz
a07019c726 Inform Gradle where to locate pre-installed JDKs 2023-08-19 20:14:11 -06:00
daz
b17d107b8c Add test for detection of java toolchains 2023-08-19 20:14:11 -06:00
daz
12dcfaa735 Bump to the latest Foojay resolver 2023-08-19 17:24:51 -06:00
Daz DeBoer
9fb6114fb4 Merge pull request #854 from gradle/dd/existing-gradle-home
- Report the cache as disabled when Gradle User Home exists #434 
- Allow cache restore over pre-existing Gradle User Home #480
2023-08-19 22:27:30 +02:00
daz
50d07aa0e5 Build outputs 2023-08-19 13:37:53 -06:00
daz
3d49588efc Allow cache to overwrite existing Gradle User Home
Fixes #480
2023-08-19 13:37:53 -06:00
daz
68e1dcdea4 Report the cache as disabled when Gradle User Home exists
Fixes #434
2023-08-19 13:37:49 -06:00
daz
8cade330d4 Include provisioned Gradle version as action output
Fixes #259
2023-08-19 20:37:12 +02:00
daz
124cb765ee Update to Gradle 8.3 2023-08-19 10:32:05 -06:00
Daz DeBoer
243af859f8 Improve and extend documentation for dependency-graph generation (#851)
* Improve documentation for dependency-graph generation

Fixes #849
Fixes #843
2023-08-18 15:50:06 -06:00
Daz DeBoer
dc5f59ec6e Update action description for SEO 2023-08-17 17:00:13 -06:00
Daz DeBoer
c87c55823d Merge pull request #850 from gradle/dd/docs
Improve docs on Gradle User Home caching
2023-08-17 23:18:35 +02:00
daz
cfdcfc37ed Docs reformat 2023-08-17 15:13:47 -06:00
daz
193108951e Improve docs on Gradle User Home caching
- Describe the limitations/properties of the GitHub Actions cache
- Document the algorithm for generating a cache key, and the way that cache entries are matched
- Describe in more detail how entries are de-duplicated
- Explain how cache entries can be optimized in Job pipelines

Fixes #831
Fixes #608
2023-08-17 14:49:12 -06:00
Daz DeBoer
f9b4995b32 Docs: clarify incompatibility with setup-java caching
Fixes #725
2023-08-16 14:26:17 -06:00
Andy Coates
4283247a19 Add example of using DEPENDENCY_GRAPH_INCLUDE_PROJECTS to docs (#844)
Users will currently need to spend some time working out the required regex when using `DEPENDENCY_GRAPH_INCLUDE_PROJECTS`. Providing an example will get users up to speed quicker.

Signed-off-by: Andy Coates <8012398+big-andy-coates@users.noreply.github.com>
2023-08-16 11:47:25 -06:00
Andy Coates
337198a5e3 840: Fix configuration name in dependency filtering section
Fixes: #840

With Gradle 8.0.2 (not tried other versions) the configuration name is runtimeClasspath not RuntimeClasspath. Using the latter results in an empty set of dependencies being reported (as it matches no configurations).

Signed-off-by: Andy Coates <8012398+big-andy-coates@users.noreply.github.com>
2023-08-16 18:55:44 +02:00
Daz DeBoer
e3028deccc Merge pull request #826 from 3flex/patch-1
Polish GitHub Dependency Graph support section
2023-08-15 15:31:22 +02:00
Daz DeBoer
cb1fda6460 Merge pull request #836 from gradle/dd/dependency-updates
Dependency updates
2023-08-15 15:17:53 +02:00
daz
19e2bdf3c0 Build outputs 2023-08-14 20:07:24 -06:00
daz
891451e1fc Update NPM dependencies 2023-08-14 20:04:27 -06:00
daz
03f0ac2c51 Bump to use the latest release 2023-08-14 19:59:38 -06:00
daz
999ba18af8 Bump dependency versions in sample app 2023-08-14 19:57:15 -06:00
daz
43f8f93391 Update to GE plugin 3.14.1 2023-08-14 19:55:05 -06:00
Matthew Haughton
e8d1617724 Polish GitHub Dependency Graph support section
Signed-off-by: Matthew Haughton <3flex@users.noreply.github.com>
2023-07-29 12:14:21 +10:00
Daz DeBoer
a4cf152f48 Merge pull request #817 from gradle/dd/270
Prepare for 2.7.0 release
2023-07-24 17:04:07 +02:00
daz
a8aac055e2 Build outputs 2023-07-24 08:55:39 -06:00
daz
7241fa5d56 Add new output to Action.yml 2023-07-24 08:43:47 -06:00
daz
9e58f8b1de Add dependency-graph-file as step output
Fixes #804
2023-07-24 08:37:14 -06:00
daz
632e888003 Update to the latest dependency-graph plugin
- Remove experimental warning
- Update documentation
2023-07-24 08:37:14 -06:00
daz
ced6859e9c Update Build Scan™ to Build Scan® 2023-07-22 08:53:58 -06:00
daz
0904709a46 Bump GE plugin versions 2023-07-21 13:32:44 -06:00
daz
1b94073332 Bump development dependencies 2023-07-21 13:13:44 -06:00
Daz DeBoer
4821f54162 Group all npm dependencies in a single dependabot PR 2023-07-21 12:19:33 -06:00
dependabot[bot]
2dbad1ea2d Bump the github-actions group with 1 update
Bumps the github-actions group with 1 update: [gradle/gradle-build-action](https://github.com/gradle/gradle-build-action).

- [Release notes](https://github.com/gradle/gradle-build-action/releases)
- [Commits](https://github.com/gradle/gradle-build-action/compare/v2.6.0...v2.6.1)

---
updated-dependencies:
- dependency-name: gradle/gradle-build-action
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: github-actions
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-07-18 00:08:00 +02:00
85 changed files with 156252 additions and 21388 deletions

View File

@@ -20,14 +20,10 @@ updates:
schedule: schedule:
interval: "weekly" interval: "weekly"
ignore: ignore:
- dependency-name: "@types/node" - dependency-name: "@types/node" # Breaking change: update with next major release
- dependency-name: "@octokit/rest" # Tied to node version
groups: groups:
runtime-dependencies: npm-dependencies:
patterns:
- "@actions/*"
- "@octokit/rest"
- "string-argv"
dev-dependencies:
patterns: patterns:
- "*" - "*"

View File

@@ -1,7 +1,7 @@
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
distributionSha256Sum=03ec176d388f2aa99defcadc3ac6adf8dd2bce5145a129659537c0874dea5ad1 distributionSha256Sum=9d926787066a081739e8200858338b4a69e837c3a821a33aca9db09dd4a41026
distributionUrl=https\://services.gradle.org/distributions/gradle-8.2.1-bin.zip distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip
networkTimeout=10000 networkTimeout=10000
validateDistributionUrl=true validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME

View File

@@ -83,7 +83,8 @@ done
# This is normally unused # This is normally unused
# shellcheck disable=SC2034 # shellcheck disable=SC2034
APP_BASE_NAME=${0##*/} APP_BASE_NAME=${0##*/}
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value. # Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum MAX_FD=maximum
@@ -144,7 +145,7 @@ if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #( case $MAX_FD in #(
max*) max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045 # shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) || MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit" warn "Could not query maximum file descriptor limit"
esac esac
@@ -152,7 +153,7 @@ if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
'' | soft) :;; #( '' | soft) :;; #(
*) *)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045 # shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" || ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD" warn "Could not set maximum file descriptor limit to $MAX_FD"
esac esac
@@ -201,11 +202,11 @@ fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command; # Collect all arguments for the java command:
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of # * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# shell script including quotes and variable substitutions, so put them in # and any embedded shellness will be escaped.
# double quotes to make sure that they get re-expanded; and # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# * put everything else in single quotes, so that it's not re-expanded. # treated as '${Hostname}' itself on the command line.
set -- \ set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \ "-Dorg.gradle.appname=$APP_BASE_NAME" \

View File

@@ -1,7 +1,7 @@
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
distributionSha256Sum=03ec176d388f2aa99defcadc3ac6adf8dd2bce5145a129659537c0874dea5ad1 distributionSha256Sum=9d926787066a081739e8200858338b4a69e837c3a821a33aca9db09dd4a41026
distributionUrl=https\://services.gradle.org/distributions/gradle-8.2.1-bin.zip distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip
networkTimeout=10000 networkTimeout=10000
validateDistributionUrl=true validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME

View File

@@ -83,7 +83,8 @@ done
# This is normally unused # This is normally unused
# shellcheck disable=SC2034 # shellcheck disable=SC2034
APP_BASE_NAME=${0##*/} APP_BASE_NAME=${0##*/}
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value. # Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum MAX_FD=maximum
@@ -144,7 +145,7 @@ if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #( case $MAX_FD in #(
max*) max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045 # shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) || MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit" warn "Could not query maximum file descriptor limit"
esac esac
@@ -152,7 +153,7 @@ if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
'' | soft) :;; #( '' | soft) :;; #(
*) *)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045 # shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" || ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD" warn "Could not set maximum file descriptor limit to $MAX_FD"
esac esac
@@ -201,11 +202,11 @@ fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command; # Collect all arguments for the java command:
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of # * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# shell script including quotes and variable substitutions, so put them in # and any embedded shellness will be escaped.
# double quotes to make sure that they get re-expanded; and # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# * put everything else in single quotes, so that it's not re-expanded. # treated as '${Hostname}' itself on the command line.
set -- \ set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \ "-Dorg.gradle.appname=$APP_BASE_NAME" \

View File

@@ -1,6 +1,6 @@
plugins { plugins {
id "com.gradle.enterprise" version "3.13.4" id "com.gradle.enterprise" version "3.16.1"
id "com.gradle.common-custom-user-data-gradle-plugin" version "1.11" id "com.gradle.common-custom-user-data-gradle-plugin" version "1.12.1"
} }
gradleEnterprise { gradleEnterprise {

View File

@@ -1,7 +1,7 @@
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
distributionSha256Sum=03ec176d388f2aa99defcadc3ac6adf8dd2bce5145a129659537c0874dea5ad1 distributionSha256Sum=9d926787066a081739e8200858338b4a69e837c3a821a33aca9db09dd4a41026
distributionUrl=https\://services.gradle.org/distributions/gradle-8.2.1-bin.zip distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip
networkTimeout=10000 networkTimeout=10000
validateDistributionUrl=true validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME

View File

@@ -83,7 +83,8 @@ done
# This is normally unused # This is normally unused
# shellcheck disable=SC2034 # shellcheck disable=SC2034
APP_BASE_NAME=${0##*/} APP_BASE_NAME=${0##*/}
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value. # Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum MAX_FD=maximum
@@ -144,7 +145,7 @@ if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #( case $MAX_FD in #(
max*) max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045 # shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) || MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit" warn "Could not query maximum file descriptor limit"
esac esac
@@ -152,7 +153,7 @@ if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
'' | soft) :;; #( '' | soft) :;; #(
*) *)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045 # shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" || ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD" warn "Could not set maximum file descriptor limit to $MAX_FD"
esac esac
@@ -201,11 +202,11 @@ fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command; # Collect all arguments for the java command:
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of # * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# shell script including quotes and variable substitutions, so put them in # and any embedded shellness will be escaped.
# double quotes to make sure that they get re-expanded; and # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# * put everything else in single quotes, so that it's not re-expanded. # treated as '${Hostname}' itself on the command line.
set -- \ set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \ "-Dorg.gradle.appname=$APP_BASE_NAME" \

View File

@@ -1,5 +1,5 @@
plugins { plugins {
id("org.gradle.toolchains.foojay-resolver-convention") version("0.4.0") id("org.gradle.toolchains.foojay-resolver-convention") version("0.7.0")
} }
rootProject.name = 'basic' rootProject.name = 'basic'

View File

@@ -8,9 +8,9 @@ repositories {
dependencies { dependencies {
api("org.apache.commons:commons-math3:3.6.1") api("org.apache.commons:commons-math3:3.6.1")
implementation("com.google.guava:guava:32.0.1-jre") implementation("com.google.guava:guava:33.0.0-jre")
testImplementation("org.junit.jupiter:junit-jupiter:5.9.3") testImplementation("org.junit.jupiter:junit-jupiter:5.10.1")
} }
tasks.test { tasks.test {

View File

@@ -1,7 +1,7 @@
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
distributionSha256Sum=03ec176d388f2aa99defcadc3ac6adf8dd2bce5145a129659537c0874dea5ad1 distributionSha256Sum=9d926787066a081739e8200858338b4a69e837c3a821a33aca9db09dd4a41026
distributionUrl=https\://services.gradle.org/distributions/gradle-8.2.1-bin.zip distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip
networkTimeout=10000 networkTimeout=10000
validateDistributionUrl=true validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME

View File

@@ -83,7 +83,8 @@ done
# This is normally unused # This is normally unused
# shellcheck disable=SC2034 # shellcheck disable=SC2034
APP_BASE_NAME=${0##*/} APP_BASE_NAME=${0##*/}
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value. # Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum MAX_FD=maximum
@@ -144,7 +145,7 @@ if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #( case $MAX_FD in #(
max*) max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045 # shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) || MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit" warn "Could not query maximum file descriptor limit"
esac esac
@@ -152,7 +153,7 @@ if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
'' | soft) :;; #( '' | soft) :;; #(
*) *)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC3045 # shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" || ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD" warn "Could not set maximum file descriptor limit to $MAX_FD"
esac esac
@@ -201,11 +202,11 @@ fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command; # Collect all arguments for the java command:
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of # * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# shell script including quotes and variable substitutions, so put them in # and any embedded shellness will be escaped.
# double quotes to make sure that they get re-expanded; and # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# * put everything else in single quotes, so that it's not re-expanded. # treated as '${Hostname}' itself on the command line.
set -- \ set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \ "-Dorg.gradle.appname=$APP_BASE_NAME" \

View File

@@ -1,6 +1,6 @@
plugins { plugins {
id("com.gradle.enterprise") version "3.13.4" id("com.gradle.enterprise") version "3.16.1"
id("com.gradle.common-custom-user-data-gradle-plugin") version "1.11" id("com.gradle.common-custom-user-data-gradle-plugin") version "1.12.1"
} }
gradleEnterprise { gradleEnterprise {

View File

@@ -0,0 +1 @@
// Required to keep dependabot happy

View File

@@ -0,0 +1 @@
rootProject.name = 'no-ge'

View File

@@ -1,5 +1,5 @@
plugins { plugins {
id "com.gradle.build-scan" version "3.13.4" id "com.gradle.build-scan" version "3.16.1"
} }
gradleEnterprise { gradleEnterprise {

View File

@@ -1,5 +1,5 @@
plugins { plugins {
id "com.gradle.enterprise" version "3.13.4" id "com.gradle.enterprise" version "3.16.1"
} }
gradleEnterprise { gradleEnterprise {

View File

@@ -38,11 +38,11 @@ jobs:
steps: steps:
- name: Checkout repository - name: Checkout repository
uses: actions/checkout@v3 uses: actions/checkout@v4
# Initializes the CodeQL tools for scanning. # Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL - name: Initialize CodeQL
uses: github/codeql-action/init@v2 uses: github/codeql-action/init@v3
with: with:
languages: ${{ matrix.language }} languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file. # If you wish to specify custom queries, you can do so here or in a config file.
@@ -53,7 +53,7 @@ jobs:
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java). # Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below) # If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild - name: Autobuild
uses: github/codeql-action/autobuild@v2 uses: github/codeql-action/autobuild@v3
# Command-line programs to run using the OS shell. # Command-line programs to run using the OS shell.
# 📚 https://git.io/JvXDl # 📚 https://git.io/JvXDl
@@ -67,4 +67,4 @@ jobs:
# make release # make release
- name: Perform CodeQL Analysis - name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v2 uses: github/codeql-action/analyze@v3

View File

@@ -15,6 +15,6 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: 'Checkout Repository' - name: 'Checkout Repository'
uses: actions/checkout@v3 uses: actions/checkout@v4
- name: 'Dependency Review' - name: 'Dependency Review'
uses: actions/dependency-review-action@v3 uses: actions/dependency-review-action@v3

View File

@@ -25,12 +25,14 @@ jobs:
cache-key-prefix: ${{github.run_number}}- cache-key-prefix: ${{github.run_number}}-
caching-config: caching-config:
uses: ./.github/workflows/integ-test-action-inputs-caching.yml uses: ./.github/workflows/integ-test-caching-config.yml
with: with:
cache-key-prefix: ${{github.run_number}}- cache-key-prefix: ${{github.run_number}}-
dependency-graph: dependency-graph:
uses: ./.github/workflows/integ-test-dependency-graph.yml uses: ./.github/workflows/integ-test-dependency-graph.yml
permissions:
contents: write
with: with:
cache-key-prefix: ${{github.run_number}}- cache-key-prefix: ${{github.run_number}}-
@@ -44,15 +46,24 @@ jobs:
with: with:
cache-key-prefix: ${{github.run_number}}- cache-key-prefix: ${{github.run_number}}-
gradle-enterprise-injection:
uses: ./.github/workflows/integ-test-inject-gradle-enterprise.yml
with:
cache-key-prefix: ${{github.run_number}}-
secrets:
GRADLE_ENTERPRISE_ACCESS_KEY: ${{ secrets.GE_SOLUTIONS_ACCESS_TOKEN }}
provision-gradle-versions: provision-gradle-versions:
uses: ./.github/workflows/integ-test-provision-gradle-versions.yml uses: ./.github/workflows/integ-test-provision-gradle-versions.yml
with: with:
cache-key-prefix: ${{github.run_number}}- cache-key-prefix: ${{github.run_number}}-
# restore-configuration-cache: restore-configuration-cache:
# uses: ./.github/workflows/integ-test-restore-configuration-cache.yml uses: ./.github/workflows/integ-test-restore-configuration-cache.yml
# with: with:
# cache-key-prefix: ${{github.run_number}}- cache-key-prefix: ${{github.run_number}}-
secrets:
GRADLE_ENCRYPTION_KEY: ${{ secrets.GRADLE_ENCRYPTION_KEY }}
restore-custom-gradle-home: restore-custom-gradle-home:
uses: ./.github/workflows/integ-test-restore-custom-gradle-home.yml uses: ./.github/workflows/integ-test-restore-custom-gradle-home.yml
@@ -83,3 +94,8 @@ jobs:
uses: ./.github/workflows/integ-test-sample-gradle-plugin.yml uses: ./.github/workflows/integ-test-sample-gradle-plugin.yml
with: with:
cache-key-prefix: ${{github.run_number}}- cache-key-prefix: ${{github.run_number}}-
toolchain-detection:
uses: ./.github/workflows/integ-test-detect-java-toolchains.yml
with:
cache-key-prefix: ${{github.run_number}}-

View File

@@ -13,14 +13,14 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Checkout sources - name: Checkout sources
uses: actions/checkout@v3 uses: actions/checkout@v4
- name: Setup Java - name: Setup Java
uses: actions/setup-java@v3 uses: actions/setup-java@v4
with: with:
distribution: temurin distribution: temurin
java-version: 8 java-version: 8
- name: Setup Gradle - name: Setup Gradle
uses: gradle/gradle-build-action@v2.6.0 # Use a released version to avoid breakages uses: gradle/gradle-build-action@v2.11.0 # Use a released version to avoid breakages
- name: Run integration tests - name: Run integration tests
working-directory: test/init-scripts working-directory: test/init-scripts
run: ./gradlew check run: ./gradlew check

View File

@@ -10,7 +10,7 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Checkout sources - name: Checkout sources
uses: actions/checkout@v3 uses: actions/checkout@v4
- name: Build and upload distribution - name: Build and upload distribution
uses: ./.github/actions/build-dist uses: ./.github/actions/build-dist
@@ -18,11 +18,11 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Checkout sources - name: Checkout sources
uses: actions/checkout@v3 uses: actions/checkout@v4
- name: Configure Gradle as default for unit test - name: Configure Gradle as default for unit test
uses: ./ uses: ./
with: with:
gradle-version: 8.2.1 gradle-version: 8.5
- name: Run tests - name: Run tests
run: | run: |
npm install npm install
@@ -45,7 +45,7 @@ jobs:
caching-config: caching-config:
needs: build-distribution needs: build-distribution
uses: ./.github/workflows/integ-test-action-inputs-caching.yml uses: ./.github/workflows/integ-test-caching-config.yml
with: with:
runner-os: '["ubuntu-latest"]' runner-os: '["ubuntu-latest"]'
download-dist: true download-dist: true
@@ -53,6 +53,8 @@ jobs:
dependency-graph: dependency-graph:
needs: build-distribution needs: build-distribution
uses: ./.github/workflows/integ-test-dependency-graph.yml uses: ./.github/workflows/integ-test-dependency-graph.yml
permissions:
contents: write
with: with:
runner-os: '["ubuntu-latest"]' runner-os: '["ubuntu-latest"]'
download-dist: true download-dist: true
@@ -71,6 +73,15 @@ jobs:
runner-os: '["ubuntu-latest"]' runner-os: '["ubuntu-latest"]'
download-dist: true download-dist: true
gradle-enterprise-injection:
needs: build-distribution
uses: ./.github/workflows/integ-test-inject-gradle-enterprise.yml
with:
runner-os: '["ubuntu-latest"]'
download-dist: true
secrets:
GRADLE_ENTERPRISE_ACCESS_KEY: ${{ secrets.GE_SOLUTIONS_ACCESS_TOKEN }}
provision-gradle-versions: provision-gradle-versions:
needs: build-distribution needs: build-distribution
uses: ./.github/workflows/integ-test-provision-gradle-versions.yml uses: ./.github/workflows/integ-test-provision-gradle-versions.yml
@@ -78,12 +89,14 @@ jobs:
runner-os: '["ubuntu-latest"]' runner-os: '["ubuntu-latest"]'
download-dist: true download-dist: true
# restore-configuration-cache: restore-configuration-cache:
# needs: build-distribution needs: build-distribution
# uses: ./.github/workflows/integ-test-restore-configuration-cache.yml uses: ./.github/workflows/integ-test-restore-configuration-cache.yml
# with: with:
# runner-os: '["ubuntu-latest"]' runner-os: '["ubuntu-latest"]'
# download-dist: true download-dist: true
secrets:
GRADLE_ENCRYPTION_KEY: ${{ secrets.GRADLE_ENCRYPTION_KEY }}
restore-containerized-gradle-home: restore-containerized-gradle-home:
needs: build-distribution needs: build-distribution
@@ -124,3 +137,10 @@ jobs:
with: with:
runner-os: '["ubuntu-latest"]' runner-os: '["ubuntu-latest"]'
download-dist: true download-dist: true
toolchain-detection:
needs: build-distribution
uses: ./.github/workflows/integ-test-detect-java-toolchains.yml
with:
runner-os: '["ubuntu-latest"]'
download-dist: true

View File

@@ -15,7 +15,7 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Checkout sources - name: Checkout sources
uses: actions/checkout@v3 uses: actions/checkout@v4
- name: Build - name: Build
run: | run: |
npm -v npm -v
@@ -33,7 +33,7 @@ jobs:
id: diff id: diff
# If index.js was different than expected, upload the expected version as an artifact # If index.js was different than expected, upload the expected version as an artifact
- uses: actions/upload-artifact@v3 - uses: actions/upload-artifact@v4
if: ${{ failure() && steps.diff.conclusion == 'failure' }} if: ${{ failure() && steps.diff.conclusion == 'failure' }}
with: with:
name: dist name: dist

View File

@@ -9,7 +9,7 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Checkout sources - name: Checkout sources
uses: actions/checkout@v3 uses: actions/checkout@v4
- name: Test build failure - name: Test build failure
uses: ./ uses: ./
continue-on-error: true continue-on-error: true
@@ -21,7 +21,7 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Checkout sources - name: Checkout sources
uses: actions/checkout@v3 uses: actions/checkout@v4
- name: Test wrapper missing - name: Test wrapper missing
uses: ./ uses: ./
continue-on-error: true continue-on-error: true
@@ -33,7 +33,7 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Checkout sources - name: Checkout sources
uses: actions/checkout@v3 uses: actions/checkout@v4
- name: Test bad config value - name: Test bad config value
uses: ./ uses: ./
continue-on-error: true continue-on-error: true

View File

@@ -8,11 +8,11 @@ env:
GRADLE_BUILD_ACTION_CACHE_DEBUG_ENABLED: true GRADLE_BUILD_ACTION_CACHE_DEBUG_ENABLED: true
jobs: jobs:
run-gradle-builds: many-gradle-builds:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Checkout sources - name: Checkout sources
uses: actions/checkout@v3 uses: actions/checkout@v4
- name: Build distribution - name: Build distribution
shell: bash shell: bash
run: | run: |
@@ -23,10 +23,10 @@ jobs:
- name: Build kotlin-dsl project - name: Build kotlin-dsl project
working-directory: .github/workflow-samples/kotlin-dsl working-directory: .github/workflow-samples/kotlin-dsl
run: ./gradlew assemble run: ./gradlew assemble
- name: Build kotlin-dsl project without build scan - name: Build kotlin-dsl project without Build Scan®
working-directory: .github/workflow-samples/kotlin-dsl working-directory: .github/workflow-samples/kotlin-dsl
run: ./gradlew assemble check --no-scan run: ./gradlew assemble check --no-scan
- name: Build kotlin-dsl project with build scan publish failure - name: Build kotlin-dsl project with Build Scan® publish failure
working-directory: .github/workflow-samples/kotlin-dsl working-directory: .github/workflow-samples/kotlin-dsl
run: ./gradlew check -Dgradle.enterprise.url=https://not.valid.server run: ./gradlew check -Dgradle.enterprise.url=https://not.valid.server
- name: Build groovy-dsl project - name: Build groovy-dsl project
@@ -41,3 +41,46 @@ jobs:
working-directory: .github/workflow-samples/groovy-dsl working-directory: .github/workflow-samples/groovy-dsl
continue-on-error: true continue-on-error: true
run: ./gradlew not-a-real-task run: ./gradlew not-a-real-task
successful-builds-with-no-summary:
runs-on: ubuntu-latest
steps:
- name: Checkout sources
uses: actions/checkout@v4
- name: Build distribution
shell: bash
run: |
npm install
npm run build
- name: Setup Gradle
uses: ./
with:
add-job-summary: on-failure
- name: Build kotlin-dsl project
working-directory: .github/workflow-samples/kotlin-dsl
run: ./gradlew assemble
- name: Build kotlin-dsl project without Build Scan®
working-directory: .github/workflow-samples/kotlin-dsl
run: ./gradlew assemble check --no-scan
pre-existing-gradle-home:
runs-on: ubuntu-latest
steps:
- name: Checkout sources
uses: actions/checkout@v4
- name: Build distribution
shell: bash
run: |
npm install
npm run build
- name: Pre-create Gradle User Home
shell: bash
run: |
mkdir ~/.gradle
mkdir ~/.gradle/caches
touch ~/.gradle/caches/dummy.txt
- name: Setup Gradle
uses: ./
- name: Run build
working-directory: .github/workflow-samples/groovy-dsl
run: ./gradlew assemble

View File

@@ -1,27 +1,51 @@
name: Demo adding build scan comment to PR name: Demo adding Build Scan® comment to PR
on: on:
pull_request: pull_request:
types: [assigned, review_requested] types: [assigned, review_requested]
permissions:
pull-requests: write
jobs: jobs:
gradle: successful-build-with-always-comment:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Checkout project sources - name: Checkout project sources
uses: actions/checkout@v3 uses: actions/checkout@v4
- name: Setup Gradle - name: Setup Gradle
uses: ./ uses: ./
with:
add-job-summary-as-pr-comment: always
- name: Run build with Gradle wrapper - name: Run build with Gradle wrapper
id: gradle id: gradle
working-directory: .github/workflow-samples/kotlin-dsl working-directory: .github/workflow-samples/kotlin-dsl
run: ./gradlew build --scan run: ./gradlew build --scan
- name: "Add build scan URL as PR comment"
uses: actions/github-script@v6 successful-build-with-comment-on-failure:
runs-on: ubuntu-latest
steps:
- name: Checkout project sources
uses: actions/checkout@v4
- name: Setup Gradle
uses: ./
with: with:
github-token: ${{secrets.GITHUB_TOKEN}} add-job-summary-as-pr-comment: on-failure
script: | - name: Run build with Gradle wrapper
github.rest.issues.createComment({ id: gradle
issue_number: context.issue.number, working-directory: .github/workflow-samples/kotlin-dsl
owner: context.repo.owner, run: ./gradlew build --scan
repo: context.repo.repo,
body: 'PR ready for review: ${{ steps.gradle.outputs.build-scan-url }}' failing-build-with-comment-on-failure:
}) runs-on: ubuntu-latest
steps:
- name: Checkout project sources
uses: actions/checkout@v4
- name: Setup Gradle
uses: ./
with:
add-job-summary-as-pr-comment: on-failure
- name: Run build with Gradle wrapper
id: gradle
working-directory: .github/workflow-samples/kotlin-dsl
run: ./gradlew no-a-real-task --scan
continue-on-error: true

View File

@@ -25,7 +25,7 @@ jobs:
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
steps: steps:
- name: Checkout sources - name: Checkout sources
uses: actions/checkout@v3 uses: actions/checkout@v4
- name: Download distribution if required - name: Download distribution if required
uses: ./.github/actions/download-dist uses: ./.github/actions/download-dist
- name: Invoke with multi-line arguments - name: Invoke with multi-line arguments

View File

@@ -25,7 +25,7 @@ jobs:
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
steps: steps:
- name: Checkout sources - name: Checkout sources
uses: actions/checkout@v3 uses: actions/checkout@v4
- name: Download distribution if required - name: Download distribution if required
uses: ./.github/actions/download-dist uses: ./.github/actions/download-dist
- name: Setup Gradle - name: Setup Gradle
@@ -45,7 +45,7 @@ jobs:
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
steps: steps:
- name: Checkout sources - name: Checkout sources
uses: actions/checkout@v3 uses: actions/checkout@v4
- name: Download distribution if required - name: Download distribution if required
uses: ./.github/actions/download-dist uses: ./.github/actions/download-dist
- name: Setup Gradle - name: Setup Gradle
@@ -65,7 +65,7 @@ jobs:
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
steps: steps:
- name: Checkout sources - name: Checkout sources
uses: actions/checkout@v3 uses: actions/checkout@v4
- name: Download distribution if required - name: Download distribution if required
uses: ./.github/actions/download-dist uses: ./.github/actions/download-dist
- name: Setup Gradle - name: Setup Gradle

View File

@@ -1,4 +1,4 @@
name: Test action inputs for caching name: Test caching configuration
on: on:
workflow_call: workflow_call:
@@ -25,7 +25,7 @@ jobs:
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
steps: steps:
- name: Checkout sources - name: Checkout sources
uses: actions/checkout@v3 uses: actions/checkout@v4
- name: Download distribution if required - name: Download distribution if required
uses: ./.github/actions/download-dist uses: ./.github/actions/download-dist
- name: Setup Gradle - name: Setup Gradle
@@ -38,7 +38,8 @@ jobs:
enterprise enterprise
# Exclude build-cache from main cache entry # Exclude build-cache from main cache entry
gradle-home-cache-excludes: | gradle-home-cache-excludes: |
caches/build-cache-1 caches/build-cache-*
caches/*/executionHistory
- name: Build using Gradle wrapper - name: Build using Gradle wrapper
working-directory: .github/workflow-samples/groovy-dsl working-directory: .github/workflow-samples/groovy-dsl
run: ./gradlew test run: ./gradlew test
@@ -52,7 +53,7 @@ jobs:
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
steps: steps:
- name: Checkout sources - name: Checkout sources
uses: actions/checkout@v3 uses: actions/checkout@v4
- name: Download distribution if required - name: Download distribution if required
uses: ./.github/actions/download-dist uses: ./.github/actions/download-dist
- name: Setup Gradle - name: Setup Gradle
@@ -63,7 +64,8 @@ jobs:
caches caches
enterprise enterprise
gradle-home-cache-excludes: | gradle-home-cache-excludes: |
caches/build-cache-1 caches/build-cache-*
caches/*/executionHistory
cache-read-only: true cache-read-only: true
- name: Execute Gradle build with --offline - name: Execute Gradle build with --offline
working-directory: .github/workflow-samples/groovy-dsl working-directory: .github/workflow-samples/groovy-dsl
@@ -77,7 +79,7 @@ jobs:
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
steps: steps:
- name: Checkout sources - name: Checkout sources
uses: actions/checkout@v3 uses: actions/checkout@v4
- name: Download distribution if required - name: Download distribution if required
uses: ./.github/actions/download-dist uses: ./.github/actions/download-dist
- name: Setup Gradle - name: Setup Gradle
@@ -88,19 +90,19 @@ jobs:
id: gradle id: gradle
working-directory: .github/workflow-samples/no-wrapper${{ matrix.build-root-suffix }} working-directory: .github/workflow-samples/no-wrapper${{ matrix.build-root-suffix }}
run: gradle help "-DgradleVersionCheck=${{matrix.gradle}}" run: gradle help "-DgradleVersionCheck=${{matrix.gradle}}"
- name: Check build scan url is captured - name: Check Build Scan url is captured
if: ${{ !steps.gradle.outputs.build-scan-url }} if: ${{ !steps.gradle.outputs.build-scan-url }}
uses: actions/github-script@v6 uses: actions/github-script@v7
with: with:
script: | script: |
core.setFailed('No build scan detected') core.setFailed('No Build Scan detected')
# Test that build scans are captured when caching is disabled because Gradle User Home already exists # Test that build scans are captured when caching is disabled because Gradle User Home already exists
cache-disabled-pre-existing-gradle-home: cache-disabled-pre-existing-gradle-home:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Checkout sources - name: Checkout sources
uses: actions/checkout@v3 uses: actions/checkout@v4
- name: Download distribution if required - name: Download distribution if required
uses: ./.github/actions/download-dist uses: ./.github/actions/download-dist
- name: Create dummy Gradle User Home - name: Create dummy Gradle User Home
@@ -111,12 +113,12 @@ jobs:
id: gradle id: gradle
working-directory: .github/workflow-samples/no-wrapper${{ matrix.build-root-suffix }} working-directory: .github/workflow-samples/no-wrapper${{ matrix.build-root-suffix }}
run: gradle help "-DgradleVersionCheck=${{matrix.gradle}}" run: gradle help "-DgradleVersionCheck=${{matrix.gradle}}"
- name: Check build scan url is captured - name: Check Build Scan url is captured
if: ${{ !steps.gradle.outputs.build-scan-url }} if: ${{ !steps.gradle.outputs.build-scan-url }}
uses: actions/github-script@v6 uses: actions/github-script@v7
with: with:
script: | script: |
core.setFailed('No build scan detected') core.setFailed('No Build Scan detected')
# Test seed the cache with cache-write-only and verify with cache-read-only # Test seed the cache with cache-write-only and verify with cache-read-only
seed-build-write-only: seed-build-write-only:
@@ -128,7 +130,7 @@ jobs:
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
steps: steps:
- name: Checkout sources - name: Checkout sources
uses: actions/checkout@v3 uses: actions/checkout@v4
- name: Download distribution if required - name: Download distribution if required
uses: ./.github/actions/download-dist uses: ./.github/actions/download-dist
- name: Setup Gradle - name: Setup Gradle
@@ -149,7 +151,7 @@ jobs:
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
steps: steps:
- name: Checkout sources - name: Checkout sources
uses: actions/checkout@v3 uses: actions/checkout@v4
- name: Download distribution if required - name: Download distribution if required
uses: ./.github/actions/download-dist uses: ./.github/actions/download-dist
- name: Setup Gradle - name: Setup Gradle

View File

@@ -1,4 +1,4 @@
name: Test execution with caching name: Test dependency graph
on: on:
workflow_call: workflow_call:
@@ -12,6 +12,9 @@ on:
type: boolean type: boolean
default: false default: false
permissions:
contents: write
env: env:
DOWNLOAD_DIST: ${{ inputs.download-dist }} DOWNLOAD_DIST: ${{ inputs.download-dist }}
GRADLE_BUILD_ACTION_CACHE_KEY_PREFIX: dependency-graph-${{ inputs.cache-key-prefix }} GRADLE_BUILD_ACTION_CACHE_KEY_PREFIX: dependency-graph-${{ inputs.cache-key-prefix }}
@@ -25,13 +28,13 @@ jobs:
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
steps: steps:
- name: Checkout sources - name: Checkout sources
uses: actions/checkout@v3 uses: actions/checkout@v4
- name: Download distribution if required - name: Download distribution if required
uses: ./.github/actions/download-dist uses: ./.github/actions/download-dist
- name: Setup Gradle for dependency-graph generate - name: Setup Gradle for dependency-graph generate
uses: ./ uses: ./
with: with:
dependency-graph: generate dependency-graph: generate-and-upload
- name: Run gradle build - name: Run gradle build
run: ./gradlew build run: ./gradlew build
working-directory: .github/workflow-samples/groovy-dsl working-directory: .github/workflow-samples/groovy-dsl
@@ -43,7 +46,7 @@ jobs:
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
steps: steps:
- name: Checkout sources - name: Checkout sources
uses: actions/checkout@v3 uses: actions/checkout@v4
- name: Download distribution if required - name: Download distribution if required
uses: ./.github/actions/download-dist uses: ./.github/actions/download-dist
- name: Setup Gradle for dependency-graph generate - name: Setup Gradle for dependency-graph generate
@@ -55,11 +58,11 @@ jobs:
working-directory: .github/workflow-samples/kotlin-dsl working-directory: .github/workflow-samples/kotlin-dsl
submit: submit:
needs: [groovy-generate, kotlin-generate] needs: [groovy-generate]
runs-on: "ubuntu-latest" runs-on: "ubuntu-latest"
steps: steps:
- name: Checkout sources - name: Checkout sources
uses: actions/checkout@v3 uses: actions/checkout@v4
- name: Download distribution if required - name: Download distribution if required
uses: ./.github/actions/download-dist uses: ./.github/actions/download-dist
- name: Submit dependency graphs - name: Submit dependency graphs
@@ -68,31 +71,36 @@ jobs:
dependency-graph: download-and-submit dependency-graph: download-and-submit
multiple-builds: multiple-builds:
runs-on: "ubuntu-latest" strategy:
matrix:
os: ${{fromJSON(inputs.runner-os)}}
runs-on: ${{ matrix.os }}
steps: steps:
- name: Checkout sources - name: Checkout sources
uses: actions/checkout@v3 uses: actions/checkout@v4
- name: Download distribution if required - name: Download distribution if required
uses: ./.github/actions/download-dist uses: ./.github/actions/download-dist
- name: Setup Gradle for dependency-graph generate - name: Setup Gradle for dependency-graph generate
uses: ./ uses: ./
with: with:
dependency-graph: generate dependency-graph: generate-and-submit
- name: Run assemble - id: gradle-assemble
run: ./gradlew assemble run: ./gradlew assemble
working-directory: .github/workflow-samples/groovy-dsl working-directory: .github/workflow-samples/groovy-dsl
env: - id: gradle-build
GITHUB_JOB_CORRELATOR: job-correlator
- name: Run build
run: ./gradlew build run: ./gradlew build
working-directory: .github/workflow-samples/groovy-dsl working-directory: .github/workflow-samples/groovy-dsl
env:
GITHUB_JOB_CORRELATOR: job-correlator
- name: Check generated dependency graphs - name: Check generated dependency graphs
shell: bash
run: | run: |
echo "gradle-assemble report file: ${{ steps.gradle-assemble.outputs.dependency-graph-file }}"
echo "gradle-build report file: ${{ steps.gradle-build.outputs.dependency-graph-file }}"
ls -l dependency-graph-reports ls -l dependency-graph-reports
if ([ ! -e dependency-graph-reports/job-correlator.json ] || [ ! -e dependency-graph-reports/job-correlator-1.json ]) if [ ! -e "${{ steps.gradle-assemble.outputs.dependency-graph-file }}" ]; then
then echo "Did not find gradle-assemble dependency graph file"
echo "Did not find expected dependency graph files"
exit 1 exit 1
fi fi
if [ ! -e "${{ steps.gradle-build.outputs.dependency-graph-file }}" ]; then
echo "Did not find gradle-build dependency graph files"
exit 1
fi

View File

@@ -0,0 +1,93 @@
name: Test detect java toolchains
on:
workflow_call:
inputs:
cache-key-prefix:
type: string
runner-os:
type: string
default: '["ubuntu-latest", "windows-latest", "macos-latest"]'
download-dist:
type: boolean
default: false
env:
DOWNLOAD_DIST: ${{ inputs.download-dist }}
GRADLE_BUILD_ACTION_CACHE_KEY_PREFIX: detect-java-toolchain-${{ inputs.cache-key-prefix }}
GRADLE_BUILD_ACTION_CACHE_DEBUG_ENABLED: true
jobs:
# Test that pre-installed runner JDKs are detected
pre-installed-toolchains:
strategy:
fail-fast: false
matrix:
os: ${{fromJSON(inputs.runner-os)}}
runs-on: ${{ matrix.os }}
steps:
- name: Checkout sources
uses: actions/checkout@v4
- name: Download distribution if required
uses: ./.github/actions/download-dist
- name: Setup Gradle
uses: ./
- name: List detected toolchains
shell: bash
working-directory: .github/workflow-samples/groovy-dsl
run: |
gradle --info javaToolchains > output.txt
cat output.txt
- name: Verify detected toolchains
shell: bash
working-directory: .github/workflow-samples/groovy-dsl
run: |
grep -q 'Eclipse Temurin JDK 1.8' output.txt || (echo "::error::Did not detect preinstalled JDK 1.8" && exit 1)
grep -q 'Eclipse Temurin JDK 11' output.txt || (echo "::error::Did not detect preinstalled JDK 11" && exit 1)
grep -q 'Eclipse Temurin JDK 17' output.txt || (echo "::error::Did not detect preinstalled JDK 17" && exit 1)
grep -q 'Eclipse Temurin JDK 21' output.txt || (echo "::error::Did not detect preinstalled JDK 21" && exit 1)
# Test that JDKs provisioned by setup-java are detected
setup-java-installed-toolchain:
strategy:
fail-fast: false
matrix:
os: ${{fromJSON(inputs.runner-os)}}
runs-on: ${{ matrix.os }}
steps:
- name: Checkout sources
uses: actions/checkout@v4
- name: Download distribution if required
uses: ./.github/actions/download-dist
- name: Setup Java 20
uses: actions/setup-java@v4
with:
distribution: 'temurin'
java-version: '20'
- name: Setup Java 16
uses: actions/setup-java@v4
with:
distribution: 'temurin'
java-version: '16'
- name: Setup Gradle
uses: ./
- name: List detected toolchains
shell: bash
working-directory: .github/workflow-samples/groovy-dsl
run: |
gradle --info javaToolchains > output.txt
cat output.txt
- name: Verify setup JDKs are detected
shell: bash
working-directory: .github/workflow-samples/groovy-dsl
run: |
grep -q 'Eclipse Temurin JDK 16' output.txt || (echo "::error::Did not detect setup-java installed JDK 16" && exit 1)
grep -q 'Eclipse Temurin JDK 20' output.txt || (echo "::error::Did not detect setup-java installed JDK 20" && exit 1)
- name: Verify pre-installed toolchains are detected
shell: bash
working-directory: .github/workflow-samples/groovy-dsl
run: |
grep -q 'Eclipse Temurin JDK 1.8' output.txt || (echo "::error::Did not detect preinstalled JDK 1.8" && exit 1)
grep -q 'Eclipse Temurin JDK 11' output.txt || (echo "::error::Did not detect preinstalled JDK 11" && exit 1)
grep -q 'Eclipse Temurin JDK 17' output.txt || (echo "::error::Did not detect preinstalled JDK 17" && exit 1)
grep -q 'Eclipse Temurin JDK 21' output.txt || (echo "::error::Did not detect preinstalled JDK 21" && exit 1)

View File

@@ -25,7 +25,7 @@ jobs:
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
steps: steps:
- name: Checkout sources - name: Checkout sources
uses: actions/checkout@v3 uses: actions/checkout@v4
- name: Download distribution if required - name: Download distribution if required
uses: ./.github/actions/download-dist uses: ./.github/actions/download-dist
- name: Execute Gradle build - name: Execute Gradle build
@@ -44,7 +44,7 @@ jobs:
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
steps: steps:
- name: Checkout sources - name: Checkout sources
uses: actions/checkout@v3 uses: actions/checkout@v4
- name: Download distribution if required - name: Download distribution if required
uses: ./.github/actions/download-dist uses: ./.github/actions/download-dist
- name: Execute Gradle build - name: Execute Gradle build

View File

@@ -30,7 +30,7 @@ jobs:
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
steps: steps:
- name: Checkout sources - name: Checkout sources
uses: actions/checkout@v3 uses: actions/checkout@v4
- name: Download distribution if required - name: Download distribution if required
uses: ./.github/actions/download-dist uses: ./.github/actions/download-dist
- name: Test use defined Gradle version - name: Test use defined Gradle version
@@ -68,11 +68,11 @@ jobs:
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
steps: steps:
- name: Checkout sources - name: Checkout sources
uses: actions/checkout@v3 uses: actions/checkout@v4
- name: Download distribution if required - name: Download distribution if required
uses: ./.github/actions/download-dist uses: ./.github/actions/download-dist
- name: Setup Java - name: Setup Java
uses: actions/setup-java@v3 uses: actions/setup-java@v4
with: with:
distribution: temurin distribution: temurin
java-version: 8 java-version: 8
@@ -84,11 +84,11 @@ jobs:
gradle-version: ${{matrix.gradle}} gradle-version: ${{matrix.gradle}}
build-root-directory: .github/workflow-samples/no-wrapper${{ matrix.build-root-suffix }} build-root-directory: .github/workflow-samples/no-wrapper${{ matrix.build-root-suffix }}
arguments: help -DgradleVersionCheck=${{matrix.gradle}} arguments: help -DgradleVersionCheck=${{matrix.gradle}}
- name: Check build scan url - name: Check Build Scan url
if: ${{ !steps.gradle.outputs.build-scan-url }} if: ${{ !steps.gradle.outputs.build-scan-url }}
uses: actions/github-script@v6 uses: actions/github-script@v7
with: with:
script: | script: |
core.setFailed('No build scan detected') core.setFailed('No Build Scan detected')

View File

@@ -0,0 +1,60 @@
name: Test gradle enterprise injection
on:
workflow_call:
inputs:
cache-key-prefix:
type: string
runner-os:
type: string
default: '["ubuntu-latest", "windows-latest", "macos-latest"]'
download-dist:
type: boolean
default: false
secrets:
GRADLE_ENTERPRISE_ACCESS_KEY:
required: true
env:
DOWNLOAD_DIST: ${{ inputs.download-dist }}
GRADLE_BUILD_ACTION_CACHE_KEY_PREFIX: provision-gradle-versions-${{ inputs.cache-key-prefix }}
GRADLE_BUILD_ACTION_CACHE_DEBUG_ENABLED: true
GRADLE_ENTERPRISE_INJECTION_ENABLED: true
GRADLE_ENTERPRISE_URL: https://ge.solutions-team.gradle.com
GRADLE_ENTERPRISE_PLUGIN_VERSION: 3.16.1
GRADLE_ENTERPRISE_CCUD_PLUGIN_VERSION: 1.12.1
GRADLE_ENTERPRISE_ACCESS_KEY: ${{ secrets.GRADLE_ENTERPRISE_ACCESS_KEY }}
jobs:
inject-gradle-enterprise:
strategy:
matrix:
gradle: [current, 7.6.2, 6.9.4, 5.6.4]
os: ${{fromJSON(inputs.runner-os)}}
runs-on: ubuntu-latest
steps:
- name: Checkout sources
uses: actions/checkout@v4
- name: Download distribution if required
uses: ./.github/actions/download-dist
- name: Setup Java
uses: actions/setup-java@v4
with:
distribution: temurin
java-version: 8
- name: Setup Gradle
id: setup-gradle
uses: ./
with:
cache-read-only: false # For testing, allow writing cache entries on non-default branches
gradle-version: ${{ matrix.gradle }}
- name: Run Gradle build
id: gradle
working-directory: .github/workflow-samples/no-ge
run: gradle help
- name: Check Build Scan url
if: ${{ !steps.gradle.outputs.build-scan-url }}
uses: actions/github-script@v7
with:
script: |
core.setFailed('No Build Scan detected')

View File

@@ -30,7 +30,7 @@ jobs:
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
steps: steps:
- name: Checkout sources - name: Checkout sources
uses: actions/checkout@v3 uses: actions/checkout@v4
- name: Download distribution if required - name: Download distribution if required
uses: ./.github/actions/download-dist uses: ./.github/actions/download-dist
- name: Setup Gradle with v6.9 - name: Setup Gradle with v6.9
@@ -55,6 +55,17 @@ jobs:
- name: Test use release-candidate - name: Test use release-candidate
working-directory: .github/workflow-samples/no-wrapper working-directory: .github/workflow-samples/no-wrapper
run: gradle help run: gradle help
- name: Setup Gradle with current
id: gradle-current
uses: ./
with:
gradle-version: current
- name: Check current version output parameter
if: ${{ !startsWith(steps.gradle-current.outputs.gradle-version , '8.') }}
uses: actions/github-script@v7
with:
script: |
core.setFailed('Gradle version parameter not set correctly: value was "${{ steps.gradle-current.outputs.gradle-version }}"')
gradle-versions: gradle-versions:
strategy: strategy:
@@ -71,28 +82,35 @@ jobs:
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
steps: steps:
- name: Checkout sources - name: Checkout sources
uses: actions/checkout@v3 uses: actions/checkout@v4
- name: Download distribution if required - name: Download distribution if required
uses: ./.github/actions/download-dist uses: ./.github/actions/download-dist
- name: Setup Java - name: Setup Java
uses: actions/setup-java@v3 uses: actions/setup-java@v4
with: with:
distribution: temurin distribution: temurin
java-version: 8 java-version: 8
- name: Setup Gradle - name: Setup Gradle
id: setup-gradle
uses: ./ uses: ./
with: with:
cache-read-only: false # For testing, allow writing cache entries on non-default branches cache-read-only: false # For testing, allow writing cache entries on non-default branches
gradle-version: ${{ matrix.gradle }} gradle-version: ${{ matrix.gradle }}
- name: Check output parameter
if: ${{ steps.setup-gradle.outputs.gradle-version != matrix.gradle }}
uses: actions/github-script@v7
with:
script: |
core.setFailed('Gradle version parameter not set correctly: value was "${{ steps.setup-gradle.outputs.gradle-version }}"')
- name: Run Gradle build - name: Run Gradle build
id: gradle id: gradle
working-directory: .github/workflow-samples/no-wrapper${{ matrix.build-root-suffix }} working-directory: .github/workflow-samples/no-wrapper${{ matrix.build-root-suffix }}
run: gradle help "-DgradleVersionCheck=${{matrix.gradle}}" run: gradle help "-DgradleVersionCheck=${{matrix.gradle}}"
- name: Check build scan url - name: Check Build Scan url
if: ${{ !steps.gradle.outputs.build-scan-url }} if: ${{ !steps.gradle.outputs.build-scan-url }}
uses: actions/github-script@v6 uses: actions/github-script@v7
with: with:
script: | script: |
core.setFailed('No build scan detected') core.setFailed('No Build Scan detected')

View File

@@ -11,6 +11,9 @@ on:
download-dist: download-dist:
type: boolean type: boolean
default: false default: false
secrets:
GRADLE_ENCRYPTION_KEY:
required: true
env: env:
DOWNLOAD_DIST: ${{ inputs.download-dist }} DOWNLOAD_DIST: ${{ inputs.download-dist }}
@@ -27,16 +30,18 @@ jobs:
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
steps: steps:
- name: Checkout sources - name: Checkout sources
uses: actions/checkout@v3 uses: actions/checkout@v4
- name: Download distribution if required - name: Download distribution if required
uses: ./.github/actions/download-dist uses: ./.github/actions/download-dist
- name: Setup Gradle - name: Setup Gradle
uses: ./ uses: ./
with: with:
cache-read-only: false # For testing, allow writing cache entries on non-default branches cache-read-only: false # For testing, allow writing cache entries on non-default branches
cache-encryption-key: ${{ secrets.GRADLE_ENCRYPTION_KEY }}
gradle-version: 8.6-rc-1
- name: Groovy build with configuration-cache enabled - name: Groovy build with configuration-cache enabled
working-directory: .github/workflow-samples/groovy-dsl working-directory: .github/workflow-samples/groovy-dsl
run: ./gradlew test --configuration-cache run: gradle test --configuration-cache
verify-build-groovy: verify-build-groovy:
env: env:
@@ -48,19 +53,21 @@ jobs:
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
steps: steps:
- name: Checkout sources - name: Checkout sources
uses: actions/checkout@v3 uses: actions/checkout@v4
- name: Download distribution if required - name: Download distribution if required
uses: ./.github/actions/download-dist uses: ./.github/actions/download-dist
- name: Setup Gradle - name: Setup Gradle
uses: ./ uses: ./
with: with:
cache-read-only: true cache-read-only: true
cache-encryption-key: ${{ secrets.GRADLE_ENCRYPTION_KEY }}
gradle-version: 8.6-rc-1
- name: Groovy build with configuration-cache enabled - name: Groovy build with configuration-cache enabled
id: execute id: execute
working-directory: .github/workflow-samples/groovy-dsl working-directory: .github/workflow-samples/groovy-dsl
run: ./gradlew test --configuration-cache run: gradle test --configuration-cache
- name: Check that configuration-cache was used - name: Check that configuration-cache was used
uses: actions/github-script@v6 uses: actions/github-script@v7
with: with:
script: | script: |
const fs = require('fs') const fs = require('fs')
@@ -79,7 +86,7 @@ jobs:
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
steps: steps:
- name: Checkout sources - name: Checkout sources
uses: actions/checkout@v3 uses: actions/checkout@v4
- name: Download distribution if required - name: Download distribution if required
uses: ./.github/actions/download-dist uses: ./.github/actions/download-dist
- name: Setup Gradle with no extracted cache entries restored - name: Setup Gradle with no extracted cache entries restored
@@ -88,9 +95,11 @@ jobs:
GRADLE_BUILD_ACTION_SKIP_RESTORE: "generated-gradle-jars|wrapper-zips|java-toolchains|instrumented-jars|dependencies|kotlin-dsl" GRADLE_BUILD_ACTION_SKIP_RESTORE: "generated-gradle-jars|wrapper-zips|java-toolchains|instrumented-jars|dependencies|kotlin-dsl"
with: with:
cache-read-only: true cache-read-only: true
cache-encryption-key: ${{ secrets.GRADLE_ENCRYPTION_KEY }}
gradle-version: 8.6-rc-1
- name: Check execute Gradle build with configuration cache enabled (but not restored) - name: Check execute Gradle build with configuration cache enabled (but not restored)
working-directory: .github/workflow-samples/groovy-dsl working-directory: .github/workflow-samples/groovy-dsl
run: ./gradlew test --configuration-cache run: gradle test --configuration-cache
seed-build-kotlin: seed-build-kotlin:
env: env:
@@ -101,16 +110,18 @@ jobs:
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
steps: steps:
- name: Checkout sources - name: Checkout sources
uses: actions/checkout@v3 uses: actions/checkout@v4
- name: Download distribution if required - name: Download distribution if required
uses: ./.github/actions/download-dist uses: ./.github/actions/download-dist
- name: Setup Gradle - name: Setup Gradle
uses: ./ uses: ./
with: with:
cache-read-only: false # For testing, allow writing cache entries on non-default branches cache-read-only: false # For testing, allow writing cache entries on non-default branches
cache-encryption-key: ${{ secrets.GRADLE_ENCRYPTION_KEY }}
gradle-version: 8.6-rc-1
- name: Execute 'help' with configuration-cache enabled - name: Execute 'help' with configuration-cache enabled
working-directory: .github/workflow-samples/kotlin-dsl working-directory: .github/workflow-samples/kotlin-dsl
run: ./gradlew help --configuration-cache run: gradle help --configuration-cache
modify-build-kotlin: modify-build-kotlin:
env: env:
@@ -122,16 +133,18 @@ jobs:
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
steps: steps:
- name: Checkout sources - name: Checkout sources
uses: actions/checkout@v3 uses: actions/checkout@v4
- name: Download distribution if required - name: Download distribution if required
uses: ./.github/actions/download-dist uses: ./.github/actions/download-dist
- name: Setup Gradle - name: Setup Gradle
uses: ./ uses: ./
with: with:
cache-read-only: false # For testing, allow writing cache entries on non-default branches cache-read-only: false # For testing, allow writing cache entries on non-default branches
cache-encryption-key: ${{ secrets.GRADLE_ENCRYPTION_KEY }}
gradle-version: 8.6-rc-1
- name: Execute 'test' with configuration-cache enabled - name: Execute 'test' with configuration-cache enabled
working-directory: .github/workflow-samples/kotlin-dsl working-directory: .github/workflow-samples/kotlin-dsl
run: ./gradlew test --configuration-cache run: gradle test --configuration-cache
# Test restore configuration-cache from the third build invocation # Test restore configuration-cache from the third build invocation
verify-build-kotlin: verify-build-kotlin:
@@ -144,19 +157,21 @@ jobs:
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
steps: steps:
- name: Checkout sources - name: Checkout sources
uses: actions/checkout@v3 uses: actions/checkout@v4
- name: Download distribution if required - name: Download distribution if required
uses: ./.github/actions/download-dist uses: ./.github/actions/download-dist
- name: Setup Gradle - name: Setup Gradle
uses: ./ uses: ./
with: with:
cache-read-only: true cache-read-only: true
cache-encryption-key: ${{ secrets.GRADLE_ENCRYPTION_KEY }}
gradle-version: 8.6-rc-1
- name: Execute 'test' again with configuration-cache enabled - name: Execute 'test' again with configuration-cache enabled
id: execute id: execute
working-directory: .github/workflow-samples/kotlin-dsl working-directory: .github/workflow-samples/kotlin-dsl
run: ./gradlew test --configuration-cache run: gradle test --configuration-cache
- name: Check that configuration-cache was used - name: Check that configuration-cache was used
uses: actions/github-script@v6 uses: actions/github-script@v7
with: with:
script: | script: |
const fs = require('fs') const fs = require('fs')

View File

@@ -20,11 +20,11 @@ jobs:
container: fedora:latest container: fedora:latest
steps: steps:
- name: Checkout sources - name: Checkout sources
uses: actions/checkout@v3 uses: actions/checkout@v4
- name: Download distribution if required - name: Download distribution if required
uses: ./.github/actions/download-dist uses: ./.github/actions/download-dist
- name: Setup Java - name: Setup Java
uses: actions/setup-java@v3 uses: actions/setup-java@v4
with: with:
java-version: 11 java-version: 11
distribution: temurin distribution: temurin
@@ -43,11 +43,11 @@ jobs:
container: fedora:latest container: fedora:latest
steps: steps:
- name: Checkout sources - name: Checkout sources
uses: actions/checkout@v3 uses: actions/checkout@v4
- name: Download distribution if required - name: Download distribution if required
uses: ./.github/actions/download-dist uses: ./.github/actions/download-dist
- name: Setup Java - name: Setup Java
uses: actions/setup-java@v3 uses: actions/setup-java@v4
with: with:
java-version: 11 java-version: 11
distribution: temurin distribution: temurin

View File

@@ -23,7 +23,7 @@ jobs:
mkdir -p $GITHUB_WORKSPACE/gradle-user-home mkdir -p $GITHUB_WORKSPACE/gradle-user-home
echo "GRADLE_USER_HOME=$GITHUB_WORKSPACE/gradle-user-home" >> $GITHUB_ENV echo "GRADLE_USER_HOME=$GITHUB_WORKSPACE/gradle-user-home" >> $GITHUB_ENV
- name: Checkout sources - name: Checkout sources
uses: actions/checkout@v3 uses: actions/checkout@v4
- name: Download distribution if required - name: Download distribution if required
uses: ./.github/actions/download-dist uses: ./.github/actions/download-dist
- name: Setup Gradle - name: Setup Gradle
@@ -44,7 +44,7 @@ jobs:
mkdir -p $GITHUB_WORKSPACE/gradle-user-home mkdir -p $GITHUB_WORKSPACE/gradle-user-home
echo "GRADLE_USER_HOME=$GITHUB_WORKSPACE/gradle-user-home" >> $GITHUB_ENV echo "GRADLE_USER_HOME=$GITHUB_WORKSPACE/gradle-user-home" >> $GITHUB_ENV
- name: Checkout sources - name: Checkout sources
uses: actions/checkout@v3 uses: actions/checkout@v4
- name: Download distribution if required - name: Download distribution if required
uses: ./.github/actions/download-dist uses: ./.github/actions/download-dist
- name: Setup Gradle - name: Setup Gradle
@@ -65,7 +65,7 @@ jobs:
mkdir -p $GITHUB_WORKSPACE/gradle-user-home mkdir -p $GITHUB_WORKSPACE/gradle-user-home
echo "GRADLE_USER_HOME=$GITHUB_WORKSPACE/gradle-user-home" >> $GITHUB_ENV echo "GRADLE_USER_HOME=$GITHUB_WORKSPACE/gradle-user-home" >> $GITHUB_ENV
- name: Checkout sources - name: Checkout sources
uses: actions/checkout@v3 uses: actions/checkout@v4
- name: Download distribution if required - name: Download distribution if required
uses: ./.github/actions/download-dist uses: ./.github/actions/download-dist
- name: Setup Gradle - name: Setup Gradle

View File

@@ -26,7 +26,7 @@ jobs:
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
steps: steps:
- name: Checkout sources - name: Checkout sources
uses: actions/checkout@v3 uses: actions/checkout@v4
- name: Download distribution if required - name: Download distribution if required
uses: ./.github/actions/download-dist uses: ./.github/actions/download-dist
- name: Setup Gradle - name: Setup Gradle
@@ -46,7 +46,7 @@ jobs:
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
steps: steps:
- name: Checkout sources - name: Checkout sources
uses: actions/checkout@v3 uses: actions/checkout@v4
- name: Download distribution if required - name: Download distribution if required
uses: ./.github/actions/download-dist uses: ./.github/actions/download-dist
- name: Setup Gradle - name: Setup Gradle
@@ -66,7 +66,7 @@ jobs:
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
steps: steps:
- name: Checkout sources - name: Checkout sources
uses: actions/checkout@v3 uses: actions/checkout@v4
- name: Download distribution if required - name: Download distribution if required
uses: ./.github/actions/download-dist uses: ./.github/actions/download-dist
- name: Setup Gradle - name: Setup Gradle
@@ -86,7 +86,7 @@ jobs:
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
steps: steps:
- name: Checkout sources - name: Checkout sources
uses: actions/checkout@v3 uses: actions/checkout@v4
- name: Download distribution if required - name: Download distribution if required
uses: ./.github/actions/download-dist uses: ./.github/actions/download-dist
- name: Setup Gradle with no extracted cache entries restored - name: Setup Gradle with no extracted cache entries restored
@@ -99,3 +99,40 @@ jobs:
working-directory: .github/workflow-samples/groovy-dsl working-directory: .github/workflow-samples/groovy-dsl
run: ./gradlew test run: ./gradlew test
# Test that a pre-existing gradle-user-home can be overwritten by the restored cache
pre-existing-gradle-home:
needs: seed-build
strategy:
matrix:
os: ${{fromJSON(inputs.runner-os)}}
runs-on: ${{ matrix.os }}
steps:
- name: Checkout sources
uses: actions/checkout@v4
- name: Download distribution if required
uses: ./.github/actions/download-dist
- name: Pre-create Gradle User Home
shell: bash
run: |
mkdir -p ~/.gradle/caches
touch ~/.gradle/gradle.properties
touch ~/.gradle/caches/dummy.txt
- name: Setup Gradle
uses: ./
with:
cache-read-only: true
cache-overwrite-existing: true
- name: Check that pre-existing content still exists
shell: bash
run: |
if [ ! -e ~/.gradle/caches/dummy.txt ]; then
echo "::error ::Should find dummy.txt after cache restore"
exit 1
fi
if [ ! -e ~/.gradle/gradle.properties ]; then
echo "::error ::Should find gradle.properties after cache restore"
exit 1
fi
- name: Execute Gradle build with --offline
working-directory: .github/workflow-samples/groovy-dsl
run: ./gradlew test --offline

View File

@@ -25,7 +25,7 @@ jobs:
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
steps: steps:
- name: Checkout sources - name: Checkout sources
uses: actions/checkout@v3 uses: actions/checkout@v4
- name: Download distribution if required - name: Download distribution if required
uses: ./.github/actions/download-dist uses: ./.github/actions/download-dist
- name: Setup Gradle - name: Setup Gradle
@@ -45,7 +45,7 @@ jobs:
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
steps: steps:
- name: Checkout sources - name: Checkout sources
uses: actions/checkout@v3 uses: actions/checkout@v4
- name: Download distribution if required - name: Download distribution if required
uses: ./.github/actions/download-dist uses: ./.github/actions/download-dist
- name: Setup Gradle - name: Setup Gradle

View File

@@ -25,7 +25,7 @@ jobs:
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
steps: steps:
- name: Checkout sources - name: Checkout sources
uses: actions/checkout@v3 uses: actions/checkout@v4
- name: Download distribution if required - name: Download distribution if required
uses: ./.github/actions/download-dist uses: ./.github/actions/download-dist
- name: Setup Gradle - name: Setup Gradle
@@ -44,7 +44,7 @@ jobs:
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
steps: steps:
- name: Checkout sources - name: Checkout sources
uses: actions/checkout@v3 uses: actions/checkout@v4
- name: Download distribution if required - name: Download distribution if required
uses: ./.github/actions/download-dist uses: ./.github/actions/download-dist
- name: Setup Gradle - name: Setup Gradle

View File

@@ -25,7 +25,7 @@ jobs:
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
steps: steps:
- name: Checkout sources - name: Checkout sources
uses: actions/checkout@v3 uses: actions/checkout@v4
- name: Download distribution if required - name: Download distribution if required
uses: ./.github/actions/download-dist uses: ./.github/actions/download-dist
- name: Setup Gradle - name: Setup Gradle
@@ -44,7 +44,7 @@ jobs:
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
steps: steps:
- name: Checkout sources - name: Checkout sources
uses: actions/checkout@v3 uses: actions/checkout@v4
- name: Download distribution if required - name: Download distribution if required
uses: ./.github/actions/download-dist uses: ./.github/actions/download-dist
- name: Setup Gradle - name: Setup Gradle

View File

@@ -1,3 +1,3 @@
# Configuration file for asdf version manager # Configuration file for asdf version manager
nodejs 16.18.1 nodejs 20.10.0
gradle 8.2.1 gradle 8.5

842
README.md

File diff suppressed because it is too large Load Diff

View File

@@ -1,5 +1,5 @@
name: "Gradle Build Action" name: "Gradle Build Action"
description: 'Configures Gradle for use in GitHub actions, caching useful state in the GitHub actions cache' description: 'Configures Gradle for GitHub actions, caching state and generating a dependency graph via Dependency Submission.'
# https://help.github.com/en/articles/metadata-syntax-for-github-actions # https://help.github.com/en/articles/metadata-syntax-for-github-actions
@@ -8,14 +8,6 @@ inputs:
description: Gradle version to use. If specified, this Gradle version will be downloaded, added to the PATH and used for invoking Gradle. description: Gradle version to use. If specified, this Gradle version will be downloaded, added to the PATH and used for invoking Gradle.
required: false required: false
gradle-executable:
description: Path to the Gradle executable. If specified, this executable will be added to the PATH and used for invoking Gradle.
required: false
build-root-directory:
description: Path to the root directory of the build. Default is the root of the GitHub workspace.
required: false
cache-disabled: cache-disabled:
description: When 'true', all caching is disabled. No entries will be written to or read from the cache. description: When 'true', all caching is disabled. No entries will be written to or read from the cache.
required: false required: false
@@ -35,6 +27,18 @@ inputs:
required: false required: false
default: false default: false
cache-overwrite-existing:
description: When 'true', a pre-existing Gradle User Home will not prevent the cache from being restored.
required: false
default: false
cache-encryption-key:
description: |
A base64 encoded AES key used to encrypt the configuration-cache data. The key is exported as 'GRADLE_ENCRYPTION_KEY' for later steps.
A suitable key can be generated with `openssl rand -base64 16`.
Configuration-cache data will not be saved/restored without an encryption key being provided.
required: false
gradle-home-cache-includes: gradle-home-cache-includes:
description: Paths within Gradle User Home to cache. description: Paths within Gradle User Home to cache.
required: false required: false
@@ -49,19 +53,51 @@ inputs:
# gradle-home-cache-excludes: | # gradle-home-cache-excludes: |
# caches/build-cache-1 # caches/build-cache-1
gradle-home-cache-cleanup:
description: When 'true', the action will attempt to remove any stale/unused entries from the Gradle User Home prior to saving to the GitHub Actions cache.
required: false
default: false
add-job-summary:
description: Specifies when a Job Summary should be inluded in the action results. Valid values are 'never', 'always' (default), and 'on-failure'.
required: false
default: 'always'
add-job-summary-as-pr-comment:
description: Specifies when each Job Summary should be added as a PR comment. Valid values are 'never' (default), 'always', and 'on-failure'. No action will be taken if the workflow was not triggered from a pull request.
required: false
default: 'never'
dependency-graph:
description: Specifies if a GitHub dependency snapshot should be generated for each Gradle build, and if so, how. Valid values are 'disabled' (default), 'generate', 'generate-and-submit', 'generate-and-upload' and 'download-and-submit'.
required: false
default: 'disabled'
artifact-retention-days:
description: Specifies the number of days to retain any artifacts generated by the action. If not set, the default retention settings for the repository will apply.
required: false
# DEPRECATED ACTION INPUTS
arguments: arguments:
description: Gradle command line arguments (supports multi-line input) description: Gradle command line arguments (supports multi-line input)
required: false required: false
deprecation-message: Using the action to execute Gradle directly is deprecated in favor of using the action to setup Gradle, and executing Gradle in a subsequent Step. See https://github.com/gradle/gradle-build-action?tab=readme-ov-file#use-the-action-to-setup-gradle.
build-root-directory:
description: Path to the root directory of the build. Default is the root of the GitHub workspace.
required: false
deprecation-message: Using the action to execute Gradle directly is deprecated in favor of using the action to setup Gradle, and executing Gradle in a subsequent Step. See https://github.com/gradle/gradle-build-action?tab=readme-ov-file#use-the-action-to-setup-gradle.
gradle-executable:
description: Path to the Gradle executable. If specified, this executable will be added to the PATH and used for invoking Gradle.
required: false
deprecation-message: Using the action to execute Gradle directly is deprecated in favor of using the action to setup Gradle, and executing Gradle in a subsequent Step. See https://github.com/gradle/gradle-build-action?tab=readme-ov-file#use-the-action-to-setup-gradle.
generate-job-summary: generate-job-summary:
description: When 'false', no Job Summary will be generated for the Job. description: When 'false', no Job Summary will be generated for the Job.
required: false required: false
default: true default: true
deprecation-message: Superceded by the new 'add-job-summary' and 'add-job-summary-as-pr-comment' parameters.
dependency-graph:
description: Specifies if a GitHub dependency snapshot should be generated for each Gradle build, and if so, how. Valid values are 'disabled' (default), 'generate', 'generate-and-submit' and 'download-and-submit'.
required: false
default: 'disabled'
# EXPERIMENTAL & INTERNAL ACTION INPUTS # EXPERIMENTAL & INTERNAL ACTION INPUTS
# The following action properties allow fine-grained tweaking of the action caching behaviour. # The following action properties allow fine-grained tweaking of the action caching behaviour.
@@ -71,14 +107,11 @@ inputs:
description: When 'true', the action will not attempt to restore the Gradle User Home entries from other Jobs. description: When 'true', the action will not attempt to restore the Gradle User Home entries from other Jobs.
required: false required: false
default: false default: false
workflow-job-context: workflow-job-context:
description: Used to uniquely identify the current job invocation. Defaults to the matrix values for this job; this should not be overridden by users (INTERNAL). description: Used to uniquely identify the current job invocation. Defaults to the matrix values for this job; this should not be overridden by users (INTERNAL).
required: false required: false
default: ${{ toJSON(matrix) }} default: ${{ toJSON(matrix) }}
gradle-home-cache-cleanup:
description: When 'true', the action will attempt to remove any stale/unused entries from the Gradle User Home prior to saving to the GitHub Actions cache.
required: false
default: false
github-token: github-token:
description: The GitHub token used to authenticate when submitting via the Dependency Submission API. description: The GitHub token used to authenticate when submitting via the Dependency Submission API.
@@ -87,10 +120,14 @@ inputs:
outputs: outputs:
build-scan-url: build-scan-url:
description: Link to the build scan if any description: Link to the Build Scan® generated by a Gradle build. Note that this output applies to a Step executing Gradle, not to the `gradle-build-action` Step itself.
dependency-graph-file:
description: Path to the GitHub Dependency Graph snapshot file generated by a Gradle build. Note that this output applies to a Step executing Gradle, not to the `gradle-build-action` Step itself.
gradle-version:
description: Version of Gradle that was setup by the action
runs: runs:
using: 'node16' using: 'node20'
main: 'dist/main/index.js' main: 'dist/main/index.js'
post: 'dist/post/index.js' post: 'dist/post/index.js'

84619
dist/main/index.js vendored

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

83754
dist/post/index.js vendored

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

5891
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -8,11 +8,9 @@
"format": "prettier --write **/*.ts", "format": "prettier --write **/*.ts",
"format-check": "prettier --check **/*.ts", "format-check": "prettier --check **/*.ts",
"lint": "eslint src/**/*.ts", "lint": "eslint src/**/*.ts",
"compile-main": "ncc build src/main.ts --out dist/main --source-map --no-source-map-register", "compile-main": "ncc build src/main.ts --out dist/main --source-map --no-source-map-register",
"compile-post": "ncc build src/post.ts --out dist/post --source-map --no-source-map-register", "compile-post": "ncc build src/post.ts --out dist/post --source-map --no-source-map-register",
"compile": "npm run compile-main && npm run compile-post", "compile": "npm run compile-main && npm run compile-post",
"test": "jest", "test": "jest",
"check": "npm run format && npm run lint", "check": "npm run format && npm run lint",
"build": "npm run check && npm run compile", "build": "npm run check && npm run compile",
@@ -30,31 +28,34 @@
], ],
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@actions/artifact": "1.1.1", "@actions/artifact": "2.0.0",
"@actions/cache": "3.2.1", "@actions/cache": "3.2.2",
"@actions/core": "1.10.0", "@actions/core": "1.10.1",
"@actions/exec": "1.1.1", "@actions/exec": "1.1.1",
"@actions/github": "5.1.1", "@actions/github": "6.0.0",
"@actions/glob": "0.4.0", "@actions/glob": "0.4.0",
"@actions/http-client": "2.1.0", "@actions/http-client": "2.2.0",
"@actions/tool-cache": "2.0.1", "@actions/tool-cache": "2.0.1",
"@octokit/rest": "19.0.13", "@octokit/rest": "19.0.13",
"@octokit/webhooks-types": "7.3.1",
"semver": "7.5.4",
"string-argv": "0.3.2" "string-argv": "0.3.2"
}, },
"devDependencies": { "devDependencies": {
"@types/node": "16.11.21", "@types/jest": "29.5.11",
"@types/jest": "29.5.3", "@types/node": "20.10.0",
"@types/unzipper": "0.10.6", "@types/unzipper": "0.10.9",
"@typescript-eslint/parser": "5.62.0", "@typescript-eslint/parser": "6.17.0",
"@vercel/ncc": "0.36.1", "@vercel/ncc": "0.38.1",
"eslint": "8.44.0", "eslint": "8.56.0",
"eslint-plugin-github": "4.8.0", "eslint-plugin-github": "4.10.1",
"eslint-plugin-jest": "27.2.2", "eslint-plugin-jest": "27.6.1",
"jest": "29.6.1", "eslint-plugin-prettier": "5.1.2",
"js-yaml": "4.1.0", "jest": "29.7.0",
"patch-package": "7.0.0", "js-yaml": "4.1.0",
"prettier": "3.0.0", "patch-package": "8.0.0",
"prettier": "3.1.1",
"ts-jest": "29.1.1", "ts-jest": "29.1.1",
"typescript": "5.1.6" "typescript": "5.3.3"
} }
} }

View File

@@ -1,11 +1,13 @@
import * as core from '@actions/core' import * as core from '@actions/core'
import * as exec from '@actions/exec' import * as exec from '@actions/exec'
import * as glob from '@actions/glob'
import path from 'path' import path from 'path'
import fs from 'fs' import fs from 'fs'
import * as params from './input-params' import * as params from './input-params'
import {CacheListener} from './cache-reporting' import {CacheListener} from './cache-reporting'
import {saveCache, restoreCache, cacheDebug, isCacheDebuggingEnabled, tryDelete, generateCacheKey} from './cache-utils' import {saveCache, restoreCache, cacheDebug, isCacheDebuggingEnabled, tryDelete, generateCacheKey} from './cache-utils'
import {GradleHomeEntryExtractor} from './cache-extract-entries' import {GradleHomeEntryExtractor, ConfigurationCacheEntryExtractor} from './cache-extract-entries'
const RESTORED_CACHE_KEY_KEY = 'restored-cache-key' const RESTORED_CACHE_KEY_KEY = 'restored-cache-key'
@@ -15,22 +17,24 @@ export class GradleStateCache {
private cacheName: string private cacheName: string
private cacheDescription: string private cacheDescription: string
protected readonly userHome: string
protected readonly gradleUserHome: string protected readonly gradleUserHome: string
constructor(gradleUserHome: string) { constructor(userHome: string, gradleUserHome: string) {
this.userHome = userHome
this.gradleUserHome = gradleUserHome this.gradleUserHome = gradleUserHome
this.cacheName = 'gradle' this.cacheName = 'gradle'
this.cacheDescription = 'Gradle User Home' this.cacheDescription = 'Gradle User Home'
} }
init(): void { init(): void {
const actionCacheDir = path.resolve(this.gradleUserHome, '.gradle-build-action') this.initializeGradleUserHome()
fs.mkdirSync(actionCacheDir, {recursive: true})
const initScriptsDir = path.resolve(this.gradleUserHome, 'init.d') // Export the GRADLE_ENCRYPTION_KEY variable if provided
fs.mkdirSync(initScriptsDir, {recursive: true}) const encryptionKey = params.getCacheEncryptionKey()
if (encryptionKey) {
this.initializeGradleUserHome(this.gradleUserHome, initScriptsDir) core.exportVariable('GRADLE_ENCRYPTION_KEY', encryptionKey)
}
} }
cacheOutputExists(): boolean { cacheOutputExists(): boolean {
@@ -79,7 +83,7 @@ export class GradleStateCache {
async afterRestore(listener: CacheListener): Promise<void> { async afterRestore(listener: CacheListener): Promise<void> {
await this.debugReportGradleUserHomeSize('as restored from cache') await this.debugReportGradleUserHomeSize('as restored from cache')
await new GradleHomeEntryExtractor(this.gradleUserHome).restore(listener) await new GradleHomeEntryExtractor(this.gradleUserHome).restore(listener)
// await new ConfigurationCacheEntryExtractor(this.gradleUserHome).restore(listener) await new ConfigurationCacheEntryExtractor(this.gradleUserHome).restore(listener)
await this.debugReportGradleUserHomeSize('after restoring common artifacts') await this.debugReportGradleUserHomeSize('after restoring common artifacts')
} }
@@ -127,10 +131,10 @@ export class GradleStateCache {
*/ */
async beforeSave(listener: CacheListener): Promise<void> { async beforeSave(listener: CacheListener): Promise<void> {
await this.debugReportGradleUserHomeSize('before saving common artifacts') await this.debugReportGradleUserHomeSize('before saving common artifacts')
this.deleteExcludedPaths() await this.deleteExcludedPaths()
await Promise.all([ await Promise.all([
new GradleHomeEntryExtractor(this.gradleUserHome).extract(listener) new GradleHomeEntryExtractor(this.gradleUserHome).extract(listener),
// new ConfigurationCacheEntryExtractor(this.gradleUserHome).extract(listener) new ConfigurationCacheEntryExtractor(this.gradleUserHome).extract(listener)
]) ])
await this.debugReportGradleUserHomeSize( await this.debugReportGradleUserHomeSize(
"after extracting common artifacts (only 'caches' and 'notifications' will be stored)" "after extracting common artifacts (only 'caches' and 'notifications' will be stored)"
@@ -140,13 +144,21 @@ export class GradleStateCache {
/** /**
* Delete any file paths that are excluded by the `gradle-home-cache-excludes` parameter. * Delete any file paths that are excluded by the `gradle-home-cache-excludes` parameter.
*/ */
private deleteExcludedPaths(): void { private async deleteExcludedPaths(): Promise<void> {
const rawPaths: string[] = params.getCacheExcludes() const rawPaths: string[] = params.getCacheExcludes()
rawPaths.push('caches/*/cc-keystore')
const resolvedPaths = rawPaths.map(x => path.resolve(this.gradleUserHome, x)) const resolvedPaths = rawPaths.map(x => path.resolve(this.gradleUserHome, x))
for (const p of resolvedPaths) { for (const p of resolvedPaths) {
cacheDebug(`Deleting excluded path: ${p}`) cacheDebug(`Removing excluded path: ${p}`)
tryDelete(p) const globber = await glob.create(p, {
implicitDescendants: false
})
for (const toDelete of await globber.glob()) {
cacheDebug(`Removing excluded file: ${toDelete}`)
await tryDelete(toDelete)
}
} }
} }
@@ -171,23 +183,59 @@ export class GradleStateCache {
return path.resolve(this.gradleUserHome, rawPath) return path.resolve(this.gradleUserHome, rawPath)
} }
private initializeGradleUserHome(gradleUserHome: string, initScriptsDir: string): void { private initializeGradleUserHome(): void {
// Create a directory for storing action metadata
const actionCacheDir = path.resolve(this.gradleUserHome, '.gradle-build-action')
fs.mkdirSync(actionCacheDir, {recursive: true})
this.copyInitScripts()
// Copy the default toolchain definitions to `~/.m2/toolchains.xml`
this.registerToolchains()
}
private copyInitScripts(): void {
// Copy init scripts from src/resources to Gradle UserHome
const initScriptsDir = path.resolve(this.gradleUserHome, 'init.d')
fs.mkdirSync(initScriptsDir, {recursive: true})
const initScriptFilenames = [ const initScriptFilenames = [
'build-result-capture.init.gradle', 'gradle-build-action.build-result-capture.init.gradle',
'build-result-capture-service.plugin.groovy', 'gradle-build-action.build-result-capture-service.plugin.groovy',
'github-dependency-graph.init.gradle', 'gradle-build-action.github-dependency-graph.init.gradle',
'github-dependency-graph-gradle-plugin-apply.groovy' 'gradle-build-action.github-dependency-graph-gradle-plugin-apply.groovy',
'gradle-build-action.inject-gradle-enterprise.init.gradle'
] ]
for (const initScriptFilename of initScriptFilenames) { for (const initScriptFilename of initScriptFilenames) {
const initScriptContent = this.readInitScriptAsString(initScriptFilename) const initScriptContent = this.readResourceFileAsString('init-scripts', initScriptFilename)
const initScriptPath = path.resolve(initScriptsDir, initScriptFilename) const initScriptPath = path.resolve(initScriptsDir, initScriptFilename)
fs.writeFileSync(initScriptPath, initScriptContent) fs.writeFileSync(initScriptPath, initScriptContent)
} }
} }
private readInitScriptAsString(resource: string): string { private registerToolchains(): void {
const preInstalledToolchains = this.readResourceFileAsString('toolchains.xml')
const m2dir = path.resolve(this.userHome, '.m2')
const toolchainXmlTarget = path.resolve(m2dir, 'toolchains.xml')
if (!fs.existsSync(toolchainXmlTarget)) {
// Write a new toolchains.xml file if it doesn't exist
fs.mkdirSync(m2dir, {recursive: true})
fs.writeFileSync(toolchainXmlTarget, preInstalledToolchains)
core.info(`Wrote default JDK locations to ${toolchainXmlTarget}`)
} else {
// Merge into an existing toolchains.xml file
const existingToolchainContent = fs.readFileSync(toolchainXmlTarget, 'utf8')
const appendedContent = preInstalledToolchains.split('<toolchains>').pop()!
const mergedContent = existingToolchainContent.replace('</toolchains>', appendedContent)
fs.writeFileSync(toolchainXmlTarget, mergedContent)
core.info(`Merged default JDK locations into ${toolchainXmlTarget}`)
}
}
private readResourceFileAsString(...paths: string[]): string {
// Resolving relative to __dirname will allow node to find the resource at runtime // Resolving relative to __dirname will allow node to find the resource at runtime
const absolutePath = path.resolve(__dirname, '..', '..', 'src', 'resources', 'init-scripts', resource) const absolutePath = path.resolve(__dirname, '..', '..', 'src', 'resources', ...paths)
return fs.readFileSync(absolutePath, 'utf8') return fs.readFileSync(absolutePath, 'utf8')
} }

View File

@@ -42,7 +42,8 @@ export class CacheCleaner {
) )
fs.writeFileSync(path.resolve(cleanupProjectDir, 'build.gradle'), 'task("noop") {}') fs.writeFileSync(path.resolve(cleanupProjectDir, 'build.gradle'), 'task("noop") {}')
await exec.exec(`gradle -g ${this.gradleUserHome} --no-daemon --build-cache --no-scan --quiet noop`, [], { const gradleCommand = `gradle -g ${this.gradleUserHome} --no-daemon --build-cache --no-scan --quiet -DGITHUB_DEPENDENCY_GRAPH_ENABLED=false noop`
await exec.exec(gradleCommand, [], {
cwd: cleanupProjectDir cwd: cleanupProjectDir
}) })
} }

View File

@@ -2,13 +2,14 @@ import path from 'path'
import fs from 'fs' import fs from 'fs'
import * as core from '@actions/core' import * as core from '@actions/core'
import * as glob from '@actions/glob' import * as glob from '@actions/glob'
import * as semver from 'semver'
import * as params from './input-params' import * as params from './input-params'
import {META_FILE_DIR} from './cache-base' import {META_FILE_DIR} from './cache-base'
import {CacheEntryListener, CacheListener} from './cache-reporting' import {CacheEntryListener, CacheListener} from './cache-reporting'
import {cacheDebug, getCacheKeyPrefix, hashFileNames, restoreCache, saveCache, tryDelete} from './cache-utils' import {cacheDebug, getCacheKeyPrefix, hashFileNames, restoreCache, saveCache, tryDelete} from './cache-utils'
import {loadBuildResults} from './build-results' import {BuildResult, loadBuildResults} from './build-results'
const SKIP_RESTORE_VAR = 'GRADLE_BUILD_ACTION_SKIP_RESTORE' const SKIP_RESTORE_VAR = 'GRADLE_BUILD_ACTION_SKIP_RESTORE'
@@ -46,6 +47,7 @@ class ExtractedCacheEntryDefinition {
pattern: string pattern: string
bundle: boolean bundle: boolean
uniqueFileNames = true uniqueFileNames = true
notCacheableReason: string | undefined
constructor(artifactType: string, pattern: string, bundle: boolean) { constructor(artifactType: string, pattern: string, bundle: boolean) {
this.artifactType = artifactType this.artifactType = artifactType
@@ -53,10 +55,24 @@ class ExtractedCacheEntryDefinition {
this.bundle = bundle this.bundle = bundle
} }
/**
* Indicate that the file names matching the cache entry pattern are NOT sufficient to uniquely identify the contents.
* If the file names are sufficient, then we use a hash of the file names to identify the entry.
* With non-unique-file-names, we hash the file contents to identify the cache entry.
*/
withNonUniqueFileNames(): ExtractedCacheEntryDefinition { withNonUniqueFileNames(): ExtractedCacheEntryDefinition {
this.uniqueFileNames = false this.uniqueFileNames = false
return this return this
} }
/**
* Specify that the cache entry, should not be saved for some reason, even though the contents exist.
* This is used to prevent configuration-cache entries being cached when they were generated by Gradle < 8.6,
*/
notCacheableBecause(reason: string): ExtractedCacheEntryDefinition {
this.notCacheableReason = reason
return this
}
} }
/** /**
@@ -142,6 +158,11 @@ abstract class AbstractEntryExtractor {
const artifactType = cacheEntryDefinition.artifactType const artifactType = cacheEntryDefinition.artifactType
const pattern = cacheEntryDefinition.pattern const pattern = cacheEntryDefinition.pattern
if (cacheEntryDefinition.notCacheableReason) {
listener.entry(pattern).markNotSaved(cacheEntryDefinition.notCacheableReason)
continue
}
// Find all matching files for this cache entry definition // Find all matching files for this cache entry definition
const globber = await glob.create(pattern, { const globber = await glob.create(pattern, {
implicitDescendants: false implicitDescendants: false
@@ -256,7 +277,7 @@ abstract class AbstractEntryExtractor {
} }
const filedata = fs.readFileSync(cacheMetadataFile, 'utf-8') const filedata = fs.readFileSync(cacheMetadataFile, 'utf-8')
cacheDebug(`Loaded cache metadata: ${filedata}`) cacheDebug(`Loaded cache metadata for ${this.extractorName}: ${filedata}`)
const extractedCacheEntryMetadata = JSON.parse(filedata) as ExtractedCacheEntryMetadata const extractedCacheEntryMetadata = JSON.parse(filedata) as ExtractedCacheEntryMetadata
return extractedCacheEntryMetadata.entries return extractedCacheEntryMetadata.entries
} }
@@ -264,12 +285,12 @@ abstract class AbstractEntryExtractor {
/** /**
* Saves information about the extracted cache entries into the 'cache-metadata.json' file. * Saves information about the extracted cache entries into the 'cache-metadata.json' file.
*/ */
private saveMetadataForCacheResults(results: ExtractedCacheEntry[]): void { protected saveMetadataForCacheResults(results: ExtractedCacheEntry[]): void {
const extractedCacheEntryMetadata = new ExtractedCacheEntryMetadata() const extractedCacheEntryMetadata = new ExtractedCacheEntryMetadata()
extractedCacheEntryMetadata.entries = results.filter(x => x.cacheKey !== undefined) extractedCacheEntryMetadata.entries = results.filter(x => x.cacheKey !== undefined)
const filedata = JSON.stringify(extractedCacheEntryMetadata) const filedata = JSON.stringify(extractedCacheEntryMetadata)
cacheDebug(`Saving cache metadata: ${filedata}`) cacheDebug(`Saving cache metadata for ${this.extractorName}: ${filedata}`)
fs.writeFileSync(this.getCacheMetadataFile(), filedata, 'utf-8') fs.writeFileSync(this.getCacheMetadataFile(), filedata, 'utf-8')
} }
@@ -351,37 +372,96 @@ export class ConfigurationCacheEntryExtractor extends AbstractEntryExtractor {
* entry is not reusable. * entry is not reusable.
*/ */
async restore(listener: CacheListener): Promise<void> { async restore(listener: CacheListener): Promise<void> {
if (listener.fullyRestored) { if (!listener.fullyRestored) {
return super.restore(listener) this.markNotRestored(listener, 'Gradle User Home was not fully restored')
return
} }
core.info('Not restoring configuration-cache state, as Gradle User Home was not fully restored') if (!params.getCacheEncryptionKey()) {
for (const cacheEntry of this.loadExtractedCacheEntries()) { this.markNotRestored(listener, 'Encryption Key was not provided')
listener.entry(cacheEntry.pattern).markRequested('NOT_RESTORED') return
} }
return await super.restore(listener)
}
private markNotRestored(listener: CacheListener, reason: string): void {
const cacheEntries = this.loadExtractedCacheEntries()
if (cacheEntries.length > 0) {
core.info(`Not restoring configuration-cache state, as ${reason}`)
for (const cacheEntry of cacheEntries) {
listener.entry(cacheEntry.pattern).markNotRestored(reason)
}
// Update the results file based on no entries restored
this.saveMetadataForCacheResults([])
}
}
async extract(listener: CacheListener): Promise<void> {
if (!params.getCacheEncryptionKey()) {
const cacheEntryDefinitions = this.getExtractedCacheEntryDefinitions()
if (cacheEntryDefinitions.length > 0) {
core.info('Not saving configuration-cache state, as no encryption key was provided')
for (const cacheEntry of cacheEntryDefinitions) {
listener.entry(cacheEntry.pattern).markNotSaved('No encryption key provided')
}
}
return
}
await super.extract(listener)
} }
/** /**
* Extract cache entries for the configuration cache in each project. * Extract cache entries for the configuration cache in each project.
*/ */
protected getExtractedCacheEntryDefinitions(): ExtractedCacheEntryDefinition[] { protected getExtractedCacheEntryDefinitions(): ExtractedCacheEntryDefinition[] {
return this.getProjectRoots().map(projectRoot => { // Group BuildResult by existing configCacheDir
const configCachePath = path.resolve(projectRoot, '.gradle/configuration-cache') const groupedResults = this.getConfigCacheDirectoriesWithAssociatedBuildResults()
return new ExtractedCacheEntryDefinition(
return Object.entries(groupedResults).map(([configCachePath, pathResults]) => {
// Create a entry definition for each unique configuration cache directory
const definition = new ExtractedCacheEntryDefinition(
'configuration-cache', 'configuration-cache',
configCachePath, configCachePath,
true true
).withNonUniqueFileNames() ).withNonUniqueFileNames()
// If any associated build result used Gradle < 8.6, then mark it as not cacheable
if (
pathResults.find(result => {
const gradleVersion = semver.coerce(result.gradleVersion)
return gradleVersion && semver.lt(gradleVersion, '8.6.0')
})
) {
core.info(
`Not saving config-cache data for ${configCachePath}. Configuration cache data is only saved for Gradle 8.6+`
)
definition.notCacheableBecause('Configuration cache data only saved for Gradle 8.6+')
}
return definition
}) })
} }
/** private getConfigCacheDirectoriesWithAssociatedBuildResults(): Record<string, BuildResult[]> {
* For every Gradle invocation, we record the project root directory. This method returns the entire return loadBuildResults().reduce(
* set of project roots, to allow saving of configuration-cache entries for each. (acc, buildResult) => {
*/ // For each build result, find the config-cache dir
private getProjectRoots(): string[] { const configCachePath = path.resolve(buildResult.rootProjectDir, '.gradle/configuration-cache')
const buildResults = loadBuildResults() // Ignore case where config-cache dir doesn't exist
const projectRootDirs = buildResults.map(x => x.rootProjectDir) if (!fs.existsSync(configCachePath)) {
return [...new Set(projectRootDirs)] // Remove duplicates return acc
}
// Group by unique config cache directories and collect associated build results
if (!acc[configCachePath]) {
acc[configCachePath] = []
}
acc[configCachePath].push(buildResult)
return acc
},
{} as Record<string, BuildResult[]>
)
} }
} }

View File

@@ -1,4 +1,3 @@
import * as core from '@actions/core'
import * as cache from '@actions/cache' import * as cache from '@actions/cache'
/** /**
@@ -10,6 +9,7 @@ export class CacheListener {
cacheReadOnly = false cacheReadOnly = false
cacheWriteOnly = false cacheWriteOnly = false
cacheDisabled = false cacheDisabled = false
cacheDisabledReason = 'disabled'
get fullyRestored(): boolean { get fullyRestored(): boolean {
return this.cacheEntries.every(x => !x.wasRequestedButNotRestored()) return this.cacheEntries.every(x => !x.wasRequestedButNotRestored())
@@ -17,7 +17,7 @@ export class CacheListener {
get cacheStatus(): string { get cacheStatus(): string {
if (!cache.isFeatureAvailable()) return 'not available' if (!cache.isFeatureAvailable()) return 'not available'
if (this.cacheDisabled) return 'disabled' if (this.cacheDisabled) return this.cacheDisabledReason
if (this.cacheWriteOnly) return 'write-only' if (this.cacheWriteOnly) return 'write-only'
if (this.cacheReadOnly) return 'read-only' if (this.cacheReadOnly) return 'read-only'
return 'enabled' return 'enabled'
@@ -111,47 +111,36 @@ export class CacheEntryListener {
} }
} }
export function writeCachingReport(listener: CacheListener): void { export function generateCachingReport(listener: CacheListener): string {
const entries = listener.cacheEntries const entries = listener.cacheEntries
core.summary.addRaw( return `
`\n<details><summary><h4>Caching for gradle-build-action was ${listener.cacheStatus} - expand for details</h4></summary>\n` <details>
) <summary><h4>Caching for gradle-build-action was ${listener.cacheStatus} - expand for details</h4></summary>
${renderEntryTable(entries)}
core.summary.addTable([ <h5>Cache Entry Details</h5>
[ <pre>
{data: '', header: true}, ${renderEntryDetails(listener)}
{data: 'Count', header: true},
{data: 'Total Size (Mb)', header: true}
],
['Entries Restored', `${getCount(entries, e => e.restoredSize)}`, `${getSize(entries, e => e.restoredSize)}`],
['Entries Saved', `${getCount(entries, e => e.savedSize)}`, `${getSize(entries, e => e.savedSize)}`]
])
core.summary.addHeading('Cache Entry Details', 5)
const entryDetails = renderEntryDetails(listener)
core.summary.addRaw(`<pre>
${entryDetails}
</pre> </pre>
</details> </details>
`) `
} }
export function logCachingReport(listener: CacheListener): void { function renderEntryTable(entries: CacheEntryListener[]): string {
const entries = listener.cacheEntries return `
<table>
core.startGroup(`Caching for gradle-build-action was ${listener.cacheStatus} - expand for details`) <tr><td></td><th>Count</th><th>Total Size (Mb)</th></tr>
<tr><td>Entries Restored</td>
core.info( <td>${getCount(entries, e => e.restoredSize)}</td>
`Entries Restored: ${getCount(entries, e => e.restoredSize)} (${getSize(entries, e => e.restoredSize)} Mb)` <td>${getSize(entries, e => e.restoredSize)}</td>
) </tr>
core.info(`Entries Saved : ${getCount(entries, e => e.savedSize)} (${getSize(entries, e => e.savedSize)} Mb)`) <tr><td>Entries Saved</td>
<td>${getCount(entries, e => e.savedSize)}</td>
core.info(`Cache Entry Details`) <td>${getSize(entries, e => e.savedSize)}</td>
core.info(renderEntryDetails(listener)) </tr>
</table>
core.endGroup() `
} }
function renderEntryDetails(listener: CacheListener): string { function renderEntryDetails(listener: CacheListener): string {
@@ -197,6 +186,9 @@ function getSavedMessage(entry: CacheEntryListener, cacheReadOnly: boolean): str
if (cacheReadOnly) { if (cacheReadOnly) {
return '(Entry not saved: cache is read-only)' return '(Entry not saved: cache is read-only)'
} }
if (entry.notRestored) {
return '(Entry not saved: not restored)'
}
return '(Entry not saved: reason unknown)' return '(Entry not saved: reason unknown)'
} }
if (entry.savedSize === 0) { if (entry.savedSize === 0) {

View File

@@ -11,7 +11,7 @@ import * as params from './input-params'
import {CacheEntryListener} from './cache-reporting' import {CacheEntryListener} from './cache-reporting'
const CACHE_PROTOCOL_VERSION = 'v8-' const CACHE_PROTOCOL_VERSION = 'v9-'
const CACHE_KEY_PREFIX_VAR = 'GRADLE_BUILD_ACTION_CACHE_KEY_PREFIX' const CACHE_KEY_PREFIX_VAR = 'GRADLE_BUILD_ACTION_CACHE_KEY_PREFIX'
const CACHE_KEY_OS_VAR = 'GRADLE_BUILD_ACTION_CACHE_KEY_ENVIRONMENT' const CACHE_KEY_OS_VAR = 'GRADLE_BUILD_ACTION_CACHE_KEY_ENVIRONMENT'
@@ -37,6 +37,10 @@ export function isCacheWriteOnly(): boolean {
return params.isCacheWriteOnly() return params.isCacheWriteOnly()
} }
export function isCacheOverwriteExisting(): boolean {
return params.isCacheOverwriteExisting()
}
export function isCacheDebuggingEnabled(): boolean { export function isCacheDebuggingEnabled(): boolean {
return params.isCacheDebuggingEnabled() return params.isCacheDebuggingEnabled()
} }
@@ -66,7 +70,7 @@ export class CacheKey {
* - The cache protocol version * - The cache protocol version
* - The name of the cache * - The name of the cache
* - The runner operating system * - The runner operating system
* - The name of the Job being executed * - The name of the workflow and Job being executed
* - The matrix values for the Job being executed (job context) * - The matrix values for the Job being executed (job context)
* - The SHA of the commit being executed * - The SHA of the commit being executed
* *
@@ -82,10 +86,10 @@ export function generateCacheKey(cacheName: string): CacheKey {
// At the most general level, share caches for all executions on the same OS // At the most general level, share caches for all executions on the same OS
const cacheKeyForEnvironment = `${cacheKeyBase}|${getCacheKeyEnvironment()}` const cacheKeyForEnvironment = `${cacheKeyBase}|${getCacheKeyEnvironment()}`
// Prefer caches that run this job // Then prefer caches that run job with the same ID
const cacheKeyForJob = `${cacheKeyForEnvironment}|${getCacheKeyJob()}` const cacheKeyForJob = `${cacheKeyForEnvironment}|${getCacheKeyJob()}`
// Prefer (even more) jobs that run this job with the same context (matrix) // Prefer (even more) jobs that run this job in the same workflow with the same context (matrix)
const cacheKeyForJobContext = `${cacheKeyForJob}[${getCacheKeyJobInstance()}]` const cacheKeyForJobContext = `${cacheKeyForJob}[${getCacheKeyJobInstance()}]`
// Exact match on Git SHA // Exact match on Git SHA
@@ -109,12 +113,7 @@ function getCacheKeyEnvironment(): string {
} }
function getCacheKeyJob(): string { function getCacheKeyJob(): string {
return process.env[CACHE_KEY_JOB_VAR] || getCacheKeyForJob(github.context.workflow, github.context.job) return process.env[CACHE_KEY_JOB_VAR] || github.context.job
}
export function getCacheKeyForJob(workflowName: string, jobId: string): string {
const sanitizedWorkflow = workflowName.replace(/,/g, '').toLowerCase()
return `${sanitizedWorkflow}-${jobId}`
} }
function getCacheKeyJobInstance(): string { function getCacheKeyJobInstance(): string {
@@ -123,25 +122,11 @@ function getCacheKeyJobInstance(): string {
return override return override
} }
// By default, we hash the full `matrix` data for the run, to uniquely identify this job invocation // By default, we hash the workflow name and the full `matrix` data for the run, to uniquely identify this job invocation
// The only way we can obtain the `matrix` data is via the `workflow-job-context` parameter in action.yml. // The only way we can obtain the `matrix` data is via the `workflow-job-context` parameter in action.yml.
const workflowName = github.context.workflow
const workflowJobContext = params.getJobMatrix() const workflowJobContext = params.getJobMatrix()
return hashStrings([workflowJobContext]) return hashStrings([workflowName, workflowJobContext])
}
export function getUniqueLabelForJobInstance(): string {
return getUniqueLabelForJobInstanceValues(github.context.workflow, github.context.job, params.getJobMatrix())
}
export function getUniqueLabelForJobInstanceValues(workflow: string, jobId: string, matrixJson: string): string {
const matrix = JSON.parse(matrixJson)
const matrixString = Object.values(matrix).join('-')
const label = matrixString ? `${workflow}-${jobId}-${matrixString}` : `${workflow}-${jobId}`
return sanitize(label)
}
function sanitize(value: string): string {
return value.replace(/[^a-zA-Z0-9_-]/g, '').toLowerCase()
} }
function getCacheKeyJobExecution(): string { function getCacheKeyJobExecution(): string {

View File

@@ -1,5 +1,11 @@
import * as core from '@actions/core' import * as core from '@actions/core'
import {isCacheCleanupEnabled, isCacheDisabled, isCacheReadOnly, isCacheWriteOnly} from './cache-utils' import {
isCacheCleanupEnabled,
isCacheDisabled,
isCacheReadOnly,
isCacheWriteOnly,
isCacheOverwriteExisting
} from './cache-utils'
import {CacheListener} from './cache-reporting' import {CacheListener} from './cache-reporting'
import {DaemonController} from './daemon-controller' import {DaemonController} from './daemon-controller'
import {GradleStateCache} from './cache-base' import {GradleStateCache} from './cache-base'
@@ -7,7 +13,7 @@ import {CacheCleaner} from './cache-cleaner'
const CACHE_RESTORED_VAR = 'GRADLE_BUILD_ACTION_CACHE_RESTORED' const CACHE_RESTORED_VAR = 'GRADLE_BUILD_ACTION_CACHE_RESTORED'
export async function restore(gradleUserHome: string, cacheListener: CacheListener): Promise<void> { export async function restore(userHome: string, gradleUserHome: string, cacheListener: CacheListener): Promise<void> {
// Bypass restore cache on all but first action step in workflow. // Bypass restore cache on all but first action step in workflow.
if (process.env[CACHE_RESTORED_VAR]) { if (process.env[CACHE_RESTORED_VAR]) {
core.info('Cache only restored on first action step.') core.info('Cache only restored on first action step.')
@@ -15,7 +21,7 @@ export async function restore(gradleUserHome: string, cacheListener: CacheListen
} }
core.exportVariable(CACHE_RESTORED_VAR, true) core.exportVariable(CACHE_RESTORED_VAR, true)
const gradleStateCache = new GradleStateCache(gradleUserHome) const gradleStateCache = new GradleStateCache(userHome, gradleUserHome)
if (isCacheDisabled()) { if (isCacheDisabled()) {
core.info('Cache is disabled: will not restore state from previous builds.') core.info('Cache is disabled: will not restore state from previous builds.')
@@ -26,10 +32,15 @@ export async function restore(gradleUserHome: string, cacheListener: CacheListen
} }
if (gradleStateCache.cacheOutputExists()) { if (gradleStateCache.cacheOutputExists()) {
core.info('Gradle User Home already exists: will not restore from cache.') if (!isCacheOverwriteExisting()) {
// Initialize pre-existing Gradle User Home. core.info('Gradle User Home already exists: will not restore from cache.')
gradleStateCache.init() // Initialize pre-existing Gradle User Home.
return gradleStateCache.init()
cacheListener.cacheDisabled = true
cacheListener.cacheDisabledReason = 'disabled due to pre-existing Gradle User Home'
return
}
core.info('Gradle User Home already exists: will overwrite with cached contents.')
} }
gradleStateCache.init() gradleStateCache.init()
@@ -54,6 +65,7 @@ export async function restore(gradleUserHome: string, cacheListener: CacheListen
} }
export async function save( export async function save(
userHome: string,
gradleUserHome: string, gradleUserHome: string,
cacheListener: CacheListener, cacheListener: CacheListener,
daemonController: DaemonController daemonController: DaemonController
@@ -79,10 +91,14 @@ export async function save(
if (isCacheCleanupEnabled()) { if (isCacheCleanupEnabled()) {
core.info('Forcing cache cleanup.') core.info('Forcing cache cleanup.')
const cacheCleaner = new CacheCleaner(gradleUserHome, process.env['RUNNER_TEMP']!) const cacheCleaner = new CacheCleaner(gradleUserHome, process.env['RUNNER_TEMP']!)
await cacheCleaner.forceCleanup() try {
await cacheCleaner.forceCleanup()
} catch (e) {
core.warning(`Cache cleanup failed. Will continue. ${String(e)}`)
}
} }
await core.group('Caching Gradle state', async () => { await core.group('Caching Gradle state', async () => {
return new GradleStateCache(gradleUserHome).save(cacheListener) return new GradleStateCache(userHome, gradleUserHome).save(cacheListener)
}) })
} }

View File

@@ -1,28 +1,36 @@
import * as core from '@actions/core' import * as core from '@actions/core'
import * as artifact from '@actions/artifact'
import * as github from '@actions/github' import * as github from '@actions/github'
import * as glob from '@actions/glob' import * as glob from '@actions/glob'
import * as toolCache from '@actions/tool-cache' import {DefaultArtifactClient} from '@actions/artifact'
import {Octokit} from '@octokit/rest' import {GitHub} from '@actions/github/lib/utils'
import {RequestError} from '@octokit/request-error'
import type {PullRequestEvent} from '@octokit/webhooks-types'
import * as path from 'path' import * as path from 'path'
import fs from 'fs' import fs from 'fs'
import * as layout from './repository-layout' import * as layout from './repository-layout'
import {DependencyGraphOption, getJobMatrix} from './input-params' import {DependencyGraphOption, getJobMatrix, getArtifactRetentionDays} from './input-params'
const DEPENDENCY_GRAPH_ARTIFACT = 'dependency-graph' const DEPENDENCY_GRAPH_PREFIX = 'dependency-graph_'
export function setup(option: DependencyGraphOption): void { export async function setup(option: DependencyGraphOption): Promise<void> {
if (option === DependencyGraphOption.Disabled || option === DependencyGraphOption.DownloadAndSubmit) { if (option === DependencyGraphOption.Disabled) {
return
}
// Download and submit early, for compatability with dependency review.
if (option === DependencyGraphOption.DownloadAndSubmit) {
await downloadAndSubmitDependencyGraphs()
return return
} }
core.info('Enabling dependency graph generation') core.info('Enabling dependency graph generation')
const jobCorrelator = getJobCorrelator()
core.exportVariable('GITHUB_DEPENDENCY_GRAPH_ENABLED', 'true') core.exportVariable('GITHUB_DEPENDENCY_GRAPH_ENABLED', 'true')
core.exportVariable('GITHUB_JOB_CORRELATOR', jobCorrelator) core.exportVariable('GITHUB_DEPENDENCY_GRAPH_JOB_CORRELATOR', getJobCorrelator())
core.exportVariable('GITHUB_JOB_ID', github.context.runId) core.exportVariable('GITHUB_DEPENDENCY_GRAPH_JOB_ID', github.context.runId)
core.exportVariable('GITHUB_DEPENDENCY_GRAPH_REF', github.context.ref)
core.exportVariable('GITHUB_DEPENDENCY_GRAPH_SHA', getShaFromContext())
core.exportVariable('GITHUB_DEPENDENCY_GRAPH_WORKSPACE', layout.workspaceDirectory())
core.exportVariable( core.exportVariable(
'DEPENDENCY_GRAPH_REPORT_DIR', 'DEPENDENCY_GRAPH_REPORT_DIR',
path.resolve(layout.workspaceDirectory(), 'dependency-graph-reports') path.resolve(layout.workspaceDirectory(), 'dependency-graph-reports')
@@ -30,104 +38,120 @@ export function setup(option: DependencyGraphOption): void {
} }
export async function complete(option: DependencyGraphOption): Promise<void> { export async function complete(option: DependencyGraphOption): Promise<void> {
switch (option) { try {
case DependencyGraphOption.Disabled: switch (option) {
return case DependencyGraphOption.Disabled:
case DependencyGraphOption.Generate: case DependencyGraphOption.Generate: // Performed via init-script: nothing to do here
await uploadDependencyGraphs() case DependencyGraphOption.DownloadAndSubmit: // Performed in setup
return return
case DependencyGraphOption.GenerateAndSubmit: case DependencyGraphOption.GenerateAndSubmit:
await submitDependencyGraphs(await uploadDependencyGraphs()) await submitDependencyGraphs(await findGeneratedDependencyGraphFiles())
return return
case DependencyGraphOption.DownloadAndSubmit: case DependencyGraphOption.GenerateAndUpload:
await downloadAndSubmitDependencyGraphs() await uploadDependencyGraphs(await findGeneratedDependencyGraphFiles())
}
} catch (e) {
core.warning(`Failed to ${option} dependency graph. Will continue. ${String(e)}`)
} }
} }
async function uploadDependencyGraphs(): Promise<string[]> { async function findGeneratedDependencyGraphFiles(): Promise<string[]> {
const workspaceDirectory = layout.workspaceDirectory() const workspaceDirectory = layout.workspaceDirectory()
const graphFiles = await findDependencyGraphFiles(workspaceDirectory) return await findDependencyGraphFiles(workspaceDirectory)
}
const relativeGraphFiles = graphFiles.map(x => getRelativePathFromWorkspace(x)) async function uploadDependencyGraphs(dependencyGraphFiles: string[]): Promise<void> {
core.info(`Uploading dependency graph files: ${relativeGraphFiles}`) const workspaceDirectory = layout.workspaceDirectory()
const artifactClient = artifact.create() const artifactClient = new DefaultArtifactClient()
artifactClient.uploadArtifact(DEPENDENCY_GRAPH_ARTIFACT, graphFiles, workspaceDirectory) for (const dependencyGraphFile of dependencyGraphFiles) {
const relativePath = getRelativePathFromWorkspace(dependencyGraphFile)
return graphFiles core.info(`Uploading dependency graph file: ${relativePath}`)
const artifactName = `${DEPENDENCY_GRAPH_PREFIX}${path.basename(dependencyGraphFile)}`
await artifactClient.uploadArtifact(artifactName, [dependencyGraphFile], workspaceDirectory, {
retentionDays: getArtifactRetentionDays()
})
}
} }
async function downloadAndSubmitDependencyGraphs(): Promise<void> { async function downloadAndSubmitDependencyGraphs(): Promise<void> {
const workspaceDirectory = layout.workspaceDirectory() try {
submitDependencyGraphs(await retrieveDependencyGraphs(workspaceDirectory)) await submitDependencyGraphs(await downloadDependencyGraphs())
} catch (e) {
core.warning(`Download and submit dependency graph failed. Will continue. ${String(e)}`)
}
} }
async function submitDependencyGraphs(dependencyGraphFiles: string[]): Promise<void> { async function submitDependencyGraphs(dependencyGraphFiles: string[]): Promise<void> {
const octokit: Octokit = getOctokit()
for (const jsonFile of dependencyGraphFiles) { for (const jsonFile of dependencyGraphFiles) {
const jsonContent = fs.readFileSync(jsonFile, 'utf8') try {
await submitDependencyGraphFile(jsonFile)
const jsonObject = JSON.parse(jsonContent) } catch (error) {
jsonObject.owner = github.context.repo.owner if (error instanceof RequestError) {
jsonObject.repo = github.context.repo.repo core.warning(buildWarningMessage(jsonFile, error))
const response = await octokit.request('POST /repos/{owner}/{repo}/dependency-graph/snapshots', jsonObject) } else {
throw error
const relativeJsonFile = getRelativePathFromWorkspace(jsonFile) }
core.notice(`Submitted ${relativeJsonFile}: ${response.data.message}`) }
} }
} }
async function retrieveDependencyGraphs(workspaceDirectory: string): Promise<string[]> { function buildWarningMessage(jsonFile: string, error: RequestError): string {
if (github.context.payload.workflow_run) { const relativeJsonFile = getRelativePathFromWorkspace(jsonFile)
return await retrieveDependencyGraphsForWorkflowRun(github.context.payload.workflow_run.id, workspaceDirectory) const mainWarning = `Failed to submit dependency graph ${relativeJsonFile}.\n${String(error)}`
if (error.message === 'Resource not accessible by integration') {
return `${mainWarning}
Please ensure that the 'contents: write' permission is available for the workflow job.
Note that this permission is never available for a 'pull_request' trigger from a repository fork.
`
} }
return retrieveDependencyGraphsForCurrentWorkflow(workspaceDirectory) return mainWarning
} }
async function retrieveDependencyGraphsForWorkflowRun(runId: number, workspaceDirectory: string): Promise<string[]> { async function submitDependencyGraphFile(jsonFile: string): Promise<void> {
const octokit: Octokit = getOctokit() const octokit = getOctokit()
const jsonContent = fs.readFileSync(jsonFile, 'utf8')
// Find the workflow run artifacts named "dependency-graph" const jsonObject = JSON.parse(jsonContent)
const artifacts = await octokit.rest.actions.listWorkflowRunArtifacts({ jsonObject.owner = github.context.repo.owner
owner: github.context.repo.owner, jsonObject.repo = github.context.repo.repo
repo: github.context.repo.repo, const response = await octokit.request('POST /repos/{owner}/{repo}/dependency-graph/snapshots', jsonObject)
run_id: runId
})
const matchArtifact = artifacts.data.artifacts.find(candidate => { const relativeJsonFile = getRelativePathFromWorkspace(jsonFile)
return candidate.name === DEPENDENCY_GRAPH_ARTIFACT core.notice(`Submitted ${relativeJsonFile}: ${response.data.message}`)
})
if (matchArtifact === undefined) {
throw new Error(`Dependency graph artifact not found. Has it been generated by workflow run '${runId}'?`)
}
// Download the dependency-graph artifact
const download = await octokit.rest.actions.downloadArtifact({
owner: github.context.repo.owner,
repo: github.context.repo.repo,
artifact_id: matchArtifact.id,
archive_format: 'zip'
})
const downloadBuffer = download.data as ArrayBuffer
const downloadZip = path.resolve(workspaceDirectory, 'dependency-graph.zip')
fs.writeFileSync(downloadZip, Buffer.from(downloadBuffer))
// Expance the dependency-graph zip and locate each dependency-graph JSON file
const extractDir = path.resolve(workspaceDirectory, 'dependency-graph')
const extracted = await toolCache.extractZip(downloadZip, extractDir)
core.info(`Extracted dependency graph artifacts to ${extracted}: ${fs.readdirSync(extracted)}`)
return findDependencyGraphFiles(extracted)
} }
async function retrieveDependencyGraphsForCurrentWorkflow(workspaceDirectory: string): Promise<string[]> { async function downloadDependencyGraphs(): Promise<string[]> {
const artifactClient = artifact.create() const workspaceDirectory = layout.workspaceDirectory()
const findBy = github.context.payload.workflow_run
? {
token: getGithubToken(),
workflowRunId: github.context.payload.workflow_run.id,
repositoryName: github.context.repo.repo,
repositoryOwner: github.context.repo.owner
}
: undefined
const artifactClient = new DefaultArtifactClient()
const downloadPath = path.resolve(workspaceDirectory, 'dependency-graph') const downloadPath = path.resolve(workspaceDirectory, 'dependency-graph')
await artifactClient.downloadArtifact(DEPENDENCY_GRAPH_ARTIFACT, downloadPath)
return await findDependencyGraphFiles(downloadPath) const dependencyGraphArtifacts = (
await artifactClient.listArtifacts({
latest: true,
findBy
})
).artifacts.filter(candidate => candidate.name.startsWith(DEPENDENCY_GRAPH_PREFIX))
for (const artifact of dependencyGraphArtifacts) {
const downloadedArtifact = await artifactClient.downloadArtifact(artifact.id, {
path: downloadPath,
findBy
})
core.info(`Downloading dependency-graph artifact ${artifact.name} to ${downloadedArtifact.downloadPath}`)
}
return findDependencyGraphFiles(downloadPath)
} }
async function findDependencyGraphFiles(dir: string): Promise<string[]> { async function findDependencyGraphFiles(dir: string): Promise<string[]> {
@@ -136,10 +160,8 @@ async function findDependencyGraphFiles(dir: string): Promise<string[]> {
return graphFiles return graphFiles
} }
function getOctokit(): Octokit { function getOctokit(): InstanceType<typeof GitHub> {
return new Octokit({ return github.getOctokit(getGithubToken())
auth: getGithubToken()
})
} }
function getGithubToken(): string { function getGithubToken(): string {
@@ -151,7 +173,26 @@ function getRelativePathFromWorkspace(file: string): string {
return path.relative(workspaceDirectory, file) return path.relative(workspaceDirectory, file)
} }
export function getJobCorrelator(): string { function getShaFromContext(): string {
const context = github.context
const pullRequestEvents = [
'pull_request',
'pull_request_comment',
'pull_request_review',
'pull_request_review_comment'
// Note that pull_request_target is omitted here.
// That event runs in the context of the base commit of the PR,
// so the snapshot should not be associated with the head commit.
]
if (pullRequestEvents.includes(context.eventName)) {
const pr = (context.payload as PullRequestEvent).pull_request
return pr.head.sha
} else {
return context.sha
}
}
function getJobCorrelator(): string {
return constructJobCorrelator(github.context.workflow, github.context.job, getJobMatrix()) return constructJobCorrelator(github.context.workflow, github.context.job, getJobMatrix())
} }

View File

@@ -13,6 +13,10 @@ export function isCacheWriteOnly(): boolean {
return getBooleanInput('cache-write-only') return getBooleanInput('cache-write-only')
} }
export function isCacheOverwriteExisting(): boolean {
return getBooleanInput('cache-overwrite-existing')
}
export function isCacheStrictMatch(): boolean { export function isCacheStrictMatch(): boolean {
return getBooleanInput('gradle-home-cache-strict-match') return getBooleanInput('gradle-home-cache-strict-match')
} }
@@ -25,6 +29,10 @@ export function isCacheCleanupEnabled(): boolean {
return getBooleanInput('gradle-home-cache-cleanup') return getBooleanInput('gradle-home-cache-cleanup')
} }
export function getCacheEncryptionKey(): string {
return core.getInput('cache-encryption-key')
}
export function getCacheIncludes(): string[] { export function getCacheIncludes(): string[] {
return core.getMultilineInput('gradle-home-cache-includes') return core.getMultilineInput('gradle-home-cache-includes')
} }
@@ -63,8 +71,25 @@ export function isJobSummaryEnabled(): boolean {
return getBooleanInput('generate-job-summary', true) return getBooleanInput('generate-job-summary', true)
} }
export function isDependencyGraphEnabled(): boolean { export function getJobSummaryOption(): JobSummaryOption {
return getBooleanInput('generate-dependency-graph', true) return parseJobSummaryOption('add-job-summary')
}
export function getPRCommentOption(): JobSummaryOption {
return parseJobSummaryOption('add-job-summary-as-pr-comment')
}
function parseJobSummaryOption(paramName: string): JobSummaryOption {
const val = core.getInput(paramName)
switch (val.toLowerCase().trim()) {
case 'never':
return JobSummaryOption.Never
case 'always':
return JobSummaryOption.Always
case 'on-failure':
return JobSummaryOption.OnFailure
}
throw TypeError(`The value '${val}' is not valid for ${paramName}. Valid values are: [never, always, on-failure].`)
} }
export function getDependencyGraphOption(): DependencyGraphOption { export function getDependencyGraphOption(): DependencyGraphOption {
@@ -76,14 +101,33 @@ export function getDependencyGraphOption(): DependencyGraphOption {
return DependencyGraphOption.Generate return DependencyGraphOption.Generate
case 'generate-and-submit': case 'generate-and-submit':
return DependencyGraphOption.GenerateAndSubmit return DependencyGraphOption.GenerateAndSubmit
case 'generate-and-upload':
return DependencyGraphOption.GenerateAndUpload
case 'download-and-submit': case 'download-and-submit':
return DependencyGraphOption.DownloadAndSubmit return DependencyGraphOption.DownloadAndSubmit
} }
throw TypeError( throw TypeError(
`The value '${val} is not valid for 'dependency-graph. Valid values are: [disabled, generate-and-upload, generate-and-submit, download-and-submit]. The default value is 'disabled'.` `The value '${val}' is not valid for 'dependency-graph'. Valid values are: [disabled, generate, generate-and-submit, generate-and-upload, download-and-submit]. The default value is 'disabled'.`
) )
} }
export function getArtifactRetentionDays(): number {
const val = core.getInput('artifact-retention-days')
return parseNumericInput('artifact-retention-days', val, 0)
// Zero indicates that the default repository settings should be used
}
export function parseNumericInput(paramName: string, paramValue: string, paramDefault: number): number {
if (paramValue.length === 0) {
return paramDefault
}
const numericValue = parseInt(paramValue)
if (isNaN(numericValue)) {
throw TypeError(`The value '${paramValue}' is not a valid numeric value for '${paramName}'.`)
}
return numericValue
}
function getBooleanInput(paramName: string, paramDefault = false): boolean { function getBooleanInput(paramName: string, paramDefault = false): boolean {
const paramValue = core.getInput(paramName) const paramValue = core.getInput(paramName)
switch (paramValue.toLowerCase().trim()) { switch (paramValue.toLowerCase().trim()) {
@@ -98,8 +142,15 @@ function getBooleanInput(paramName: string, paramDefault = false): boolean {
} }
export enum DependencyGraphOption { export enum DependencyGraphOption {
Disabled, Disabled = 'disabled',
Generate, Generate = 'generate',
GenerateAndSubmit, GenerateAndSubmit = 'generate-and-submit',
DownloadAndSubmit GenerateAndUpload = 'generate-and-upload',
DownloadAndSubmit = 'download-and-submit'
}
export enum JobSummaryOption {
Never = 'never',
Always = 'always',
OnFailure = 'on-failure'
} }

View File

@@ -1,45 +1,94 @@
import * as core from '@actions/core' import * as core from '@actions/core'
import * as github from '@actions/github'
import {SUMMARY_ENV_VAR} from '@actions/core/lib/summary'
import {RequestError} from '@octokit/request-error'
import * as params from './input-params'
import {BuildResult} from './build-results' import {BuildResult} from './build-results'
import {writeCachingReport, CacheListener, logCachingReport} from './cache-reporting' import {CacheListener, generateCachingReport} from './cache-reporting'
export async function writeJobSummary(buildResults: BuildResult[], cacheListener: CacheListener): Promise<void> { export async function generateJobSummary(buildResults: BuildResult[], cacheListener: CacheListener): Promise<void> {
core.info('Writing job summary') const summaryTable = renderSummaryTable(buildResults)
const cachingReport = generateCachingReport(cacheListener)
if (buildResults.length === 0) { if (shouldGenerateJobSummary(buildResults)) {
core.debug('No Gradle build results found. Summary table will not be generated.') core.info('Generating Job Summary')
core.summary.addRaw(summaryTable)
core.summary.addRaw(cachingReport)
await core.summary.write()
} else { } else {
writeSummaryTable(buildResults) core.info('============================')
core.info(summaryTable)
core.info('============================')
core.info(cachingReport)
core.info('============================')
} }
writeCachingReport(cacheListener) if (shouldAddPRComment(buildResults)) {
await addPRComment(summaryTable)
await core.summary.write() }
} }
export async function logJobSummary(buildResults: BuildResult[], cacheListener: CacheListener): Promise<void> { async function addPRComment(jobSummary: string): Promise<void> {
if (buildResults.length === 0) { const context = github.context
core.debug('No Gradle build results found. Summary table will not be logged.') if (context.payload.pull_request == null) {
} else { core.info('No pull_request trigger: not adding PR comment')
logSummaryTable(buildResults) return
} }
logCachingReport(cacheListener) const pull_request_number = context.payload.pull_request.number
core.info(`Adding Job Summary as comment to PR #${pull_request_number}.`)
const prComment = `<h3>Job Summary for gradle-build-action</h3>
<h5>${github.context.workflow} :: <em>${github.context.job}</em></h5>
${jobSummary}`
const github_token = params.getGithubToken()
const octokit = github.getOctokit(github_token)
try {
await octokit.rest.issues.createComment({
...context.repo,
issue_number: pull_request_number,
body: prComment
})
} catch (error) {
if (error instanceof RequestError) {
core.warning(buildWarningMessage(error))
} else {
throw error
}
}
} }
function writeSummaryTable(results: BuildResult[]): void { function buildWarningMessage(error: RequestError): string {
core.summary.addHeading('Gradle Builds', 3) const mainWarning = `Failed to generate PR comment.\n${String(error)}`
if (error.message === 'Resource not accessible by integration') {
return `${mainWarning}
Please ensure that the 'pull-requests: write' permission is available for the workflow job.
Note that this permission is never available for a workflow triggered from a repository fork.
`
}
return mainWarning
}
core.summary.addRaw(` function renderSummaryTable(results: BuildResult[]): string {
if (results.length === 0) {
return 'No Gradle build results detected.'
}
return `
<table> <table>
<tr> <tr>
<th>Root Project</th> <th>Gradle Root Project</th>
<th>Requested Tasks</th> <th>Requested Tasks</th>
<th>Gradle Version</th> <th>Gradle Version</th>
<th>Build Outcome</th> <th>Build Outcome</th>
<th>Build Scan</th> <th>Build Scan®</th>
</tr>${results.map(result => renderBuildResultRow(result)).join('')} </tr>${results.map(result => renderBuildResultRow(result)).join('')}
</table> </table>
`) `
} }
function renderBuildResultRow(result: BuildResult): string { function renderBuildResultRow(result: BuildResult): string {
@@ -72,23 +121,37 @@ function renderBuildScan(result: BuildResult): string {
} }
function renderBuildScanBadge(outcomeText: string, outcomeColor: string, targetUrl: string): string { function renderBuildScanBadge(outcomeText: string, outcomeColor: string, targetUrl: string): string {
const badgeUrl = `https://img.shields.io/badge/Build%20Scan%E2%84%A2-${outcomeText}-${outcomeColor}?logo=Gradle` const badgeUrl = `https://img.shields.io/badge/Build%20Scan%C2%AE-${outcomeText}-${outcomeColor}?logo=Gradle`
const badgeHtml = `<img src="${badgeUrl}" alt="Build Scan ${outcomeText}" />` const badgeHtml = `<img src="${badgeUrl}" alt="Build Scan ${outcomeText}" />`
return `<a href="${targetUrl}" rel="nofollow">${badgeHtml}</a>` return `<a href="${targetUrl}" rel="nofollow">${badgeHtml}</a>`
} }
function logSummaryTable(results: BuildResult[]): void { function shouldGenerateJobSummary(buildResults: BuildResult[]): boolean {
core.info('============================') // Check if Job Summary is supported on this platform
core.info('Gradle Builds') if (!process.env[SUMMARY_ENV_VAR]) {
core.info('----------------------------') return false
core.info('Root Project | Requested Tasks | Gradle Version | Build Outcome | Build Scan™') }
core.info('----------------------------')
for (const result of results) { // Check if Job Summary is disabled using the deprecated input
core.info( if (!params.isJobSummaryEnabled()) {
`${result.rootProjectName} | ${result.requestedTasks} | ${result.gradleVersion} | ${ return false
result.buildFailed ? 'FAILED' : 'SUCCESS' }
} | ${result.buildScanFailed ? 'Publish failed' : result.buildScanUri}`
) return shouldAddJobSummary(params.getJobSummaryOption(), buildResults)
}
function shouldAddPRComment(buildResults: BuildResult[]): boolean {
return shouldAddJobSummary(params.getPRCommentOption(), buildResults)
}
function shouldAddJobSummary(option: params.JobSummaryOption, buildResults: BuildResult[]): boolean {
switch (option) {
case params.JobSummaryOption.Always:
return true
case params.JobSummaryOption.Never:
return false
case params.JobSummaryOption.OnFailure:
core.info(`Got these build results: ${JSON.stringify(buildResults)}`)
return buildResults.some(result => result.buildFailed)
} }
core.info('============================')
} }

View File

@@ -38,6 +38,12 @@ async function addToPath(executable: string): Promise<string> {
} }
async function installGradle(version: string): Promise<string> { async function installGradle(version: string): Promise<string> {
const versionInfo = await resolveGradleVersion(version)
core.setOutput('gradle-version', versionInfo.version)
return installGradleVersion(versionInfo)
}
async function resolveGradleVersion(version: string): Promise<GradleVersionInfo> {
switch (version) { switch (version) {
case 'current': case 'current':
return gradleCurrent() return gradleCurrent()
@@ -55,36 +61,33 @@ async function installGradle(version: string): Promise<string> {
} }
} }
async function gradleCurrent(): Promise<string> { async function gradleCurrent(): Promise<GradleVersionInfo> {
const versionInfo = await gradleVersionDeclaration(`${gradleVersionsBaseUrl}/current`) return await gradleVersionDeclaration(`${gradleVersionsBaseUrl}/current`)
return installGradleVersion(versionInfo)
} }
async function gradleReleaseCandidate(): Promise<string> { async function gradleReleaseCandidate(): Promise<GradleVersionInfo> {
const versionInfo = await gradleVersionDeclaration(`${gradleVersionsBaseUrl}/release-candidate`) const versionInfo = await gradleVersionDeclaration(`${gradleVersionsBaseUrl}/release-candidate`)
if (versionInfo && versionInfo.version && versionInfo.downloadUrl) { if (versionInfo && versionInfo.version && versionInfo.downloadUrl) {
return installGradleVersion(versionInfo) return versionInfo
} }
core.info('No current release-candidate found, will fallback to current') core.info('No current release-candidate found, will fallback to current')
return gradleCurrent() return gradleCurrent()
} }
async function gradleNightly(): Promise<string> { async function gradleNightly(): Promise<GradleVersionInfo> {
const versionInfo = await gradleVersionDeclaration(`${gradleVersionsBaseUrl}/nightly`) return await gradleVersionDeclaration(`${gradleVersionsBaseUrl}/nightly`)
return installGradleVersion(versionInfo)
} }
async function gradleReleaseNightly(): Promise<string> { async function gradleReleaseNightly(): Promise<GradleVersionInfo> {
const versionInfo = await gradleVersionDeclaration(`${gradleVersionsBaseUrl}/release-nightly`) return await gradleVersionDeclaration(`${gradleVersionsBaseUrl}/release-nightly`)
return installGradleVersion(versionInfo)
} }
async function gradle(version: string): Promise<string> { async function gradle(version: string): Promise<GradleVersionInfo> {
const versionInfo = await findGradleVersionDeclaration(version) const versionInfo = await findGradleVersionDeclaration(version)
if (!versionInfo) { if (!versionInfo) {
throw new Error(`Gradle version ${version} does not exists`) throw new Error(`Gradle version ${version} does not exists`)
} }
return installGradleVersion(versionInfo) return versionInfo
} }
async function gradleVersionDeclaration(url: string): Promise<GradleVersionInfo> { async function gradleVersionDeclaration(url: string): Promise<GradleVersionInfo> {

View File

@@ -1,9 +0,0 @@
buildscript {
repositories {
maven { url "https://plugins.gradle.org/m2/" }
}
dependencies {
classpath "org.gradle:github-dependency-graph-gradle-plugin:0.1.0"
}
}
apply plugin: org.gradle.github.GitHubDependencyGraphPlugin

View File

@@ -50,12 +50,16 @@ abstract class BuildResultsRecorder implements BuildService<BuildResultsRecorder
if (!runnerTempDir || !githubActionStep) { if (!runnerTempDir || !githubActionStep) {
return return
} }
def buildResultsDir = new File(runnerTempDir, ".build-results") try {
buildResultsDir.mkdirs() def buildResultsDir = new File(runnerTempDir, ".build-results")
def buildResultsFile = new File(buildResultsDir, githubActionStep + getParameters().getInvocationId().get() + ".json") buildResultsDir.mkdirs()
if (!buildResultsFile.exists()) { def buildResultsFile = new File(buildResultsDir, githubActionStep + getParameters().getInvocationId().get() + ".json")
buildResultsFile << groovy.json.JsonOutput.toJson(buildResults) if (!buildResultsFile.exists()) {
buildResultsFile << groovy.json.JsonOutput.toJson(buildResults)
}
} catch (Exception e) {
println "\ngradle-build-action failed to write build-results file. Will continue.\n> ${e.getLocalizedMessage()}"
} }
} }
} }

View File

@@ -23,7 +23,7 @@ if (isTopLevelBuild) {
captureUsingBuildFinished(gradle, invocationId) captureUsingBuildFinished(gradle, invocationId)
} }
// The `buildScanPublished` hook allows the capture of the build scan URI. // The `buildScanPublished` hook allows the capture of the Build Scan URI.
// Results captured this way will overwrite any results from the other mechanism. // Results captured this way will overwrite any results from the other mechanism.
settings.pluginManager.withPlugin("com.gradle.enterprise") { settings.pluginManager.withPlugin("com.gradle.enterprise") {
captureUsingBuildScanPublished(settings.extensions["gradleEnterprise"].buildScan, settings.rootProject, invocationId) captureUsingBuildScanPublished(settings.extensions["gradleEnterprise"].buildScan, settings.rootProject, invocationId)
@@ -34,7 +34,7 @@ if (isTopLevelBuild) {
// By default, use 'buildFinished' to capture build results // By default, use 'buildFinished' to capture build results
captureUsingBuildFinished(gradle, invocationId) captureUsingBuildFinished(gradle, invocationId)
// The `buildScanPublished` hook allows the capture of the build scan URI. // The `buildScanPublished` hook allows the capture of the Build Scan URI.
// Results captured this way will overwrite any results from 'buildFinished'. // Results captured this way will overwrite any results from 'buildFinished'.
gradle.rootProject.pluginManager.withPlugin("com.gradle.build-scan") { gradle.rootProject.pluginManager.withPlugin("com.gradle.build-scan") {
captureUsingBuildScanPublished(gradle.rootProject.extensions["buildScan"], gradle.rootProject, invocationId) captureUsingBuildScanPublished(gradle.rootProject.extensions["buildScan"], gradle.rootProject, invocationId)
@@ -82,7 +82,7 @@ def captureUsingBuildFinished(gradle, invocationId) {
def captureUsingBuildService(settings, invocationId) { def captureUsingBuildService(settings, invocationId) {
gradle.ext.invocationId = invocationId gradle.ext.invocationId = invocationId
apply from: 'build-result-capture-service.plugin.groovy' apply from: 'gradle-build-action.build-result-capture-service.plugin.groovy'
} }
class BuildResults { class BuildResults {
@@ -121,18 +121,23 @@ class BuildResults {
if (!runnerTempDir || !githubActionStep) { if (!runnerTempDir || !githubActionStep) {
return return
} }
def buildResultsDir = new File(runnerTempDir, ".build-results")
buildResultsDir.mkdirs()
def buildResultsFile = new File(buildResultsDir, githubActionStep + invocationId + ".json")
// Overwrite any contents written by buildFinished or build service, since this result is a superset. try {
if (buildResultsFile.exists()) { def buildResultsDir = new File(runnerTempDir, ".build-results")
if (overwrite) { buildResultsDir.mkdirs()
buildResultsFile.text = groovy.json.JsonOutput.toJson(buildResults) def buildResultsFile = new File(buildResultsDir, githubActionStep + invocationId + ".json")
// Overwrite any contents written by buildFinished or build service, since this result is a superset.
if (buildResultsFile.exists()) {
if (overwrite) {
buildResultsFile.text = groovy.json.JsonOutput.toJson(buildResults)
}
} else {
buildResultsFile << groovy.json.JsonOutput.toJson(buildResults)
} }
} else {
buildResultsFile << groovy.json.JsonOutput.toJson(buildResults) } catch (Exception e) {
println "\ngradle-build-action failed to write build-results file. Will continue.\n> ${e.getLocalizedMessage()}"
} }
} }
} }

View File

@@ -0,0 +1,15 @@
buildscript {
def getInputParam = { String name ->
def envVarName = name.toUpperCase().replace('.', '_').replace('-', '_')
return System.getProperty(name) ?: System.getenv(envVarName)
}
def pluginRepositoryUrl = getInputParam('gradle.plugin-repository.url') ?: 'https://plugins.gradle.org/m2'
repositories {
maven { url pluginRepositoryUrl }
}
dependencies {
classpath "org.gradle:github-dependency-graph-gradle-plugin:1.0.0"
}
}
apply plugin: org.gradle.github.GitHubDependencyGraphPlugin

View File

@@ -1,7 +1,7 @@
import org.gradle.util.GradleVersion import org.gradle.util.GradleVersion
// Only run when dependency graph is explicitly enabled // Only run when dependency graph is explicitly enabled
if (System.env.GITHUB_DEPENDENCY_GRAPH_ENABLED != "true") { if (getVariable('GITHUB_DEPENDENCY_GRAPH_ENABLED') != "true") {
return return
} }
@@ -15,17 +15,22 @@ if (GradleVersion.current().baseVersion < GradleVersion.version("5.0")) {
// This is only required for top-level builds // This is only required for top-level builds
def isTopLevelBuild = gradle.getParent() == null def isTopLevelBuild = gradle.getParent() == null
if (isTopLevelBuild) { if (isTopLevelBuild) {
def jobCorrelator = ensureUniqueJobCorrelator(System.env.GITHUB_JOB_CORRELATOR) def reportFile = getUniqueReportFile(getVariable('GITHUB_DEPENDENCY_GRAPH_JOB_CORRELATOR'))
if (jobCorrelator == null) { if (reportFile == null) {
println "::warning::No dependency snapshot generated for step: report file for '${jobCorrelator}' created in earlier step. Each build invocation requires a unique job correlator: specify GITHUB_JOB_CORRELATOR var for this step." println "::warning::No dependency snapshot generated for step. Could not determine unique job correlator - specify GITHUB_DEPENDENCY_GRAPH_JOB_CORRELATOR var for this step."
return return
} }
println "Generating dependency graph for '${jobCorrelator}'" def githubOutput = System.getenv("GITHUB_OUTPUT")
if (githubOutput) {
new File(githubOutput) << "dependency-graph-file=${reportFile.absolutePath}\n"
}
println "Generating dependency graph into '${reportFile}'"
} }
apply from: 'github-dependency-graph-gradle-plugin-apply.groovy' apply from: 'gradle-build-action.github-dependency-graph-gradle-plugin-apply.groovy'
/** /**
* Using the supplied jobCorrelator value: * Using the supplied jobCorrelator value:
@@ -33,21 +38,28 @@ apply from: 'github-dependency-graph-gradle-plugin-apply.groovy'
* - If so, tries to find a unique value that does not yet have a corresponding report file. * - If so, tries to find a unique value that does not yet have a corresponding report file.
* - When found, this value is set as a System property override. * - When found, this value is set as a System property override.
*/ */
String ensureUniqueJobCorrelator(String jobCorrelator) { File getUniqueReportFile(String jobCorrelator) {
def reportDir = System.env.DEPENDENCY_GRAPH_REPORT_DIR def reportDir = getVariable('DEPENDENCY_GRAPH_REPORT_DIR')
def reportFile = new File(reportDir, jobCorrelator + ".json") def reportFile = new File(reportDir, jobCorrelator + ".json")
if (!reportFile.exists()) return jobCorrelator if (!reportFile.exists()) return reportFile
// Try at most 100 suffixes // Try at most 100 suffixes
for (int i = 1; i < 100; i++) { for (int i = 1; i < 100; i++) {
def candidateCorrelator = jobCorrelator + "-" + i def candidateCorrelator = jobCorrelator + "-" + i
def candidateFile = new File(reportDir, candidateCorrelator + ".json") def candidateFile = new File(reportDir, candidateCorrelator + ".json")
if (!candidateFile.exists()) { if (!candidateFile.exists()) {
System.properties['GITHUB_JOB_CORRELATOR'] = candidateCorrelator System.properties['GITHUB_DEPENDENCY_GRAPH_JOB_CORRELATOR'] = candidateCorrelator
return candidateCorrelator return candidateFile
} }
} }
// Could not determine unique job correlator // Could not determine unique job correlator
return null return null
} }
/**
* Return the environment variable value, or equivalent system property (if set)
*/
String getVariable(String name) {
return System.properties[name] ?: System.getenv(name)
}

View File

@@ -0,0 +1,192 @@
import org.gradle.util.GradleVersion
// note that there is no mechanism to share code between the initscript{} block and the main script, so some logic is duplicated
// conditionally apply the GE / Build Scan plugin to the classpath so it can be applied to the build further down in this script
initscript {
def isTopLevelBuild = !gradle.parent
if (!isTopLevelBuild) {
return
}
def getInputParam = { String name ->
def envVarName = name.toUpperCase().replace('.', '_').replace('-', '_')
return System.getProperty(name) ?: System.getenv(envVarName)
}
// finish early if injection is disabled
def gradleInjectionEnabled = getInputParam("gradle-enterprise.injection-enabled")
if (gradleInjectionEnabled != "true") {
return
}
def pluginRepositoryUrl = getInputParam('gradle-enterprise.plugin-repository.url')
def gePluginVersion = getInputParam('gradle-enterprise.plugin.version')
def ccudPluginVersion = getInputParam('gradle-enterprise.ccud-plugin.version')
def atLeastGradle5 = GradleVersion.current() >= GradleVersion.version('5.0')
def atLeastGradle4 = GradleVersion.current() >= GradleVersion.version('4.0')
if (gePluginVersion || ccudPluginVersion && atLeastGradle4) {
pluginRepositoryUrl = pluginRepositoryUrl ?: 'https://plugins.gradle.org/m2'
logger.quiet("Gradle Enterprise plugins resolution: $pluginRepositoryUrl")
repositories {
maven { url pluginRepositoryUrl }
}
}
dependencies {
if (gePluginVersion) {
classpath atLeastGradle5 ?
"com.gradle:gradle-enterprise-gradle-plugin:$gePluginVersion" :
"com.gradle:build-scan-plugin:1.16"
}
if (ccudPluginVersion && atLeastGradle4) {
classpath "com.gradle:common-custom-user-data-gradle-plugin:$ccudPluginVersion"
}
}
}
def BUILD_SCAN_PLUGIN_ID = 'com.gradle.build-scan'
def BUILD_SCAN_PLUGIN_CLASS = 'com.gradle.scan.plugin.BuildScanPlugin'
def GRADLE_ENTERPRISE_PLUGIN_ID = 'com.gradle.enterprise'
def GRADLE_ENTERPRISE_PLUGIN_CLASS = 'com.gradle.enterprise.gradleplugin.GradleEnterprisePlugin'
def GRADLE_ENTERPRISE_EXTENSION_CLASS = 'com.gradle.enterprise.gradleplugin.GradleEnterpriseExtension'
def CI_AUTO_INJECTION_CUSTOM_VALUE_NAME = 'CI auto injection'
def CI_AUTO_INJECTION_CUSTOM_VALUE_VALUE = 'gradle-build-action'
def CCUD_PLUGIN_ID = 'com.gradle.common-custom-user-data-gradle-plugin'
def CCUD_PLUGIN_CLASS = 'com.gradle.CommonCustomUserDataGradlePlugin'
def isTopLevelBuild = !gradle.parent
if (!isTopLevelBuild) {
return
}
def getInputParam = { String name ->
def envVarName = name.toUpperCase().replace('.', '_').replace('-', '_')
return System.getProperty(name) ?: System.getenv(envVarName)
}
// finish early if injection is disabled
def gradleInjectionEnabled = getInputParam("gradle-enterprise.injection-enabled")
if (gradleInjectionEnabled != "true") {
return
}
def geUrl = getInputParam('gradle-enterprise.url')
def geAllowUntrustedServer = Boolean.parseBoolean(getInputParam('gradle-enterprise.allow-untrusted-server'))
def geEnforceUrl = Boolean.parseBoolean(getInputParam('gradle-enterprise.enforce-url'))
def buildScanUploadInBackground = Boolean.parseBoolean(getInputParam('gradle-enterprise.build-scan.upload-in-background'))
def gePluginVersion = getInputParam('gradle-enterprise.plugin.version')
def ccudPluginVersion = getInputParam('gradle-enterprise.ccud-plugin.version')
def atLeastGradle4 = GradleVersion.current() >= GradleVersion.version('4.0')
// finish early if configuration parameters passed in via system properties are not valid/supported
if (ccudPluginVersion && isNotAtLeast(ccudPluginVersion, '1.7')) {
logger.warn("Common Custom User Data Gradle plugin must be at least 1.7. Configured version is $ccudPluginVersion.")
return
}
// register buildScanPublished listener and optionally apply the GE / Build Scan plugin
if (GradleVersion.current() < GradleVersion.version('6.0')) {
rootProject {
buildscript.configurations.getByName("classpath").incoming.afterResolve { ResolvableDependencies incoming ->
def resolutionResult = incoming.resolutionResult
if (gePluginVersion) {
def scanPluginComponent = resolutionResult.allComponents.find {
it.moduleVersion.with { group == "com.gradle" && (name == "build-scan-plugin" || name == "gradle-enterprise-gradle-plugin") }
}
if (!scanPluginComponent) {
logger.quiet("Applying $BUILD_SCAN_PLUGIN_CLASS via init script")
logger.quiet("Connection to Gradle Enterprise: $geUrl, allowUntrustedServer: $geAllowUntrustedServer")
applyPluginExternally(pluginManager, BUILD_SCAN_PLUGIN_CLASS)
buildScan.server = geUrl
buildScan.allowUntrustedServer = geAllowUntrustedServer
buildScan.publishAlways()
if (buildScan.metaClass.respondsTo(buildScan, 'setUploadInBackground', Boolean)) buildScan.uploadInBackground = buildScanUploadInBackground // uploadInBackground not available for build-scan-plugin 1.16
buildScan.value CI_AUTO_INJECTION_CUSTOM_VALUE_NAME, CI_AUTO_INJECTION_CUSTOM_VALUE_VALUE
}
if (geUrl && geEnforceUrl) {
pluginManager.withPlugin(BUILD_SCAN_PLUGIN_ID) {
afterEvaluate {
logger.quiet("Enforcing Gradle Enterprise: $geUrl, allowUntrustedServer: $geAllowUntrustedServer")
buildScan.server = geUrl
buildScan.allowUntrustedServer = geAllowUntrustedServer
}
}
}
}
if (ccudPluginVersion && atLeastGradle4) {
def ccudPluginComponent = resolutionResult.allComponents.find {
it.moduleVersion.with { group == "com.gradle" && name == "common-custom-user-data-gradle-plugin" }
}
if (!ccudPluginComponent) {
logger.quiet("Applying $CCUD_PLUGIN_CLASS via init script")
pluginManager.apply(initscript.classLoader.loadClass(CCUD_PLUGIN_CLASS))
}
}
}
}
} else {
gradle.settingsEvaluated { settings ->
if (gePluginVersion) {
if (!settings.pluginManager.hasPlugin(GRADLE_ENTERPRISE_PLUGIN_ID)) {
logger.quiet("Applying $GRADLE_ENTERPRISE_PLUGIN_CLASS via init script")
logger.quiet("Connection to Gradle Enterprise: $geUrl, allowUntrustedServer: $geAllowUntrustedServer")
applyPluginExternally(settings.pluginManager, GRADLE_ENTERPRISE_PLUGIN_CLASS)
extensionsWithPublicType(settings, GRADLE_ENTERPRISE_EXTENSION_CLASS).collect { settings[it.name] }.each { ext ->
ext.server = geUrl
ext.allowUntrustedServer = geAllowUntrustedServer
ext.buildScan.publishAlways()
ext.buildScan.uploadInBackground = buildScanUploadInBackground
ext.buildScan.value CI_AUTO_INJECTION_CUSTOM_VALUE_NAME, CI_AUTO_INJECTION_CUSTOM_VALUE_VALUE
}
}
if (geUrl && geEnforceUrl) {
extensionsWithPublicType(settings, GRADLE_ENTERPRISE_EXTENSION_CLASS).collect { settings[it.name] }.each { ext ->
logger.quiet("Enforcing Gradle Enterprise: $geUrl, allowUntrustedServer: $geAllowUntrustedServer")
ext.server = geUrl
ext.allowUntrustedServer = geAllowUntrustedServer
}
}
}
if (ccudPluginVersion) {
if (!settings.pluginManager.hasPlugin(CCUD_PLUGIN_ID)) {
logger.quiet("Applying $CCUD_PLUGIN_CLASS via init script")
settings.pluginManager.apply(initscript.classLoader.loadClass(CCUD_PLUGIN_CLASS))
}
}
}
}
void applyPluginExternally(def pluginManager, String pluginClassName) {
def externallyApplied = 'gradle.enterprise.externally-applied'
def oldValue = System.getProperty(externallyApplied)
System.setProperty(externallyApplied, 'true')
try {
pluginManager.apply(initscript.classLoader.loadClass(pluginClassName))
} finally {
if (oldValue == null) {
System.clearProperty(externallyApplied)
} else {
System.setProperty(externallyApplied, oldValue)
}
}
}
static def extensionsWithPublicType(def container, String publicType) {
container.extensions.extensionsSchema.elements.findAll { it.publicType.concreteClass.name == publicType }
}
static boolean isNotAtLeast(String versionUnderTest, String referenceVersion) {
GradleVersion.version(versionUnderTest) < GradleVersion.version(referenceVersion)
}

View File

@@ -0,0 +1,44 @@
<?xml version="1.0" encoding="UTF-8"?>
<toolchains>
<!-- JDK Toolchains installed by default on GitHub-hosted runners -->
<toolchain>
<type>jdk</type>
<provides>
<version>8</version>
<vendor>Eclipse Temurin</vendor>
</provides>
<configuration>
<jdkHome>${env.JAVA_HOME_8_X64}</jdkHome>
</configuration>
</toolchain>
<toolchain>
<type>jdk</type>
<provides>
<version>11</version>
<vendor>Eclipse Temurin</vendor>
</provides>
<configuration>
<jdkHome>${env.JAVA_HOME_11_X64}</jdkHome>
</configuration>
</toolchain>
<toolchain>
<type>jdk</type>
<provides>
<version>17</version>
<vendor>Eclipse Temurin</vendor>
</provides>
<configuration>
<jdkHome>${env.JAVA_HOME_17_X64}</jdkHome>
</configuration>
</toolchain>
<toolchain>
<type>jdk</type>
<provides>
<version>21</version>
<vendor>Eclipse Temurin</vendor>
</provides>
<configuration>
<jdkHome>${env.JAVA_HOME_21_X64}</jdkHome>
</configuration>
</toolchain>
</toolchains>

View File

@@ -1,23 +1,24 @@
import * as core from '@actions/core' import * as core from '@actions/core'
import * as exec from '@actions/exec' import * as exec from '@actions/exec'
import {SUMMARY_ENV_VAR} from '@actions/core/lib/summary'
import * as path from 'path' import * as path from 'path'
import * as os from 'os' import * as os from 'os'
import * as caches from './caches' import * as caches from './caches'
import * as layout from './repository-layout' import * as layout from './repository-layout'
import * as params from './input-params' import * as params from './input-params'
import * as dependencyGraph from './dependency-graph' import * as dependencyGraph from './dependency-graph'
import * as jobSummary from './job-summary'
import {logJobSummary, writeJobSummary} from './job-summary'
import {loadBuildResults} from './build-results' import {loadBuildResults} from './build-results'
import {CacheListener} from './cache-reporting' import {CacheListener} from './cache-reporting'
import {DaemonController} from './daemon-controller' import {DaemonController} from './daemon-controller'
const GRADLE_SETUP_VAR = 'GRADLE_BUILD_ACTION_SETUP_COMPLETED' const GRADLE_SETUP_VAR = 'GRADLE_BUILD_ACTION_SETUP_COMPLETED'
const USER_HOME = 'USER_HOME'
const GRADLE_USER_HOME = 'GRADLE_USER_HOME' const GRADLE_USER_HOME = 'GRADLE_USER_HOME'
const CACHE_LISTENER = 'CACHE_LISTENER' const CACHE_LISTENER = 'CACHE_LISTENER'
export async function setup(): Promise<void> { export async function setup(): Promise<void> {
const userHome = await determineUserHome()
const gradleUserHome = await determineGradleUserHome() const gradleUserHome = await determineGradleUserHome()
// Bypass setup on all but first action step in workflow. // Bypass setup on all but first action step in workflow.
@@ -30,15 +31,16 @@ export async function setup(): Promise<void> {
// Record setup complete: visible in post-action, to control action completion // Record setup complete: visible in post-action, to control action completion
core.saveState(GRADLE_SETUP_VAR, true) core.saveState(GRADLE_SETUP_VAR, true)
// Save the Gradle User Home for use in the post-action step. // Save the User Home and Gradle User Home for use in the post-action step.
core.saveState(USER_HOME, userHome)
core.saveState(GRADLE_USER_HOME, gradleUserHome) core.saveState(GRADLE_USER_HOME, gradleUserHome)
const cacheListener = new CacheListener() const cacheListener = new CacheListener()
await caches.restore(gradleUserHome, cacheListener) await caches.restore(userHome, gradleUserHome, cacheListener)
core.saveState(CACHE_LISTENER, cacheListener.stringify()) core.saveState(CACHE_LISTENER, cacheListener.stringify())
dependencyGraph.setup(params.getDependencyGraphOption()) await dependencyGraph.setup(params.getDependencyGraphOption())
} }
export async function complete(): Promise<void> { export async function complete(): Promise<void> {
@@ -46,23 +48,22 @@ export async function complete(): Promise<void> {
core.info('Gradle setup post-action only performed for first gradle-build-action step in workflow.') core.info('Gradle setup post-action only performed for first gradle-build-action step in workflow.')
return return
} }
core.info('In final post-action step, saving state and writing summary') core.info('In post-action step')
const buildResults = loadBuildResults() const buildResults = loadBuildResults()
const userHome = core.getState(USER_HOME)
const gradleUserHome = core.getState(GRADLE_USER_HOME) const gradleUserHome = core.getState(GRADLE_USER_HOME)
const cacheListener: CacheListener = CacheListener.rehydrate(core.getState(CACHE_LISTENER)) const cacheListener: CacheListener = CacheListener.rehydrate(core.getState(CACHE_LISTENER))
const daemonController = new DaemonController(buildResults) const daemonController = new DaemonController(buildResults)
await caches.save(gradleUserHome, cacheListener, daemonController) await caches.save(userHome, gradleUserHome, cacheListener, daemonController)
if (shouldGenerateJobSummary()) { await jobSummary.generateJobSummary(buildResults, cacheListener)
await writeJobSummary(buildResults, cacheListener)
} else {
logJobSummary(buildResults, cacheListener)
}
dependencyGraph.complete(params.getDependencyGraphOption()) await dependencyGraph.complete(params.getDependencyGraphOption())
core.info('Completed post-action step')
} }
async function determineGradleUserHome(): Promise<string> { async function determineGradleUserHome(): Promise<string> {
@@ -91,12 +92,3 @@ async function determineUserHome(): Promise<string> {
core.debug(`Determined user.home from java -version output: '${userHome}'`) core.debug(`Determined user.home from java -version output: '${userHome}'`)
return userHome return userHome
} }
function shouldGenerateJobSummary(): boolean {
// Check if Job Summary is supported on this platform
if (!process.env[SUMMARY_ENV_VAR]) {
return false
}
return params.isJobSummaryEnabled()
}

View File

@@ -20,7 +20,7 @@ dependencies {
testImplementation ('io.ratpack:ratpack-groovy-test:1.9.0') { testImplementation ('io.ratpack:ratpack-groovy-test:1.9.0') {
exclude group: 'org.codehaus.groovy', module: 'groovy-all' exclude group: 'org.codehaus.groovy', module: 'groovy-all'
} }
testImplementation 'com.fasterxml.jackson.dataformat:jackson-dataformat-smile:2.15.2' testImplementation 'com.fasterxml.jackson.dataformat:jackson-dataformat-smile:2.16.0'
} }
test { test {

View File

@@ -1,7 +1,7 @@
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
distributionSha256Sum=03ec176d388f2aa99defcadc3ac6adf8dd2bce5145a129659537c0874dea5ad1 distributionSha256Sum=591855b517fc635b9e04de1d05d5e76ada3f89f5fc76f87978d1b245b4f69225
distributionUrl=https\://services.gradle.org/distributions/gradle-8.2.1-bin.zip distributionUrl=https\://services.gradle.org/distributions/gradle-8.3-bin.zip
networkTimeout=10000 networkTimeout=10000
validateDistributionUrl=true validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME

View File

@@ -83,7 +83,8 @@ done
# This is normally unused # This is normally unused
# shellcheck disable=SC2034 # shellcheck disable=SC2034
APP_BASE_NAME=${0##*/} APP_BASE_NAME=${0##*/}
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value. # Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum MAX_FD=maximum

View File

@@ -1,6 +1,6 @@
plugins { plugins {
id "com.gradle.enterprise" version "3.13.4" id "com.gradle.enterprise" version "3.16.1"
id "com.gradle.common-custom-user-data-gradle-plugin" version "1.11" id "com.gradle.common-custom-user-data-gradle-plugin" version "1.12.1"
} }
gradleEnterprise { gradleEnterprise {

View File

@@ -16,6 +16,8 @@ import java.nio.file.Files
import java.util.zip.GZIPOutputStream import java.util.zip.GZIPOutputStream
class BaseInitScriptTest extends Specification { class BaseInitScriptTest extends Specification {
static final String GE_PLUGIN_VERSION = '3.16.1'
static final String CCUD_PLUGIN_VERSION = '1.12.1'
static final TestGradleVersion GRADLE_3_X = new TestGradleVersion(GradleVersion.version('3.5.1'), 7, 9) static final TestGradleVersion GRADLE_3_X = new TestGradleVersion(GradleVersion.version('3.5.1'), 7, 9)
static final TestGradleVersion GRADLE_4_X = new TestGradleVersion(GradleVersion.version('4.10.3'), 7, 10) static final TestGradleVersion GRADLE_4_X = new TestGradleVersion(GradleVersion.version('4.10.3'), 7, 10)
@@ -24,7 +26,7 @@ class BaseInitScriptTest extends Specification {
static final TestGradleVersion GRADLE_6_X = new TestGradleVersion(GradleVersion.version('6.9.4'), 8, 15) static final TestGradleVersion GRADLE_6_X = new TestGradleVersion(GradleVersion.version('6.9.4'), 8, 15)
static final TestGradleVersion GRADLE_7_X = new TestGradleVersion(GradleVersion.version('7.6.2'), 8, 19) static final TestGradleVersion GRADLE_7_X = new TestGradleVersion(GradleVersion.version('7.6.2'), 8, 19)
static final TestGradleVersion GRADLE_8_0 = new TestGradleVersion(GradleVersion.version('8.0.2'), 8, 19) static final TestGradleVersion GRADLE_8_0 = new TestGradleVersion(GradleVersion.version('8.0.2'), 8, 19)
static final TestGradleVersion GRADLE_8_X = new TestGradleVersion(GradleVersion.version('8.2.1'), 8, 19) static final TestGradleVersion GRADLE_8_X = new TestGradleVersion(GradleVersion.version('8.5'), 8, 19)
static final List<TestGradleVersion> ALL_VERSIONS = [ static final List<TestGradleVersion> ALL_VERSIONS = [
GRADLE_3_X, // First version where TestKit supports environment variables GRADLE_3_X, // First version where TestKit supports environment variables
@@ -126,12 +128,17 @@ class BaseInitScriptTest extends Specification {
buildFile << '' buildFile << ''
} }
def declareGePluginApplication(GradleVersion gradleVersion) { def declareGePluginApplication(GradleVersion gradleVersion, URI serverUrl = mockScansServer.address) {
settingsFile.text = maybeAddPluginsToSettings(gradleVersion) + settingsFile.text settingsFile.text = maybeAddPluginsToSettings(gradleVersion, null, serverUrl) + settingsFile.text
buildFile.text = maybeAddPluginsToRootProject(gradleVersion) + buildFile.text buildFile.text = maybeAddPluginsToRootProject(gradleVersion, null, serverUrl) + buildFile.text
} }
String maybeAddPluginsToSettings(GradleVersion gradleVersion) { def declareGePluginAndCcudPluginApplication(GradleVersion gradleVersion, URI serverUrl = mockScansServer.address) {
settingsFile.text = maybeAddPluginsToSettings(gradleVersion, CCUD_PLUGIN_VERSION, serverUrl) + settingsFile.text
buildFile.text = maybeAddPluginsToRootProject(gradleVersion, CCUD_PLUGIN_VERSION, serverUrl) + buildFile.text
}
String maybeAddPluginsToSettings(GradleVersion gradleVersion, String ccudPluginVersion, URI serverUri) {
if (gradleVersion < GradleVersion.version('5.0')) { if (gradleVersion < GradleVersion.version('5.0')) {
'' // applied in build.gradle '' // applied in build.gradle
} else if (gradleVersion < GradleVersion.version('6.0')) { } else if (gradleVersion < GradleVersion.version('6.0')) {
@@ -139,10 +146,11 @@ class BaseInitScriptTest extends Specification {
} else { } else {
""" """
plugins { plugins {
id 'com.gradle.enterprise' version '3.13.4' id 'com.gradle.enterprise' version '${GE_PLUGIN_VERSION}'
${ccudPluginVersion ? "id 'com.gradle.common-custom-user-data-gradle-plugin' version '$ccudPluginVersion'" : ""}
} }
gradleEnterprise { gradleEnterprise {
server = '$mockScansServer.address' server = '$serverUri'
buildScan { buildScan {
publishAlways() publishAlways()
} }
@@ -151,24 +159,26 @@ class BaseInitScriptTest extends Specification {
} }
} }
String maybeAddPluginsToRootProject(GradleVersion gradleVersion) { String maybeAddPluginsToRootProject(GradleVersion gradleVersion, String ccudPluginVersion, URI serverUrl) {
if (gradleVersion < GradleVersion.version('5.0')) { if (gradleVersion < GradleVersion.version('5.0')) {
""" """
plugins { plugins {
id 'com.gradle.build-scan' version '1.16' id 'com.gradle.build-scan' version '1.16'
${ccudPluginVersion ? "id 'com.gradle.common-custom-user-data-gradle-plugin' version '$ccudPluginVersion'" : ""}
} }
buildScan { buildScan {
server = '$mockScansServer.address' server = '$serverUrl'
publishAlways() publishAlways()
} }
""" """
} else if (gradleVersion < GradleVersion.version('6.0')) { } else if (gradleVersion < GradleVersion.version('6.0')) {
""" """
plugins { plugins {
id 'com.gradle.build-scan' version '3.13.4' id 'com.gradle.build-scan' version '${GE_PLUGIN_VERSION}'
${ccudPluginVersion ? "id 'com.gradle.common-custom-user-data-gradle-plugin' version '$ccudPluginVersion'" : ""}
} }
gradleEnterprise { gradleEnterprise {
server = '$mockScansServer.address' server = '$serverUrl'
buildScan { buildScan {
publishAlways() publishAlways()
} }

View File

@@ -5,7 +5,7 @@ import groovy.json.JsonSlurper
import static org.junit.Assume.assumeTrue import static org.junit.Assume.assumeTrue
class TestBuildResultRecorder extends BaseInitScriptTest { class TestBuildResultRecorder extends BaseInitScriptTest {
def initScript = 'build-result-capture.init.gradle' def initScript = 'gradle-build-action.build-result-capture.init.gradle'
def "produces build results file for build with #testGradleVersion"() { def "produces build results file for build with #testGradleVersion"() {
assumeTrue testGradleVersion.compatibleWithCurrentJvm assumeTrue testGradleVersion.compatibleWithCurrentJvm
@@ -148,13 +148,30 @@ class TestBuildResultRecorder extends BaseInitScriptTest {
testGradleVersion << ALL_VERSIONS testGradleVersion << ALL_VERSIONS
} }
def "produces no build results file when RUNNER_TEMP dir is not a writable directory with #testGradleVersion"() {
assumeTrue testGradleVersion.compatibleWithCurrentJvm
when:
def invalidDir = new File(testProjectDir, 'invalid-runner-temp')
invalidDir.createNewFile()
run(['help'], initScript, testGradleVersion.gradleVersion, [], [RUNNER_TEMP: invalidDir.absolutePath])
then:
def buildResultsDir = new File(testProjectDir, '.build-results')
assert !buildResultsDir.exists()
where:
testGradleVersion << ALL_VERSIONS
}
def "produces build results file with build scan when GE plugin is applied in settingsEvaluated"() { def "produces build results file with build scan when GE plugin is applied in settingsEvaluated"() {
assumeTrue testGradleVersion.compatibleWithCurrentJvm assumeTrue testGradleVersion.compatibleWithCurrentJvm
when: when:
settingsFile.text = """ settingsFile.text = """
plugins { plugins {
id 'com.gradle.enterprise' version '3.13.4' apply(false) id 'com.gradle.enterprise' version '3.16.1' apply(false)
} }
gradle.settingsEvaluated { gradle.settingsEvaluated {
apply plugin: 'com.gradle.enterprise' apply plugin: 'com.gradle.enterprise'

View File

@@ -3,7 +3,7 @@ package com.gradle.gradlebuildaction
import static org.junit.Assume.assumeTrue import static org.junit.Assume.assumeTrue
class TestDependencyGraph extends BaseInitScriptTest { class TestDependencyGraph extends BaseInitScriptTest {
def initScript = 'github-dependency-graph.init.gradle' def initScript = 'gradle-build-action.github-dependency-graph.init.gradle'
static final List<TestGradleVersion> NO_DEPENDENCY_GRAPH_VERSIONS = [GRADLE_3_X, GRADLE_4_X] static final List<TestGradleVersion> NO_DEPENDENCY_GRAPH_VERSIONS = [GRADLE_3_X, GRADLE_4_X]
static final List<TestGradleVersion> DEPENDENCY_GRAPH_VERSIONS = ALL_VERSIONS - NO_DEPENDENCY_GRAPH_VERSIONS static final List<TestGradleVersion> DEPENDENCY_GRAPH_VERSIONS = ALL_VERSIONS - NO_DEPENDENCY_GRAPH_VERSIONS
@@ -29,22 +29,23 @@ class TestDependencyGraph extends BaseInitScriptTest {
then: then:
assert reportFile.exists() assert reportFile.exists()
assert gitHubOutputFile.text == "dependency-graph-file=${reportFile.absolutePath}\n"
where: where:
testGradleVersion << DEPENDENCY_GRAPH_VERSIONS testGradleVersion << [GRADLE_8_X]
} }
// Dependency-graph plugin doesn't support config-cache for 8.0 of Gradle
def "produces dependency graph with configuration-cache on latest Gradle"() { def "produces dependency graph with configuration-cache on latest Gradle"() {
assumeTrue testGradleVersion.compatibleWithCurrentJvm assumeTrue testGradleVersion.compatibleWithCurrentJvm
when: when:
run(['help'], initScript, testGradleVersion.gradleVersion, [], envVars) run(['help', '--configuration-cache'], initScript, testGradleVersion.gradleVersion, [], envVars)
then: then:
assert reportFile.exists() assert reportFile.exists()
where: where:
// Dependency-graph plugin doesn't support config-cache for 8.0 of Gradle
testGradleVersion << [GRADLE_8_X] testGradleVersion << [GRADLE_8_X]
} }
@@ -109,12 +110,13 @@ class TestDependencyGraph extends BaseInitScriptTest {
def getEnvVars() { def getEnvVars() {
return [ return [
GITHUB_DEPENDENCY_GRAPH_ENABLED: "true", GITHUB_DEPENDENCY_GRAPH_ENABLED: "true",
GITHUB_JOB_CORRELATOR: "CORRELATOR", GITHUB_DEPENDENCY_GRAPH_JOB_CORRELATOR: "CORRELATOR",
GITHUB_JOB_ID: "1", GITHUB_DEPENDENCY_GRAPH_JOB_ID: "1",
GITHUB_REF: "main", GITHUB_DEPENDENCY_GRAPH_REF: "main",
GITHUB_SHA: "123456", GITHUB_DEPENDENCY_GRAPH_SHA: "123456",
GITHUB_WORKSPACE: testProjectDir.absolutePath, GITHUB_DEPENDENCY_GRAPH_WORKSPACE: testProjectDir.absolutePath,
DEPENDENCY_GRAPH_REPORT_DIR: reportsDir.absolutePath DEPENDENCY_GRAPH_REPORT_DIR: reportsDir.absolutePath,
GITHUB_OUTPUT: gitHubOutputFile.absolutePath
] ]
} }
@@ -125,4 +127,8 @@ class TestDependencyGraph extends BaseInitScriptTest {
def getReportFile() { def getReportFile() {
return new File(reportsDir, "CORRELATOR.json") return new File(reportsDir, "CORRELATOR.json")
} }
def getGitHubOutputFile() {
return new File(testProjectDir, "GITHUB_OUTPUT")
}
} }

View File

@@ -0,0 +1,401 @@
package com.gradle.gradlebuildaction
import org.gradle.testkit.runner.BuildResult
import org.gradle.util.GradleVersion
import static org.junit.Assume.assumeTrue
class TestGradleEnterpriseInjection extends BaseInitScriptTest {
static final List<TestGradleVersion> CCUD_COMPATIBLE_VERSIONS = ALL_VERSIONS - [GRADLE_3_X]
def initScript = 'gradle-build-action.inject-gradle-enterprise.init.gradle'
private static final GradleVersion GRADLE_6 = GradleVersion.version('6.0')
def "does not apply GE plugins when not requested"() {
assumeTrue testGradleVersion.compatibleWithCurrentJvm
when:
def result = run([], initScript, testGradleVersion.gradleVersion)
then:
outputMissesGePluginApplicationViaInitScript(result)
outputMissesCcudPluginApplicationViaInitScript(result)
where:
testGradleVersion << ALL_VERSIONS
}
def "does not override GE plugin when already defined in project"() {
assumeTrue testGradleVersion.compatibleWithCurrentJvm
given:
declareGePluginApplication(testGradleVersion.gradleVersion)
when:
def result = run(testGradleVersion, testConfig())
then:
outputMissesGePluginApplicationViaInitScript(result)
outputMissesCcudPluginApplicationViaInitScript(result)
and:
outputContainsBuildScanUrl(result)
where:
testGradleVersion << ALL_VERSIONS
}
def "applies GE plugin via init script when not defined in project"() {
assumeTrue testGradleVersion.compatibleWithCurrentJvm
when:
def result = run(testGradleVersion, testConfig())
then:
outputContainsGePluginApplicationViaInitScript(result, testGradleVersion.gradleVersion)
outputMissesCcudPluginApplicationViaInitScript(result)
and:
outputContainsBuildScanUrl(result)
where:
testGradleVersion << ALL_VERSIONS
}
def "applies GE and CCUD plugins via init script when not defined in project"() {
assumeTrue testGradleVersion.compatibleWithCurrentJvm
when:
def result = run(testGradleVersion, testConfig().withCCUDPlugin())
then:
outputContainsGePluginApplicationViaInitScript(result, testGradleVersion.gradleVersion)
outputContainsCcudPluginApplicationViaInitScript(result)
and:
outputContainsBuildScanUrl(result)
where:
testGradleVersion << CCUD_COMPATIBLE_VERSIONS
}
def "applies CCUD plugin via init script where GE plugin already applied"() {
assumeTrue testGradleVersion.compatibleWithCurrentJvm
given:
declareGePluginApplication(testGradleVersion.gradleVersion)
when:
def result = run(testGradleVersion, testConfig().withCCUDPlugin())
then:
outputMissesGePluginApplicationViaInitScript(result)
outputContainsCcudPluginApplicationViaInitScript(result)
and:
outputContainsBuildScanUrl(result)
where:
testGradleVersion << CCUD_COMPATIBLE_VERSIONS
}
def "does not override CCUD plugin when already defined in project"() {
assumeTrue testGradleVersion.compatibleWithCurrentJvm
given:
declareGePluginAndCcudPluginApplication(testGradleVersion.gradleVersion)
when:
def result = run(testGradleVersion, testConfig().withCCUDPlugin())
then:
outputMissesGePluginApplicationViaInitScript(result)
outputMissesCcudPluginApplicationViaInitScript(result)
and:
outputContainsBuildScanUrl(result)
where:
testGradleVersion << CCUD_COMPATIBLE_VERSIONS
}
def "ignores GE URL and allowUntrustedServer when GE plugin is not applied by the init script"() {
assumeTrue testGradleVersion.compatibleWithCurrentJvm
given:
declareGePluginApplication(testGradleVersion.gradleVersion)
when:
def config = testConfig().withServer(URI.create('https://ge-server.invalid'))
def result = run(testGradleVersion, config)
then:
outputMissesGePluginApplicationViaInitScript(result)
outputMissesCcudPluginApplicationViaInitScript(result)
and:
outputContainsBuildScanUrl(result)
where:
testGradleVersion << ALL_VERSIONS
}
def "configures GE URL and allowUntrustedServer when GE plugin is applied by the init script"() {
assumeTrue testGradleVersion.compatibleWithCurrentJvm
when:
def config = testConfig().withServer(mockScansServer.address)
def result = run(testGradleVersion, config)
then:
outputContainsGePluginApplicationViaInitScript(result, testGradleVersion.gradleVersion)
outputContainsGeConnectionInfo(result, mockScansServer.address.toString(), true)
outputMissesCcudPluginApplicationViaInitScript(result)
outputContainsPluginRepositoryInfo(result, 'https://plugins.gradle.org/m2')
and:
outputContainsBuildScanUrl(result)
where:
testGradleVersion << ALL_VERSIONS
}
def "enforces GE URL and allowUntrustedServer in project if enforce url parameter is enabled"() {
assumeTrue testGradleVersion.compatibleWithCurrentJvm
given:
declareGePluginApplication(testGradleVersion.gradleVersion, URI.create('https://ge-server.invalid'))
when:
def config = testConfig().withServer(mockScansServer.address, true)
def result = run(testGradleVersion, config)
then:
outputMissesGePluginApplicationViaInitScript(result)
outputMissesCcudPluginApplicationViaInitScript(result)
and:
outputEnforcesGeUrl(result, mockScansServer.address.toString(), true)
and:
outputContainsBuildScanUrl(result)
where:
testGradleVersion << ALL_VERSIONS
}
def "can configure alternative repository for plugins when GE plugin is applied by the init script"() {
assumeTrue testGradleVersion.compatibleWithCurrentJvm
when:
def config = testConfig().withPluginRepository(new URI('https://plugins.grdev.net/m2'))
def result = run(testGradleVersion, config)
then:
outputContainsGePluginApplicationViaInitScript(result, testGradleVersion.gradleVersion)
outputContainsGeConnectionInfo(result, mockScansServer.address.toString(), true)
outputMissesCcudPluginApplicationViaInitScript(result)
outputContainsPluginRepositoryInfo(result, 'https://plugins.grdev.net/m2')
and:
outputContainsBuildScanUrl(result)
where:
testGradleVersion << ALL_VERSIONS
}
def "stops gracefully when requested CCUD plugin version is <1.7"() {
assumeTrue testGradleVersion.compatibleWithCurrentJvm
when:
def config = testConfig().withCCUDPlugin("1.6.6")
def result = run(testGradleVersion, config)
then:
outputMissesGePluginApplicationViaInitScript(result)
outputMissesCcudPluginApplicationViaInitScript(result)
result.output.contains('Common Custom User Data Gradle plugin must be at least 1.7. Configured version is 1.6.6.')
where:
testGradleVersion << ALL_VERSIONS
}
def "can configure GE via CCUD system property overrides when CCUD plugin is inject via init script"() {
assumeTrue testGradleVersion.compatibleWithCurrentJvm
when:
def config = testConfig().withCCUDPlugin().withServer(URI.create('https://ge-server.invalid'))
def result = run(testGradleVersion, config, ["help", "-Dgradle.enterprise.url=${mockScansServer.address}".toString()])
then:
outputContainsGePluginApplicationViaInitScript(result, testGradleVersion.gradleVersion)
outputContainsCcudPluginApplicationViaInitScript(result)
and:
outputContainsBuildScanUrl(result)
where:
testGradleVersion << CCUD_COMPATIBLE_VERSIONS
}
def "init script is configuration cache compatible"() {
assumeTrue testGradleVersion.compatibleWithCurrentJvm
when:
def config = testConfig().withCCUDPlugin()
def result = run(testGradleVersion, config, ["help", "--configuration-cache"])
then:
outputContainsGePluginApplicationViaInitScript(result, testGradleVersion.gradleVersion)
outputContainsCcudPluginApplicationViaInitScript(result)
and:
outputContainsBuildScanUrl(result)
when:
result = run(testGradleVersion, config, ["help", "--configuration-cache"])
then:
outputMissesGePluginApplicationViaInitScript(result)
outputMissesCcudPluginApplicationViaInitScript(result)
and:
outputContainsBuildScanUrl(result)
where:
testGradleVersion << CONFIGURATION_CACHE_VERSIONS
}
void outputContainsBuildScanUrl(BuildResult result) {
def message = "Publishing build scan...\n${mockScansServer.address}s/$PUBLIC_BUILD_SCAN_ID"
assert result.output.contains(message)
assert 1 == result.output.count(message)
}
void outputContainsGePluginApplicationViaInitScript(BuildResult result, GradleVersion gradleVersion) {
def pluginApplicationLogMsgGradle4And5 = "Applying com.gradle.scan.plugin.BuildScanPlugin via init script"
def pluginApplicationLogMsgGradle6AndHigher = "Applying com.gradle.enterprise.gradleplugin.GradleEnterprisePlugin via init script"
if (gradleVersion < GRADLE_6) {
assert result.output.contains(pluginApplicationLogMsgGradle4And5)
assert 1 == result.output.count(pluginApplicationLogMsgGradle4And5)
assert !result.output.contains(pluginApplicationLogMsgGradle6AndHigher)
} else {
assert result.output.contains(pluginApplicationLogMsgGradle6AndHigher)
assert 1 == result.output.count(pluginApplicationLogMsgGradle6AndHigher)
assert !result.output.contains(pluginApplicationLogMsgGradle4And5)
}
}
void outputMissesGePluginApplicationViaInitScript(BuildResult result) {
def pluginApplicationLogMsgGradle4And5 = "Applying com.gradle.scan.plugin.BuildScanPlugin via init script"
def pluginApplicationLogMsgGradle6AndHigher = "Applying com.gradle.enterprise.gradleplugin.GradleEnterprisePlugin via init script"
assert !result.output.contains(pluginApplicationLogMsgGradle4And5)
assert !result.output.contains(pluginApplicationLogMsgGradle6AndHigher)
}
void outputContainsCcudPluginApplicationViaInitScript(BuildResult result) {
def pluginApplicationLogMsg = "Applying com.gradle.CommonCustomUserDataGradlePlugin via init script"
assert result.output.contains(pluginApplicationLogMsg)
assert 1 == result.output.count(pluginApplicationLogMsg)
}
void outputMissesCcudPluginApplicationViaInitScript(BuildResult result) {
def pluginApplicationLogMsg = "Applying com.gradle.CommonCustomUserDataGradlePlugin via init script"
assert !result.output.contains(pluginApplicationLogMsg)
}
void outputContainsGeConnectionInfo(BuildResult result, String geUrl, boolean geAllowUntrustedServer) {
def geConnectionInfo = "Connection to Gradle Enterprise: $geUrl, allowUntrustedServer: $geAllowUntrustedServer"
assert result.output.contains(geConnectionInfo)
assert 1 == result.output.count(geConnectionInfo)
}
void outputContainsPluginRepositoryInfo(BuildResult result, String gradlePluginRepositoryUrl) {
def repositoryInfo = "Gradle Enterprise plugins resolution: ${gradlePluginRepositoryUrl}"
assert result.output.contains(repositoryInfo)
assert 1 == result.output.count(repositoryInfo)
}
void outputEnforcesGeUrl(BuildResult result, String geUrl, boolean geAllowUntrustedServer) {
def enforceUrl = "Enforcing Gradle Enterprise: $geUrl, allowUntrustedServer: $geAllowUntrustedServer"
assert result.output.contains(enforceUrl)
assert 1 == result.output.count(enforceUrl)
}
private BuildResult run(TestGradleVersion testGradleVersion, TestConfig config, List<String> args = ["help"]) {
if (testKitSupportsEnvVars(testGradleVersion.gradleVersion)) {
return run(args, initScript, testGradleVersion.gradleVersion, [], config.envVars)
} else {
return run(args, initScript, testGradleVersion.gradleVersion, config.jvmArgs, [:])
}
}
private boolean testKitSupportsEnvVars(GradleVersion gradleVersion) {
// TestKit supports env vars for Gradle 3.5+, except on M1 Mac where only 6.9+ is supported
def isM1Mac = System.getProperty("os.arch") == "aarch64"
if (isM1Mac) {
return gradleVersion >= GRADLE_6_X.gradleVersion
} else {
return gradleVersion >= GRADLE_3_X.gradleVersion
}
}
private TestConfig testConfig() {
new TestConfig()
}
class TestConfig {
String serverUrl = mockScansServer.address.toString()
boolean enforceUrl = false
String ccudPluginVersion = null
String pluginRepositoryUrl = null
TestConfig withCCUDPlugin(String version = CCUD_PLUGIN_VERSION) {
ccudPluginVersion = version
return this
}
TestConfig withServer(URI url, boolean enforceUrl = false) {
serverUrl = url.toASCIIString()
this.enforceUrl = enforceUrl
return this
}
TestConfig withPluginRepository(URI pluginRepositoryUrl) {
this.pluginRepositoryUrl = pluginRepositoryUrl
return this
}
def getEnvVars() {
Map<String, String> envVars = [
GRADLE_ENTERPRISE_INJECTION_ENABLED: "true",
GRADLE_ENTERPRISE_URL: serverUrl,
GRADLE_ENTERPRISE_ALLOW_UNTRUSTED_SERVER: "true",
GRADLE_ENTERPRISE_PLUGIN_VERSION: GE_PLUGIN_VERSION,
GRADLE_ENTERPRISE_BUILD_SCAN_UPLOAD_IN_BACKGROUND: "true" // Need to upload in background since our Mock server doesn't cope with foreground upload
]
if (enforceUrl) envVars.put("GRADLE_ENTERPRISE_ENFORCE_URL", "true")
if (ccudPluginVersion != null) envVars.put("GRADLE_ENTERPRISE_CCUD_PLUGIN_VERSION", ccudPluginVersion)
if (pluginRepositoryUrl != null) envVars.put("GRADLE_ENTERPRISE_PLUGIN_REPOSITORY_URL", pluginRepositoryUrl)
return envVars
}
def getJvmArgs() {
List<String> jvmArgs = [
"-Dgradle-enterprise.injection-enabled=true",
"-Dgradle-enterprise.url=$serverUrl",
"-Dgradle-enterprise.allow-untrusted-server=true",
"-Dgradle-enterprise.plugin.version=$GE_PLUGIN_VERSION",
"-Dgradle-enterprise.build-scan.upload-in-background=true"
]
if (enforceUrl) jvmArgs.add("-Dgradle-enterprise.enforce-url=true")
if (ccudPluginVersion != null) jvmArgs.add("-Dgradle-enterprise.ccud-plugin.version=$ccudPluginVersion")
if (pluginRepositoryUrl != null) jvmArgs.add("-Dgradle-enterprise.plugin-repository.url=$pluginRepositoryUrl")
return jvmArgs.collect { it.toString() } // Convert from GStrings
}
}
}

View File

@@ -49,7 +49,7 @@ test('will cleanup unused gradle versions', async () => {
const gradle802 = path.resolve(gradleUserHome, "caches/8.0.2") const gradle802 = path.resolve(gradleUserHome, "caches/8.0.2")
const wrapper802 = path.resolve(gradleUserHome, "wrapper/dists/gradle-8.0.2-bin") const wrapper802 = path.resolve(gradleUserHome, "wrapper/dists/gradle-8.0.2-bin")
const gradleCurrent = path.resolve(gradleUserHome, "caches/8.2.1") const gradleCurrent = path.resolve(gradleUserHome, "caches/8.5")
expect(fs.existsSync(gradle802)).toBe(true) expect(fs.existsSync(gradle802)).toBe(true)
expect(fs.existsSync(wrapper802)).toBe(true) expect(fs.existsSync(wrapper802)).toBe(true)

View File

@@ -17,10 +17,4 @@ describe('cacheUtils-utils', () => {
expect(posixHash).toBe(windowsHash) expect(posixHash).toBe(windowsHash)
}) })
}) })
describe('sanitizes workflow name in cache key', () => {
it('with comma', () => {
const cacheKey = cacheUtils.getCacheKeyForJob("Workflow, with,commas", "JOB_ID")
expect(cacheKey).toBe('workflow withcommas-JOB_ID')
})
})
}) })

View File

@@ -0,0 +1,22 @@
import * as inputParams from '../../src/input-params'
describe('input params', () => {
describe('parses numeric input', () => {
it('uses default value', () => {
const val = inputParams.parseNumericInput('param-name', '', 88)
expect(val).toBe(88)
})
it('parses numeric input', () => {
const val = inputParams.parseNumericInput('param-name', '34', 88)
expect(val).toBe(34)
})
it('fails on non-numeric input', () => {
const t = () => {
inputParams.parseNumericInput('param-name', 'xyz', 88)
};
expect(t).toThrow(TypeError)
expect(t).toThrow("The value 'xyz' is not a valid numeric value for 'param-name'.")
})
})
})