Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion docs/docs/20-usage/20-workflow-syntax.md
Original file line number Diff line number Diff line change
Expand Up @@ -689,7 +689,10 @@ For more details and examples check the [Advanced usage docs](./90-advanced-usag

## `clone`

Woodpecker automatically configures a default clone step if it is not explicitly defined. If you are using the `local` backend, the [plugin-git](https://github.com/woodpecker-ci/plugin-git) binary must be in your `$PATH` for the default clone step to work. If this is not the case, you can still write a manual clone step.
Woodpecker automatically configures a default clone step if it is not explicitly defined.
If you are using the `local` backend, the [plugin-git](https://github.com/woodpecker-ci/plugin-git) binary from your `$PATH` is used for the default clone step.
If it is not in your `$PATH`, the agent downloads the release set by [`WOODPECKER_BACKEND_LOCAL_PLUGIN_GIT_VERSION`](../30-administration/10-configuration/11-backends/30-local.md#backend_local_plugin_git_version).
You can also write a manual clone step.

You can manually configure the clone step in your workflow to customize it:

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,3 +84,12 @@ Directory to create folders for workflows.
- Default: `true`

Sets `HOME`, `USERPROFILE` and related variables to an isolated directory for each workflow. If set to `false`, the user's own home directory is used and no netrc file is written.

---

### BACKEND_LOCAL_PLUGIN_GIT_VERSION

- Name: `WOODPECKER_BACKEND_LOCAL_PLUGIN_GIT_VERSION`
- Default: `latest`

The [plugin-git](https://github.com/woodpecker-ci/plugin-git/releases) release to download for the clone step if `plugin-git` is not in `$PATH`, for example `2.12.1`.
122 changes: 75 additions & 47 deletions pipeline/backend/local/clone.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,19 +17,28 @@ package local
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"os/exec"
"path/filepath"
"slices"
"strings"

"github.com/rs/zerolog/log"

"go.woodpecker-ci.org/woodpecker/v3/pipeline/backend/types"
)

// pluginGitReleaseAPI is the GitHub API endpoint of the plugin-git releases (overridden in tests).
var pluginGitReleaseAPI = "https://api.github.com/repos/woodpecker-ci/plugin-git/releases"

// errNotFound is returned by httpGet on a 404 response.
var errNotFound = errors.New("not found")

// checkGitCloneCap check if we have the git binary on hand.
func checkGitCloneCap() error {
_, err := exec.LookPath("git")
Expand Down Expand Up @@ -58,7 +67,7 @@ func (e *local) setupClone(ctx context.Context, state *workflowState) error {
if e.os == "windows" {
state.pluginGitBinary += ".exe"
}
return e.downloadLatestGitPluginBinary(ctx, state.pluginGitBinary)
return e.downloadGitPluginBinary(ctx, state.pluginGitBinary)
}

// execClone executes a clone-step locally.
Expand Down Expand Up @@ -140,63 +149,82 @@ func (e *local) writeNetRC(step *types.Step, state *workflowState) (string, erro
return rmCmd, os.WriteFile(file, []byte(genNetRC(step.Environment)), 0o600)
}

// downloadLatestGitPluginBinary download the latest plugin-git binary based on runtime OS and Arch
// and saves it to dest.
func (e *local) downloadLatestGitPluginBinary(ctx context.Context, dest string) error {
type asset struct {
Name string
BrowserDownloadURL string `json:"browser_download_url"`
// downloadGitPluginBinary downloads the plugin-git binary of the configured release for the
// runtime OS and Arch and saves it to dest.
func (e *local) downloadGitPluginBinary(ctx context.Context, dest string) error {
version := e.pluginGitVersion
if version == "" {
version = "latest"
}

type release struct {
Assets []asset
releaseURL := pluginGitReleaseAPI + "/latest"
if version != "latest" {
releaseURL = pluginGitReleaseAPI + "/tags/" + url.PathEscape(version)
}

// get latest release
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, "https://api.github.com/repos/woodpecker-ci/plugin-git/releases/latest", nil)
req.Header.Set("Accept", "application/vnd.github+json")
req.Header.Set("X-GitHub-Api-Version", "2022-11-28")
resp, err := http.DefaultClient.Do(req)
raw, err := httpGet(ctx, releaseURL)
if errors.Is(err, errNotFound) {
return fmt.Errorf("plugin-git release '%s' does not exist", version)
}
if err != nil {
return fmt.Errorf("could not get latest release: %w", err)
return fmt.Errorf("could not get plugin-git release '%s': %w", version, err)
}
raw, _ := io.ReadAll(resp.Body)
Comment thread
6543 marked this conversation as resolved.
Resolved
_ = resp.Body.Close()
var rel release
if err := json.Unmarshal(raw, &rel); err != nil {

var release struct {
Assets []struct {
Name string `json:"name"`
BrowserDownloadURL string `json:"browser_download_url"`
} `json:"assets"`
}
if err := json.Unmarshal(raw, &release); err != nil {
return fmt.Errorf("could not unmarshal github response: %w", err)
}

for _, at := range rel.Assets {
if strings.Contains(at.Name, e.os) && strings.Contains(at.Name, e.arch) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, at.BrowserDownloadURL, nil)
if err != nil {
return err
}
assetResp, err := http.DefaultClient.Do(req)
if err != nil {
return fmt.Errorf("could not download plugin-git: %w", err)
}
defer assetResp.Body.Close()

file, err := os.Create(dest)
if err != nil {
return fmt.Errorf("could not create plugin-git: %w", err)
}
defer file.Close()

if _, err := io.Copy(file, assetResp.Body); err != nil {
return fmt.Errorf("could not download plugin-git: %w", err)
}
if err := os.Chmod(dest, 0o755); err != nil {
return err
}
for _, asset := range release.Assets {
if !matchesPlatform(asset.Name, e.os, e.arch) {
continue
}

// download successful
log.Trace().Msgf("download of 'plugin-git' to '%s' successful", dest)
return nil
binary, err := httpGet(ctx, asset.BrowserDownloadURL)
if err != nil {
return fmt.Errorf("could not download plugin-git: %w", err)
}
if err := os.WriteFile(dest, binary, 0o755); err != nil {
return fmt.Errorf("could not write plugin-git: %w", err)
}

log.Trace().Msgf("download of 'plugin-git' %s to '%s' successful", version, dest)
return nil
}

return fmt.Errorf("could not download plugin-git, binary for this os/arch not found")
return fmt.Errorf("plugin-git release '%s' has no binary for %s/%s", version, e.os, e.arch)
}

// matchesPlatform reports whether an asset name contains os and arch as separate parts,
// so "linux-arm_plugin-git" matches linux/arm but "linux-arm64_plugin-git" does not.
Comment thread
6543 marked this conversation as resolved.
Resolved
func matchesPlatform(name, os, arch string) bool {
parts := strings.FieldsFunc(name, func(r rune) bool {
return r == '-' || r == '_' || r == '.'
})
return slices.Contains(parts, os) && slices.Contains(parts, arch)
}

// httpGet returns the body of a GET request and fails on non-200 responses.
func httpGet(ctx context.Context, url string) ([]byte, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusNotFound {
return nil, fmt.Errorf("GET %s: %w", url, errNotFound)
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("GET %s: unexpected status %s", url, resp.Status)
}
return io.ReadAll(resp.Body)
}
92 changes: 92 additions & 0 deletions pipeline/backend/local/clone_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
// Copyright 2026 Woodpecker Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package local

import (
"fmt"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestDownloadGitPluginBinary(t *testing.T) {
binary := []byte("plugin-git binary")

tests := []struct {
name string
arch string
version string
assetCode int
wantAsset string
wantErr string
}{
{name: "latest", arch: "arm64", assetCode: http.StatusOK, wantAsset: "/assets/linux-arm64_plugin-git"},
{name: "pinned version", arch: "arm64", version: "2.12.1", assetCode: http.StatusOK, wantAsset: "/assets/linux-arm64_plugin-git"},
{name: "arm does not match arm64", arch: "arm", assetCode: http.StatusOK, wantAsset: "/assets/linux-arm_plugin-git"},
{name: "unknown version", arch: "arm64", version: "0.0.0", wantErr: "plugin-git release '0.0.0' does not exist"},
{name: "unsupported arch", arch: "386", wantErr: "plugin-git release 'latest' has no binary for linux/386"},
{name: "asset download error", arch: "arm64", assetCode: http.StatusBadGateway, wantErr: "unexpected status 502"},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var gotAsset string
mux := http.NewServeMux()
srv := httptest.NewServer(mux)
defer srv.Close()

release := func(w http.ResponseWriter, _ *http.Request) {
// arm64 is listed before arm, like in the real releases
fmt.Fprintf(w, `{"assets":[
{"name":"checksums.txt","browser_download_url":"%[1]s/assets/checksums.txt"},
{"name":"linux-amd64_plugin-git","browser_download_url":"%[1]s/assets/linux-amd64_plugin-git"},
{"name":"linux-arm64_plugin-git","browser_download_url":"%[1]s/assets/linux-arm64_plugin-git"},
{"name":"linux-arm_plugin-git","browser_download_url":"%[1]s/assets/linux-arm_plugin-git"}
]}`, srv.URL)
}
mux.HandleFunc("/releases/latest", release)
mux.HandleFunc("/releases/tags/2.12.1", release)
mux.HandleFunc("/assets/", func(w http.ResponseWriter, r *http.Request) {
gotAsset = r.URL.Path
w.WriteHeader(tt.assetCode)
_, _ = w.Write(binary)
})

orig := pluginGitReleaseAPI
pluginGitReleaseAPI = srv.URL + "/releases"
defer func() { pluginGitReleaseAPI = orig }()

e := &local{os: "linux", arch: tt.arch, pluginGitVersion: tt.version}
dest := filepath.Join(t.TempDir(), "plugin-git")
err := e.downloadGitPluginBinary(t.Context(), dest)

if tt.wantErr != "" {
assert.ErrorContains(t, err, tt.wantErr)
assert.NoFileExists(t, dest)
return
}
require.NoError(t, err)
assert.Equal(t, tt.wantAsset, gotAsset)
content, err := os.ReadFile(dest)
require.NoError(t, err)
assert.Equal(t, binary, content)
})
}
}
6 changes: 6 additions & 0 deletions pipeline/backend/local/flags.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,10 @@ var Flags = []cli.Flag{
Usage: "set HOME, USERPROFILE and other variables to an isolated directory, if false we ignore netrc",
Value: true,
},
&cli.StringFlag{
Sources: cli.EnvVars("WOODPECKER_BACKEND_LOCAL_PLUGIN_GIT_VERSION"),
Name: "backend-local-plugin-git-version",
Usage: "plugin-git release to download if plugin-git is not in $PATH",
Value: "latest",
},
}
12 changes: 7 additions & 5 deletions pipeline/backend/local/local.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,11 +46,12 @@ type stepState struct {
}

type local struct {
tempDir string
isolatedHome bool
workflows sync.Map
pluginGitBinary string
os, arch string
tempDir string
isolatedHome bool
workflows sync.Map
pluginGitBinary string
pluginGitVersion string
os, arch string
}

var CLIWorkaroundExecAtDir string // To handle edge case for running local backend via cli exec
Expand Down Expand Up @@ -86,6 +87,7 @@ func (e *local) Load(ctx context.Context) (*types.BackendInfo, error) {
if ok {
e.tempDir = c.String("backend-local-temp-dir")
e.isolatedHome = c.Bool("backend-local-isolated-home")
e.pluginGitVersion = c.String("backend-local-plugin-git-version")
}

e.loadClone()
Expand Down