Compare commits

..

15 Commits

Author SHA1 Message Date
Paul Merlin
90ccf054e6 Merge branch 'master' into releases/v1 2020-09-13 13:48:42 +02:00
Paul Merlin
c6b57b9c8c Merge branch 'master' into releases/v1 2020-06-22 16:45:23 +02:00
Paul Merlin
791b98c565 Merge branch 'master' into releases/v1 2020-06-15 19:35:42 +02:00
Paul Merlin
27da3e28b3 Merge branch 'master' into releases/v1 2020-06-15 16:40:55 +02:00
Paul Merlin
e220e54c83 Merge branch 'master' into releases/v1 2020-06-14 12:41:26 +02:00
Paul Merlin
720051268d Cleanup 2020-06-13 16:37:23 +02:00
Paul Merlin
36d51a403a Merge branch 'master' into releases/v1 2020-06-13 16:33:57 +02:00
Paul Merlin
d0c5f7955e build 2019-12-09 15:22:02 +01:00
Paul Merlin
a2ba194e38 Merge branch 'master' into releases/v1 2019-12-09 15:20:11 +01:00
Paul Merlin
064f85c156 build 2019-10-28 13:31:49 +01:00
Paul Merlin
580b26a94c Merge branch 'master' into releases/v1 2019-10-28 13:30:49 +01:00
Paul Merlin
c61d0fe2b5 Merge branch 'master' into releases/v1 2019-10-28 13:27:16 +01:00
Paul Merlin
6170f06e8d build 2019-09-23 12:20:06 +02:00
Paul Merlin
e561eefa28 Merge branch 'master' into releases/v1 2019-09-23 12:17:48 +02:00
Paul Merlin
2d5ca45eab publishing v1 of action 2019-09-21 16:11:55 +02:00
43 changed files with 3002 additions and 2261 deletions

View File

@@ -4,10 +4,9 @@ name: prod
on: on:
pull_request: pull_request:
push: push:
workflow_dispatch:
jobs: jobs:
basic-build: check:
strategy: strategy:
matrix: matrix:
os: [ubuntu-latest, macos-latest, windows-latest] os: [ubuntu-latest, macos-latest, windows-latest]
@@ -15,110 +14,27 @@ jobs:
steps: steps:
- name: Checkout sources - name: Checkout sources
uses: actions/checkout@v2 uses: actions/checkout@v2
- name: Build using Gradle wrapper - name: Test wrapper
uses: ./ uses: ./
with: with:
build-root-directory: __tests__/samples/basic wrapper-directory: __tests__/data/basic
build-root-directory: __tests__/data/basic
dependencies-cache-enabled: true
configuration-cache-enabled: true
arguments: test arguments: test
- name: Test dist download
gradle-execution:
needs: basic-build
strategy:
matrix:
os: [ubuntu-latest, macos-latest, windows-latest]
include:
- os: windows-latest
script-suffix: '.bat'
runs-on: ${{ matrix.os }}
steps:
- name: Checkout sources
uses: actions/checkout@v2
- name: Test use defined Gradle version
uses: ./ uses: ./
with: with:
gradle-version: 6.9 gradle-version: rc
build-root-directory: __tests__/samples/no-wrapper build-root-directory: __tests__/data/basic
arguments: help
- name: Test use Gradle version alias
uses: ./
with:
gradle-version: release-candidate
build-root-directory: __tests__/samples/no-wrapper
arguments: help
- name: Test use defined Gradle executable
uses: ./
with:
gradle-executable: __tests__/samples/basic/gradlew${{ matrix.script-suffix }}
build-root-directory: __tests__/samples/no-wrapper
arguments: help
- name: Test custom wrapper location (deprecated)
uses: ./
with:
build-root-directory: __tests__/samples/no-wrapper
wrapper-directory: __tests__/samples/basic
arguments: help
dependencies-cache:
needs: basic-build
strategy:
matrix:
os: [ubuntu-latest, macos-latest, windows-latest]
runs-on: ${{ matrix.os }}
steps:
- name: Checkout sources
uses: actions/checkout@v2
- name: Test dependencies-cache-enabled
uses: ./
with:
build-root-directory: __tests__/samples/basic
arguments: test --no-daemon
dependencies-cache-enabled: true
configuration-cache:
needs: basic-build
strategy:
matrix:
os: [ubuntu-latest, macos-latest, windows-latest]
runs-on: ${{ matrix.os }}
steps:
- name: Checkout sources
uses: actions/checkout@v2
- name: Test configuration-cache-enabled
uses: ./
with:
build-root-directory: __tests__/samples/basic
arguments: test --configuration-cache --no-daemon
configuration-cache-enabled: true
dependencies-cache-enabled: true
# Configuration cache requires dependencies cache, since it assumes dependencies are already downloaded.
cache-read-only:
needs: basic-build
strategy:
matrix:
os: [ubuntu-latest, macos-latest, windows-latest]
runs-on: ${{ matrix.os }}
steps:
- name: Checkout sources
uses: actions/checkout@v2
- name: Test cache-read-only
uses: ./
with:
build-root-directory: __tests__/samples/basic
arguments: test --no-daemon
dependencies-cache-enabled: true dependencies-cache-enabled: true
configuration-cache-enabled: true configuration-cache-enabled: true
cache-read-only: true arguments: test --configuration-cache
- name: Stop Gradle daemon
failures: # These build invocations are informational only, and are expected to fail
needs: basic-build
runs-on: ubuntu-latest
steps:
- name: Checkout sources
uses: actions/checkout@v2
- name: Test wrapper missing
uses: ./ uses: ./
continue-on-error: true
with: with:
build-root-directory: __tests__/samples/no-wrapper gradle-version: rc
arguments: help build-root-directory: __tests__/data/basic
dependencies-cache-enabled: true
configuration-cache-enabled: true
arguments: --stop

4
.gitignore vendored
View File

@@ -98,9 +98,5 @@ Thumbs.db
__tests__/runner/* __tests__/runner/*
# lib/**/* # lib/**/*
# IntelliJ IDEA config files
.idea/ .idea/
*.iml *.iml
# ASDF tool configuration
.tool-versions

View File

