├── .github ├── pipeline-version ├── CODEOWNERS ├── dependabot.yml ├── workflows │ ├── pb-synchronize-labels.yml │ ├── pb-minimal-labels.yml │ ├── pb-update-draft-release.yml │ ├── pb-update-go.yml │ ├── pb-update-pipeline.yml │ ├── pb-update-gradle.yml │ ├── pb-tests.yml │ └── pb-create-package.yml ├── pipeline-descriptor.yml ├── release-drafter.yml └── labels.yml ├── gradle ├── testdata │ ├── 5fa754fef54387acdf1ab3107e4ddcaf141e713cd5f946afad4edfbf9461928f.toml │ ├── 5fa754fef54387acdf1ab3107e4ddcaf141e713cd5f946afad4edfbf9461928f │ │ └── stub-gradle-distribution.zip │ └── gradle-wrapper.properties ├── init_test.go ├── distribution.go ├── distribution_test.go ├── gradle_properties.go ├── detect.go ├── build.go ├── gradle_properties_test.go ├── detect_test.go └── build_test.go ├── NOTICE ├── scripts └── build.sh ├── .gitignore ├── cmd └── main │ └── main.go ├── go.mod ├── go.sum ├── README.md └── LICENSE /.github/pipeline-version: -------------------------------------------------------------------------------- 1 | 1.44.0 2 | -------------------------------------------------------------------------------- /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | * @paketo-buildpacks/java-maintainers -------------------------------------------------------------------------------- /gradle/testdata/5fa754fef54387acdf1ab3107e4ddcaf141e713cd5f946afad4edfbf9461928f.toml: -------------------------------------------------------------------------------- 1 | uri = "https://localhost/stub-gradle-distribution.zip" 2 | sha256 = "5fa754fef54387acdf1ab3107e4ddcaf141e713cd5f946afad4edfbf9461928f" 3 | -------------------------------------------------------------------------------- /gradle/testdata/5fa754fef54387acdf1ab3107e4ddcaf141e713cd5f946afad4edfbf9461928f/stub-gradle-distribution.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/paketo-buildpacks/gradle/HEAD/gradle/testdata/5fa754fef54387acdf1ab3107e4ddcaf141e713cd5f946afad4edfbf9461928f/stub-gradle-distribution.zip -------------------------------------------------------------------------------- /gradle/testdata/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.6-bin.zip 4 | networkTimeout=10000 5 | zipStoreBase=GRADLE_USER_HOME 6 | zipStorePath=wrapper/dists 7 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: gomod 4 | directory: / 5 | schedule: 6 | interval: daily 7 | ignore: 8 | - dependency-name: github.com/onsi/gomega 9 | labels: 10 | - semver:patch 11 | - type:dependency-upgrade 12 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | gradle 2 | 3 | Copyright (c) 2020-Present CloudFoundry.org Foundation, Inc. All Rights Reserved. 4 | 5 | This project is licensed to you under the Apache License, Version 2.0 (the "License"). 6 | You may not use this project except in compliance with the License. 7 | 8 | This project may include a number of subcomponents with separate copyright notices 9 | and license terms. Your use of these subcomponents is subject to the terms and 10 | conditions of the subcomponent's license, as noted in the LICENSE file. 11 | -------------------------------------------------------------------------------- /.github/workflows/pb-synchronize-labels.yml: -------------------------------------------------------------------------------- 1 | name: Synchronize Labels 2 | "on": 3 | push: 4 | branches: 5 | - main 6 | paths: 7 | - .github/labels.yml 8 | jobs: 9 | synchronize: 10 | name: Synchronize Labels 11 | runs-on: 12 | - ubuntu-latest 13 | steps: 14 | - uses: actions/checkout@v4 15 | - uses: micnncim/action-label-syncer@v1 16 | env: 17 | GITHUB_TOKEN: ${{ secrets.PAKETO_BOT_GITHUB_TOKEN }} 18 | -------------------------------------------------------------------------------- /scripts/build.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -euo pipefail 3 | 4 | GOMOD=$(head -1 go.mod | awk '{print $2}') 5 | GOOS="linux" GOARCH="amd64" go build -ldflags='-s -w' -o linux/amd64/bin/main "$GOMOD/cmd/main" 6 | GOOS="linux" GOARCH="arm64" go build -ldflags='-s -w' -o linux/arm64/bin/main "$GOMOD/cmd/main" 7 | 8 | if [ "${STRIP:-false}" != "false" ]; then 9 | strip linux/amd64/bin/main linux/arm64/bin/main 10 | fi 11 | 12 | if [ "${COMPRESS:-none}" != "none" ]; then 13 | $COMPRESS linux/amd64/bin/main linux/arm64/bin/main 14 | fi 15 | 16 | ln -fs main linux/amd64/bin/build 17 | ln -fs main linux/arm64/bin/build 18 | ln -fs main linux/amd64/bin/detect 19 | ln -fs main linux/arm64/bin/detect -------------------------------------------------------------------------------- /.github/pipeline-descriptor.yml: -------------------------------------------------------------------------------- 1 | github: 2 | username: ${{ secrets.JAVA_GITHUB_USERNAME }} 3 | token: ${{ secrets.PAKETO_BOT_GITHUB_TOKEN }} 4 | 5 | codeowners: 6 | - path: "*" 7 | owner: "@paketo-buildpacks/java-maintainers" 8 | 9 | package: 10 | repositories: ["docker.io/paketobuildpacks/gradle"] 11 | register: true 12 | registry_token: ${{ secrets.PAKETO_BOT_GITHUB_TOKEN }} 13 | 14 | docker_credentials: 15 | - registry: docker.io 16 | username: ${{ secrets.PAKETO_BUILDPACKS_DOCKERHUB_USERNAME }} 17 | password: ${{ secrets.PAKETO_BUILDPACKS_DOCKERHUB_PASSWORD }} 18 | 19 | dependencies: 20 | - id: gradle 21 | uses: docker://ghcr.io/paketo-buildpacks/actions/gradle-dependency:main 22 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Copyright 2018-2020 the original author or authors. 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # https://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | bin/ 16 | linux/ 17 | dependencies/ 18 | package/ 19 | scratch/ 20 | 21 | -------------------------------------------------------------------------------- /.github/release-drafter.yml: -------------------------------------------------------------------------------- 1 | template: $CHANGES 2 | name-template: $RESOLVED_VERSION 3 | tag-template: v$RESOLVED_VERSION 4 | categories: 5 | - title: ⭐️ Enhancements 6 | labels: 7 | - type:enhancement 8 | - title: "\U0001F41E Bug Fixes" 9 | labels: 10 | - type:bug 11 | - title: "\U0001F4D4 Documentation" 12 | labels: 13 | - type:documentation 14 | - title: ⛏ Dependency Upgrades 15 | labels: 16 | - type:dependency-upgrade 17 | - title: "\U0001F6A7 Tasks" 18 | labels: 19 | - type:task 20 | exclude-labels: 21 | - type:question 22 | version-resolver: 23 | major: 24 | labels: 25 | - semver:major 26 | minor: 27 | labels: 28 | - semver:minor 29 | patch: 30 | labels: 31 | - semver:patch 32 | default: patch 33 | -------------------------------------------------------------------------------- /.github/workflows/pb-minimal-labels.yml: -------------------------------------------------------------------------------- 1 | name: Minimal Labels 2 | "on": 3 | pull_request: 4 | types: 5 | - synchronize 6 | - reopened 7 | - labeled 8 | - unlabeled 9 | jobs: 10 | semver: 11 | name: Minimal Semver Labels 12 | runs-on: 13 | - ubuntu-latest 14 | steps: 15 | - uses: mheap/github-action-required-labels@v5 16 | with: 17 | count: 1 18 | labels: semver:major, semver:minor, semver:patch 19 | mode: exactly 20 | type: 21 | name: Minimal Type Labels 22 | runs-on: 23 | - ubuntu-latest 24 | steps: 25 | - uses: mheap/github-action-required-labels@v5 26 | with: 27 | count: 1 28 | labels: type:bug, type:dependency-upgrade, type:documentation, type:enhancement, type:question, type:task 29 | mode: exactly 30 | -------------------------------------------------------------------------------- /.github/workflows/pb-update-draft-release.yml: -------------------------------------------------------------------------------- 1 | name: Update Draft Release 2 | "on": 3 | push: 4 | branches: 5 | - main 6 | jobs: 7 | update: 8 | name: Update Draft Release 9 | runs-on: 10 | - ubuntu-latest 11 | steps: 12 | - id: release-drafter 13 | uses: release-drafter/release-drafter@v5 14 | env: 15 | GITHUB_TOKEN: ${{ secrets.PAKETO_BOT_GITHUB_TOKEN }} 16 | - uses: actions/checkout@v4 17 | - name: Update draft release with buildpack information 18 | uses: docker://ghcr.io/paketo-buildpacks/actions/draft-release:main 19 | with: 20 | github_token: ${{ secrets.PAKETO_BOT_GITHUB_TOKEN }} 21 | release_body: ${{ steps.release-drafter.outputs.body }} 22 | release_id: ${{ steps.release-drafter.outputs.id }} 23 | release_name: ${{ steps.release-drafter.outputs.name }} 24 | release_tag_name: ${{ steps.release-drafter.outputs.tag_name }} 25 | -------------------------------------------------------------------------------- /gradle/init_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package gradle_test 18 | 19 | import ( 20 | "testing" 21 | 22 | "github.com/sclevine/spec" 23 | "github.com/sclevine/spec/report" 24 | ) 25 | 26 | func TestUnit(t *testing.T) { 27 | suite := spec.New("gradle", spec.Report(report.Terminal{})) 28 | suite("Build", testBuild) 29 | suite("Detect", testDetect) 30 | suite("Distribution", testDistribution) 31 | suite("Properties", testGradleProperties) 32 | suite.Run(t) 33 | } 34 | -------------------------------------------------------------------------------- /cmd/main/main.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package main 18 | 19 | import ( 20 | "os" 21 | 22 | "github.com/paketo-buildpacks/libbs" 23 | "github.com/paketo-buildpacks/libpak" 24 | "github.com/paketo-buildpacks/libpak/bard" 25 | 26 | "github.com/paketo-buildpacks/gradle/v7/gradle" 27 | ) 28 | 29 | func main() { 30 | libpak.Main( 31 | gradle.Detect{}, 32 | gradle.Build{ 33 | ApplicationFactory: libbs.NewApplicationFactory(), 34 | Logger: bard.NewLogger(os.Stdout), 35 | HomeDirectoryResolver: gradle.OSHomeDirectoryResolver{}, 36 | }, 37 | ) 38 | } 39 | -------------------------------------------------------------------------------- /.github/labels.yml: -------------------------------------------------------------------------------- 1 | - name: semver:major 2 | description: A change requiring a major version bump 3 | color: f9d0c4 4 | - name: semver:minor 5 | description: A change requiring a minor version bump 6 | color: f9d0c4 7 | - name: semver:patch 8 | description: A change requiring a patch version bump 9 | color: f9d0c4 10 | - name: type:bug 11 | description: A general bug 12 | color: e3d9fc 13 | - name: type:dependency-upgrade 14 | description: A dependency upgrade 15 | color: e3d9fc 16 | - name: type:documentation 17 | description: A documentation update 18 | color: e3d9fc 19 | - name: type:enhancement 20 | description: A general enhancement 21 | color: e3d9fc 22 | - name: type:question 23 | description: A user question 24 | color: e3d9fc 25 | - name: type:task 26 | description: A general task 27 | color: e3d9fc 28 | - name: type:informational 29 | description: Provides information or notice to the community 30 | color: e3d9fc 31 | - name: type:poll 32 | description: Request for feedback from the community 33 | color: e3d9fc 34 | - name: note:ideal-for-contribution 35 | description: An issue that a contributor can help us with 36 | color: 54f7a8 37 | - name: note:on-hold 38 | description: We can't start working on this issue yet 39 | color: 54f7a8 40 | - name: note:good-first-issue 41 | description: A good first issue to get started with 42 | color: 54f7a8 43 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/paketo-buildpacks/gradle/v7 2 | 3 | go 1.25.5 4 | 5 | require ( 6 | github.com/buildpacks/libcnb v1.30.4 7 | github.com/magiconair/properties v1.8.10 8 | github.com/onsi/gomega v1.38.3 9 | github.com/paketo-buildpacks/libbs v1.18.1 10 | github.com/paketo-buildpacks/libpak v1.73.0 11 | github.com/sclevine/spec v1.4.0 12 | ) 13 | 14 | require ( 15 | github.com/BurntSushi/toml v1.5.0 // indirect 16 | github.com/Masterminds/semver/v3 v3.4.0 // indirect 17 | github.com/creack/pty v1.1.24 // indirect 18 | github.com/google/go-cmp v0.7.0 // indirect 19 | github.com/h2non/filetype v1.1.3 // indirect 20 | github.com/heroku/color v0.0.6 // indirect 21 | github.com/imdario/mergo v0.3.16 // indirect 22 | github.com/mattn/go-colorable v0.1.14 // indirect 23 | github.com/mattn/go-isatty v0.0.20 // indirect 24 | github.com/mattn/go-shellwords v1.0.12 // indirect 25 | github.com/mitchellh/hashstructure/v2 v2.0.2 // indirect 26 | github.com/paketo-buildpacks/libjvm v1.46.0 // indirect 27 | github.com/paketo-buildpacks/source-removal v1.0.4 // indirect 28 | github.com/pavlo-v-chernykh/keystore-go/v4 v4.5.0 // indirect 29 | github.com/xi2/xz v0.0.0-20171230120015-48954b6210f8 // indirect 30 | go.yaml.in/yaml/v3 v3.0.4 // indirect 31 | golang.org/x/crypto v0.46.0 // indirect 32 | golang.org/x/net v0.48.0 // indirect 33 | golang.org/x/sys v0.39.0 // indirect 34 | golang.org/x/text v0.32.0 // indirect 35 | software.sslmate.com/src/go-pkcs12 v0.6.0 // indirect 36 | ) 37 | -------------------------------------------------------------------------------- /gradle/distribution.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package gradle 18 | 19 | import ( 20 | "fmt" 21 | "os" 22 | 23 | "github.com/buildpacks/libcnb" 24 | "github.com/paketo-buildpacks/libpak" 25 | "github.com/paketo-buildpacks/libpak/bard" 26 | "github.com/paketo-buildpacks/libpak/crush" 27 | ) 28 | 29 | type Distribution struct { 30 | LayerContributor libpak.DependencyLayerContributor 31 | Logger bard.Logger 32 | } 33 | 34 | func NewDistribution(dependency libpak.BuildpackDependency, cache libpak.DependencyCache) (Distribution, libcnb.BOMEntry) { 35 | contributor, entry := libpak.NewDependencyLayer(dependency, cache, libcnb.LayerTypes{ 36 | Cache: true, 37 | }) 38 | return Distribution{LayerContributor: contributor}, entry 39 | } 40 | 41 | func (d Distribution) Contribute(layer libcnb.Layer) (libcnb.Layer, error) { 42 | d.LayerContributor.Logger = d.Logger 43 | 44 | return d.LayerContributor.Contribute(layer, func(artifact *os.File) (libcnb.Layer, error) { 45 | d.Logger.Bodyf("Expanding to %s", layer.Path) 46 | if err := crush.ExtractZip(artifact, layer.Path, 1); err != nil { 47 | return libcnb.Layer{}, fmt.Errorf("unable to expand Gradle\n%w", err) 48 | } 49 | 50 | return layer, nil 51 | }) 52 | } 53 | 54 | func (d Distribution) Name() string { 55 | return d.LayerContributor.LayerName() 56 | } 57 | -------------------------------------------------------------------------------- /gradle/distribution_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package gradle_test 18 | 19 | import ( 20 | "os" 21 | "path/filepath" 22 | "testing" 23 | 24 | "github.com/buildpacks/libcnb" 25 | . "github.com/onsi/gomega" 26 | "github.com/paketo-buildpacks/libpak" 27 | "github.com/sclevine/spec" 28 | 29 | "github.com/paketo-buildpacks/gradle/v7/gradle" 30 | ) 31 | 32 | func testDistribution(t *testing.T, context spec.G, it spec.S) { 33 | var ( 34 | Expect = NewWithT(t).Expect 35 | 36 | ctx libcnb.BuildContext 37 | ) 38 | 39 | it.Before(func() { 40 | var err error 41 | 42 | ctx.Layers.Path, err = os.MkdirTemp("", "distribution-layers") 43 | Expect(err).NotTo(HaveOccurred()) 44 | }) 45 | 46 | it.After(func() { 47 | Expect(os.RemoveAll(ctx.Layers.Path)).To(Succeed()) 48 | }) 49 | 50 | it("contributes distribution", func() { 51 | dep := libpak.BuildpackDependency{ 52 | URI: "https://localhost/stub-gradle-distribution.zip", 53 | SHA256: "5fa754fef54387acdf1ab3107e4ddcaf141e713cd5f946afad4edfbf9461928f", 54 | } 55 | dc := libpak.DependencyCache{CachePath: "testdata"} 56 | 57 | d, _ := gradle.NewDistribution(dep, dc) 58 | layer, err := ctx.Layers.Layer("test-layer") 59 | Expect(err).NotTo(HaveOccurred()) 60 | 61 | layer, err = d.Contribute(layer) 62 | Expect(err).NotTo(HaveOccurred()) 63 | 64 | Expect(layer.Cache).To(BeTrue()) 65 | Expect(filepath.Join(layer.Path, "fixture-marker")).To(BeARegularFile()) 66 | }) 67 | 68 | } 69 | -------------------------------------------------------------------------------- /gradle/gradle_properties.go: -------------------------------------------------------------------------------- 1 | package gradle 2 | 3 | import ( 4 | "fmt" 5 | "github.com/magiconair/properties" 6 | "github.com/paketo-buildpacks/libpak/bard" 7 | "os" 8 | "path/filepath" 9 | 10 | "github.com/buildpacks/libcnb" 11 | ) 12 | 13 | type PropertiesFile struct { 14 | Binding libcnb.Binding 15 | GradlePropertiesHome string 16 | GradlePropertiesFileName string 17 | GradlePropertiesName string 18 | Logger bard.Logger 19 | } 20 | 21 | func (p PropertiesFile) Contribute(layer libcnb.Layer) (libcnb.Layer, error) { 22 | path, ok := p.Binding.SecretFilePath(p.GradlePropertiesFileName) 23 | if !ok { 24 | return libcnb.Layer{}, nil 25 | } 26 | 27 | originalPropertiesFilePath := filepath.Join(p.GradlePropertiesHome, p.GradlePropertiesFileName) 28 | if p.GradlePropertiesName == "gradle-properties" { 29 | p.Logger.Debug("symlinking gradle-properties bound file") 30 | gradlePropertiesPath := originalPropertiesFilePath 31 | if err := os.Symlink(path, gradlePropertiesPath); os.IsExist(err) { 32 | err = os.Remove(gradlePropertiesPath) 33 | if err != nil { 34 | return libcnb.Layer{}, fmt.Errorf("unable to remove old symlink for %s\n%w", p.GradlePropertiesFileName, err) 35 | } 36 | 37 | err = os.Symlink(path, gradlePropertiesPath) 38 | if err != nil { 39 | return libcnb.Layer{}, fmt.Errorf("unable to create symlink for %s on retry\n%w", p.GradlePropertiesFileName, err) 40 | } 41 | } else if err != nil { 42 | return libcnb.Layer{}, fmt.Errorf("unable to symlink bound %s\n%w", p.GradlePropertiesFileName, err) 43 | } 44 | } else if p.GradlePropertiesName == "gradle-wrapper-properties" { 45 | file, err := os.ReadFile(path) 46 | if err != nil { 47 | return libcnb.Layer{}, fmt.Errorf("unable to read bound gradle-wrapper.properties file at %s\n%w", path, err) 48 | } 49 | p.Logger.Debugf("applying these bound gradle-wrapper-properties to default one: \n%s\n", string(file)) 50 | mergedProperties := properties.MustLoadFiles([]string{originalPropertiesFilePath, path}, properties.UTF8, true) 51 | propertiesFile, err := os.Create(originalPropertiesFilePath) 52 | if err != nil { 53 | return libcnb.Layer{}, fmt.Errorf("unable to create/update original gradle-wrapper.properties file at %s\n%w", originalPropertiesFilePath, err) 54 | } 55 | _, err = mergedProperties.Write(propertiesFile, properties.UTF8) 56 | if err != nil { 57 | return libcnb.Layer{}, fmt.Errorf("unable to merge gradle-wrapper.properties files.\n%w", err) 58 | } 59 | } 60 | 61 | return layer, nil 62 | } 63 | 64 | func (p PropertiesFile) Name() string { 65 | return p.GradlePropertiesName 66 | } 67 | -------------------------------------------------------------------------------- /.github/workflows/pb-update-go.yml: -------------------------------------------------------------------------------- 1 | name: Update Go 2 | "on": 3 | schedule: 4 | - cron: 21 2 * * 1 5 | workflow_dispatch: {} 6 | jobs: 7 | update: 8 | name: Update Go 9 | runs-on: 10 | - ubuntu-latest 11 | steps: 12 | - uses: actions/setup-go@v5 13 | with: 14 | go-version: "1.25" 15 | - uses: actions/checkout@v4 16 | - name: Update Go Version & Modules 17 | id: update-go 18 | run: | 19 | #!/usr/bin/env bash 20 | 21 | set -euo pipefail 22 | 23 | if [ -z "${GO_VERSION:-}" ]; then 24 | echo "No go version set" 25 | exit 1 26 | fi 27 | 28 | OLD_GO_VERSION=$(grep -P '^go \d\.\d+' go.mod | cut -d ' ' -f 2 | cut -d '.' -f 1-2) 29 | 30 | go mod edit -go="$GO_VERSION" 31 | go mod tidy 32 | go get -u -t ./... 33 | go mod tidy 34 | 35 | git add go.mod go.sum 36 | git checkout -- . 37 | 38 | if [ "$OLD_GO_VERSION" == "$GO_VERSION" ]; then 39 | COMMIT_TITLE="Bump Go Modules" 40 | COMMIT_BODY="Bumps Go modules used by the project. See the commit for details on what modules were updated." 41 | COMMIT_SEMVER="semver:patch" 42 | else 43 | COMMIT_TITLE="Bump Go from ${OLD_GO_VERSION} to ${GO_VERSION}" 44 | COMMIT_BODY="Bumps Go from ${OLD_GO_VERSION} to ${GO_VERSION} and update Go modules used by the project. See the commit for details on what modules were updated." 45 | COMMIT_SEMVER="semver:minor" 46 | fi 47 | 48 | echo "commit-title=${COMMIT_TITLE}" >> "$GITHUB_OUTPUT" 49 | echo "commit-body=${COMMIT_BODY}" >> "$GITHUB_OUTPUT" 50 | echo "commit-semver=${COMMIT_SEMVER}" >> "$GITHUB_OUTPUT" 51 | env: 52 | GO_VERSION: "1.25" 53 | - uses: peter-evans/create-pull-request@v6 54 | with: 55 | author: ${{ secrets.JAVA_GITHUB_USERNAME }} <${{ secrets.JAVA_GITHUB_USERNAME }}@users.noreply.github.com> 56 | body: |- 57 | ${{ steps.update-go.outputs.commit-body }} 58 | 59 |
60 | Release Notes 61 | ${{ steps.pipeline.outputs.release-notes }} 62 |
63 | branch: update/go 64 | commit-message: |- 65 | ${{ steps.update-go.outputs.commit-title }} 66 | 67 | ${{ steps.update-go.outputs.commit-body }} 68 | delete-branch: true 69 | labels: ${{ steps.update-go.outputs.commit-semver }}, type:task 70 | signoff: true 71 | title: ${{ steps.update-go.outputs.commit-title }} 72 | token: ${{ secrets.PAKETO_BOT_GITHUB_TOKEN }} 73 | -------------------------------------------------------------------------------- /.github/workflows/pb-update-pipeline.yml: -------------------------------------------------------------------------------- 1 | name: Update Pipeline 2 | "on": 3 | push: 4 | branches: 5 | - main 6 | paths: 7 | - .github/pipeline-descriptor.yml 8 | schedule: 9 | - cron: 0 5 * * 1-5 10 | workflow_dispatch: {} 11 | jobs: 12 | update: 13 | name: Update Pipeline 14 | runs-on: 15 | - ubuntu-latest 16 | steps: 17 | - uses: actions/setup-go@v5 18 | with: 19 | go-version: "1.25" 20 | - name: Install octo 21 | run: | 22 | #!/usr/bin/env bash 23 | 24 | set -euo pipefail 25 | 26 | go install -ldflags="-s -w" github.com/paketo-buildpacks/pipeline-builder/cmd/octo@latest 27 | - uses: actions/checkout@v4 28 | - name: Update Pipeline 29 | id: pipeline 30 | run: | 31 | #!/usr/bin/env bash 32 | 33 | set -euo pipefail 34 | 35 | if [[ -f .github/pipeline-version ]]; then 36 | OLD_VERSION=$(cat .github/pipeline-version) 37 | else 38 | OLD_VERSION="0.0.0" 39 | fi 40 | 41 | rm .github/workflows/pb-*.yml || true 42 | octo --descriptor "${DESCRIPTOR}" 43 | 44 | PAYLOAD=$(gh api /repos/paketo-buildpacks/pipeline-builder/releases/latest) 45 | 46 | NEW_VERSION=$(jq -n -r --argjson PAYLOAD "${PAYLOAD}" '$PAYLOAD.name') 47 | echo "${NEW_VERSION}" > .github/pipeline-version 48 | 49 | RELEASE_NOTES=$( 50 | gh api \ 51 | -F text="$(jq -n -r --argjson PAYLOAD "${PAYLOAD}" '$PAYLOAD.body')" \ 52 | -F mode="gfm" \ 53 | -F context="paketo-buildpacks/pipeline-builder" \ 54 | -X POST /markdown 55 | ) 56 | 57 | git add .github/ 58 | git add .gitignore 59 | 60 | if [ -f scripts/build.sh ]; then 61 | git add scripts/build.sh 62 | fi 63 | 64 | git checkout -- . 65 | 66 | echo "old-version=${OLD_VERSION}" >> "$GITHUB_OUTPUT" 67 | echo "new-version=${NEW_VERSION}" >> "$GITHUB_OUTPUT" 68 | 69 | DELIMITER=$(openssl rand -hex 16) # roughly the same entropy as uuid v4 used in https://github.com/actions/toolkit/blob/b36e70495fbee083eb20f600eafa9091d832577d/packages/core/src/file-command.ts#L28 70 | printf "release-notes<<%s\n%s\n%s\n" "${DELIMITER}" "${RELEASE_NOTES}" "${DELIMITER}" >> "${GITHUB_OUTPUT}" # see https://docs.github.com/en/actions/using-workflows/workflow-commands-for-github-actions#multiline-strings 71 | env: 72 | DESCRIPTOR: .github/pipeline-descriptor.yml 73 | GITHUB_TOKEN: ${{ secrets.PAKETO_BOT_GITHUB_TOKEN }} 74 | - uses: peter-evans/create-pull-request@v6 75 | with: 76 | author: ${{ secrets.JAVA_GITHUB_USERNAME }} <${{ secrets.JAVA_GITHUB_USERNAME }}@users.noreply.github.com> 77 | body: |- 78 | Bumps pipeline from `${{ steps.pipeline.outputs.old-version }}` to `${{ steps.pipeline.outputs.new-version }}`. 79 | 80 |
81 | Release Notes 82 | ${{ steps.pipeline.outputs.release-notes }} 83 |
84 | branch: update/pipeline 85 | commit-message: |- 86 | Bump pipeline from ${{ steps.pipeline.outputs.old-version }} to ${{ steps.pipeline.outputs.new-version }} 87 | 88 | Bumps pipeline from ${{ steps.pipeline.outputs.old-version }} to ${{ steps.pipeline.outputs.new-version }}. 89 | delete-branch: true 90 | labels: semver:patch, type:task 91 | signoff: true 92 | title: Bump pipeline from ${{ steps.pipeline.outputs.old-version }} to ${{ steps.pipeline.outputs.new-version }} 93 | token: ${{ secrets.PAKETO_BOT_GITHUB_TOKEN }} 94 | -------------------------------------------------------------------------------- /.github/workflows/pb-update-gradle.yml: -------------------------------------------------------------------------------- 1 | name: Update gradle 2 | "on": 3 | schedule: 4 | - cron: 0 5 * * 1-5 5 | workflow_dispatch: {} 6 | jobs: 7 | update: 8 | name: Update Buildpack Dependency 9 | runs-on: 10 | - ubuntu-latest 11 | steps: 12 | - uses: actions/setup-go@v5 13 | with: 14 | go-version: "1.25" 15 | - name: Install update-buildpack-dependency 16 | run: | 17 | #!/usr/bin/env bash 18 | 19 | set -euo pipefail 20 | 21 | go install -ldflags="-s -w" github.com/paketo-buildpacks/libpak/cmd/update-buildpack-dependency@latest 22 | - uses: buildpacks/github-actions/setup-tools@v5.9.7 23 | with: 24 | crane-version: 0.20.3 25 | yj-version: 5.1.0 26 | - uses: actions/checkout@v4 27 | - id: dependency 28 | uses: docker://ghcr.io/paketo-buildpacks/actions/gradle-dependency:main 29 | - name: Update Buildpack Dependency 30 | id: buildpack 31 | run: | 32 | #!/usr/bin/env bash 33 | 34 | set -euo pipefail 35 | 36 | VERSION_DEPS=$(yj -tj < buildpack.toml | jq -r ".metadata.dependencies[] | select( .id == env.ID ) | select( .version | test( env.VERSION_PATTERN ) )") 37 | ARCH=${ARCH:-amd64} 38 | OLD_VERSION=$(echo "$VERSION_DEPS" | jq -r 'select( .purl | contains( env.ARCH ) ) | .version') 39 | 40 | if [ -z "$OLD_VERSION" ]; then 41 | ARCH="" # empty means noarch 42 | OLD_VERSION=$(echo "$VERSION_DEPS" | jq -r ".version") 43 | fi 44 | 45 | update-buildpack-dependency \ 46 | --buildpack-toml buildpack.toml \ 47 | --id "${ID}" \ 48 | --arch "${ARCH}" \ 49 | --version-pattern "${VERSION_PATTERN}" \ 50 | --version "${VERSION}" \ 51 | --cpe-pattern "${CPE_PATTERN:-}" \ 52 | --cpe "${CPE:-}" \ 53 | --purl-pattern "${PURL_PATTERN:-}" \ 54 | --purl "${PURL:-}" \ 55 | --uri "${URI}" \ 56 | --sha256 "${SHA256}" \ 57 | --source "${SOURCE_URI}" \ 58 | --source-sha256 "${SOURCE_SHA256}" 59 | 60 | git add buildpack.toml 61 | git checkout -- . 62 | 63 | if [ "$(echo "$OLD_VERSION" | awk -F '.' '{print $1}')" != "$(echo "$VERSION" | awk -F '.' '{print $1}')" ]; then 64 | LABEL="semver:major" 65 | elif [ "$(echo "$OLD_VERSION" | awk -F '.' '{print $2}')" != "$(echo "$VERSION" | awk -F '.' '{print $2}')" ]; then 66 | LABEL="semver:minor" 67 | else 68 | LABEL="semver:patch" 69 | fi 70 | 71 | echo "old-version=${OLD_VERSION}" >> "$GITHUB_OUTPUT" 72 | echo "new-version=${VERSION}" >> "$GITHUB_OUTPUT" 73 | echo "version-label=${LABEL}" >> "$GITHUB_OUTPUT" 74 | env: 75 | ARCH: "" 76 | CPE: ${{ steps.dependency.outputs.cpe }} 77 | CPE_PATTERN: "" 78 | ID: gradle 79 | PURL: ${{ steps.dependency.outputs.purl }} 80 | PURL_PATTERN: "" 81 | SHA256: ${{ steps.dependency.outputs.sha256 }} 82 | SOURCE_SHA256: ${{ steps.dependency.outputs.source_sha256 }} 83 | SOURCE_URI: ${{ steps.dependency.outputs.source }} 84 | URI: ${{ steps.dependency.outputs.uri }} 85 | VERSION: ${{ steps.dependency.outputs.version }} 86 | VERSION_PATTERN: '[\d]+\.[\d]+\.[\d]+' 87 | - uses: peter-evans/create-pull-request@v6 88 | with: 89 | author: ${{ secrets.JAVA_GITHUB_USERNAME }} <${{ secrets.JAVA_GITHUB_USERNAME }}@users.noreply.github.com> 90 | body: Bumps `gradle` from `${{ steps.buildpack.outputs.old-version }}` to `${{ steps.buildpack.outputs.new-version }}`. 91 | branch: update/buildpack/gradle 92 | commit-message: |- 93 | Bump gradle from ${{ steps.buildpack.outputs.old-version }} to ${{ steps.buildpack.outputs.new-version }} 94 | 95 | Bumps gradle from ${{ steps.buildpack.outputs.old-version }} to ${{ steps.buildpack.outputs.new-version }}. 96 | delete-branch: true 97 | labels: ${{ steps.buildpack.outputs.version-label }}, type:dependency-upgrade 98 | signoff: true 99 | title: Bump gradle from ${{ steps.buildpack.outputs.old-version }} to ${{ steps.buildpack.outputs.new-version }} 100 | token: ${{ secrets.PAKETO_BOT_GITHUB_TOKEN }} 101 | -------------------------------------------------------------------------------- /gradle/detect.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package gradle 18 | 19 | import ( 20 | "fmt" 21 | "github.com/buildpacks/libcnb" 22 | "github.com/paketo-buildpacks/libpak" 23 | "github.com/paketo-buildpacks/libpak/bard" 24 | "os" 25 | "path/filepath" 26 | "strings" 27 | ) 28 | 29 | const ( 30 | PlanEntryGradle = "gradle" 31 | PlanEntryJVMApplicationPackage = "jvm-application-package" 32 | PlanEntryJDK = "jdk" 33 | PlanEntrySyft = "syft" 34 | PlanEntryYarn = "yarn" 35 | PlanEntryNode = "node" 36 | ) 37 | 38 | type Detect struct{} 39 | 40 | func (Detect) Detect(context libcnb.DetectContext) (libcnb.DetectResult, error) { 41 | 42 | result := libcnb.DetectResult{} 43 | l := bard.NewLogger(os.Stdout) 44 | cr, err := libpak.NewConfigurationResolver(context.Buildpack, &l) 45 | if err != nil { 46 | return libcnb.DetectResult{}, err 47 | } 48 | 49 | buildFile, _ := cr.Resolve("BP_GRADLE_BUILD_FILE") 50 | 51 | if buildFile != "" { 52 | 53 | file := filepath.Join(context.Application.Path, buildFile) 54 | _, err = os.Stat(file) 55 | if os.IsNotExist(err) { 56 | l.Logger.Infof("SKIPPED: BP_GRADLE_BUILD_FILE was specified but %s could not be found", file) 57 | return libcnb.DetectResult{Pass: false}, nil 58 | } else if err != nil { 59 | return libcnb.DetectResult{}, fmt.Errorf("unable to determine if %s exists\n%w", file, err) 60 | } 61 | 62 | } 63 | 64 | var files []string 65 | if buildFile != "" { 66 | files = []string{ 67 | filepath.Join(context.Application.Path, buildFile), 68 | } 69 | } else { 70 | files = []string{ 71 | filepath.Join(context.Application.Path, "build.gradle"), 72 | filepath.Join(context.Application.Path, "build.gradle.kts"), 73 | filepath.Join(context.Application.Path, "settings.gradle"), 74 | filepath.Join(context.Application.Path, "settings.gradle.kts"), 75 | } 76 | } 77 | if err := findFile(files, func(file string) bool { 78 | result = libcnb.DetectResult{ 79 | Pass: true, 80 | Plans: []libcnb.BuildPlan{ 81 | { 82 | Provides: []libcnb.BuildPlanProvide{ 83 | {Name: PlanEntryGradle}, 84 | {Name: PlanEntryJVMApplicationPackage}, 85 | }, 86 | Requires: []libcnb.BuildPlanRequire{ 87 | {Name: PlanEntrySyft}, 88 | {Name: PlanEntryGradle}, 89 | {Name: PlanEntryJDK}, 90 | }, 91 | }, 92 | }, 93 | } 94 | return true 95 | }); err != nil { 96 | return libcnb.DetectResult{}, err 97 | } 98 | 99 | // Gradle's detection has passed 100 | if len(result.Plans) > 0 { 101 | if cr.ResolveBool("BP_JAVA_INSTALL_NODE") { 102 | var fileFound bool 103 | files := []string{filepath.Join(context.Application.Path, "yarn.lock"), filepath.Join(context.Application.Path, "package.json")} 104 | if customNodePath, _ := cr.Resolve("BP_NODE_PROJECT_PATH"); customNodePath != "" { 105 | files = []string{filepath.Join(context.Application.Path, customNodePath, "yarn.lock"), filepath.Join(context.Application.Path, customNodePath, "package.json")} 106 | } 107 | if err := findFile(files, func(file string) bool { 108 | if strings.Contains(file, "yarn.lock") { 109 | result.Plans[0].Requires = append(result.Plans[0].Requires, libcnb.BuildPlanRequire{Name: PlanEntryYarn, Metadata: map[string]interface{}{"build": true}}) 110 | result.Plans[0].Requires = append(result.Plans[0].Requires, libcnb.BuildPlanRequire{Name: PlanEntryNode, Metadata: map[string]interface{}{"build": true}}) 111 | fileFound = true 112 | return true 113 | } else if strings.Contains(file, "package.json") { 114 | result.Plans[0].Requires = append(result.Plans[0].Requires, libcnb.BuildPlanRequire{Name: PlanEntryNode, Metadata: map[string]interface{}{"build": true}}) 115 | fileFound = true 116 | } 117 | return false 118 | }); err != nil { 119 | return libcnb.DetectResult{}, err 120 | } 121 | if !fileFound { 122 | l.Infof("unable to find a yarn.lock or package.json file, you may need to set BP_NODE_PROJECT_PATH") 123 | } 124 | } 125 | return result, nil 126 | } 127 | l.Logger.Info("SKIPPED: No plans could be resolved") 128 | return libcnb.DetectResult{Pass: false}, nil 129 | } 130 | 131 | func findFile(files []string, runWhenFound func(fileFound string) bool) error { 132 | for _, file := range files { 133 | _, err := os.Stat(file) 134 | if os.IsNotExist(err) { 135 | continue 136 | } else if err != nil { 137 | return fmt.Errorf("unable to determine if file %s exists \n%w", file, err) 138 | } 139 | if runWhenFound(file) { 140 | break 141 | } 142 | } 143 | return nil 144 | } 145 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/BurntSushi/toml v1.5.0 h1:W5quZX/G/csjUnuI8SUYlsHs9M38FC7znL0lIO+DvMg= 2 | github.com/BurntSushi/toml v1.5.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= 3 | github.com/Masterminds/semver/v3 v3.4.0 h1:Zog+i5UMtVoCU8oKka5P7i9q9HgrJeGzI9SA1Xbatp0= 4 | github.com/Masterminds/semver/v3 v3.4.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM= 5 | github.com/buildpacks/libcnb v1.30.4 h1:Jp6cJxYsZQgqix+lpRdSpjHt5bv5yCJqgkw9zWmS6xU= 6 | github.com/buildpacks/libcnb v1.30.4/go.mod h1:vjEDAlK3/Rf67AcmBzphXoqIlbdFgBNUK5d8wjreJbY= 7 | github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s= 8 | github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE= 9 | github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= 10 | github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 11 | github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= 12 | github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= 13 | github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1vB6EwHI= 14 | github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8= 15 | github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= 16 | github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= 17 | github.com/google/pprof v0.0.0-20250403155104-27863c87afa6 h1:BHT72Gu3keYf3ZEu2J0b1vyeLSOYI8bm5wbJM/8yDe8= 18 | github.com/google/pprof v0.0.0-20250403155104-27863c87afa6/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA= 19 | github.com/h2non/filetype v1.1.3 h1:FKkx9QbD7HR/zjK1Ia5XiBsq9zdLi5Kf3zGyFTAFkGg= 20 | github.com/h2non/filetype v1.1.3/go.mod h1:319b3zT68BvV+WRj7cwy856M2ehB3HqNOt6sy1HndBY= 21 | github.com/heroku/color v0.0.6 h1:UTFFMrmMLFcL3OweqP1lAdp8i1y/9oHqkeHjQ/b/Ny0= 22 | github.com/heroku/color v0.0.6/go.mod h1:ZBvOcx7cTF2QKOv4LbmoBtNl5uB17qWxGuzZrsi1wLU= 23 | github.com/imdario/mergo v0.3.16 h1:wwQJbIsHYGMUyLSPrEq1CT16AhnhNJQ51+4fdHUnCl4= 24 | github.com/imdario/mergo v0.3.16/go.mod h1:WBLT9ZmE3lPoWsEzCh9LPo3TiwVN+ZKEjmz+hD27ysY= 25 | github.com/jarcoal/httpmock v1.3.1 h1:iUx3whfZWVf3jT01hQTO/Eo5sAYtB2/rqaUuOtpInww= 26 | github.com/jarcoal/httpmock v1.3.1/go.mod h1:3yb8rc4BI7TCBhFY8ng0gjuLKJNquuDNiPaZjnENuYg= 27 | github.com/magiconair/properties v1.8.10 h1:s31yESBquKXCV9a/ScB3ESkOjUYYv+X0rg8SYxI99mE= 28 | github.com/magiconair/properties v1.8.10/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0= 29 | github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE= 30 | github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE= 31 | github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8= 32 | github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= 33 | github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= 34 | github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= 35 | github.com/mattn/go-shellwords v1.0.12 h1:M2zGm7EW6UQJvDeQxo4T51eKPurbeFbe8WtebGE2xrk= 36 | github.com/mattn/go-shellwords v1.0.12/go.mod h1:EZzvwXDESEeg03EKmM+RmDnNOPKG4lLtQsUlTZDWQ8Y= 37 | github.com/mitchellh/hashstructure/v2 v2.0.2 h1:vGKWl0YJqUNxE8d+h8f6NJLcCJrgbhC4NcD46KavDd4= 38 | github.com/mitchellh/hashstructure/v2 v2.0.2/go.mod h1:MG3aRVU/N29oo/V/IhBX8GR/zz4kQkprJgF2EVszyDE= 39 | github.com/onsi/ginkgo/v2 v2.25.3 h1:Ty8+Yi/ayDAGtk4XxmmfUy4GabvM+MegeB4cDLRi6nw= 40 | github.com/onsi/ginkgo/v2 v2.25.3/go.mod h1:43uiyQC4Ed2tkOzLsEYm7hnrb7UJTWHYNsuy3bG/snE= 41 | github.com/onsi/gomega v1.38.3 h1:eTX+W6dobAYfFeGC2PV6RwXRu/MyT+cQguijutvkpSM= 42 | github.com/onsi/gomega v1.38.3/go.mod h1:ZCU1pkQcXDO5Sl9/VVEGlDyp+zm0m1cmeG5TOzLgdh4= 43 | github.com/paketo-buildpacks/libbs v1.18.1 h1:rM+dJ8MA4INv01N0K1a0AXeya2FRuf8IlOelSkufT5Q= 44 | github.com/paketo-buildpacks/libbs v1.18.1/go.mod h1:EFVjgeFoQLMQFclsQM9p0inJWCQMVsNpWnz/RvGAAlk= 45 | github.com/paketo-buildpacks/libjvm v1.46.0 h1:+mEOsK30a1if0T3ZvSs6di/w5cp/j14uD3DyYUusavI= 46 | github.com/paketo-buildpacks/libjvm v1.46.0/go.mod h1:jNQuS8SQfbbHN9kenMpBhpxaE0uCa9ZkKLrN89IU0VY= 47 | github.com/paketo-buildpacks/libpak v1.73.0 h1:OgdkOn4VLIzRo0WcSx1iRmqeLrcMAZbIk7pOOJSyl5Q= 48 | github.com/paketo-buildpacks/libpak v1.73.0/go.mod h1:EY01BAEtNPT1kI+/OTGTAkitNzKiFzCTGAmxapBUPJ4= 49 | github.com/paketo-buildpacks/source-removal v1.0.4 h1:B77IsLbVyeDEaYbxTxCmdSN1anQJW+LIh8nJdkKSTjU= 50 | github.com/paketo-buildpacks/source-removal v1.0.4/go.mod h1:+hfPfjQjWoYX9+AumcLPLk0c1FFnoJ8+53jUATHI3ls= 51 | github.com/pavlo-v-chernykh/keystore-go/v4 v4.5.0 h1:2nosf3P75OZv2/ZO/9Px5ZgZ5gbKrzA3joN1QMfOGMQ= 52 | github.com/pavlo-v-chernykh/keystore-go/v4 v4.5.0/go.mod h1:lAVhWwbNaveeJmxrxuSTxMgKpF6DjnuVpn6T8WiBwYQ= 53 | github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= 54 | github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 55 | github.com/sclevine/spec v1.4.0 h1:z/Q9idDcay5m5irkZ28M7PtQM4aOISzOpj4bUPkDee8= 56 | github.com/sclevine/spec v1.4.0/go.mod h1:LvpgJaFyvQzRvc1kaDs0bulYwzC70PbiYjC4QnFHkOM= 57 | github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY= 58 | github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= 59 | github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= 60 | github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= 61 | github.com/xi2/xz v0.0.0-20171230120015-48954b6210f8 h1:nIPpBwaJSVYIxUFsDv3M8ofmx9yWTog9BfvIu0q41lo= 62 | github.com/xi2/xz v0.0.0-20171230120015-48954b6210f8/go.mod h1:HUYIGzjTL3rfEspMxjDjgmT5uz5wzYJKVo23qUhYTos= 63 | go.uber.org/automaxprocs v1.6.0 h1:O3y2/QNTOdbF+e/dpXNNW7Rx2hZ4sTIPyybbxyNqTUs= 64 | go.uber.org/automaxprocs v1.6.0/go.mod h1:ifeIMSnPZuznNm6jmdzmU3/bfk01Fe2fotchwEFJ8r8= 65 | go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= 66 | go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= 67 | golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU= 68 | golang.org/x/crypto v0.46.0/go.mod h1:Evb/oLKmMraqjZ2iQTwDwvCtJkczlDuTmdJXoZVzqU0= 69 | golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU= 70 | golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY= 71 | golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 72 | golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 73 | golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk= 74 | golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= 75 | golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU= 76 | golang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY= 77 | golang.org/x/tools v0.39.0 h1:ik4ho21kwuQln40uelmciQPp9SipgNDdrafrYA4TmQQ= 78 | golang.org/x/tools v0.39.0/go.mod h1:JnefbkDPyD8UU2kI5fuf8ZX4/yUeh9W877ZeBONxUqQ= 79 | google.golang.org/protobuf v1.36.10 h1:AYd7cD/uASjIL6Q9LiTjz8JLcrh/88q5UObnmY3aOOE= 80 | google.golang.org/protobuf v1.36.10/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= 81 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= 82 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 83 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 84 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 85 | software.sslmate.com/src/go-pkcs12 v0.6.0 h1:f3sQittAeF+pao32Vb+mkli+ZyT+VwKaD014qFGq6oU= 86 | software.sslmate.com/src/go-pkcs12 v0.6.0/go.mod h1:Qiz0EyvDRJjjxGyUQa2cCNZn/wMyzrRJ/qcDXOQazLI= 87 | -------------------------------------------------------------------------------- /gradle/build.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package gradle 18 | 19 | import ( 20 | "crypto/sha256" 21 | "encoding/hex" 22 | "fmt" 23 | "io" 24 | "os" 25 | "os/user" 26 | "path/filepath" 27 | 28 | "github.com/paketo-buildpacks/libpak/effect" 29 | "github.com/paketo-buildpacks/libpak/sbom" 30 | 31 | "github.com/paketo-buildpacks/libpak/bindings" 32 | 33 | "github.com/buildpacks/libcnb" 34 | "github.com/paketo-buildpacks/libbs" 35 | "github.com/paketo-buildpacks/libpak" 36 | "github.com/paketo-buildpacks/libpak/bard" 37 | ) 38 | 39 | type Build struct { 40 | Logger bard.Logger 41 | ApplicationFactory ApplicationFactory 42 | HomeDirectoryResolver HomeDirectoryResolver 43 | } 44 | 45 | type ApplicationFactory interface { 46 | NewApplication(additionalMetadata map[string]interface{}, arguments []string, artifactResolver libbs.ArtifactResolver, 47 | cache libbs.Cache, command string, bom *libcnb.BOM, applicationPath string, bomScanner sbom.SBOMScanner) (libbs.Application, error) 48 | } 49 | 50 | type HomeDirectoryResolver interface { 51 | Location() (string, error) 52 | } 53 | 54 | type OSHomeDirectoryResolver struct{} 55 | 56 | func (p OSHomeDirectoryResolver) Location() (string, error) { 57 | u, err := user.Current() 58 | if err != nil { 59 | return "", fmt.Errorf("unable to determine user home directory\n%w", err) 60 | } 61 | 62 | return u.HomeDir, nil 63 | } 64 | 65 | func (b Build) Build(context libcnb.BuildContext) (libcnb.BuildResult, error) { 66 | b.Logger.Title(context.Buildpack) 67 | result := libcnb.NewBuildResult() 68 | 69 | cr, err := libpak.NewConfigurationResolver(context.Buildpack, &b.Logger) 70 | if err != nil { 71 | return libcnb.BuildResult{}, fmt.Errorf("unable to create configuration resolver\n%w", err) 72 | } 73 | 74 | dr, err := libpak.NewDependencyResolver(context) 75 | if err != nil { 76 | return libcnb.BuildResult{}, fmt.Errorf("unable to create dependency resolver\n%w", err) 77 | } 78 | 79 | dc, err := libpak.NewDependencyCache(context) 80 | if err != nil { 81 | return libcnb.BuildResult{}, fmt.Errorf("unable to create dependency cache\n%w", err) 82 | } 83 | dc.Logger = b.Logger 84 | 85 | command := filepath.Join(context.Application.Path, "gradlew") 86 | if _, err := os.Stat(command); os.IsNotExist(err) { 87 | dep, err := dr.Resolve("gradle", "") 88 | if err != nil { 89 | return libcnb.BuildResult{}, fmt.Errorf("unable to find dependency\n%w", err) 90 | } 91 | 92 | d, be := NewDistribution(dep, dc) 93 | d.Logger = b.Logger 94 | result.Layers = append(result.Layers, d) 95 | result.BOM.Entries = append(result.BOM.Entries, be) 96 | command = filepath.Join(context.Layers.Path, d.Name(), "bin", "gradle") 97 | } else if err != nil { 98 | return libcnb.BuildResult{}, fmt.Errorf("unable to stat %s\n%w", command, err) 99 | } else { 100 | if err := os.Chmod(command, 0755); err != nil { 101 | b.Logger.Bodyf("WARNING: unable to chmod %s:\n%s", command, err) 102 | } 103 | } 104 | 105 | homeDir, err := b.HomeDirectoryResolver.Location() 106 | if err != nil { 107 | return libcnb.BuildResult{}, fmt.Errorf("unable to resolve home directory\n%w", err) 108 | } 109 | gradleHome := filepath.Join(homeDir, ".gradle") 110 | 111 | c := libbs.Cache{Path: gradleHome} 112 | c.Logger = b.Logger 113 | result.Layers = append(result.Layers, c) 114 | 115 | args, err := libbs.ResolveArguments("BP_GRADLE_BUILD_ARGUMENTS", cr) 116 | if err != nil { 117 | return libcnb.BuildResult{}, fmt.Errorf("unable to resolve build arguments\n%w", err) 118 | } 119 | 120 | additionalArgs, err := libbs.ResolveArguments("BP_GRADLE_ADDITIONAL_BUILD_ARGUMENTS", cr) 121 | if err != nil { 122 | return libcnb.BuildResult{}, fmt.Errorf("unable to resolve additional build arguments\n%w", err) 123 | } else { 124 | args = append(args, additionalArgs...) 125 | } 126 | 127 | initScriptPath, _ := cr.Resolve("BP_GRADLE_INIT_SCRIPT_PATH") 128 | if initScriptPath != "" { 129 | args = append([]string{"--init-script", initScriptPath}, args...) 130 | } 131 | 132 | md := map[string]interface{}{} 133 | if binding, ok, err := bindings.ResolveOne(context.Platform.Bindings, bindings.OfType("gradle")); err != nil { 134 | return libcnb.BuildResult{}, fmt.Errorf("unable to resolve binding\n%w", err) 135 | } else if ok { 136 | b.Logger.Debug("binding of type gradle successfully detected, configuring layer") 137 | gradlePropertiesPath, ok := binding.SecretFilePath("gradle.properties") 138 | if ok { 139 | gradlePropertiesFile, err := os.Open(gradlePropertiesPath) 140 | if err != nil { 141 | return libcnb.BuildResult{}, fmt.Errorf("unable to open gradle.properties\n%w", err) 142 | } 143 | 144 | hasher := sha256.New() 145 | if _, err := io.Copy(hasher, gradlePropertiesFile); err != nil { 146 | return libcnb.BuildResult{}, fmt.Errorf("unable to hash gradle.properties\n%w", err) 147 | } 148 | md["gradle-properties-sha256"] = hex.EncodeToString(hasher.Sum(nil)) 149 | 150 | result.Layers = append(result.Layers, PropertiesFile{ 151 | binding, 152 | gradleHome, 153 | "gradle.properties", 154 | "gradle-properties", 155 | b.Logger, 156 | }) 157 | } 158 | } 159 | 160 | gradleWrapperHome := filepath.Join("gradle", "wrapper") 161 | if binding, ok, err := bindings.ResolveOne(context.Platform.Bindings, bindings.OfType("gradle-wrapper")); err != nil { 162 | return libcnb.BuildResult{}, fmt.Errorf("unable to resolve binding\n%w", err) 163 | } else if ok { 164 | b.Logger.Debug("binding of type gradle-wrapper successfully detected, configuring layer") 165 | gradleWrapperPropertiesPath, ok := binding.SecretFilePath("gradle-wrapper.properties") 166 | if ok { 167 | gradleWrapperPropertiesFile, err := os.Open(gradleWrapperPropertiesPath) 168 | if err != nil { 169 | return libcnb.BuildResult{}, fmt.Errorf("unable to open gradle-wrapper.properties\n%w", err) 170 | } 171 | 172 | hasher := sha256.New() 173 | if _, err := io.Copy(hasher, gradleWrapperPropertiesFile); err != nil { 174 | return libcnb.BuildResult{}, fmt.Errorf("unable to hash gradle-wrapper.properties\n%w", err) 175 | } 176 | md["gradle-wrapper-properties-sha256"] = hex.EncodeToString(hasher.Sum(nil)) 177 | 178 | result.Layers = append(result.Layers, PropertiesFile{ 179 | binding, 180 | gradleWrapperHome, 181 | "gradle-wrapper.properties", 182 | "gradle-wrapper-properties", 183 | b.Logger, 184 | }) 185 | } 186 | } 187 | 188 | art := libbs.ArtifactResolver{ 189 | ArtifactConfigurationKey: "BP_GRADLE_BUILT_ARTIFACT", 190 | ConfigurationResolver: cr, 191 | ModuleConfigurationKey: "BP_GRADLE_BUILT_MODULE", 192 | InterestingFileDetector: libbs.JARInterestingFileDetector{}, 193 | AdditionalHelpMessage: "If this is unexpected, please try setting `rootProject.name` in `settings.gradle` or add a project.toml file and exclude the `build/` directory. For details see https://buildpacks.io/docs/app-developer-guide/using-project-descriptor/.", 194 | } 195 | 196 | bomScanner := sbom.NewSyftCLISBOMScanner(context.Layers, effect.CommandExecutor{}, b.Logger) 197 | a, err := b.ApplicationFactory.NewApplication( 198 | md, 199 | args, 200 | art, 201 | c, 202 | command, 203 | result.BOM, 204 | context.Application.Path, 205 | bomScanner, 206 | ) 207 | if err != nil { 208 | return libcnb.BuildResult{}, fmt.Errorf("unable to create application layer\n%w", err) 209 | } 210 | a.Logger = b.Logger 211 | result.Layers = append(result.Layers, a) 212 | 213 | return result, nil 214 | } 215 | -------------------------------------------------------------------------------- /gradle/gradle_properties_test.go: -------------------------------------------------------------------------------- 1 | package gradle_test 2 | 3 | import ( 4 | "github.com/magiconair/properties" 5 | "github.com/paketo-buildpacks/libpak/sherpa" 6 | "os" 7 | "path/filepath" 8 | "testing" 9 | 10 | "github.com/buildpacks/libcnb" 11 | . "github.com/onsi/gomega" 12 | "github.com/sclevine/spec" 13 | 14 | "github.com/paketo-buildpacks/gradle/v7/gradle" 15 | ) 16 | 17 | func testGradleProperties(t *testing.T, context spec.G, it spec.S) { 18 | var ( 19 | Expect = NewWithT(t).Expect 20 | 21 | ctx libcnb.BuildContext 22 | gradleProps gradle.PropertiesFile 23 | gradleLayer libcnb.Layer 24 | gradleHome string 25 | gradleWrapperHome string 26 | gradleWrapperTargetPropsPath string 27 | gradleTargetPropsPath string 28 | bindingPath string 29 | homeDir string 30 | ) 31 | 32 | it.Before(func() { 33 | var err error 34 | 35 | ctx.Platform.Path, err = os.MkdirTemp("", "gradle-test-platform") 36 | Expect(err).NotTo(HaveOccurred()) 37 | 38 | ctx.Application.Path, err = os.MkdirTemp("", "build-application") 39 | Expect(err).NotTo(HaveOccurred()) 40 | 41 | ctx.Layers.Path, err = os.MkdirTemp("", "build-layers") 42 | Expect(err).NotTo(HaveOccurred()) 43 | 44 | homeDir, err = os.MkdirTemp("", "home-dir") 45 | Expect(err).NotTo(HaveOccurred()) 46 | 47 | gradleHome = filepath.Join(homeDir, ".gradle") 48 | gradleTargetPropsPath = filepath.Join(gradleHome, "gradle.properties") 49 | 50 | gradleWrapperHome = filepath.Join(ctx.Application.Path, "gradle", "wrapper") 51 | gradleWrapperTargetPropsPath = filepath.Join(gradleWrapperHome, "gradle-wrapper.properties") 52 | }) 53 | 54 | it.After(func() { 55 | Expect(os.RemoveAll(ctx.Platform.Path)).To(Succeed()) 56 | Expect(os.RemoveAll(ctx.Application.Path)).To(Succeed()) 57 | Expect(os.RemoveAll(ctx.Layers.Path)).To(Succeed()) 58 | Expect(os.RemoveAll(homeDir)).To(Succeed()) 59 | }) 60 | 61 | context("no binding is present", func() { 62 | it("does nothing ", func() { 63 | layer, err := gradleProps.Contribute(gradleLayer) 64 | Expect(err).NotTo(HaveOccurred()) 65 | Expect(layer).To(Equal(gradleLayer)) 66 | 67 | Expect(gradleHome).ToNot(BeADirectory()) 68 | Expect(gradleTargetPropsPath).ToNot(BeAnExistingFile()) 69 | }) 70 | }) 71 | 72 | context("a gradle properties binding is present", func() { 73 | it.Before(func() { 74 | var err error 75 | 76 | bindingPath = filepath.Join(ctx.Platform.Path, "bindings", "some-gradle") 77 | ctx.Platform.Bindings = libcnb.Bindings{ 78 | { 79 | Name: "some-gradle", 80 | Type: "gradle", 81 | Secret: map[string]string{"gradle.properties": "gradle-properties-content"}, 82 | Path: bindingPath, 83 | }, 84 | } 85 | gradleSrcPropsPath, ok := ctx.Platform.Bindings[0].SecretFilePath("gradle.properties") 86 | Expect(os.MkdirAll(filepath.Dir(gradleSrcPropsPath), 0777)).To(Succeed()) 87 | Expect(ok).To(BeTrue()) 88 | Expect(os.WriteFile( 89 | gradleSrcPropsPath, 90 | []byte("gradle-properties-content"), 91 | 0644, 92 | )).To(Succeed()) 93 | 94 | // normally done by cache layer 95 | Expect(os.MkdirAll(gradleHome, 0755)).ToNot(HaveOccurred()) 96 | 97 | gradleLayer, err = ctx.Layers.Layer("gradle-properties") 98 | Expect(err).NotTo(HaveOccurred()) 99 | 100 | gradleProps = gradle.PropertiesFile{ 101 | Binding: ctx.Platform.Bindings[0], 102 | GradlePropertiesHome: gradleHome, 103 | GradlePropertiesFileName: "gradle.properties", 104 | GradlePropertiesName: "gradle-properties", 105 | } 106 | }) 107 | 108 | it("creates a symlink for gradle.properties under $GRADLE_USER_HOME", func() { 109 | layer, err := gradleProps.Contribute(gradleLayer) 110 | Expect(err).NotTo(HaveOccurred()) 111 | Expect(layer).To(Equal(gradleLayer)) 112 | 113 | info, err := os.Lstat(gradleTargetPropsPath) 114 | Expect(err).NotTo(HaveOccurred()) 115 | Expect(info.Mode()&os.ModeSymlink != 0).To(BeTrue()) // is symlink bit set 116 | 117 | target, err := os.Readlink(gradleTargetPropsPath) 118 | Expect(err).NotTo(HaveOccurred()) 119 | Expect(target).To(Equal(filepath.Join(bindingPath, "gradle.properties"))) 120 | 121 | data, err := os.ReadFile(gradleTargetPropsPath) 122 | Expect(err).ToNot(HaveOccurred()) 123 | Expect(string(data)).To(Equal("gradle-properties-content")) 124 | }) 125 | 126 | it("recreates symlink for gradle.properties under $GRADLE_USER_HOME", func() { 127 | Expect(os.MkdirAll(filepath.Dir(gradleTargetPropsPath), 0755)).ToNot(HaveOccurred()) 128 | err := os.Symlink("/dev/null", gradleTargetPropsPath) 129 | Expect(err).NotTo(HaveOccurred()) 130 | Expect(gradleTargetPropsPath).To(BeAnExistingFile()) 131 | 132 | layer, err := gradleProps.Contribute(gradleLayer) 133 | Expect(err).NotTo(HaveOccurred()) 134 | Expect(layer).To(Equal(gradleLayer)) 135 | 136 | info, err := os.Lstat(gradleTargetPropsPath) 137 | Expect(err).NotTo(HaveOccurred()) 138 | Expect(info.Mode()&os.ModeSymlink != 0).To(BeTrue()) // is symlink bit set 139 | 140 | target, err := os.Readlink(gradleTargetPropsPath) 141 | Expect(err).NotTo(HaveOccurred()) 142 | // symlink should point to our binding, not /dev/null 143 | Expect(target).To(Equal(filepath.Join(bindingPath, "gradle.properties"))) 144 | 145 | data, err := os.ReadFile(gradleTargetPropsPath) 146 | Expect(err).ToNot(HaveOccurred()) 147 | Expect(string(data)).To(Equal("gradle-properties-content")) 148 | }) 149 | 150 | }) 151 | 152 | context("a gradle wrapper properties binding is present and contributes its content", func() { 153 | it.Before(func() { 154 | var err error 155 | 156 | bindingPath = filepath.Join(ctx.Platform.Path, "bindings", "some-gradle") 157 | ctx.Platform.Bindings = libcnb.Bindings{ 158 | { 159 | Name: "some-gradle", 160 | Type: "gradle-wrapper", 161 | Secret: map[string]string{"gradle-wrapper.properties": `distributionUrl=https://g.o/gradle-7.5-bin.zip 162 | networkTimeout=43`}, 163 | Path: bindingPath, 164 | }, 165 | } 166 | Expect(os.MkdirAll(gradleWrapperHome, 0755)).ToNot(HaveOccurred()) 167 | gradleSrcPropsPath, ok := ctx.Platform.Bindings[0].SecretFilePath("gradle-wrapper.properties") 168 | Expect(os.MkdirAll(filepath.Dir(gradleSrcPropsPath), 0777)).To(Succeed()) 169 | Expect(ok).To(BeTrue()) 170 | 171 | Expect(os.WriteFile( 172 | gradleSrcPropsPath, 173 | []byte(`distributionUrl=https://g.o/gradle-7.5-bin.zip 174 | networkTimeout=43`), 175 | 0644, 176 | )).To(Succeed()) 177 | 178 | originalGradleWrapperProperties, err := os.Open(filepath.Join("testdata", "gradle-wrapper.properties")) 179 | Expect(err).NotTo(HaveOccurred()) 180 | 181 | err = sherpa.CopyFile(originalGradleWrapperProperties, gradleWrapperTargetPropsPath) 182 | Expect(err).NotTo(HaveOccurred()) 183 | 184 | gradleLayer, err = ctx.Layers.Layer("gradle-wrapper-properties") 185 | Expect(err).NotTo(HaveOccurred()) 186 | 187 | gradleProps = gradle.PropertiesFile{ 188 | Binding: ctx.Platform.Bindings[0], 189 | GradlePropertiesHome: gradleWrapperHome, 190 | GradlePropertiesFileName: "gradle-wrapper.properties", 191 | GradlePropertiesName: "gradle-wrapper-properties", 192 | } 193 | }) 194 | 195 | it("merges gradle wrapper properties files", func() { 196 | layer, err := gradleProps.Contribute(gradleLayer) 197 | Expect(err).NotTo(HaveOccurred()) 198 | Expect(layer).To(Equal(gradleLayer)) 199 | 200 | patchedProperties := properties.MustLoadFile(filepath.Join("testdata", "gradle-wrapper.properties"), properties.UTF8) 201 | previousValue, ok, err := patchedProperties.Set("networkTimeout", "43") 202 | Expect(err).NotTo(HaveOccurred()) 203 | Expect(previousValue).To(Equal("10000")) 204 | Expect(ok).To(Equal(true)) 205 | previousValue, ok, err = patchedProperties.Set("distributionUrl", "https://g.o/gradle-7.5-bin.zip") 206 | Expect(err).NotTo(HaveOccurred()) 207 | Expect(previousValue).To(Equal("https://services.gradle.org/distributions/gradle-7.6-bin.zip")) 208 | Expect(ok).To(Equal(true)) 209 | 210 | finalProperties := properties.MustLoadFile(gradleWrapperTargetPropsPath, properties.UTF8) 211 | 212 | Expect(finalProperties).To(Equal(patchedProperties)) 213 | }) 214 | 215 | }) 216 | 217 | } 218 | -------------------------------------------------------------------------------- /.github/workflows/pb-tests.yml: -------------------------------------------------------------------------------- 1 | name: Tests 2 | "on": 3 | merge_group: 4 | types: 5 | - checks_requested 6 | branches: 7 | - main 8 | pull_request: {} 9 | push: 10 | branches: 11 | - main 12 | jobs: 13 | create-package: 14 | name: Create Package Test 15 | runs-on: 16 | - ubuntu-latest 17 | steps: 18 | - uses: actions/setup-go@v5 19 | with: 20 | go-version: "1.25" 21 | - name: Install create-package 22 | run: | 23 | #!/usr/bin/env bash 24 | 25 | set -euo pipefail 26 | 27 | go install -ldflags="-s -w" github.com/paketo-buildpacks/libpak/cmd/create-package@latest 28 | - uses: buildpacks/github-actions/setup-pack@v5.9.7 29 | with: 30 | pack-version: 0.39.1 31 | - name: Enable pack Experimental 32 | run: | 33 | #!/usr/bin/env bash 34 | 35 | set -euo pipefail 36 | 37 | echo "Enabling pack experimental features" 38 | pack config experimental true 39 | - uses: actions/checkout@v4 40 | - uses: actions/cache@v4 41 | with: 42 | key: ${{ runner.os }}-go-${{ hashFiles('**/buildpack.toml', '**/package.toml') }} 43 | path: |- 44 | ${{ env.HOME }}/.pack 45 | ${{ env.HOME }}/carton-cache 46 | restore-keys: ${{ runner.os }}-go- 47 | - name: Compute Version 48 | id: version 49 | run: | 50 | #!/usr/bin/env bash 51 | 52 | set -euo pipefail 53 | 54 | if [[ ${GITHUB_REF:-} != "refs/"* ]]; then 55 | echo "GITHUB_REF set to [${GITHUB_REF:-}], but that is unexpected. It should start with 'refs/*'" 56 | exit 255 57 | fi 58 | 59 | if [[ ${GITHUB_REF} =~ refs/tags/v([0-9]+\.[0-9]+\.[0-9]+) ]]; then 60 | VERSION=${BASH_REMATCH[1]} 61 | 62 | MAJOR_VERSION="$(echo "${VERSION}" | awk -F '.' '{print $1 }')" 63 | MINOR_VERSION="$(echo "${VERSION}" | awk -F '.' '{print $1 "." $2 }')" 64 | 65 | echo "version-major=${MAJOR_VERSION}" >> "$GITHUB_OUTPUT" 66 | echo "version-minor=${MINOR_VERSION}" >> "$GITHUB_OUTPUT" 67 | elif [[ ${GITHUB_REF} =~ refs/heads/(.+) ]]; then 68 | VERSION=${BASH_REMATCH[1]} 69 | else 70 | VERSION=$(git rev-parse --short HEAD) 71 | fi 72 | 73 | echo "version=${VERSION}" >> "$GITHUB_OUTPUT" 74 | echo "Selected ${VERSION} from 75 | * ref: ${GITHUB_REF} 76 | * sha: ${GITHUB_SHA} 77 | " 78 | - name: Create Package 79 | run: | 80 | #!/usr/bin/env bash 81 | 82 | set -euo pipefail 83 | 84 | # With Go 1.20, we need to set this so that we produce statically compiled binaries 85 | # 86 | # Starting with Go 1.20, Go will produce binaries that are dynamically linked against libc 87 | # which can cause compatibility issues. The compiler links against libc on the build system 88 | # but that may be newer than on the stacks we support. 89 | export CGO_ENABLED=0 90 | 91 | if [[ "${INCLUDE_DEPENDENCIES}" == "true" ]]; then 92 | create-package \ 93 | --source "${SOURCE_PATH:-.}" \ 94 | --cache-location "${HOME}"/carton-cache \ 95 | --destination "${HOME}"/buildpack \ 96 | --include-dependencies \ 97 | --version "${VERSION}" 98 | else 99 | create-package \ 100 | --source "${SOURCE_PATH:-.}" \ 101 | --destination "${HOME}"/buildpack \ 102 | --version "${VERSION}" 103 | fi 104 | 105 | PACKAGE_FILE="${SOURCE_PATH:-.}/package.toml" 106 | if [ -f "${PACKAGE_FILE}" ]; then 107 | cp "${PACKAGE_FILE}" "${HOME}/buildpack/package.toml" 108 | printf '[buildpack]\nuri = "%s"\n\n[platform]\nos = "%s"\n' "${HOME}/buildpack" "${OS}" >> "${HOME}/buildpack/package.toml" 109 | fi 110 | env: 111 | INCLUDE_DEPENDENCIES: "true" 112 | OS: linux 113 | VERSION: ${{ steps.version.outputs.version }} 114 | - name: Package Buildpack 115 | run: |- 116 | #!/usr/bin/env bash 117 | 118 | set -euo pipefail 119 | 120 | COMPILED_BUILDPACK="${HOME}/buildpack" 121 | 122 | # create-package puts the buildpack here, we need to run from that directory 123 | # for component buildpacks so that pack doesn't need a package.toml 124 | cd "${COMPILED_BUILDPACK}" 125 | CONFIG="" 126 | if [ -f "${COMPILED_BUILDPACK}/package.toml" ]; then 127 | CONFIG="--config ${COMPILED_BUILDPACK}/package.toml --flatten" 128 | fi 129 | 130 | PACKAGE_LIST=($PACKAGES) 131 | # Extract first repo (Docker Hub) as the main to package & register 132 | PACKAGE=${PACKAGE_LIST[0]} 133 | 134 | if [[ "${PUBLISH:-x}" == "true" ]]; then 135 | pack -v buildpack package \ 136 | "${PACKAGE}:${VERSION}" ${CONFIG} \ 137 | --publish 138 | 139 | if [[ -n ${VERSION_MINOR:-} && -n ${VERSION_MAJOR:-} ]]; then 140 | crane tag "${PACKAGE}:${VERSION}" "${VERSION_MINOR}" 141 | crane tag "${PACKAGE}:${VERSION}" "${VERSION_MAJOR}" 142 | fi 143 | crane tag "${PACKAGE}:${VERSION}" latest 144 | echo "digest=$(crane digest "${PACKAGE}:${VERSION}")" >> "$GITHUB_OUTPUT" 145 | 146 | # copy to other repositories specified 147 | for P in "${PACKAGE_LIST[@]}" 148 | do 149 | if [ "$P" != "$PACKAGE" ]; then 150 | crane copy "${PACKAGE}:${VERSION}" "${P}:${VERSION}" 151 | if [[ -n ${VERSION_MINOR:-} && -n ${VERSION_MAJOR:-} ]]; then 152 | crane tag "${P}:${VERSION}" "${VERSION_MINOR}" 153 | crane tag "${P}:${VERSION}" "${VERSION_MAJOR}" 154 | fi 155 | crane tag "${P}:${VERSION}" latest 156 | fi 157 | done 158 | else 159 | if [ -n "$TTL_SH_PUBLISH" ] && [ "$TTL_SH_PUBLISH" = "true" ]; then 160 | TAG="${PACKAGE}-$(mktemp -u XXXXX | awk '{print tolower($0)}'):${VERSION}" 161 | pack -v buildpack package "${TAG}" ${CONFIG} --format "${FORMAT}" --publish 162 | else 163 | TAG="${PACKAGE}:${VERSION}" 164 | pack -v buildpack package "${TAG}" ${CONFIG} --format "${FORMAT}" 165 | fi 166 | 167 | echo "ttl-image-tag=${TAG:-}" >> "$GITHUB_OUTPUT" 168 | fi 169 | env: 170 | FORMAT: image 171 | PACKAGES: test 172 | TTL_SH_PUBLISH: "false" 173 | VERSION: ${{ steps.version.outputs.version }} 174 | unit: 175 | name: Unit Test 176 | runs-on: 177 | - ubuntu-latest 178 | steps: 179 | - uses: actions/checkout@v4 180 | - uses: actions/cache@v4 181 | with: 182 | key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} 183 | path: ${{ env.HOME }}/go/pkg/mod 184 | restore-keys: ${{ runner.os }}-go- 185 | - uses: actions/setup-go@v5 186 | with: 187 | go-version: "1.25" 188 | - name: Install richgo 189 | run: | 190 | #!/usr/bin/env bash 191 | 192 | set -euo pipefail 193 | 194 | echo "Installing richgo ${RICHGO_VERSION}" 195 | 196 | mkdir -p "${HOME}"/bin 197 | echo "${HOME}/bin" >> "${GITHUB_PATH}" 198 | 199 | curl \ 200 | --location \ 201 | --show-error \ 202 | --silent \ 203 | "https://github.com/kyoh86/richgo/releases/download/v${RICHGO_VERSION}/richgo_${RICHGO_VERSION}_linux_amd64.tar.gz" \ 204 | | tar -C "${HOME}"/bin -xz richgo 205 | env: 206 | RICHGO_VERSION: 0.3.10 207 | - name: Run Tests 208 | run: | 209 | #!/usr/bin/env bash 210 | 211 | set -euo pipefail 212 | 213 | richgo test ./... 214 | env: 215 | RICHGO_FORCE_COLOR: "1" 216 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Paketo Buildpack for Gradle 2 | 3 | ## Buildpack ID: `paketo-buildpacks/gradle` 4 | ## Registry URLs: `docker.io/paketobuildpacks/gradle` 5 | 6 | The Paketo Buildpack for Gradle is a Cloud Native Buildpack that build Gradle-based applications from source. 7 | 8 | ## Behavior 9 | 10 | This buildpack will participate if any of the following conditions are met 11 | 12 | * `/build.gradle` exists 13 | * `/build.gradle.kts` exists 14 | 15 | The buildpack will do the following: 16 | 17 | * Requests that a JDK be installed 18 | * Links the `~/.gradle` to a layer for caching 19 | * If `/gradlew` exists 20 | * Runs `/gradlew --no-daemon assemble` to build the application 21 | * If `/gradlew` does not exist 22 | * Contributes Gradle to a layer with all commands on `$PATH` 23 | * Runs `/bin/gradle --no-daemon assemble` to build the application 24 | * Removes the source code in ``, following include/exclude rules 25 | * If `$BP_GRADLE_BUILT_ARTIFACT` matched a single file 26 | * Restores `$BP_GRADLE_BUILT_ARTIFACT` from the layer, expands the single file to `` 27 | * If `$BP_GRADLE_BUILT_ARTIFACT` matched a directory or multiple files 28 | * Restores the files matched by `$BP_GRADLE_BUILT_ARTIFACT` to `` 29 | * If `$BP_JAVA_INSTALL_NODE` is set to true and the buildpack finds one of the following at `` or at the path set by `$BP_NODE_PROJECT_PATH`: 30 | * a `yarn.lock` file, the buildpack requests that `yarn` and `node` are installed at build time 31 | * a `package.json` file, the buildpack requests that `node` is installed at build time 32 | 33 | ## Configuration 34 | 35 | | Environment Variable | Description | 36 | |-----------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| 37 | | `$BP_GRADLE_BUILD_ARGUMENTS` | Configure the arguments to pass to build system. Defaults to `--no-daemon -Dorg.gradle.welcome=never assemble`. | 38 | | `$BP_GRADLE_ADDITIONAL_BUILD_ARGUMENTS` | Configure the additional arguments to pass to build system. Defaults to empty string. | 39 | | `$BP_GRADLE_BUILD_FILE` | Configure the location of the build configuration file. If it doesn't exist this build pack will not be applied. Defaults to `build.gradle`. | 40 | | `$BP_GRADLE_BUILT_MODULE` | Configure the module to find application artifact in. Defaults to the root module (empty). | 41 | | `$BP_GRADLE_BUILT_ARTIFACT` | Configure the built application artifact explicitly. Supersedes `$BP_GRADLE_BUILT_MODULE`. Defaults to `build/libs/*.[jw]ar`. Can match a single file, multiple files or a directory. Can be one or more space separated patterns. | 42 | | `$BP_GRADLE_INIT_SCRIPT_PATH` | Specifies a custom location to a Gradle init script, i.e. a `init.gradle` file. | 43 | | `$BP_INCLUDE_FILES` | Colon separated list of glob patterns to match source files. Any matched file will be retained in the final image. Defaults to `` (i.e. nothing). | 44 | | `$BP_EXCLUDE_FILES` | Colon separated list of glob patterns to match source files. Any matched file will be specifically removed from the final image. If include patterns are also specified, then they are applied first and exclude patterns can be used to further reduce the fileset. | 45 | | `$BP_JAVA_INSTALL_NODE` | Configure whether to request that `yarn` and `node` are installed by another buildpack**. If set to `true`, the buildpack will check the app root or path set by `$BP_NODE_PROJECT_PATH` for either: A `yarn.lock` file, which requires that `yarn` and `node` are installed or, a `package.json` file, which requires that `node` is installed. Defaults to `false` | 46 | | `$BP_NODE_PROJECT_PATH` | Configure a project subdirectory to look for `package.json` and `yarn.lock` files | 47 | 48 | ### Note 49 | ** If the node and/or yarn requirements are met and the [Node Engine](https://github.com/paketo-buildpacks/node-engine) or [Yarn](https://github.com/paketo-buildpacks/yarn) participate in the build, environment variables related to these buildpacks can be set, such as `BP_NODE_PROJECT_PATH` or `BP_NODE_VERSION`. See the [Paketo Node.js docs](https://paketo.io/docs/howto/nodejs/) for more info. 50 | 51 | ## Bindings 52 | 53 | The buildpack optionally accepts the following bindings: 54 | 55 | ### Type: `gradle` 56 | 57 | | Secret | Description | 58 | | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | 59 | | `gradle.properties` | If present, the contents of the file are copied to `$GRADLE_USER_HOME/gradle.properties` which is [picked up by gradle and merged](https://docs.gradle.org/current/userguide/build_environment.html#sec:gradle_configuration_properties) when it runs. | 60 | 61 | ### Type: `gradle-wrapper` 62 | 63 | | Secret | Description | 64 | |-----------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| 65 | | `gradle-wrapper.properties` | If present, the values of the properties file override the default ones found at /gradle/wrapper/gradle-wrapper.properties which is [picked up by the gradle wrapper](https://docs.gradle.org/current/userguide/gradle_wrapper.html#customizing_wrapper). | 66 | 67 | 68 | ### Type: `dependency-mapping` 69 | 70 | | Key | Value | Description | 71 | | --------------------- | ------- | ------------------------------------------------------------------------------------------------- | 72 | | `` | `` | If needed, the buildpack will fetch the dependency with digest `` from `` | 73 | 74 | ## License 75 | 76 | This buildpack is released under version 2.0 of the [Apache License][a]. 77 | 78 | [a]: http://www.apache.org/licenses/LICENSE-2.0 79 | -------------------------------------------------------------------------------- /gradle/detect_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package gradle_test 18 | 19 | import ( 20 | "os" 21 | "path/filepath" 22 | "testing" 23 | 24 | "github.com/buildpacks/libcnb" 25 | . "github.com/onsi/gomega" 26 | "github.com/sclevine/spec" 27 | 28 | "github.com/paketo-buildpacks/gradle/v7/gradle" 29 | ) 30 | 31 | func testDetect(t *testing.T, context spec.G, it spec.S) { 32 | var ( 33 | Expect = NewWithT(t).Expect 34 | 35 | ctx libcnb.DetectContext 36 | detect gradle.Detect 37 | ) 38 | 39 | it.Before(func() { 40 | var err error 41 | 42 | ctx.Application.Path, err = os.MkdirTemp("", "gradle") 43 | Expect(err).NotTo(HaveOccurred()) 44 | os.Unsetenv("BP_GRADLE_BUILD_FILE") 45 | os.Unsetenv("BP_JAVA_INSTALL_NODE") 46 | os.Unsetenv("BP_NODE_PROJECT_PATH") 47 | }) 48 | 49 | it.After(func() { 50 | Expect(os.RemoveAll(ctx.Application.Path)).To(Succeed()) 51 | }) 52 | 53 | it("fails without build.gradle or build.gradle.kts", func() { 54 | Expect(detect.Detect(ctx)).To(Equal(libcnb.DetectResult{})) 55 | }) 56 | 57 | it("fails without configured build file", func() { 58 | Expect(os.WriteFile(filepath.Join(ctx.Application.Path, "build.gradle"), []byte{}, 0644)) 59 | os.Setenv("BP_GRADLE_BUILD_FILE", filepath.Join(ctx.Application.Path, "no-such-build.gradle")) 60 | Expect(detect.Detect(ctx)).To(Equal(libcnb.DetectResult{})) 61 | }) 62 | 63 | it("passes if no package-manager file is found", func() { 64 | Expect(os.WriteFile(filepath.Join(ctx.Application.Path, "build.gradle"), []byte{}, 0644)) 65 | os.Setenv("BP_JAVA_INSTALL_NODE", "true") 66 | 67 | Expect(detect.Detect(ctx)).To(Equal(libcnb.DetectResult{ 68 | Pass: true, 69 | Plans: []libcnb.BuildPlan{ 70 | { 71 | Provides: []libcnb.BuildPlanProvide{ 72 | {Name: "gradle"}, 73 | {Name: "jvm-application-package"}, 74 | }, 75 | Requires: []libcnb.BuildPlanRequire{ 76 | {Name: "syft"}, 77 | {Name: "gradle"}, 78 | {Name: "jdk"}, 79 | }, 80 | }, 81 | }, 82 | })) 83 | }) 84 | 85 | it("passes with build.gradle", func() { 86 | Expect(os.WriteFile(filepath.Join(ctx.Application.Path, "build.gradle"), []byte{}, 0644)) 87 | 88 | Expect(detect.Detect(ctx)).To(Equal(libcnb.DetectResult{ 89 | Pass: true, 90 | Plans: []libcnb.BuildPlan{ 91 | { 92 | Provides: []libcnb.BuildPlanProvide{ 93 | {Name: "gradle"}, 94 | {Name: "jvm-application-package"}, 95 | }, 96 | Requires: []libcnb.BuildPlanRequire{ 97 | {Name: "syft"}, 98 | {Name: "gradle"}, 99 | {Name: "jdk"}, 100 | }, 101 | }, 102 | }, 103 | })) 104 | }) 105 | 106 | it("passes with build.gradle.kts", func() { 107 | Expect(os.WriteFile(filepath.Join(ctx.Application.Path, "build.gradle.kts"), []byte{}, 0644)) 108 | 109 | Expect(detect.Detect(ctx)).To(Equal(libcnb.DetectResult{ 110 | Pass: true, 111 | Plans: []libcnb.BuildPlan{ 112 | { 113 | Provides: []libcnb.BuildPlanProvide{ 114 | {Name: "gradle"}, 115 | {Name: "jvm-application-package"}, 116 | }, 117 | Requires: []libcnb.BuildPlanRequire{ 118 | {Name: "syft"}, 119 | {Name: "gradle"}, 120 | {Name: "jdk"}, 121 | }, 122 | }, 123 | }, 124 | })) 125 | }) 126 | 127 | it("passes with settings.gradle", func() { 128 | Expect(os.WriteFile(filepath.Join(ctx.Application.Path, "settings.gradle"), []byte{}, 0644)) 129 | 130 | Expect(detect.Detect(ctx)).To(Equal(libcnb.DetectResult{ 131 | Pass: true, 132 | Plans: []libcnb.BuildPlan{ 133 | { 134 | Provides: []libcnb.BuildPlanProvide{ 135 | {Name: "gradle"}, 136 | {Name: "jvm-application-package"}, 137 | }, 138 | Requires: []libcnb.BuildPlanRequire{ 139 | {Name: "syft"}, 140 | {Name: "gradle"}, 141 | {Name: "jdk"}, 142 | }, 143 | }, 144 | }, 145 | })) 146 | }) 147 | 148 | it("passes with settings.gradle.kts", func() { 149 | Expect(os.WriteFile(filepath.Join(ctx.Application.Path, "settings.gradle.kts"), []byte{}, 0644)) 150 | 151 | Expect(detect.Detect(ctx)).To(Equal(libcnb.DetectResult{ 152 | Pass: true, 153 | Plans: []libcnb.BuildPlan{ 154 | { 155 | Provides: []libcnb.BuildPlanProvide{ 156 | {Name: "gradle"}, 157 | {Name: "jvm-application-package"}, 158 | }, 159 | Requires: []libcnb.BuildPlanRequire{ 160 | {Name: "syft"}, 161 | {Name: "gradle"}, 162 | {Name: "jdk"}, 163 | }, 164 | }, 165 | }, 166 | })) 167 | }) 168 | 169 | it("passes with package.json", func() { 170 | Expect(os.WriteFile(filepath.Join(ctx.Application.Path, "build.gradle"), []byte{}, 0644)) 171 | Expect(os.WriteFile(filepath.Join(ctx.Application.Path, "package.json"), []byte{}, 0644)) 172 | os.Setenv("BP_JAVA_INSTALL_NODE", "true") 173 | 174 | Expect(detect.Detect(ctx)).To(Equal(libcnb.DetectResult{ 175 | Pass: true, 176 | Plans: []libcnb.BuildPlan{ 177 | { 178 | Provides: []libcnb.BuildPlanProvide{ 179 | {Name: "gradle"}, 180 | {Name: "jvm-application-package"}, 181 | }, 182 | Requires: []libcnb.BuildPlanRequire{ 183 | {Name: "syft"}, 184 | {Name: "gradle"}, 185 | {Name: "jdk"}, 186 | {Name: "node", Metadata: map[string]interface{}{"build": true}}, 187 | }, 188 | }, 189 | }, 190 | })) 191 | }) 192 | 193 | it("passes with yarn.lock", func() { 194 | Expect(os.WriteFile(filepath.Join(ctx.Application.Path, "build.gradle"), []byte{}, 0644)) 195 | Expect(os.WriteFile(filepath.Join(ctx.Application.Path, "yarn.lock"), []byte{}, 0644)) 196 | os.Setenv("BP_JAVA_INSTALL_NODE", "true") 197 | 198 | Expect(detect.Detect(ctx)).To(Equal(libcnb.DetectResult{ 199 | Pass: true, 200 | Plans: []libcnb.BuildPlan{ 201 | { 202 | Provides: []libcnb.BuildPlanProvide{ 203 | {Name: "gradle"}, 204 | {Name: "jvm-application-package"}, 205 | }, 206 | Requires: []libcnb.BuildPlanRequire{ 207 | {Name: "syft"}, 208 | {Name: "gradle"}, 209 | {Name: "jdk"}, 210 | {Name: "yarn", Metadata: map[string]interface{}{"build": true}}, 211 | {Name: "node", Metadata: map[string]interface{}{"build": true}}, 212 | }, 213 | }, 214 | }, 215 | })) 216 | }) 217 | 218 | it("passes without duplication with both yarn.lock & package.json", func() { 219 | Expect(os.WriteFile(filepath.Join(ctx.Application.Path, "build.gradle"), []byte{}, 0644)) 220 | Expect(os.WriteFile(filepath.Join(ctx.Application.Path, "yarn.lock"), []byte{}, 0644)) 221 | Expect(os.WriteFile(filepath.Join(ctx.Application.Path, "package.json"), []byte{}, 0644)) 222 | os.Setenv("BP_JAVA_INSTALL_NODE", "true") 223 | 224 | Expect(detect.Detect(ctx)).To(Equal(libcnb.DetectResult{ 225 | Pass: true, 226 | Plans: []libcnb.BuildPlan{ 227 | { 228 | Provides: []libcnb.BuildPlanProvide{ 229 | {Name: "gradle"}, 230 | {Name: "jvm-application-package"}, 231 | }, 232 | Requires: []libcnb.BuildPlanRequire{ 233 | {Name: "syft"}, 234 | {Name: "gradle"}, 235 | {Name: "jdk"}, 236 | {Name: "yarn", Metadata: map[string]interface{}{"build": true}}, 237 | {Name: "node", Metadata: map[string]interface{}{"build": true}}, 238 | }, 239 | }, 240 | }, 241 | })) 242 | }) 243 | 244 | it("passes with custom path set via BP_NODE_PROJECT_PATH", func() { 245 | os.Setenv("BP_NODE_PROJECT_PATH", "frontend") 246 | os.Setenv("BP_JAVA_INSTALL_NODE", "true") 247 | os.Mkdir(filepath.Join(ctx.Application.Path, "frontend"), 0755) 248 | Expect(os.WriteFile(filepath.Join(ctx.Application.Path, "build.gradle"), []byte{}, 0644)) 249 | Expect(os.WriteFile(filepath.Join(ctx.Application.Path, "frontend/yarn.lock"), []byte{}, 0644)) 250 | 251 | Expect(detect.Detect(ctx)).To(Equal(libcnb.DetectResult{ 252 | Pass: true, 253 | Plans: []libcnb.BuildPlan{ 254 | { 255 | Provides: []libcnb.BuildPlanProvide{ 256 | {Name: "gradle"}, 257 | {Name: "jvm-application-package"}, 258 | }, 259 | Requires: []libcnb.BuildPlanRequire{ 260 | {Name: "syft"}, 261 | {Name: "gradle"}, 262 | {Name: "jdk"}, 263 | {Name: "yarn", Metadata: map[string]interface{}{"build": true}}, 264 | {Name: "node", Metadata: map[string]interface{}{"build": true}}, 265 | }, 266 | }, 267 | }, 268 | })) 269 | }) 270 | 271 | it("does not detect false positive without env-var", func() { 272 | Expect(os.WriteFile(filepath.Join(ctx.Application.Path, "build.gradle"), []byte{}, 0644)) 273 | Expect(os.WriteFile(filepath.Join(ctx.Application.Path, "yarn.lock"), []byte{}, 0644)) 274 | Expect(os.WriteFile(filepath.Join(ctx.Application.Path, "package.json"), []byte{}, 0644)) 275 | 276 | Expect(detect.Detect(ctx)).To(Equal(libcnb.DetectResult{ 277 | Pass: true, 278 | Plans: []libcnb.BuildPlan{ 279 | { 280 | Provides: []libcnb.BuildPlanProvide{ 281 | {Name: "gradle"}, 282 | {Name: "jvm-application-package"}, 283 | }, 284 | Requires: []libcnb.BuildPlanRequire{ 285 | {Name: "syft"}, 286 | {Name: "gradle"}, 287 | {Name: "jdk"}, 288 | }, 289 | }, 290 | }, 291 | })) 292 | }) 293 | } 294 | -------------------------------------------------------------------------------- /.github/workflows/pb-create-package.yml: -------------------------------------------------------------------------------- 1 | name: Create Package 2 | "on": 3 | release: 4 | types: 5 | - published 6 | jobs: 7 | create-package: 8 | name: Create Package 9 | runs-on: 10 | - ubuntu-latest 11 | steps: 12 | - name: Docker login docker.io 13 | if: ${{ (github.event_name != 'pull_request' || ! github.event.pull_request.head.repo.fork) && (github.actor != 'dependabot[bot]') }} 14 | uses: docker/login-action@v3 15 | with: 16 | password: ${{ secrets.PAKETO_BUILDPACKS_DOCKERHUB_PASSWORD }} 17 | registry: docker.io 18 | username: ${{ secrets.PAKETO_BUILDPACKS_DOCKERHUB_USERNAME }} 19 | - uses: actions/setup-go@v5 20 | with: 21 | go-version: "1.25" 22 | - name: Install create-package 23 | run: | 24 | #!/usr/bin/env bash 25 | 26 | set -euo pipefail 27 | 28 | go install -ldflags="-s -w" github.com/paketo-buildpacks/libpak/cmd/create-package@latest 29 | - uses: buildpacks/github-actions/setup-tools@v5.9.7 30 | with: 31 | crane-version: 0.20.3 32 | yj-version: 5.1.0 33 | - uses: buildpacks/github-actions/setup-pack@v5.9.7 34 | with: 35 | pack-version: 0.39.1 36 | - name: Enable pack Experimental 37 | run: | 38 | #!/usr/bin/env bash 39 | 40 | set -euo pipefail 41 | 42 | echo "Enabling pack experimental features" 43 | pack config experimental true 44 | - uses: actions/checkout@v4 45 | - if: ${{ false }} 46 | uses: actions/cache@v4 47 | with: 48 | key: ${{ runner.os }}-go-${{ hashFiles('**/buildpack.toml', '**/package.toml') }} 49 | path: |- 50 | ${{ env.HOME }}/.pack 51 | ${{ env.HOME }}/carton-cache 52 | restore-keys: ${{ runner.os }}-go- 53 | - name: Compute Version 54 | id: version 55 | run: | 56 | #!/usr/bin/env bash 57 | 58 | set -euo pipefail 59 | 60 | if [[ ${GITHUB_REF:-} != "refs/"* ]]; then 61 | echo "GITHUB_REF set to [${GITHUB_REF:-}], but that is unexpected. It should start with 'refs/*'" 62 | exit 255 63 | fi 64 | 65 | if [[ ${GITHUB_REF} =~ refs/tags/v([0-9]+\.[0-9]+\.[0-9]+) ]]; then 66 | VERSION=${BASH_REMATCH[1]} 67 | 68 | MAJOR_VERSION="$(echo "${VERSION}" | awk -F '.' '{print $1 }')" 69 | MINOR_VERSION="$(echo "${VERSION}" | awk -F '.' '{print $1 "." $2 }')" 70 | 71 | echo "version-major=${MAJOR_VERSION}" >> "$GITHUB_OUTPUT" 72 | echo "version-minor=${MINOR_VERSION}" >> "$GITHUB_OUTPUT" 73 | elif [[ ${GITHUB_REF} =~ refs/heads/(.+) ]]; then 74 | VERSION=${BASH_REMATCH[1]} 75 | else 76 | VERSION=$(git rev-parse --short HEAD) 77 | fi 78 | 79 | echo "version=${VERSION}" >> "$GITHUB_OUTPUT" 80 | echo "Selected ${VERSION} from 81 | * ref: ${GITHUB_REF} 82 | * sha: ${GITHUB_SHA} 83 | " 84 | - name: Create Package 85 | run: | 86 | #!/usr/bin/env bash 87 | 88 | set -euo pipefail 89 | 90 | # With Go 1.20, we need to set this so that we produce statically compiled binaries 91 | # 92 | # Starting with Go 1.20, Go will produce binaries that are dynamically linked against libc 93 | # which can cause compatibility issues. The compiler links against libc on the build system 94 | # but that may be newer than on the stacks we support. 95 | export CGO_ENABLED=0 96 | 97 | if [[ "${INCLUDE_DEPENDENCIES}" == "true" ]]; then 98 | create-package \ 99 | --source "${SOURCE_PATH:-.}" \ 100 | --cache-location "${HOME}"/carton-cache \ 101 | --destination "${HOME}"/buildpack \ 102 | --include-dependencies \ 103 | --version "${VERSION}" 104 | else 105 | create-package \ 106 | --source "${SOURCE_PATH:-.}" \ 107 | --destination "${HOME}"/buildpack \ 108 | --version "${VERSION}" 109 | fi 110 | 111 | PACKAGE_FILE="${SOURCE_PATH:-.}/package.toml" 112 | if [ -f "${PACKAGE_FILE}" ]; then 113 | cp "${PACKAGE_FILE}" "${HOME}/buildpack/package.toml" 114 | printf '[buildpack]\nuri = "%s"\n\n[platform]\nos = "%s"\n' "${HOME}/buildpack" "${OS}" >> "${HOME}/buildpack/package.toml" 115 | fi 116 | env: 117 | INCLUDE_DEPENDENCIES: "false" 118 | OS: linux 119 | SOURCE_PATH: "" 120 | VERSION: ${{ steps.version.outputs.version }} 121 | - name: Package Buildpack 122 | id: package 123 | run: |- 124 | #!/usr/bin/env bash 125 | 126 | set -euo pipefail 127 | 128 | COMPILED_BUILDPACK="${HOME}/buildpack" 129 | 130 | # create-package puts the buildpack here, we need to run from that directory 131 | # for component buildpacks so that pack doesn't need a package.toml 132 | cd "${COMPILED_BUILDPACK}" 133 | CONFIG="" 134 | if [ -f "${COMPILED_BUILDPACK}/package.toml" ]; then 135 | CONFIG="--config ${COMPILED_BUILDPACK}/package.toml --flatten" 136 | fi 137 | 138 | PACKAGE_LIST=($PACKAGES) 139 | # Extract first repo (Docker Hub) as the main to package & register 140 | PACKAGE=${PACKAGE_LIST[0]} 141 | 142 | if [[ "${PUBLISH:-x}" == "true" ]]; then 143 | pack -v buildpack package \ 144 | "${PACKAGE}:${VERSION}" ${CONFIG} \ 145 | --publish 146 | 147 | if [[ -n ${VERSION_MINOR:-} && -n ${VERSION_MAJOR:-} ]]; then 148 | crane tag "${PACKAGE}:${VERSION}" "${VERSION_MINOR}" 149 | crane tag "${PACKAGE}:${VERSION}" "${VERSION_MAJOR}" 150 | fi 151 | crane tag "${PACKAGE}:${VERSION}" latest 152 | echo "digest=$(crane digest "${PACKAGE}:${VERSION}")" >> "$GITHUB_OUTPUT" 153 | 154 | # copy to other repositories specified 155 | for P in "${PACKAGE_LIST[@]}" 156 | do 157 | if [ "$P" != "$PACKAGE" ]; then 158 | crane copy "${PACKAGE}:${VERSION}" "${P}:${VERSION}" 159 | if [[ -n ${VERSION_MINOR:-} && -n ${VERSION_MAJOR:-} ]]; then 160 | crane tag "${P}:${VERSION}" "${VERSION_MINOR}" 161 | crane tag "${P}:${VERSION}" "${VERSION_MAJOR}" 162 | fi 163 | crane tag "${P}:${VERSION}" latest 164 | fi 165 | done 166 | else 167 | if [ -n "$TTL_SH_PUBLISH" ] && [ "$TTL_SH_PUBLISH" = "true" ]; then 168 | TAG="${PACKAGE}-$(mktemp -u XXXXX | awk '{print tolower($0)}'):${VERSION}" 169 | pack -v buildpack package "${TAG}" ${CONFIG} --format "${FORMAT}" --publish 170 | else 171 | TAG="${PACKAGE}:${VERSION}" 172 | pack -v buildpack package "${TAG}" ${CONFIG} --format "${FORMAT}" 173 | fi 174 | 175 | echo "ttl-image-tag=${TAG:-}" >> "$GITHUB_OUTPUT" 176 | fi 177 | env: 178 | PACKAGES: docker.io/paketobuildpacks/gradle 179 | PUBLISH: "true" 180 | VERSION: ${{ steps.version.outputs.version }} 181 | VERSION_MAJOR: ${{ steps.version.outputs.version-major }} 182 | VERSION_MINOR: ${{ steps.version.outputs.version-minor }} 183 | - name: Update release with digest 184 | run: | 185 | #!/usr/bin/env bash 186 | 187 | set -euo pipefail 188 | 189 | PAYLOAD=$(cat "${GITHUB_EVENT_PATH}") 190 | 191 | RELEASE_ID=$(jq -n -r --argjson PAYLOAD "${PAYLOAD}" '$PAYLOAD.release.id') 192 | RELEASE_TAG_NAME=$(jq -n -r --argjson PAYLOAD "${PAYLOAD}" '$PAYLOAD.release.tag_name') 193 | RELEASE_NAME=$(jq -n -r --argjson PAYLOAD "${PAYLOAD}" '$PAYLOAD.release.name') 194 | RELEASE_BODY=$(jq -n -r --argjson PAYLOAD "${PAYLOAD}" '$PAYLOAD.release.body') 195 | 196 | gh api \ 197 | --method PATCH \ 198 | "/repos/:owner/:repo/releases/${RELEASE_ID}" \ 199 | --field "tag_name=${RELEASE_TAG_NAME}" \ 200 | --field "name=${RELEASE_NAME}" \ 201 | --field "body=${RELEASE_BODY///\`${DIGEST}\`}" 202 | env: 203 | DIGEST: ${{ steps.package.outputs.digest }} 204 | GITHUB_TOKEN: ${{ secrets.PAKETO_BOT_GITHUB_TOKEN }} 205 | - if: ${{ true }} 206 | uses: docker://ghcr.io/buildpacks/actions/registry/request-add-entry:5.9.7 207 | with: 208 | address: docker.io/paketobuildpacks/gradle@${{ steps.package.outputs.digest }} 209 | id: paketo-buildpacks/gradle 210 | token: ${{ secrets.PAKETO_BOT_GITHUB_TOKEN }} 211 | version: ${{ steps.version.outputs.version }} 212 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | https://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | https://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /gradle/build_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2018-2020 the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package gradle_test 18 | 19 | import ( 20 | "errors" 21 | "os" 22 | "path/filepath" 23 | "testing" 24 | 25 | "github.com/paketo-buildpacks/libpak" 26 | "github.com/paketo-buildpacks/libpak/sbom" 27 | 28 | "github.com/buildpacks/libcnb" 29 | . "github.com/onsi/gomega" 30 | "github.com/sclevine/spec" 31 | 32 | "github.com/paketo-buildpacks/libbs" 33 | 34 | "github.com/paketo-buildpacks/gradle/v7/gradle" 35 | ) 36 | 37 | func testBuild(t *testing.T, context spec.G, it spec.S) { 38 | var ( 39 | Expect = NewWithT(t).Expect 40 | 41 | ctx libcnb.BuildContext 42 | gradleBuild gradle.Build 43 | homeDir string 44 | gradlewFilepath string 45 | ) 46 | 47 | it.Before(func() { 48 | var err error 49 | 50 | ctx.Application.Path, err = os.MkdirTemp("", "build-application") 51 | Expect(err).NotTo(HaveOccurred()) 52 | 53 | ctx.Layers.Path, err = os.MkdirTemp("", "build-layers") 54 | Expect(err).NotTo(HaveOccurred()) 55 | 56 | homeDir, err = os.MkdirTemp("", "home-dir") 57 | Expect(err).NotTo(HaveOccurred()) 58 | 59 | gradlewFilepath = filepath.Join(ctx.Application.Path, "gradlew") 60 | 61 | gradleBuild = gradle.Build{ 62 | ApplicationFactory: &FakeApplicationFactory{}, 63 | HomeDirectoryResolver: FakeHomeDirectoryResolver{path: homeDir}, 64 | } 65 | 66 | t.Setenv("BP_ARCH", "amd64") 67 | }) 68 | 69 | it.After(func() { 70 | Expect(os.RemoveAll(ctx.Application.Path)).To(Succeed()) 71 | Expect(os.RemoveAll(ctx.Layers.Path)).To(Succeed()) 72 | Expect(os.RemoveAll(homeDir)).To(Succeed()) 73 | }) 74 | 75 | it("does not contribute distribution if wrapper exists", func() { 76 | Expect(os.WriteFile(gradlewFilepath, []byte{}, 0644)).To(Succeed()) 77 | ctx.StackID = "test-stack-id" 78 | 79 | result, err := gradleBuild.Build(ctx) 80 | Expect(err).NotTo(HaveOccurred()) 81 | 82 | Expect(result.Layers).To(HaveLen(2)) 83 | Expect(result.Layers[0].Name()).To(Equal("cache")) 84 | Expect(result.Layers[1].Name()).To(Equal("application")) 85 | Expect(result.Layers[1].(libbs.Application).Command).To(Equal(gradlewFilepath)) 86 | }) 87 | 88 | it("makes sure that gradlew is executable", func() { 89 | Expect(os.WriteFile(gradlewFilepath, []byte{}, 0644)).To(Succeed()) 90 | ctx.StackID = "test-stack-id" 91 | 92 | _, err := gradleBuild.Build(ctx) 93 | Expect(err).NotTo(HaveOccurred()) 94 | 95 | fi, err := os.Stat(gradlewFilepath) 96 | Expect(err).NotTo(HaveOccurred()) 97 | Expect(fi.Mode()).To(BeEquivalentTo(0755)) 98 | }) 99 | 100 | it("proceeds without error if gradlew could not have been made executable", func() { 101 | if _, err := os.Stat("/dev/null"); errors.Is(err, os.ErrNotExist) { 102 | t.Skip("No /dev/null thus not a unix system. Skipping chmod test.") 103 | } 104 | Expect(os.Symlink("/dev/null", gradlewFilepath)).To(Succeed()) 105 | fi, err := os.Stat(gradlewFilepath) 106 | Expect(err).NotTo(HaveOccurred()) 107 | originalMode := fi.Mode() 108 | Expect(originalMode).ToNot(BeEquivalentTo(0755)) 109 | ctx.StackID = "test-stack-id" 110 | 111 | _, err = gradleBuild.Build(ctx) 112 | Expect(err).NotTo(HaveOccurred()) 113 | 114 | fi, err = os.Stat(gradlewFilepath) 115 | Expect(err).NotTo(HaveOccurred()) 116 | Expect(fi.Mode()).To(BeEquivalentTo(originalMode)) 117 | }) 118 | 119 | it("contributes distribution for API <=0.6", func() { 120 | ctx.Buildpack.Metadata = map[string]interface{}{ 121 | "dependencies": []map[string]interface{}{ 122 | { 123 | "id": "gradle", 124 | "version": "1.1.1", 125 | "stacks": []interface{}{"test-stack-id"}, 126 | }, 127 | }, 128 | } 129 | ctx.StackID = "test-stack-id" 130 | ctx.Buildpack.API = "0.6" 131 | 132 | result, err := gradleBuild.Build(ctx) 133 | Expect(err).NotTo(HaveOccurred()) 134 | 135 | Expect(result.Layers).To(HaveLen(3)) 136 | Expect(result.Layers[0].Name()).To(Equal("gradle")) 137 | Expect(result.Layers[1].Name()).To(Equal("cache")) 138 | Expect(result.Layers[2].Name()).To(Equal("application")) 139 | Expect(result.Layers[2].(libbs.Application).Command).To(Equal(filepath.Join(ctx.Layers.Path, "gradle", "bin", "gradle"))) 140 | 141 | Expect(result.BOM.Entries).To(HaveLen(1)) 142 | Expect(result.BOM.Entries[0].Name).To(Equal("gradle")) 143 | Expect(result.BOM.Entries[0].Build).To(BeTrue()) 144 | Expect(result.BOM.Entries[0].Launch).To(BeFalse()) 145 | }) 146 | 147 | it("contributes distribution for API 0.7+", func() { 148 | ctx.Buildpack.Metadata = map[string]interface{}{ 149 | "dependencies": []map[string]interface{}{ 150 | { 151 | "id": "gradle", 152 | "version": "1.1.1", 153 | "stacks": []interface{}{"test-stack-id"}, 154 | "cpes": []string{"cpe:2.3:a:apache:gradle:1.1.1:*:*:*:*:*:*:*"}, 155 | "purl": "pkg:generic/gradle@1.1.1", 156 | }, 157 | }, 158 | } 159 | ctx.StackID = "test-stack-id" 160 | 161 | result, err := gradleBuild.Build(ctx) 162 | Expect(err).NotTo(HaveOccurred()) 163 | 164 | Expect(result.Layers).To(HaveLen(3)) 165 | Expect(result.Layers[0].Name()).To(Equal("gradle")) 166 | Expect(result.Layers[1].Name()).To(Equal("cache")) 167 | Expect(result.Layers[2].Name()).To(Equal("application")) 168 | Expect(result.Layers[2].(libbs.Application).Command).To(Equal(filepath.Join(ctx.Layers.Path, "gradle", "bin", "gradle"))) 169 | 170 | Expect(result.BOM.Entries).To(HaveLen(1)) 171 | Expect(result.BOM.Entries[0].Name).To(Equal("gradle")) 172 | Expect(result.BOM.Entries[0].Build).To(BeTrue()) 173 | Expect(result.BOM.Entries[0].Launch).To(BeFalse()) 174 | }) 175 | 176 | context("BP_GRADLE_INIT_SCRIPT_PATH configuration is set", func() { 177 | it.Before(func() { 178 | ctx.Buildpack.Metadata = map[string]interface{}{ 179 | "configurations": []map[string]interface{}{ 180 | {"name": "BP_GRADLE_INIT_SCRIPT_PATH", "default": "/workspace/init.gradle"}, 181 | }, 182 | } 183 | }) 184 | 185 | it("sets the settings path", func() { 186 | Expect(os.WriteFile(gradlewFilepath, []byte{}, 0644)).To(Succeed()) 187 | 188 | result, err := gradleBuild.Build(ctx) 189 | Expect(err).NotTo(HaveOccurred()) 190 | 191 | Expect(result.Layers[1].(libbs.Application).Arguments).To(Equal([]string{ 192 | "--init-script", "/workspace/init.gradle", 193 | })) 194 | }) 195 | }) 196 | 197 | context("BP_GRADLE_INIT_SCRIPT_PATH env var is set", func() { 198 | it.Before(func() { 199 | Expect(os.Setenv("BP_GRADLE_INIT_SCRIPT_PATH", "/workspace/init.gradle")).To(Succeed()) 200 | }) 201 | 202 | it.After(func() { 203 | Expect(os.Unsetenv(("BP_GRADLE_INIT_SCRIPT_PATH"))).To(Succeed()) 204 | }) 205 | 206 | it("sets the settings path", func() { 207 | Expect(os.WriteFile(gradlewFilepath, []byte{}, 0644)).To(Succeed()) 208 | 209 | result, err := gradleBuild.Build(ctx) 210 | Expect(err).NotTo(HaveOccurred()) 211 | 212 | Expect(result.Layers[1].(libbs.Application).Arguments).To(Equal([]string{ 213 | "--init-script", "/workspace/init.gradle", 214 | })) 215 | }) 216 | }) 217 | 218 | context("BP_GRADLE_BUILD_ARGUMENTS env var is set", func() { 219 | it.Before(func() { 220 | Expect(os.Setenv("BP_GRADLE_BUILD_ARGUMENTS", "--no-daemon -Dorg.gradle.welcome=never assemble")).To(Succeed()) 221 | }) 222 | 223 | it.After(func() { 224 | Expect(os.Unsetenv(("BP_GRADLE_BUILD_ARGUMENTS"))).To(Succeed()) 225 | }) 226 | it("sets some build arguments", func() { 227 | Expect(os.WriteFile(gradlewFilepath, []byte{}, 0644)).To(Succeed()) 228 | 229 | result, err := gradleBuild.Build(ctx) 230 | Expect(err).NotTo(HaveOccurred()) 231 | 232 | Expect(result.Layers[1].(libbs.Application).Arguments).To(Equal([]string{ 233 | "--no-daemon", "-Dorg.gradle.welcome=never", "assemble", 234 | })) 235 | }) 236 | }) 237 | 238 | context("BP_GRADLE_BUILD_ARGUMENTS and BP_GRADLE_ADDITIONAL_BUILD_ARGUMENTS env var is set", func() { 239 | it.Before(func() { 240 | Expect(os.Setenv("BP_GRADLE_BUILD_ARGUMENTS", "--no-daemon assemble")).To(Succeed()) 241 | Expect(os.Setenv("BP_GRADLE_ADDITIONAL_BUILD_ARGUMENTS", "--no-build-cache")).To(Succeed()) 242 | }) 243 | 244 | it.After(func() { 245 | Expect(os.Unsetenv(("BP_GRADLE_BUILD_ARGUMENTS"))).To(Succeed()) 246 | Expect(os.Unsetenv(("BP_GRADLE_ADDITIONAL_BUILD_ARGUMENTS"))).To(Succeed()) 247 | }) 248 | it("sets some build and additional build arguments", func() { 249 | Expect(os.WriteFile(gradlewFilepath, []byte{}, 0644)).To(Succeed()) 250 | 251 | result, err := gradleBuild.Build(ctx) 252 | Expect(err).NotTo(HaveOccurred()) 253 | 254 | Expect(result.Layers[1].(libbs.Application).Arguments).To(Equal([]string{ 255 | "--no-daemon", "assemble", "--no-build-cache", 256 | })) 257 | }) 258 | }) 259 | 260 | context("gradle properties bindings exists", func() { 261 | var bindingPath string 262 | 263 | it.Before(func() { 264 | var err error 265 | ctx.StackID = "test-stack-id" 266 | ctx.Platform.Path, err = os.MkdirTemp("", "gradle-test-platform") 267 | Expect(err).NotTo(HaveOccurred()) 268 | Expect(os.WriteFile(gradlewFilepath, []byte{}, 0644)).To(Succeed()) 269 | bindingPath = filepath.Join(ctx.Platform.Path, "bindings", "some-gradle") 270 | ctx.Platform.Bindings = libcnb.Bindings{ 271 | { 272 | Name: "some-gradle", 273 | Type: "gradle", 274 | Secret: map[string]string{"gradle.properties": "gradle-properties-content"}, 275 | Path: bindingPath, 276 | }, 277 | } 278 | gradlePropertiesPath, ok := ctx.Platform.Bindings[0].SecretFilePath("gradle.properties") 279 | Expect(os.MkdirAll(filepath.Dir(gradlePropertiesPath), 0777)).To(Succeed()) 280 | Expect(ok).To(BeTrue()) 281 | Expect(os.WriteFile( 282 | gradlePropertiesPath, 283 | []byte("gradle-properties-content"), 284 | 0644, 285 | )).To(Succeed()) 286 | }) 287 | 288 | it.After(func() { 289 | Expect(os.RemoveAll(ctx.Platform.Path)).To(Succeed()) 290 | }) 291 | 292 | it("provides gradle.properties under $GRADLE_USER_HOME", func() { 293 | result, err := gradleBuild.Build(ctx) 294 | Expect(err).NotTo(HaveOccurred()) 295 | 296 | Expect(result.Layers).To(HaveLen(3)) 297 | Expect(result.Layers[1].Name()).To(Equal("gradle-properties")) 298 | Expect(result.Layers[1]) 299 | }) 300 | 301 | it("adds the hash of gradle.properties to the layer metadata", func() { 302 | result, err := gradleBuild.Build(ctx) 303 | Expect(err).NotTo(HaveOccurred()) 304 | 305 | md := result.Layers[2].(libbs.Application).LayerContributor.ExpectedMetadata 306 | mdMap, ok := md.(map[string]interface{}) 307 | Expect(ok).To(BeTrue()) 308 | // expected: sha256 of the string "gradle-properties-content" 309 | expected := "6621087fb513e8db5544d34ccad59720793a1a5a9eb20a2df554422b8b5e50e5" 310 | Expect(mdMap["gradle-properties-sha256"]).To(Equal(expected)) 311 | }) 312 | }) 313 | 314 | context("gradle wrapper properties binding exists", func() { 315 | var bindingPath string 316 | 317 | it.Before(func() { 318 | var err error 319 | ctx.StackID = "test-stack-id" 320 | ctx.Platform.Path, err = os.MkdirTemp("", "gradle-test-platform") 321 | Expect(err).NotTo(HaveOccurred()) 322 | Expect(os.WriteFile(gradlewFilepath, []byte{}, 0644)).To(Succeed()) 323 | bindingPath = filepath.Join(ctx.Platform.Path, "bindings", "some-gradle") 324 | ctx.Platform.Bindings = libcnb.Bindings{ 325 | { 326 | Name: "some-gradle", 327 | Type: "gradle-wrapper", 328 | Secret: map[string]string{"gradle-wrapper.properties": "gradle-wrapper-properties-content"}, 329 | Path: bindingPath, 330 | }, 331 | } 332 | gradlePropertiesPath, ok := ctx.Platform.Bindings[0].SecretFilePath("gradle-wrapper.properties") 333 | Expect(os.MkdirAll(filepath.Dir(gradlePropertiesPath), 0777)).To(Succeed()) 334 | Expect(ok).To(BeTrue()) 335 | Expect(os.WriteFile( 336 | gradlePropertiesPath, 337 | []byte("gradle-wrapper-properties-content"), 338 | 0644, 339 | )).To(Succeed()) 340 | }) 341 | 342 | it.After(func() { 343 | Expect(os.RemoveAll(ctx.Platform.Path)).To(Succeed()) 344 | }) 345 | 346 | it("contributes bound gradle-wrapper.properties", func() { 347 | result, err := gradleBuild.Build(ctx) 348 | Expect(err).NotTo(HaveOccurred()) 349 | 350 | Expect(result.Layers).To(HaveLen(3)) 351 | Expect(result.Layers[1].Name()).To(Equal("gradle-wrapper-properties")) 352 | Expect(result.Layers[1]) 353 | }) 354 | 355 | it("adds the hash of gradle-wrapper.properties to the layer metadata", func() { 356 | result, err := gradleBuild.Build(ctx) 357 | Expect(err).NotTo(HaveOccurred()) 358 | 359 | md := result.Layers[2].(libbs.Application).LayerContributor.ExpectedMetadata 360 | mdMap, ok := md.(map[string]interface{}) 361 | Expect(ok).To(BeTrue()) 362 | // expected: sha256 of the string "gradle-wrapper-properties-content" 363 | expected := "8d98502ceb9504c887b12cfba9427c5338d133a2f10613cb0137695ca09c7ddc" 364 | Expect(mdMap["gradle-wrapper-properties-sha256"]).To(Equal(expected)) 365 | }) 366 | }) 367 | 368 | } 369 | 370 | type FakeApplicationFactory struct{} 371 | 372 | func (f *FakeApplicationFactory) NewApplication( 373 | additionalMetdata map[string]interface{}, 374 | args []string, 375 | _ libbs.ArtifactResolver, 376 | _ libbs.Cache, 377 | command string, 378 | _ *libcnb.BOM, 379 | _ string, 380 | _ sbom.SBOMScanner, 381 | ) (libbs.Application, error) { 382 | contributor := libpak.NewLayerContributor( 383 | "Compiled Application", 384 | additionalMetdata, 385 | libcnb.LayerTypes{Cache: true}, 386 | ) 387 | return libbs.Application{ 388 | LayerContributor: contributor, 389 | Command: command, 390 | Arguments: args, 391 | }, nil 392 | } 393 | 394 | type FakeHomeDirectoryResolver struct { 395 | path string 396 | } 397 | 398 | func (f FakeHomeDirectoryResolver) Location() (string, error) { 399 | return f.path, nil 400 | } 401 | --------------------------------------------------------------------------------