@@ -1,10 +1,12 @@
# Execute Gradle builds in GitHub Actions workflows # Execute Gradle commands in GitHub Actions workflows
This GitHub Action can be used to execute a Gradle build on any platform supported by GitHub Actions. This GitHub Action can be used to run arbitrary Gradle commands on any platform supported by GitHub Actions.
You might also be interested by the related [Gradle Plugin](https://github.com/eskatos/gradle-github-actions-plugin) that allows your build to easily get GitHub Actions environment and tag Gradle Build Scans accordingly.
## Usage ## Usage
The following workflow will run `./gradlew build` using the wrapper from the repository on ubuntu, macos and windows. The only prerequisite is to have Java installed: you define the version of Java you need to run the build using the `actions/setup-java` action. The following workflow will run `./gradlew build` using the wrapper from the repository on ubuntu, macos and windows. The only prerequisite is to have Java installed, you can define the version you need to run the build using the `actions/setup-java` action.
```yaml ```yaml
# .github/workflows/gradle-build-pr.yml # .github/workflows/gradle-build-pr.yml
@@ -21,7 +23,7 @@ jobs:
- uses: actions/setup-java@v1 - uses: actions/setup-java@v1
with: with:
java-version: 11 java-version: 11
- uses: gradle/gradle-build-action@v1 - uses: eskatos/gradle-command-action@v1
with: with:
arguments: build arguments: build
``` ```
@@ -45,7 +47,7 @@ See `gradle --help` for more information.
If you need to pass environment variables, simply use the GitHub Actions workflow syntax: If you need to pass environment variables, simply use the GitHub Actions workflow syntax:
```yaml ```yaml
- uses: gradle/gradle-build-action@v1 - uses: eskatos/gradle-command-action@v1
env: env:
CI: true CI: true
``` ```
@@ -53,33 +55,31 @@ If you need to pass environment variables, simply use the GitHub Actions workflo
## Run a build from a different directory ## Run a build from a different directory
```yaml ```yaml
- uses: gradle/gradle-build-action@v1 - uses: eskatos/gradle-command-action@v1
with: with:
build-root-directory: some/subdirectory build-root-directory: some/subdirectory
``` ```
## Use a specific `gradle` executable
```yaml
- uses: gradle/gradle-build-action@v1
with:
gradle-executable: path/to/gradle
```
## Use a Gradle wrapper from a different directory ## Use a Gradle wrapper from a different directory
```yaml ```yaml
- uses: gradle/gradle-build-action@v1 - uses: eskatos/gradle-command-action@v1
with: with:
gradle-executable: path/to/gradlew wrapper-directory: path/to/wrapper-directory
``` ```
NOTE: The `wrapper-directory` input has been deprecated. Use `gradle-executable` instead. ## Use a specific `gradle` executable
```yaml
- uses: eskatos/gradle-command-action@v1
with:
gradle-executable: path/to/gradle
```
## Setup and use a declared Gradle version ## Setup and use a declared Gradle version
```yaml ```yaml
- uses: gradle/gradle-build-action@v1 - uses: eskatos/gradle-command-action@v1
with: with:
gradle-version: 6.5 gradle-version: 6.5
``` ```
@@ -90,11 +90,11 @@ Moreover, you can use the following aliases:
| Alias | Selects | | Alias | Selects |
| --- |---| | --- |---|
| `wrapper` | The Gradle wrapper's version (default, useful for matrix builds) | | `wrapper` | The Gradle wrapper's version (default, useful for matrix builds) |
| `current` | The current [stable release](https://gradle.org/install/) | | `current` | The current [stable release](https://gradle.org/install/) |
| `release-candidate` | The current [release candidate](https://gradle.org/release-candidate/) if any, otherwise fallback to `current` | | `rc` | The current [release candidate](https://gradle.org/release-candidate/) if any, otherwise fallback to `current` |
| `nightly` | The latest [nightly](https://gradle.org/nightly/), fails if none. | | `nightly` | The latest [nightly](https://gradle.org/nightly/), fails if none. |
| `release-nightly` | The latest [release nightly](https://gradle.org/release-nightly/), fails if none. | | `release-nightly` | The latest [release nightly](https://gradle.org/release-nightly/), fails if none. |
This can be handy to, for example, automatically test your build with the next Gradle version once a release candidate is out: This can be handy to, for example, automatically test your build with the next Gradle version once a release candidate is out:
@@ -112,9 +112,9 @@ jobs:
- uses: actions/setup-java@v1 - uses: actions/setup-java@v1
with: with:
java-version: 11 java-version: 11
- uses: gradle/gradle-build-action@v1 - uses: eskatos/gradle-command-action@v1
with: with:
gradle-version: release-candidate gradle-version: rc
arguments: build --dry-run # just test build configuration arguments: build --dry-run # just test build configuration
``` ```
@@ -122,30 +122,26 @@ jobs:
This action provides 3 levels of caching to help speed up your GitHub Actions: This action provides 3 levels of caching to help speed up your GitHub Actions:
- `distributions` caches any downloaded Gradle zips, including any downloaded [wrapper](https://docs.gradle.org/current/userguide/gradle_wrapper.html) versions, saving time downloading Gradle distributions ; - `wrapper` caches the local [wrapper](https://docs.gradle.org/current/userguide/gradle_wrapper.html) installation, saving time downloading and unpacking Gradle distributions ;
- `dependencies` caches the [dependencies](https://docs.gradle.org/current/userguide/dependency_resolution.html#sub:cache_copy), saving time downloading dependencies ; - `dependencies` caches the [dependencies](https://docs.gradle.org/current/userguide/dependency_resolution.html#sub:cache_copy), saving time downloading dependencies ;
- `configuration` caches the [build configuration](https://docs.gradle.org/nightly/userguide/configuration_cache.html), saving time configuring the build. - `configuration` caches the [build configuration](https://docs.gradle.org/nightly/userguide/configuration_cache.html), saving time configuring the build.
Only the first one, caching downloaded distributions, is enabled by default. Only the first one, caching the wrapper installation, is enabled by default.
Future versions of this action will enable all caching by default. Future versions of this action will enable all caching by default.
You can control which level is enabled as follows: You can control which level is enabled as follows:
```yaml ```yaml
distributions-cache-enabled: true wrapper-cache-enabled: true
dependencies-cache-enabled: true dependencies-cache-enabled: true
configuration-cache-enabled: true configuration-cache-enabled: true
``` ```
NOTE: The `wrapper-cache-enabled` flag has been deprecated, replaced by `distributions-cache-enabled` which enables caching for all downloaded distributions, including Gradle wrapper downloads. The wrapper installation cache is simple and can't be configured further.
The distributions cache is simple and can't be configured further.
The dependencies and configuration cache will compute a cache key in a best effort manner. The dependencies and configuration cache will compute a cache key in a best effort manner.
Keep reading to learn how to better control how they work. Keep reading to learn how to better control how they work.
Note that enabling configuration cache without the dependencies cache is not permitted, since a hit in the configuration cache assumes that dependencies are already present in the local dependencies cache.
### Configuring the dependencies and configuration caches ### Configuring the dependencies and configuration caches
Both the dependencies and configuration caches use the same default configuration: Both the dependencies and configuration caches use the same default configuration:
@@ -167,11 +163,11 @@ If the defaults don't suit your needs you can override them with the following i
```yaml ```yaml
dependencies-cache-key: | dependencies-cache-key: |
**/gradle.properties **/gradle.properties
gradle/dependency-locks/** gradle/dependency-locking/**
dependencies-cache-exact: true dependencies-cache-exact: true
configuration-cache-key: | configuration-cache-key: |
**/gradle.properties **/gradle.properties
gradle/dependency-locks/** gradle/dependency-locking/**
configuration-cache-exact: true configuration-cache-exact: true
``` ```
@@ -183,25 +179,13 @@ If you happen to use Gradle [dependency locking](https://docs.gradle.org/current
```yaml ```yaml
dependencies-cache-enabled: true dependencies-cache-enabled: true
dependencies-cache-key: gradle/dependency-locks/** dependencies-cache-key: gradle/dependency-locking/**
dependencies-cache-exact: true dependencies-cache-exact: true
``` ```
### Using the caches read-only
Cache storage space is limited for GitHub actions, and writing new cache entries can trigger the deletion of exising entries.
In some circumstances, it makes sense for a Gradle invocation to use any existing cache entries but not to write and changes back.
For example, you may want to write cache entries for builds on your `main` branch, but not for any PR build invocations.
Use the following configuration to avoid writing cache entries for the action invocation:
```yaml
cache-read-only: true
```
## Build scans ## Build scans
If your build publishes a [build scan](https://gradle.com/build-scans/) the `gradle-build-action` action will emit the link to the published build scan as an output named `build-scan-url`. If your build publishes a [build scan](https://gradle.com/build-scans/) the `gradle-command-action` action will emit the link to the published build scan as an output named `build-scan-url`.
You can then use that link in subsequent actions of your workflow. You can then use that link in subsequent actions of your workflow.
@@ -222,20 +206,12 @@ jobs:
- uses: actions/setup-java@v1 - uses: actions/setup-java@v1
with: with:
java-version: 11 java-version: 11
- uses: gradle/gradle-build-action@v1 - uses: eskatos/gradle-command-action@v1
with: with:
arguments: build arguments: build
id: gradle id: gradle
- name: "Comment build scan url" - uses: example/action-that-comments-on-the-pr@v0
uses: actions/github-script@v3 if: failure()
if: github.event_name == 'pull_request' && failure()
with: with:
github-token: ${{secrets.GITHUB_TOKEN}} comment: Build failed ${{ steps.gradle.outputs.build-scan-url }}
script: |
github.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: '❌ ${{ github.workflow }} failed: ${{ steps.gradle.outputs.build-scan-url }}'
})
``` ```

View File

@@ -1,65 +0,0 @@
import * as cacheUtils from '../src/cache-utils'
import * as path from 'path'
describe('cacheUtils-utils', () => {
describe('can hash', () => {
it('a directory', async () => {
const hash = await cacheUtils.hashFiles(
path.resolve('__tests__/data/crypto-utils-test/gradle')
)
expect(hash).toBe(
process.platform === 'win32'
? '3364336e94e746ce65a31748a6371b7efd7d499e18ad605c74c91cde0edc0a44'
: '63b9f14f65d014e585099c9c274b9dcbddf5cfd1a8978e5a24efb89ff9304348'
)
})
it('a directory with a glob', async () => {
const hash = await cacheUtils.hashFiles(
path.resolve('__tests__/data/crypto-utils-test/'),
['gradle/**']
)
expect(hash).toBe(
process.platform === 'win32'
? '3364336e94e746ce65a31748a6371b7efd7d499e18ad605c74c91cde0edc0a44'
: '63b9f14f65d014e585099c9c274b9dcbddf5cfd1a8978e5a24efb89ff9304348'
)
})
it('a directory with globs', async () => {
const hash = await cacheUtils.hashFiles(
path.resolve('__tests__/data/crypto-utils-test/'),
['**/*.gradle', 'gradle/**']
)
expect(hash).toBe(
process.platform === 'win32'
? 'd9b66fded38f79f601ce745d64ed726a8df8c0b242b02bcd2c1d331f54742ad6'
: 'f42cd10636f09799f4e01cc84e7ae906cc1d9140f1446f8dcd054d19cbc44c2b'
)
})
})
describe('can truncate args', () => {
test('handles zero-length string', () => {
expect(cacheUtils.truncateArgs('')).toBe('')
})
test('leaves short string untouched', () => {
expect(
cacheUtils.truncateArgs('short string that-should-be-untouched')
).toBe('short string that-should-be-untouched')
})
test('truncates long string', () => {
const longString = 'a'.repeat(500)
expect(cacheUtils.truncateArgs(longString)).toBe('a'.repeat(400))
})
test('trims leading and trailing whitespace', () => {
expect(cacheUtils.truncateArgs(' this is an arg ')).toBe(
'this is an arg'
)
})
test('removes repeated whitespace', () => {
expect(
cacheUtils.truncateArgs(
' this one has long \t\n\t\r spaces '
)
).toBe('this one has long spaces')
})
})
})

View File

@@ -6,7 +6,7 @@ describe('cache', () => {
it('from wrapper properties file', async () => { it('from wrapper properties file', async () => {
const version = cacheWrapper.extractGradleWrapperSlugFrom( const version = cacheWrapper.extractGradleWrapperSlugFrom(
path.resolve( path.resolve(
'__tests__/data/cache-wrapper-test/gradle-wrapper.properties' '__tests__/data/basic/gradle/wrapper/gradle-wrapper.properties'
) )
) )
expect(version).toBe('6.6.1-bin') expect(version).toBe('6.6.1-bin')

View File

@@ -0,0 +1,39 @@
import * as cryptoUtils from '../src/crypto-utils'
import * as path from 'path'
describe('crypto-utils', () => {
describe('can hash', () => {
it('a directory', async () => {
const hash = await cryptoUtils.hashFiles(
path.resolve('__tests__/data/basic/gradle')
)
expect(hash).toBe(
process.platform === 'win32'
? '3364336e94e746ce65a31748a6371b7efd7d499e18ad605c74c91cde0edc0a44'
: '63b9f14f65d014e585099c9c274b9dcbddf5cfd1a8978e5a24efb89ff9304348'
)
})
it('a directory with a glob', async () => {
const hash = await cryptoUtils.hashFiles(
path.resolve('__tests__/data/basic/'),
['gradle/**']
)
expect(hash).toBe(
process.platform === 'win32'
? '3364336e94e746ce65a31748a6371b7efd7d499e18ad605c74c91cde0edc0a44'
: '63b9f14f65d014e585099c9c274b9dcbddf5cfd1a8978e5a24efb89ff9304348'
)
})
it('a directory with globs', async () => {
const hash = await cryptoUtils.hashFiles(
path.resolve('__tests__/data/basic/'),
['**/*.gradle', 'gradle/**']
)
expect(hash).toBe(
process.platform === 'win32'
? 'd9b66fded38f79f601ce745d64ed726a8df8c0b242b02bcd2c1d331f54742ad6'
: 'f42cd10636f09799f4e01cc84e7ae906cc1d9140f1446f8dcd054d19cbc44c2b'
)
})
})
})

View File

@@ -1,5 +0,0 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.6.1-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

View File

@@ -1,6 +0,0 @@
#
# https://help.github.com/articles/dealing-with-line-endings/
#
# These are explicitly windows files and should use crlf
*.bat text eol=crlf

View File

@@ -1,5 +0,0 @@
# Ignore Gradle project-specific cache directory
.gradle
# Ignore Gradle build output directory
build

View File

@@ -1,11 +0,0 @@
plugins {
id 'java'
}
repositories {
mavenCentral()
}
dependencies {
testImplementation('junit:junit:4.12')
}

View File

@@ -1,5 +0,0 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.1.1-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

View File

@@ -1,185 +0,0 @@
#!/usr/bin/env sh
#
# Copyright 2015 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# 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"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=`expr $i + 1`
done
case $i in
0) set -- ;;
1) set -- "$args0" ;;
2) set -- "$args0" "$args1" ;;
3) set -- "$args0" "$args1" "$args2" ;;
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=`save "$@"`
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
exec "$JAVACMD" "$@"

View File

@@ -1,104 +0,0 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@@ -1 +0,0 @@
rootProject.name = 'basic'

View File

@@ -1,10 +0,0 @@
package basic;
import org.junit.Test;
public class BasicTest {
@Test
public void test() {
assert true;
}
}

View File

@@ -1,6 +0,0 @@
#
# https://help.github.com/articles/dealing-with-line-endings/
#
# These are explicitly windows files and should use crlf
*.bat text eol=crlf

View File

@@ -1,5 +0,0 @@
# Ignore Gradle project-specific cache directory
.gradle
# Ignore Gradle build output directory
build

View File

@@ -1,3 +0,0 @@
rootProject.name = 'no-wrapper'
println "Using Gradle version: ${gradle.gradleVersion}"

View File

@@ -1,5 +1,6 @@
name: "Gradle Build Action" name: "Gradle Command"
description: 'Executes a Gradle build, caching useful state in the GitHub actions cache' description: 'Execute Gradle Command Line'
author: 'Paul Merlin <paul@nospere.org>'
# https://help.github.com/en/articles/metadata-syntax-for-github-actions # https://help.github.com/en/articles/metadata-syntax-for-github-actions
@@ -7,7 +8,6 @@ inputs:
wrapper-directory: wrapper-directory:
description: Path to the Gradle Wrapper directory description: Path to the Gradle Wrapper directory
required: false required: false
deprecationMessage: Use 'gradle-executable' to point to a gradlew[.bat] file in a non-default location
gradle-executable: gradle-executable:
description: Path to the Gradle executable description: Path to the Gradle executable
required: false required: false
@@ -20,41 +20,27 @@ inputs:
arguments: arguments:
description: Gradle command line arguments, see gradle --help description: Gradle command line arguments, see gradle --help
required: false required: false
distributions-cache-enabled:
description: Whether caching downloaded Gradle distributions is enabled or not, default to 'true'
required: false
default: true
wrapper-cache-enabled: wrapper-cache-enabled:
description: Whether caching wrapper installation is enabled or not, default to 'true' description: Whether caching wrapper installation is enabled or not, default to 'true'
required: false required: false
default: true
deprecationMessage: Replaced by 'distributions-cache-enabled' which enables caching for all downloaded Gradle distributions
dependencies-cache-enabled: dependencies-cache-enabled:
description: Whether caching dependencies is enabled or not, default to 'false' description: Whether caching dependencies is enabled or not, default to 'false'
required: false required: false
default: false
dependencies-cache-key: dependencies-cache-key:
description: Globs of files to hash in the build root directory, separated by new lines, use best-effort if unset description: Globs of files to hash in the build root directory, separated by new lines, use best-effort if unset
required: false required: false
dependencies-cache-exact: dependencies-cache-exact:
description: Whether to restore only if exact match, default to 'false' description: Whether to restore only if exact match, default to 'false'
required: false required: false
default: false
configuration-cache-enabled: configuration-cache-enabled:
description: Whether caching build configuration is enabled or not, default to 'false' description: Whether caching build configuration is enabled or not, default to 'false'
required: false required: false
default: false
configuration-cache-key: configuration-cache-key:
description: Globs of files to hash in the build root directory, separated by new lines, use best-effort if unset description: Globs of files to hash in the build root directory, separated by new lines, use best-effort if unset
required: false required: false
configuration-cache-exact: configuration-cache-exact:
description: Whether to restore only if exact match, default to 'false' description: Whether to restore only if exact match, default to 'false'
required: false required: false
default: false
cache-read-only:
description: When 'true', existing entries will be read from the cache but no entries will be written
required: false
default: false
outputs: outputs:
build-scan-url: build-scan-url:

2
dist/main/index.js vendored

File diff suppressed because one or more lines are too long

2
dist/post/index.js vendored

File diff suppressed because one or more lines are too long

4058
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,8 +1,8 @@
{ {
"name": "gradle-build-action", "name": "gradle-command-action",
"version": "1.0.0", "version": "1.0.0",
"private": true, "private": true,
"description": "Execute Gradle Build", "description": "Execute Gradle Command Line",
"scripts": { "scripts": {
"format": "prettier --write **/*.ts", "format": "prettier --write **/*.ts",
"format-check": "prettier --check **/*.ts", "format-check": "prettier --check **/*.ts",
@@ -13,7 +13,7 @@
}, },
"repository": { "repository": {
"type": "git", "type": "git",
"url": "git+https://github.com/gradle/gradle-build-action.git" "url": "git+https://github.com/eskatos/gradle-command-action.git"
}, },
"keywords": [ "keywords": [
"github", "github",
@@ -24,28 +24,30 @@
"author": "Paul Merlin <paul@nosphere.org>", "author": "Paul Merlin <paul@nosphere.org>",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@actions/cache": "1.0.7", "@actions/cache": "1.0.2",
"@actions/core": "1.4.0", "@actions/core": "1.2.5",
"@actions/exec": "1.1.0", "@actions/exec": "1.0.4",
"@actions/glob": "0.2.0", "@actions/glob": "0.1.0",
"@actions/http-client": "1.0.11", "@actions/io": "1.0.2",
"@actions/tool-cache": "1.7.1", "@actions/tool-cache": "1.6.0",
"string-argv": "0.3.1" "string-argv": "0.3.1",
"typed-rest-client": "1.7.3",
"unzipper": "0.10.11"
}, },
"devDependencies": { "devDependencies": {
"@types/jest": "26.0.23", "@types/jest": "26.0.13",
"@types/node": "14.17.3", "@types/node": "12.12.6",
"@types/unzipper": "0.10.4", "@types/unzipper": "0.10.3",
"@typescript-eslint/parser": "4.28.2", "@typescript-eslint/parser": "4.1.0",
"@zeit/ncc": "0.22.3", "@zeit/ncc": "0.22.3",
"eslint": "7.30.0", "eslint": "7.9.0",
"eslint-plugin-github": "4.1.3", "eslint-plugin-github": "4.1.1",
"eslint-plugin-jest": "24.3.6", "eslint-plugin-jest": "24.0.1",
"jest": "26.6.3", "jest": "26.4.2",
"jest-circus": "26.6.3", "jest-circus": "26.4.2",
"js-yaml": "3.14.1", "js-yaml": "3.14.0",
"prettier": "2.3.2", "prettier": "2.1.1",
"ts-jest": "26.5.6", "ts-jest": "26.3.0",
"typescript": "4.3.5" "typescript": "4.0.2"
} }
} }

View File

@@ -1,16 +1,13 @@
import * as path from 'path' import path from 'path'
import * as fs from 'fs' import fs from 'fs'
import * as core from '@actions/core' import * as core from '@actions/core'
import * as cache from '@actions/cache' import * as cache from '@actions/cache'
import * as cacheUtils from './cache-utils' import * as github from './github-utils'
import * as crypto from './crypto-utils'
import { import {inputCacheKeyGlobs, tryDeleteFiles} from './cache-dependencies'
inputCacheKeyGlobs,
tryDeleteFiles,
isDependenciesCacheDisabled
} from './cache-dependencies'
const CONFIGURATION_CACHE_PATH = 'CONFIGURATION_CACHE_PATH' const CONFIGURATION_CACHE_PATH = 'CONFIGURATION_CACHE_PATH'
const CONFIGURATION_CACHE_KEY = 'CONFIGURATION_CACHE_KEY' const CONFIGURATION_CACHE_KEY = 'CONFIGURATION_CACHE_KEY'
@@ -21,33 +18,22 @@ export async function restoreCachedConfiguration(
): Promise<void> { ): Promise<void> {
if (isConfigurationCacheDisabled()) return if (isConfigurationCacheDisabled()) return
if (isDependenciesCacheDisabled()) {
throw new Error(
`Must enable dependencies-cache when configuration-cache is enabled`
)
}
const cachePath = path.resolve(rootDir, '.gradle/configuration-cache') const cachePath = path.resolve(rootDir, '.gradle/configuration-cache')
if (fs.existsSync(cachePath)) return if (fs.existsSync(cachePath)) return
core.saveState(CONFIGURATION_CACHE_PATH, cachePath) core.saveState(CONFIGURATION_CACHE_PATH, cachePath)
const inputCacheExact = core.getBooleanInput('configuration-cache-exact') const inputCacheExact = github.inputBoolean('configuration-cache-exact')
const cacheKeyPrefix = 'configuration|'
const args = core.getInput('arguments')
const argsKey = cacheUtils.truncateArgs(args)
const cacheKeyWithArgs = `${cacheKeyPrefix}${argsKey}|`
const cacheKeyGlobs = inputCacheKeyGlobs('configuration-cache-key') const cacheKeyGlobs = inputCacheKeyGlobs('configuration-cache-key')
const hash = await cacheUtils.hashFiles(rootDir, cacheKeyGlobs)
const cacheKey = `${cacheKeyWithArgs}${hash}`
const hash = await crypto.hashFiles(rootDir, cacheKeyGlobs)
const cacheKeyPrefix = 'configuration-'
const cacheKey = `${cacheKeyPrefix}${hash}`
core.saveState(CONFIGURATION_CACHE_KEY, cacheKey) core.saveState(CONFIGURATION_CACHE_KEY, cacheKey)
const cacheResult = await cache.restoreCache( const cacheResult = await cache.restoreCache(
[cachePath], [cachePath],
cacheKey, cacheKey,
inputCacheExact ? [] : [cacheKeyWithArgs, cacheKeyPrefix] inputCacheExact ? [] : [cacheKeyPrefix]
) )
if (!cacheResult) { if (!cacheResult) {
@@ -91,8 +77,6 @@ export async function cacheConfiguration(): Promise<void> {
return return
} }
core.info(`Will cache configuration with key ${cacheKey}`)
try { try {
await cache.saveCache([cachePath], cacheKey) await cache.saveCache([cachePath], cacheKey)
} catch (error) { } catch (error) {
@@ -109,5 +93,5 @@ export async function cacheConfiguration(): Promise<void> {
} }
function isConfigurationCacheDisabled(): boolean { function isConfigurationCacheDisabled(): boolean {
return !core.getBooleanInput('configuration-cache-enabled') return !github.inputBoolean('configuration-cache-enabled', false)
} }

View File

@@ -5,7 +5,8 @@ import * as os from 'os'
import * as core from '@actions/core' import * as core from '@actions/core'
import * as cache from '@actions/cache' import * as cache from '@actions/cache'
import * as cacheUtils from './cache-utils' import * as github from './github-utils'
import * as crypto from './crypto-utils'
const DEPENDENCIES_CACHE_PATH = 'DEPENDENCIES_CACHE_PATH' const DEPENDENCIES_CACHE_PATH = 'DEPENDENCIES_CACHE_PATH'
const DEPENDENCIES_CACHE_KEY = 'DEPENDENCIES_CACHE_KEY' const DEPENDENCIES_CACHE_KEY = 'DEPENDENCIES_CACHE_KEY'
@@ -20,23 +21,18 @@ export async function restoreCachedDependencies(
if (fs.existsSync(cachePath)) return if (fs.existsSync(cachePath)) return
core.saveState(DEPENDENCIES_CACHE_PATH, cachePath) core.saveState(DEPENDENCIES_CACHE_PATH, cachePath)
const inputCacheExact = core.getBooleanInput('dependencies-cache-exact') const inputCacheExact = github.inputBoolean('dependencies-cache-exact')
const cacheKeyPrefix = 'dependencies|'
const args = core.getInput('arguments')
const argsKey = cacheUtils.truncateArgs(args)
const cacheKeyWithArgs = `${cacheKeyPrefix}${argsKey}|`
const cacheKeyGlobs = inputCacheKeyGlobs('dependencies-cache-key') const cacheKeyGlobs = inputCacheKeyGlobs('dependencies-cache-key')
const hash = await cacheUtils.hashFiles(rootDir, cacheKeyGlobs)
const cacheKey = `${cacheKeyWithArgs}${hash}`
const hash = await crypto.hashFiles(rootDir, cacheKeyGlobs)
const cacheKeyPrefix = 'dependencies-'
const cacheKey = `${cacheKeyPrefix}${hash}`
core.saveState(DEPENDENCIES_CACHE_KEY, cacheKey) core.saveState(DEPENDENCIES_CACHE_KEY, cacheKey)
const cacheResult = await cache.restoreCache( const cacheResult = await cache.restoreCache(
[cachePath], [cachePath],
cacheKey, cacheKey,
inputCacheExact ? [] : [cacheKeyWithArgs, cacheKeyPrefix] inputCacheExact ? [] : [cacheKeyPrefix]
) )
if (!cacheResult) { if (!cacheResult) {
@@ -78,8 +74,6 @@ export async function cacheDependencies(): Promise<void> {
return return
} }
core.info(`Will cache dependencies with key ${cacheKey}`)
try { try {
await cache.saveCache([cachePath], cacheKey) await cache.saveCache([cachePath], cacheKey)
} catch (error) { } catch (error) {
@@ -109,13 +103,13 @@ export function tryDeleteFiles(filePaths: string[]): boolean {
return !failure return !failure
} }
export function isDependenciesCacheDisabled(): boolean { function isDependenciesCacheDisabled(): boolean {
return !core.getBooleanInput('dependencies-cache-enabled') return !github.inputBoolean('dependencies-cache-enabled', false)
} }
export function inputCacheKeyGlobs(input: string): string[] { export function inputCacheKeyGlobs(input: string): string[] {
const inputValue = core.getMultilineInput(input) const inputValue = github.inputArrayOrNull(input)
return inputValue.length > 0 return inputValue
? inputValue ? inputValue
: [ : [
'**/*.gradle', '**/*.gradle',

View File

@@ -1,17 +0,0 @@
import * as path from 'path'
import * as glob from '@actions/glob'
export async function hashFiles(
baseDir: string,
patterns: string[] = ['**'],
followSymbolicLinks = false
): Promise<string | null> {
const combinedPatterns = patterns
.map(pattern => `${baseDir}${path.sep}${pattern}`)
.join('\n')
return glob.hashFiles(combinedPatterns, {followSymbolicLinks})
}
export function truncateArgs(args: string): string {
return args.trim().replace(/\s+/g, ' ').substr(0, 400)
}

View File

@@ -5,7 +5,11 @@ import * as os from 'os'
import * as core from '@actions/core' import * as core from '@actions/core'
import * as cache from '@actions/cache' import * as cache from '@actions/cache'
const WRAPPER_SLUG = 'WRAPPER_SLUG' import * as github from './github-utils'
const WRAPPER_CACHE_KEY = 'WRAPPER_CACHE_KEY'
const WRAPPER_CACHE_PATH = 'WRAPPER_CACHE_PATH'
const WRAPPER_CACHE_RESULT = 'WRAPPER_CACHE_RESULT'
export async function restoreCachedWrapperDist( export async function restoreCachedWrapperDist(
gradlewDirectory: string | null gradlewDirectory: string | null
@@ -13,62 +17,68 @@ export async function restoreCachedWrapperDist(
if (isWrapperCacheDisabled()) return if (isWrapperCacheDisabled()) return
if (gradlewDirectory == null) return if (gradlewDirectory == null) return
const wrapperProperties = path.join( const wrapperSlug = extractGradleWrapperSlugFrom(
path.resolve(gradlewDirectory), path.join(
'gradle/wrapper/gradle-wrapper.properties' path.resolve(gradlewDirectory),
) 'gradle/wrapper/gradle-wrapper.properties'
const wrapperSlug = extractGradleWrapperSlugFrom(wrapperProperties)
if (!wrapperSlug) {
core.warning(
`Could not calculate wrapper version from ${wrapperProperties}`
) )
return )
} if (!wrapperSlug) return
const wrapperDir = getWrapperDir(wrapperSlug) const wrapperCacheKey = `wrapper-${wrapperSlug}`
const cacheKey = getCacheKey(wrapperSlug) const wrapperCachePath = path.resolve(
const cachePath = getCachePath(wrapperSlug) os.homedir(),
`.gradle/wrapper/dists/gradle-${wrapperSlug}`
)
if (fs.existsSync(wrapperCachePath)) return
// Check if the wrapper has already been downloaded to Gradle User Home core.saveState(WRAPPER_CACHE_KEY, wrapperCacheKey)
if (fs.existsSync(wrapperDir)) return core.saveState(WRAPPER_CACHE_PATH, wrapperCachePath)
try { try {
const restoredKey = await cache.restoreCache([cachePath], cacheKey) const restoredKey = await cache.restoreCache(
[wrapperCachePath],
wrapperCacheKey
)
if (restoredKey) { if (!restoredKey) {
core.info( core.info(
`Wrapper installation restored from cache key: ${restoredKey}` 'Wrapper installation cache not found, expect a Gradle distribution download.'
) )
} else { return
core.info(
`Wrapper installation cache not found. Will download and cache with key: ${cacheKey}.`
)
// Save the slug to trigger caching of the downloaded wrapper
core.saveState(WRAPPER_SLUG, wrapperSlug)
} }
core.saveState(WRAPPER_CACHE_RESULT, restoredKey)
core.info(
`Wrapper installation restored from cache key: ${restoredKey}`
)
return
} catch (error) { } catch (error) {
core.info( core.info(
`Wrapper installation cache restore failed for key: ${cacheKey}.\n ${error}` `Wrapper installation cache restore failed, expect a Gradle distribution download\n ${error}`
) )
return
} }
} }
export async function cacheWrapperDist(): Promise<void> { export async function cacheWrapperDist(): Promise<void> {
if (isWrapperCacheDisabled()) return if (isWrapperCacheDisabled()) return
const wrapperSlug = core.getState(WRAPPER_SLUG) const cacheKey = core.getState(WRAPPER_CACHE_KEY)
if (!wrapperSlug) return const cachePath = core.getState(WRAPPER_CACHE_PATH)
const cacheResult = core.getState(WRAPPER_CACHE_RESULT)
const wrapperDir = getWrapperDir(wrapperSlug) if (!cachePath || !fs.existsSync(cachePath)) {
const cacheKey = getCacheKey(wrapperSlug) core.debug('No wrapper installation to cache.')
const cachePath = getCachePath(wrapperSlug)
if (!fs.existsSync(wrapperDir)) {
core.warning(`No wrapper installation to cache at ${wrapperDir}`)
return return
} }
core.info(`Will cache wrapper zip ${cachePath} with key ${cacheKey}`) if (cacheResult && cacheKey === cacheResult) {
core.info(
`Wrapper installation cache hit occurred on the cache key ${cacheKey}, not saving cache.`
)
return
}
try { try {
await cache.saveCache([cachePath], cacheKey) await cache.saveCache([cachePath], cacheKey)
@@ -105,28 +115,5 @@ export function extractGradleWrapperSlugFromDistUri(
} }
function isWrapperCacheDisabled(): boolean { function isWrapperCacheDisabled(): boolean {
// Check if either 'distributions' or 'wrapper' cache has been disabled return !github.inputBoolean('wrapper-cache-enabled', true)
const wrapperCacheEnabled = core.getBooleanInput('wrapper-cache-enabled')
const distributionsCacheEnabled = core.getBooleanInput(
'distributions-cache-enabled'
)
return !wrapperCacheEnabled || !distributionsCacheEnabled
}
function getCacheKey(wrapperSlug: string): string {
return `wrapper-v1-${wrapperSlug}`
}
function getWrapperDir(wrapperSlug: string): string {
return path.resolve(
os.homedir(),
`.gradle/wrapper/dists/gradle-${wrapperSlug}`
)
}
function getCachePath(wrapperSlug: string): string {
return path.resolve(
os.homedir(),
`.gradle/wrapper/dists/gradle-${wrapperSlug}/*/gradle-${wrapperSlug}.zip`
)
} }

44
src/crypto-utils.ts Normal file
View File

@@ -0,0 +1,44 @@
import * as crypto from 'crypto'
import * as fs from 'fs'
import * as path from 'path'
import * as stream from 'stream'
import * as util from 'util'
import * as glob from '@actions/glob'
export async function hashFiles(
baseDir: string,
globs: string[] = ['**'],
followSymbolicLinks = false
): Promise<string | null> {
let hasMatch = false
type FileHashes = Record<string, Buffer>
const hashes: FileHashes = {}
for await (const globPattern of globs) {
const globMatch = `${baseDir}${path.sep}${globPattern}`
const globber = await glob.create(globMatch, {followSymbolicLinks})
for await (const file of globber.globGenerator()) {
// console.log(file)
if (!file.startsWith(`${baseDir}${path.sep}`)) {
// console.log(`Ignore '${file}' since it is not under '${baseDir}'.`)
continue
}
if (fs.statSync(file).isDirectory()) {
// console.log(`Skip directory '${file}'.`)
continue
}
const hash = crypto.createHash('sha256')
const pipeline = util.promisify(stream.pipeline)
await pipeline(fs.createReadStream(file), hash)
hashes[path.relative(baseDir, file)] = hash.digest()
hasMatch = true
}
}
if (!hasMatch) return null
const result = crypto.createHash('sha256')
for (const file of Object.keys(hashes).sort()) {
result.update(hashes[file])
}
result.end()
return result.digest('hex')
}

24
src/github-utils.ts Normal file
View File

@@ -0,0 +1,24 @@
import * as core from '@actions/core'
export function inputOrNull(name: string): string | null {
const inputString = core.getInput(name, {required: false})
if (inputString.length === 0) {
return null
}
return inputString
}
export function inputArrayOrNull(name: string): string[] | null {
const string = inputOrNull(name)
if (!string) return null
return string
.split('\n')
.map(s => s.trim())
.filter(s => s !== '')
}
export function inputBoolean(name: string, defaultValue = false): boolean {
const string = inputOrNull(name)
if (!string) return defaultValue
return string === 'true'
}

View File

@@ -1,6 +1,3 @@
import * as path from 'path'
import fs from 'fs'
const IS_WINDOWS = process.platform === 'win32' const IS_WINDOWS = process.platform === 'win32'
export function wrapperFilename(): string { export function wrapperFilename(): string {
@@ -10,15 +7,3 @@ export function wrapperFilename(): string {
export function installScriptFilename(): string { export function installScriptFilename(): string {
return IS_WINDOWS ? 'gradle.bat' : 'gradle' return IS_WINDOWS ? 'gradle.bat' : 'gradle'
} }
export function validateGradleWrapper(gradlewDirectory: string): void {
const wrapperProperties = path.resolve(
gradlewDirectory,
'gradle/wrapper/gradle-wrapper.properties'
)
if (!fs.existsSync(wrapperProperties)) {
throw new Error(
`Cannot locate a Gradle wrapper properties file at '${wrapperProperties}'. Specify 'gradle-version' or 'gradle-executable' for projects without Gradle wrapper configured.`
)
}
}

View File

@@ -2,6 +2,7 @@ import * as core from '@actions/core'
import * as path from 'path' import * as path from 'path'
import {parseArgsStringToArgv} from 'string-argv' import {parseArgsStringToArgv} from 'string-argv'
import * as github from './github-utils'
import * as cacheWrapper from './cache-wrapper' import * as cacheWrapper from './cache-wrapper'
import * as execution from './execution' import * as execution from './execution'
import * as gradlew from './gradlew' import * as gradlew from './gradlew'
@@ -10,15 +11,11 @@ import * as provision from './provision'
// Invoked by GitHub Actions // Invoked by GitHub Actions
export async function run(): Promise<void> { export async function run(): Promise<void> {
try { try {
const workspaceDirectory = process.env[`GITHUB_WORKSPACE`] || '' const baseDirectory = process.env[`GITHUB_WORKSPACE`] || ''
const buildRootDirectory = resolveBuildRootDirectory(workspaceDirectory)
const result = await execution.execute( const result = await execution.execute(
await resolveGradleExecutable( await resolveGradleExecutable(baseDirectory),
workspaceDirectory, resolveBuildRootDirectory(baseDirectory),
buildRootDirectory
),
buildRootDirectory,
parseCommandLineArguments() parseCommandLineArguments()
) )
@@ -36,47 +33,43 @@ export async function run(): Promise<void> {
run() run()
async function resolveGradleExecutable( async function resolveGradleExecutable(baseDirectory: string): Promise<string> {
workspaceDirectory: string, const gradleVersion = github.inputOrNull('gradle-version')
buildRootDirectory: string if (gradleVersion !== null && gradleVersion !== 'wrapper') {
): Promise<string> {
const gradleVersion = core.getInput('gradle-version')
if (gradleVersion !== '' && gradleVersion !== 'wrapper') {
return path.resolve(await provision.gradleVersion(gradleVersion)) return path.resolve(await provision.gradleVersion(gradleVersion))
} }
const gradleExecutable = core.getInput('gradle-executable') const gradleExecutable = github.inputOrNull('gradle-executable')
if (gradleExecutable !== '') { if (gradleExecutable !== null) {
if (gradleExecutable.endsWith(gradlew.wrapperFilename())) { if (gradleExecutable.endsWith(gradlew.wrapperFilename())) {
await cacheWrapper.restoreCachedWrapperDist( await cacheWrapper.restoreCachedWrapperDist(
path.resolve(gradleExecutable, '..') path.resolve(gradleExecutable, '..')
) )
} }
return path.resolve(workspaceDirectory, gradleExecutable) return path.resolve(baseDirectory, gradleExecutable)
} }
const wrapperDirectory = core.getInput('wrapper-directory') const wrapperDirectory = github.inputOrNull('wrapper-directory')
const gradlewDirectory = const gradlewDirectory =
wrapperDirectory !== '' wrapperDirectory !== null
? path.resolve(workspaceDirectory, wrapperDirectory) ? path.join(baseDirectory, wrapperDirectory)
: buildRootDirectory : baseDirectory
gradlew.validateGradleWrapper(gradlewDirectory)
await cacheWrapper.restoreCachedWrapperDist(gradlewDirectory) await cacheWrapper.restoreCachedWrapperDist(gradlewDirectory)
return path.resolve(gradlewDirectory, gradlew.wrapperFilename()) return path.resolve(gradlewDirectory, gradlew.wrapperFilename())
} }
function resolveBuildRootDirectory(baseDirectory: string): string { function resolveBuildRootDirectory(baseDirectory: string): string {
const buildRootDirectory = core.getInput('build-root-directory') const buildRootDirectory = github.inputOrNull('build-root-directory')
const resolvedBuildRootDirectory = const resolvedBuildRootDirectory =
buildRootDirectory === '' buildRootDirectory === null
? path.resolve(baseDirectory) ? path.resolve(baseDirectory)
: path.resolve(baseDirectory, buildRootDirectory) : path.resolve(baseDirectory, buildRootDirectory)
return resolvedBuildRootDirectory return resolvedBuildRootDirectory
} }
function parseCommandLineArguments(): string[] { function parseCommandLineArguments(): string[] {
const input = core.getInput('arguments') const input = github.inputOrNull('arguments')
return parseArgsStringToArgv(input) return input === null ? [] : parseArgsStringToArgv(input)
} }

View File

@@ -1,20 +1,12 @@
import * as core from '@actions/core'
import * as cacheWrapper from './cache-wrapper' import * as cacheWrapper from './cache-wrapper'
import * as cacheDependencies from './cache-dependencies' import * as cacheDependencies from './cache-dependencies'
import * as cacheConfiguration from './cache-configuration' import * as cacheConfiguration from './cache-configuration'
// Invoked by GitHub Actions // Invoked by GitHub Actions
export async function run(): Promise<void> { export async function run(): Promise<void> {
if (isCacheReadOnly()) return
await cacheWrapper.cacheWrapperDist() await cacheWrapper.cacheWrapperDist()
await cacheDependencies.cacheDependencies() await cacheDependencies.cacheDependencies()
await cacheConfiguration.cacheConfiguration() await cacheConfiguration.cacheConfiguration()
} }
function isCacheReadOnly(): boolean {
return core.getBooleanInput('cache-read-only')
}
run() run()

View File

@@ -1,13 +1,15 @@
import * as fs from 'fs' import * as fs from 'fs'
import * as os from 'os' import * as os from 'os'
import * as path from 'path' import * as path from 'path'
import * as httpm from '@actions/http-client' import * as httpm from 'typed-rest-client/HttpClient'
import * as unzip from 'unzipper'
import * as core from '@actions/core' import * as core from '@actions/core'
import * as cache from '@actions/cache' import * as io from '@actions/io'
import * as toolCache from '@actions/tool-cache' import * as toolCache from '@actions/tool-cache'
import * as gradlew from './gradlew' import * as gradlew from './gradlew'
const httpc = new httpm.HttpClient('eskatos/gradle-command-action')
const gradleVersionsBaseUrl = 'https://services.gradle.org/versions' const gradleVersionsBaseUrl = 'https://services.gradle.org/versions'
/** /**
@@ -18,11 +20,6 @@ export async function gradleVersion(version: string): Promise<string> {
case 'current': case 'current':
return gradleCurrent() return gradleCurrent()
case 'rc': case 'rc':
core.warning(
`Specifying gradle-version 'rc' has been deprecated. Use 'release-candidate' instead.`
)
return gradleReleaseCandidate()
case 'release-candidate':
return gradleReleaseCandidate() return gradleReleaseCandidate()
case 'nightly': case 'nightly':
return gradleNightly() return gradleNightly()
@@ -37,7 +34,7 @@ async function gradleCurrent(): Promise<string> {
const versionInfo = await gradleVersionDeclaration( const versionInfo = await gradleVersionDeclaration(
`${gradleVersionsBaseUrl}/current` `${gradleVersionsBaseUrl}/current`
) )
return provisionGradle(versionInfo) return provisionGradle(versionInfo.version, versionInfo.downloadUrl)
} }
async function gradleReleaseCandidate(): Promise<string> { async function gradleReleaseCandidate(): Promise<string> {
@@ -45,7 +42,7 @@ async function gradleReleaseCandidate(): Promise<string> {
`${gradleVersionsBaseUrl}/release-candidate` `${gradleVersionsBaseUrl}/release-candidate`
) )
if (versionInfo && versionInfo.version && versionInfo.downloadUrl) { if (versionInfo && versionInfo.version && versionInfo.downloadUrl) {
return provisionGradle(versionInfo) return provisionGradle(versionInfo.version, versionInfo.downloadUrl)
} }
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()
@@ -55,14 +52,14 @@ async function gradleNightly(): Promise<string> {
const versionInfo = await gradleVersionDeclaration( const versionInfo = await gradleVersionDeclaration(
`${gradleVersionsBaseUrl}/nightly` `${gradleVersionsBaseUrl}/nightly`
) )
return provisionGradle(versionInfo) return provisionGradle(versionInfo.version, versionInfo.downloadUrl)
} }
async function gradleReleaseNightly(): Promise<string> { async function gradleReleaseNightly(): Promise<string> {
const versionInfo = await gradleVersionDeclaration( const versionInfo = await gradleVersionDeclaration(
`${gradleVersionsBaseUrl}/release-nightly` `${gradleVersionsBaseUrl}/release-nightly`
) )
return provisionGradle(versionInfo) return provisionGradle(versionInfo.version, versionInfo.downloadUrl)
} }
async function gradle(version: string): Promise<string> { async function gradle(version: string): Promise<string> {
@@ -70,7 +67,7 @@ async function gradle(version: string): Promise<string> {
if (!versionInfo) { if (!versionInfo) {
throw new Error(`Gradle version ${version} does not exists`) throw new Error(`Gradle version ${version} does not exists`)
} }
return provisionGradle(versionInfo) return provisionGradle(versionInfo.version, versionInfo.downloadUrl)
} }
async function gradleVersionDeclaration( async function gradleVersionDeclaration(
@@ -90,79 +87,42 @@ async function findGradleVersionDeclaration(
}) })
} }
async function provisionGradle( async function provisionGradle(version: string, url: string): Promise<string> {
versionInfo: GradleVersionInfo const cachedInstall: string = toolCache.find('gradle', version)
): Promise<string> { if (cachedInstall.length > 0) {
const installsDir = path.join(os.homedir(), 'gradle-installations/installs') const cachedExecutable = executableFrom(cachedInstall)
const installDir = path.join(installsDir, `gradle-${versionInfo.version}`) core.info(`Provisioned Gradle executable ${cachedExecutable}`)
if (fs.existsSync(installDir)) { return cachedExecutable
core.info(`Gradle installation already exists at ${installDir}`)
return executableFrom(installDir)
} }
const downloadPath = await downloadAndCacheGradleDistribution(versionInfo) const home = os.homedir()
await toolCache.extractZip(downloadPath, installsDir) const tmpdir = path.join(home, 'gradle-provision-tmpdir')
core.info(`Extracted Gradle ${versionInfo.version} to ${installDir}`) const downloadsDir = path.join(tmpdir, 'downloads')
const installsDir = path.join(tmpdir, 'installs')
await io.mkdirP(downloadsDir)
await io.mkdirP(installsDir)
core.info(`Downloading ${url}`)
const downloadPath = path.join(downloadsDir, `gradle-${version}-bin.zip`)
await httpDownload(url, downloadPath)
core.info(
`Downloaded at ${downloadPath}, size ${fs.statSync(downloadPath).size}`
)
await extractZip(downloadPath, installsDir)
const installDir = path.join(installsDir, `gradle-${version}`)
core.info(`Extracted in ${installDir}`)
const executable = executableFrom(installDir) const executable = executableFrom(installDir)
fs.chmodSync(executable, '755') fs.chmodSync(executable, '755')
core.info(`Provisioned Gradle executable ${executable}`) core.info(`Provisioned Gradle executable ${executable}`)
toolCache.cacheDir(installDir, 'gradle', version)
return executable return executable
} }
async function downloadAndCacheGradleDistribution(
versionInfo: GradleVersionInfo
): Promise<string> {
const downloadPath = path.join(
os.homedir(),
`gradle-installations/downloads/gradle-${versionInfo.version}-bin.zip`
)
if (isDistributionsCacheDisabled()) {
await downloadGradleDistribution(versionInfo, downloadPath)
return downloadPath
}
const cacheKey = `gradle-${versionInfo.version}`
const restoreKey = await cache.restoreCache([downloadPath], cacheKey)
if (restoreKey) {
core.info(
`Restored Gradle distribution ${cacheKey} from cache to ${downloadPath}`
)
} else {
core.info(
`Gradle distribution ${versionInfo.version} not found in cache. Will download.`
)
await downloadGradleDistribution(versionInfo, downloadPath)
try {
await cache.saveCache([downloadPath], cacheKey)
} catch (error) {
if (error.name === cache.ValidationError.name) {
throw error
} else if (error.name === cache.ReserveCacheError.name) {
core.info(error.message)
} else {
core.info(`[warning] ${error.message}`)
}
}
}
return downloadPath
}
async function downloadGradleDistribution(
versionInfo: GradleVersionInfo,
downloadPath: string
): Promise<void> {
await toolCache.downloadTool(versionInfo.downloadUrl, downloadPath)
core.info(
`Downloaded ${versionInfo.downloadUrl} to ${downloadPath} (size ${
fs.statSync(downloadPath).size
})`
)
}
function executableFrom(installDir: string): string { function executableFrom(installDir: string): string {
return path.join(installDir, 'bin', `${gradlew.installScriptFilename()}`) return path.join(installDir, 'bin', `${gradlew.installScriptFilename()}`)
} }
@@ -178,13 +138,36 @@ async function httpGetGradleVersions(
} }
async function httpGetString(url: string): Promise<string> { async function httpGetString(url: string): Promise<string> {
const httpClient = new httpm.HttpClient('gradle/gradle-build-action') const response = await httpc.get(url)
const response = await httpClient.get(url)
return response.readBody() return response.readBody()
} }
function isDistributionsCacheDisabled(): boolean { async function httpDownload(url: string, localPath: string): Promise<void> {
return !core.getBooleanInput('distributions-cache-enabled') const response = await httpc.get(url)
return new Promise<void>(function (resolve, reject) {
const writeStream = fs.createWriteStream(localPath)
response.message
.pipe(writeStream)
.on('close', () => {
resolve()
})
.on('error', err => {
reject(err)
})
})
}
async function extractZip(zip: string, destination: string): Promise<void> {
return new Promise<void>(function (resolve, reject) {
fs.createReadStream(zip)
.pipe(unzip.Extract({path: destination}))
.on('close', () => {
resolve()
})
.on('error', err => {
reject(err)
})
})
} }
interface GradleVersionInfo { interface GradleVersionInfo {