0
0
mirror of https://github.com/thegeeklab/wp-git-action.git synced 2024-06-02 18:29:41 +02:00

Compare commits

...

29 Commits
v2.0.2 ... main

Author SHA1 Message Date
renovate[bot]
366e5682ae
chore(deps): update docker.io/library/alpine docker tag to v3.20 (#124)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2024-06-01 13:21:40 +02:00
renovate[bot]
248c5fb81b chore(deps): update dependency golangci/golangci-lint to v1.59.0 2024-05-27 04:04:50 +00:00
renovate[bot]
31a66da658
fix(deps): update module github.com/rs/zerolog to v1.33.0 (#125)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2024-05-24 09:37:58 +02:00
renovate[bot]
6f326d055b chore(docker): update docker.io/library/golang:1.22 docker digest to f43c6f0 2024-05-18 07:47:17 +00:00
99812a77c7
chore: migrate to wp-plugin-go v3 (#121) 2024-05-17 21:49:59 +02:00
renovate[bot]
9beccd28de
chore(docker): update docker.io/library/golang:1.22 docker digest to 91ad6f9 (#120)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2024-05-16 13:40:58 +02:00
5a85b78897
fix: revert to adhoc commands for actions (#119) 2024-05-14 13:39:04 +02:00
c1402d7c33
fix: disable cmd trace for git config commands (#118) 2024-05-14 10:19:04 +02:00
c97278aa5a
ci: fix golangci-lint deprecations 2024-05-12 11:08:25 +02:00
fcf2d25be2
rename action type 2024-05-08 12:45:24 +02:00
renovate[bot]
51113c4d34
chore(docker): update docker.io/library/golang:1.22 docker digest to b1e05e2 (#117)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2024-05-08 08:34:40 +02:00
98d75d4493
fix: check is cmd is nil before execution (#116) 2024-05-07 11:57:18 +02:00
5930a2ad75
fix: fix command exec order (#115) 2024-05-06 22:43:56 +02:00
dbc0ea945b
chore: pass ssh key to git config instead of file (#114) 2024-05-06 22:17:45 +02:00
a07e0d2ef6
cleanup import 2024-05-06 21:27:23 +02:00
e8dee1de8e
use assert instead of require 2024-05-06 21:04:48 +02:00
198aab7784
refactor: use struct receiver (#112) 2024-05-06 20:29:57 +02:00
c2608f913f
fix: use repo.Branch to init new repo (#110) 2024-05-06 08:52:25 +02:00
renovate[bot]
922b204862 chore(deps): update dependency golangci/golangci-lint to v1.58.0 2024-05-06 05:04:26 +00:00
179014e52e
refactor: rework batch command execution (#109) 2024-05-05 22:14:55 +02:00
renovate[bot]
92a7c252d2
fix(deps): update module github.com/urfave/cli/v2 to v2.27.2 (#105)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2024-04-29 10:26:08 +02:00
renovate[bot]
b95656cfcd chore(docker): update docker.io/library/golang:1.22 docker digest to d5302d4 2024-04-25 04:13:32 +00:00
renovate[bot]
cdc3f19368
fix(deps): update module github.com/thegeeklab/wp-plugin-go to v1.7.1 (#103)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2024-04-22 12:36:43 +02:00
renovate[bot]
44808d607e chore(docker): update docker.io/library/golang:1.22 docker digest to 450e382 2024-04-11 06:51:32 +00:00
renovate[bot]
3240432f59 chore(docker): update docker.io/library/golang:1.22 docker digest to 3cb9b4d 2024-04-10 07:32:09 +00:00
renovate[bot]
25c79e1080
fix(deps): update module golang.org/x/sys to v0.19.0 (#100)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2024-04-05 08:52:36 +02:00
renovate[bot]
e4f64bd81c chore(docker): update docker.io/library/golang:1.22 docker digest to c4fb952 2024-04-04 03:02:26 +00:00
renovate[bot]
ae0b8fd6d7 chore(deps): update dependency golangci/golangci-lint to v1.57.2 2024-04-01 03:26:31 +00:00
renovate[bot]
d16b1d4549
chore(deps): update quay.io/thegeeklab/wp-docker-buildx docker tag to v4 (#97)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2024-03-27 08:43:01 +01:00
33 changed files with 1232 additions and 797 deletions

View File

@ -23,7 +23,6 @@ linters:
- errchkjson
- errname
- errorlint
- execinquery
- exhaustive
- exportloopref
- forcetypeassert
@ -37,12 +36,12 @@ linters:
- gocyclo
- godot
- godox
- goerr113
- err113
- gofmt
- gofumpt
- goheader
- goimports
- gomnd
- mnd
- gomoddirectives
- gomodguard
- goprintffuncname

View File

@ -7,7 +7,7 @@ when:
steps:
- name: dryrun
image: quay.io/thegeeklab/wp-docker-buildx:3
image: quay.io/thegeeklab/wp-docker-buildx:4
settings:
containerfile: Containerfile.multiarch
dry_run: true
@ -20,7 +20,7 @@ steps:
- event: [pull_request]
- name: publish-dockerhub
image: quay.io/thegeeklab/wp-docker-buildx:3
image: quay.io/thegeeklab/wp-docker-buildx:4
group: container
settings:
auto_tag: true
@ -41,7 +41,7 @@ steps:
- ${CI_REPO_DEFAULT_BRANCH}
- name: publish-quay
image: quay.io/thegeeklab/wp-docker-buildx:3
image: quay.io/thegeeklab/wp-docker-buildx:4
group: container
settings:
auto_tag: true

View File

@ -1,4 +1,4 @@
FROM --platform=$BUILDPLATFORM docker.io/library/golang:1.22@sha256:0b55ab82ac2a54a6f8f85ec8b943b9e470c39e32c109b766bbc1b801f3fa8d3b as build
FROM --platform=$BUILDPLATFORM docker.io/library/golang:1.22@sha256:f43c6f049f04cbbaeb28f0aad3eea15274a7d0a7899a617d0037aec48d7ab010 as build
ARG TARGETOS
ARG TARGETARCH
@ -8,7 +8,7 @@ WORKDIR /src
RUN make build
FROM docker.io/library/alpine:3.19@sha256:c5b1261d6d3e43071626931fc004f70149baeba2c8ec672bd4f27761f8e1ad6b
FROM docker.io/library/alpine:3.20@sha256:77726ef6b57ddf65bb551896826ec38bc3e53f75cdde31354fbffb4f25238ebd
LABEL maintainer="Robert Kaussow <mail@thegeeklab.de>"
LABEL org.opencontainers.image.authors="Robert Kaussow <mail@thegeeklab.de>"

View File

@ -1,7 +1,7 @@
# renovate: datasource=github-releases depName=mvdan/gofumpt
GOFUMPT_PACKAGE_VERSION := v0.6.0
# renovate: datasource=github-releases depName=golangci/golangci-lint
GOLANGCI_LINT_PACKAGE_VERSION := v1.57.1
GOLANGCI_LINT_PACKAGE_VERSION := v1.59.0
EXECUTABLE := wp-git-action
@ -19,7 +19,6 @@ GOLANGCI_LINT_PACKAGE ?= github.com/golangci/golangci-lint/cmd/golangci-lint@$(G
XGO_PACKAGE ?= src.techknowlogick.com/xgo@latest
GOTESTSUM_PACKAGE ?= gotest.tools/gotestsum@latest
GENERATE ?=
XGO_VERSION := go-1.22.x
XGO_TARGETS ?= linux/amd64,linux/arm-6,linux/arm-7,linux/arm64
@ -65,12 +64,7 @@ lint: golangci-lint
.PHONY: generate
generate:
$(GO) generate $(GENERATE)
.PHONY: generate-docs
generate-docs:
$(GO) generate ./cmd/$(EXECUTABLE)/flags.go
$(GO) generate $(PACKAGES)
.PHONY: test
test:

View File

@ -1,58 +0,0 @@
//go:build generate
// +build generate
package main
import (
"bytes"
"embed"
"fmt"
"os"
"text/template"
"github.com/thegeeklab/wp-git-action/plugin"
"github.com/thegeeklab/wp-plugin-go/docs"
wp "github.com/thegeeklab/wp-plugin-go/plugin"
wp_template "github.com/thegeeklab/wp-plugin-go/template"
"github.com/urfave/cli/v2"
)
//go:embed templates/docs-data.yaml.tmpl
var yamlTemplate embed.FS
func main() {
settings := &plugin.Settings{}
app := &cli.App{
Flags: settingsFlags(settings, wp.FlagsPluginCategory),
}
out, err := toYAML(app)
if err != nil {
panic(err)
}
fi, err := os.Create("../../docs/data/data-raw.yaml")
if err != nil {
panic(err)
}
defer fi.Close()
if _, err := fi.WriteString(out); err != nil {
panic(err)
}
}
func toYAML(app *cli.App) (string, error) {
var w bytes.Buffer
yamlTmpl, err := template.New("docs").Funcs(wp_template.LoadFuncMap()).ParseFS(yamlTemplate, "templates/docs-data.yaml.tmpl")
if err != nil {
fmt.Println(yamlTmpl)
return "", err
}
if err := yamlTmpl.ExecuteTemplate(&w, "docs-data.yaml.tmpl", docs.GetTemplateData(app)); err != nil {
return "", err
}
return w.String(), nil
}

View File

@ -1,163 +0,0 @@
package main
import (
"github.com/thegeeklab/wp-git-action/plugin"
"github.com/urfave/cli/v2"
)
// settingsFlags has the cli.Flags for the plugin.Settings.
//
//go:generate go run docs.go flags.go
func settingsFlags(settings *plugin.Settings, category string) []cli.Flag {
return []cli.Flag{
&cli.StringSliceFlag{
Name: "action",
Usage: "git action to execute",
EnvVars: []string{"PLUGIN_ACTION"},
Destination: &settings.Action,
Required: true,
Category: category,
},
&cli.StringFlag{
Name: "author-name",
Usage: "git author name",
EnvVars: []string{"PLUGIN_AUTHOR_NAME", "CI_COMMIT_AUTHOR"},
Destination: &settings.Repo.Author.Name,
Required: true,
Category: category,
},
&cli.StringFlag{
Name: "author-email",
Usage: "git author email",
EnvVars: []string{"PLUGIN_AUTHOR_EMAIL", "CI_COMMIT_AUTHOR_EMAIL"},
Destination: &settings.Repo.Author.Email,
Required: true,
Category: category,
},
&cli.StringFlag{
Name: "netrc.machine",
Usage: "netrc remote machine name",
EnvVars: []string{"PLUGIN_NETRC_MACHINE", "CI_NETRC_MACHINE"},
Destination: &settings.Netrc.Machine,
Value: "github.com",
Category: category,
},
&cli.StringFlag{
Name: "netrc.username",
Usage: "netrc login user on the remote machine",
EnvVars: []string{"PLUGIN_NETRC_USERNAME", "CI_NETRC_USERNAME"},
Destination: &settings.Netrc.Login,
Value: "token",
Category: category,
},
&cli.StringFlag{
Name: "netrc.password",
Usage: "netrc login password on the remote machine",
EnvVars: []string{"PLUGIN_NETRC_PASSWORD", "CI_NETRC_PASSWORD"},
Destination: &settings.Netrc.Password,
Category: category,
},
&cli.StringFlag{
Name: "ssh-key",
Usage: "ssh private key for the remote repository",
EnvVars: []string{"PLUGIN_SSH_KEY"},
Destination: &settings.SSHKey,
Category: category,
},
&cli.StringFlag{
Name: "remote-url",
Usage: "url of the remote repository",
EnvVars: []string{"PLUGIN_REMOTE_URL", "CI_REPO_CLONE_URL"},
Destination: &settings.Repo.RemoteURL,
Category: category,
},
&cli.StringFlag{
Name: "branch",
Usage: "name of the git source branch",
EnvVars: []string{"PLUGIN_BRANCH"},
Destination: &settings.Repo.Branch,
Value: "main",
Category: category,
},
&cli.StringFlag{
Name: "path",
Usage: "path to clone git repository",
EnvVars: []string{"PLUGIN_PATH"},
Destination: &settings.Repo.WorkDir,
Category: category,
},
&cli.StringFlag{
Name: "commit-message",
Usage: "commit message",
EnvVars: []string{"PLUGIN_MESSAGE"},
Destination: &settings.Repo.CommitMsg,
Value: "[skip ci] commit dirty state",
Category: category,
},
&cli.BoolFlag{
Name: "force-push",
Usage: "enable force push to remote repository",
EnvVars: []string{"PLUGIN_FORCE"},
Destination: &settings.Repo.ForcePush,
Value: false,
Category: category,
},
&cli.BoolFlag{
Name: "followtags",
Usage: "follow tags for pushes to remote repository",
EnvVars: []string{"PLUGIN_FOLLOWTAGS"},
Destination: &settings.Repo.PushFollowTags,
Value: false,
Category: category,
},
&cli.BoolFlag{
Name: "insecure-skip-ssl-verify",
Usage: "skip ssl verification of the remote machine",
EnvVars: []string{"PLUGIN_INSECURE_SKIP_SSL_VERIFY"},
Destination: &settings.Repo.InsecureSkipSSLVerify,
Value: false,
Category: category,
},
&cli.BoolFlag{
Name: "empty-commit",
Usage: "allow empty commits",
EnvVars: []string{"PLUGIN_EMPTY_COMMIT"},
Destination: &settings.Repo.EmptyCommit,
Value: false,
Category: category,
},
&cli.BoolFlag{
Name: "no-verify",
Usage: "bypass the pre-commit and commit-msg hooks",
EnvVars: []string{"PLUGIN_NO_VERIFY"},
Destination: &settings.Repo.NoVerify,
Value: false,
Category: category,
},
&cli.StringFlag{
Name: "pages.directory",
Usage: "source directory to be synchronized with the pages banch",
EnvVars: []string{"PLUGIN_PAGES_DIRECTORY"},
Destination: &settings.Pages.Directory,
Value: "docs/",
Category: category,
},
&cli.StringSliceFlag{
Name: "pages.exclude",
Usage: "files or directories to exclude from the pages rsync command",
EnvVars: []string{"PLUGIN_PAGES_EXCLUDE"},
Destination: &settings.Pages.Exclude,
Category: category,
},
&cli.BoolFlag{
Name: "pages.delete",
Usage: "add delete flag to pages rsync command",
EnvVars: []string{"PLUGIN_PAGES_DELETE"},
Destination: &settings.Pages.Delete,
Value: true,
Category: category,
},
}
}

View File

@ -1,10 +1,7 @@
package main
import (
"fmt"
"github.com/thegeeklab/wp-git-action/plugin"
wp "github.com/thegeeklab/wp-plugin-go/plugin"
)
//nolint:gochecknoglobals
@ -14,14 +11,5 @@ var (
)
func main() {
settings := &plugin.Settings{}
options := wp.Options{
Name: "wp-git-action",
Description: "Perform git actions.",
Version: BuildVersion,
VersionMetadata: fmt.Sprintf("date=%s", BuildDate),
Flags: settingsFlags(settings, wp.FlagsPluginCategory),
}
plugin.New(options, settings).Run()
plugin.New(nil, BuildVersion, BuildDate).Run()
}

View File

@ -1,18 +0,0 @@
---
{{- if .GlobalArgs }}
properties:
{{- range $v := .GlobalArgs }}
- name: {{ $v.Name }}
{{- with $v.Description }}
description: |
{{ . | ToSentence }}
{{- end }}
{{- with $v.Type }}
type: {{ . }}
{{- end }}
{{- with $v.Default }}
defaultValue: {{ . }}
{{- end }}
required: {{ default false $v.Required }}
{{ end -}}
{{ end -}}

View File

@ -60,15 +60,22 @@ properties:
defaultValue: false
required: false
- name: insecure_skip_ssl_verify
- name: insecure_skip_verify
description: |
Skip ssl verification of the remote machine.
Skip SSL verification.
Activating this option is insecure and should be avoided in most cases.
type: bool
defaultValue: false
required: false
- name: log_level
description: |
Plugin log level.
type: string
defaultValue: "info"
required: false
- name: message
description: |
Commit message.

View File

@ -4,41 +4,37 @@ import (
"fmt"
"os"
"golang.org/x/sys/execabs"
plugin_exec "github.com/thegeeklab/wp-plugin-go/v3/exec"
)
// FetchSource fetches the source from remote.
func FetchSource(repo Repository) *execabs.Cmd {
func (r *Repository) FetchSource() *plugin_exec.Cmd {
args := []string{
"fetch",
"origin",
fmt.Sprintf("+%s:", repo.Branch),
fmt.Sprintf("+%s:", r.Branch),
}
cmd := execabs.Command(
gitBin,
args...,
)
cmd.Dir = repo.WorkDir
cmd := plugin_exec.Command(gitBin, args...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Dir = r.WorkDir
return cmd
}
// CheckoutHead handles branch checkout.
func CheckoutHead(repo Repository) *execabs.Cmd {
func (r *Repository) CheckoutHead() *plugin_exec.Cmd {
args := []string{
"checkout",
"-qf",
repo.Branch,
r.Branch,
}
cmd := execabs.Command(
gitBin,
args...,
)
cmd.Dir = repo.WorkDir
cmd := plugin_exec.Command(gitBin, args...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Dir = r.WorkDir
return cmd
}

73
git/clone_test.go Normal file
View File

@ -0,0 +1,73 @@
package git
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestFetchSource(t *testing.T) {
tests := []struct {
name string
repo Repository
want []string
}{
{
name: "fetch from origin with branch",
repo: Repository{
WorkDir: "/path/to/repo",
Branch: "main",
},
want: []string{gitBin, "fetch", "origin", "+main:"},
},
{
name: "fetch from origin with different branch",
repo: Repository{
WorkDir: "/path/to/repo",
Branch: "develop",
},
want: []string{gitBin, "fetch", "origin", "+develop:"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cmd := tt.repo.FetchSource()
assert.Equal(t, tt.want, cmd.Cmd.Args)
assert.Equal(t, tt.repo.WorkDir, cmd.Cmd.Dir)
})
}
}
func TestCheckoutHead(t *testing.T) {
tests := []struct {
name string
repo Repository
want []string
}{
{
name: "checkout head with branch",
repo: Repository{
WorkDir: "/path/to/repo",
Branch: "main",
},
want: []string{gitBin, "checkout", "-qf", "main"},
},
{
name: "checkout head with different branch",
repo: Repository{
WorkDir: "/path/to/repo",
Branch: "develop",
},
want: []string{gitBin, "checkout", "-qf", "develop"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cmd := tt.repo.CheckoutHead()
assert.Equal(t, tt.want, cmd.Cmd.Args)
assert.Equal(t, tt.repo.WorkDir, cmd.Cmd.Dir)
})
}
}

View File

@ -3,97 +3,55 @@ package git
import (
"os"
"golang.org/x/sys/execabs"
plugin_exec "github.com/thegeeklab/wp-plugin-go/v3/exec"
)
// ForceAdd forces the addition of all dirty files.
func ForceAdd(repo Repository) *execabs.Cmd {
cmd := execabs.Command(
gitBin,
"add",
"--all",
"--force",
)
cmd.Dir = repo.WorkDir
cmd.Stderr = os.Stderr
return cmd
}
// Add updates the index to match the working tree.
func Add(repo Repository) *execabs.Cmd {
cmd := execabs.Command(
gitBin,
"add",
)
cmd.Dir = repo.WorkDir
func (r *Repository) Add() *plugin_exec.Cmd {
cmd := plugin_exec.Command(gitBin, "add", "--all")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if repo.Add != "" {
cmd.Args = append(cmd.Args, repo.Add)
} else {
cmd.Args = append(cmd.Args, "--all")
}
cmd.Dir = r.WorkDir
return cmd
}
// TestCleanTree returns non-zero if diff between index and local repository.
func TestCleanTree(repo Repository) *execabs.Cmd {
cmd := execabs.Command(
gitBin,
// IsCleanTree returns non-zero if diff between index and local repository.
func (r *Repository) IsCleanTree() *plugin_exec.Cmd {
args := []string{
"diff-index",
"--quiet",
"HEAD",
"--ignore-submodules",
)
cmd.Dir = repo.WorkDir
cmd.Stderr = os.Stderr
}
cmd := plugin_exec.Command(gitBin, args...)
cmd.Dir = r.WorkDir
cmd.Trace = false
return cmd
}
// EmptyCommit simply create an empty commit.
func EmptyCommit(repo Repository) *execabs.Cmd {
args := []string{
"commit",
"--allow-empty",
"-m",
repo.CommitMsg,
}
cmd := execabs.Command(
gitBin,
args...,
)
cmd.Dir = repo.WorkDir
cmd.Stderr = os.Stderr
if repo.NoVerify {
cmd.Args = append(cmd.Args, "--no-verify")
}
return cmd
}
// ForceCommit commits every change while skipping CI.
func ForceCommit(repo Repository) *execabs.Cmd {
// Commit creates a new commit with the specified commit message.
func (r *Repository) Commit() *plugin_exec.Cmd {
args := []string{
"commit",
"-m",
repo.CommitMsg,
r.CommitMsg,
}
cmd := execabs.Command(
gitBin,
args...,
)
cmd.Dir = repo.WorkDir
if r.EmptyCommit {
args = append(args, "--allow-empty")
}
if r.NoVerify {
args = append(args, "--no-verify")
}
cmd := plugin_exec.Command(gitBin, args...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if repo.NoVerify {
cmd.Args = append(cmd.Args, "--no-verify")
}
cmd.Dir = r.WorkDir
return cmd
}

105
git/commit_test.go Normal file
View File

@ -0,0 +1,105 @@
package git
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestAdd(t *testing.T) {
tests := []struct {
name string
repo Repository
want []string
}{
{
name: "add all files",
repo: Repository{
WorkDir: "/path/to/repo",
},
want: []string{gitBin, "add", "--all"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cmd := tt.repo.Add()
assert.Equal(t, tt.want, cmd.Cmd.Args)
assert.Equal(t, tt.repo.WorkDir, cmd.Cmd.Dir)
})
}
}
func TestIsCleanTree(t *testing.T) {
tests := []struct {
name string
repo Repository
want []string
}{
{
name: "clean working tree",
repo: Repository{
WorkDir: "/path/to/repo",
},
want: []string{gitBin, "diff-index", "--quiet", "HEAD", "--ignore-submodules"},
},
{
name: "unclean working tree",
repo: Repository{
WorkDir: "/path/to/unclean/repo",
},
want: []string{gitBin, "diff-index", "--quiet", "HEAD", "--ignore-submodules"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cmd := tt.repo.IsCleanTree()
assert.Equal(t, tt.want, cmd.Cmd.Args)
assert.Equal(t, tt.repo.WorkDir, cmd.Cmd.Dir)
})
}
}
func TestCommit(t *testing.T) {
tests := []struct {
name string
repo Repository
want []string
}{
{
name: "commit with message",
repo: Repository{
WorkDir: "/path/to/repo",
CommitMsg: "Initial commit",
},
want: []string{gitBin, "commit", "-m", "Initial commit"},
},
{
name: "commit with empty commit",
repo: Repository{
WorkDir: "/path/to/repo",
CommitMsg: "Empty commit",
EmptyCommit: true,
},
want: []string{gitBin, "commit", "-m", "Empty commit", "--allow-empty"},
},
{
name: "commit with no verify",
repo: Repository{
WorkDir: "/path/to/repo",
CommitMsg: "No verify commit",
NoVerify: true,
},
want: []string{gitBin, "commit", "-m", "No verify commit", "--no-verify"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cmd := tt.repo.Commit()
assert.Equal(t, tt.want, cmd.Cmd.Args)
assert.Equal(t, tt.repo.WorkDir, cmd.Cmd.Dir)
})
}
}

View File

@ -1,84 +1,88 @@
package git
import (
"os"
"strconv"
"golang.org/x/sys/execabs"
plugin_exec "github.com/thegeeklab/wp-plugin-go/v3/exec"
)
// repoUserEmail sets the global git author email.
func ConfigAutocorrect(repo Repository) *execabs.Cmd {
// ConfigAutocorrect sets the local git autocorrect configuration for the given repository.
// The autocorrect setting determines how git handles minor typos in commands.
func (r *Repository) ConfigAutocorrect() *plugin_exec.Cmd {
args := []string{
"config",
"--local",
"help.autocorrect",
repo.Autocorrect,
r.Autocorrect,
}
cmd := execabs.Command(
gitBin,
args...,
)
cmd.Dir = repo.WorkDir
cmd.Stderr = os.Stderr
cmd := plugin_exec.Command(gitBin, args...)
cmd.Dir = r.WorkDir
cmd.Trace = false
return cmd
}
// repoUserEmail sets the global git author email.
func ConfigUserEmail(repo Repository) *execabs.Cmd {
// ConfigUserEmail sets the global git author email.
func (r *Repository) ConfigUserEmail() *plugin_exec.Cmd {
args := []string{
"config",
"--local",
"user.email",
repo.Author.Email,
r.Author.Email,
}
cmd := execabs.Command(
gitBin,
args...,
)
cmd.Dir = repo.WorkDir
cmd.Stderr = os.Stderr
cmd := plugin_exec.Command(gitBin, args...)
cmd.Dir = r.WorkDir
cmd.Trace = false
return cmd
}
// repoUserName sets the global git author name.
func ConfigUserName(repo Repository) *execabs.Cmd {
// ConfigUserName configures the user.name git config setting for the given repository.
func (r *Repository) ConfigUserName() *plugin_exec.Cmd {
args := []string{
"config",
"--local",
"user.name",
repo.Author.Name,
r.Author.Name,
}
cmd := execabs.Command(
gitBin,
args...,
)
cmd.Dir = repo.WorkDir
cmd.Stderr = os.Stderr
cmd := plugin_exec.Command(gitBin, args...)
cmd.Dir = r.WorkDir
cmd.Trace = false
return cmd
}
// ConfigSSLVerify disables globally the git ssl verification.
func ConfigSSLVerify(repo Repository) *execabs.Cmd {
// ConfigSSLVerify configures the http.sslVerify git config setting for the given repository.
func (r *Repository) ConfigSSLVerify(skipVerify bool) *plugin_exec.Cmd {
args := []string{
"config",
"--local",
"http.sslVerify",
strconv.FormatBool(!repo.InsecureSkipSSLVerify),
strconv.FormatBool(!skipVerify),
}
cmd := execabs.Command(
gitBin,
args...,
)
cmd.Dir = repo.WorkDir
cmd.Stderr = os.Stderr
cmd := plugin_exec.Command(gitBin, args...)
cmd.Dir = r.WorkDir
cmd.Trace = false
return cmd
}
// ConfigSSHCommand sets custom SSH key.
func (r *Repository) ConfigSSHCommand(sshKey string) *plugin_exec.Cmd {
args := []string{
"config",
"--local",
"core.sshCommand",
"ssh -i " + sshKey,
}
cmd := plugin_exec.Command(gitBin, args...)
cmd.Dir = r.WorkDir
cmd.Trace = false
return cmd
}

147
git/config_test.go Normal file
View File

@ -0,0 +1,147 @@
package git
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestConfigAutocorrect(t *testing.T) {
tests := []struct {
name string
repo Repository
want []string
}{
{
name: "enable autocorrect",
repo: Repository{
WorkDir: "/path/to/repo",
Autocorrect: "1",
},
want: []string{gitBin, "config", "--local", "help.autocorrect", "1"},
},
{
name: "disable autocorrect",
repo: Repository{
WorkDir: "/path/to/repo",
Autocorrect: "0",
},
want: []string{gitBin, "config", "--local", "help.autocorrect", "0"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cmd := tt.repo.ConfigAutocorrect()
assert.Equal(t, tt.want, cmd.Cmd.Args)
assert.Equal(t, tt.repo.WorkDir, cmd.Cmd.Dir)
})
}
}
func TestConfigUserEmail(t *testing.T) {
tests := []struct {
name string
repo Repository
want []string
}{
{
name: "set user email",
repo: Repository{
WorkDir: "/path/to/repo",
Author: Author{
Email: "user@example.com",
},
},
want: []string{gitBin, "config", "--local", "user.email", "user@example.com"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cmd := tt.repo.ConfigUserEmail()
assert.Equal(t, tt.want, cmd.Cmd.Args)
assert.Equal(t, tt.repo.WorkDir, cmd.Cmd.Dir)
})
}
}
func TestConfigUserName(t *testing.T) {
tests := []struct {
name string
repo Repository
want []string
}{
{
name: "set user name",
repo: Repository{
WorkDir: "/path/to/repo",
Author: Author{
Name: "John Doe",
},
},
want: []string{gitBin, "config", "--local", "user.name", "John Doe"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cmd := tt.repo.ConfigUserName()
assert.Equal(t, tt.want, cmd.Cmd.Args)
assert.Equal(t, tt.repo.WorkDir, cmd.Cmd.Dir)
})
}
}
func TestConfigSSLVerify(t *testing.T) {
tests := []struct {
name string
repo Repository
skipVerify bool
want []string
}{
{
name: "enable SSL verification",
repo: Repository{WorkDir: "/path/to/repo"},
skipVerify: false,
want: []string{gitBin, "config", "--local", "http.sslVerify", "true"},
},
{
name: "disable SSL verification",
repo: Repository{WorkDir: "/path/to/repo"},
skipVerify: true,
want: []string{gitBin, "config", "--local", "http.sslVerify", "false"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cmd := tt.repo.ConfigSSLVerify(tt.skipVerify)
assert.Equal(t, tt.want, cmd.Cmd.Args)
assert.Equal(t, tt.repo.WorkDir, cmd.Cmd.Dir)
})
}
}
func TestConfigSSHCommand(t *testing.T) {
tests := []struct {
name string
repo Repository
sshKey string
want []string
}{
{
name: "set SSH command with key",
repo: Repository{},
sshKey: "/path/to/ssh/key",
want: []string{gitBin, "config", "--local", "core.sshCommand", "ssh -i /path/to/ssh/key"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cmd := tt.repo.ConfigSSHCommand(tt.sshKey)
assert.Equal(t, tt.want, cmd.Cmd.Args)
})
}
}

26
git/git.go Normal file
View File

@ -0,0 +1,26 @@
package git
type Author struct {
Name string
Email string
}
type Repository struct {
RemoteName string
RemoteURL string
Branch string
CommitMsg string
Autocorrect string
NoVerify bool
EmptyCommit bool
PushFollowTags bool
ForcePush bool
WorkDir string
IsEmpty bool
Author Author
}
const gitBin = "/usr/bin/git"

View File

@ -3,17 +3,21 @@ package git
import (
"os"
"golang.org/x/sys/execabs"
plugin_exec "github.com/thegeeklab/wp-plugin-go/v3/exec"
)
// RemoteRemove drops the defined remote from a git repo.
func Init(repo Repository) *execabs.Cmd {
cmd := execabs.Command(
gitBin,
// Init creates a new Git repository in the specified directory.
func (r *Repository) Init() *plugin_exec.Cmd {
args := []string{
"init",
)
cmd.Dir = repo.WorkDir
"-b",
r.Branch,
}
cmd := plugin_exec.Command(gitBin, args...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Dir = r.WorkDir
return cmd
}

32
git/init_test.go Normal file
View File

@ -0,0 +1,32 @@
package git
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestInit(t *testing.T) {
tests := []struct {
name string
repo Repository
expected []string
}{
{
name: "init repo",
repo: Repository{
WorkDir: "/path/to/repo",
Branch: "main",
},
expected: []string{gitBin, "init", "-b", "main"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cmd := tt.repo.Init()
assert.Equal(t, tt.expected, cmd.Cmd.Args)
assert.Equal(t, tt.repo.WorkDir, cmd.Cmd.Dir)
})
}
}

View File

@ -4,73 +4,62 @@ import (
"fmt"
"os"
"golang.org/x/sys/execabs"
plugin_exec "github.com/thegeeklab/wp-plugin-go/v3/exec"
)
// RemoteRemove drops the defined remote from a git repo.
func RemoteRemove(repo Repository) *execabs.Cmd {
func (r *Repository) RemoteRemove() *plugin_exec.Cmd {
args := []string{
"remote",
"rm",
repo.RemoteName,
r.RemoteName,
}
cmd := execabs.Command(
gitBin,
args...,
)
cmd.Dir = repo.WorkDir
cmd := plugin_exec.Command(gitBin, args...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Dir = r.WorkDir
return cmd
}
// RemoteAdd adds an additional remote to a git repo.
func RemoteAdd(repo Repository) *execabs.Cmd {
func (r *Repository) RemoteAdd() *plugin_exec.Cmd {
args := []string{
"remote",
"add",
repo.RemoteName,
repo.RemoteURL,
r.RemoteName,
r.RemoteURL,
}
cmd := execabs.Command(
gitBin,
args...,
)
cmd.Dir = repo.WorkDir
cmd := plugin_exec.Command(gitBin, args...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Dir = r.WorkDir
return cmd
}
// RemotePush pushs the changes from the local head to a remote branch.
func RemotePush(repo Repository) *execabs.Cmd {
func (r *Repository) RemotePush() *plugin_exec.Cmd {
args := []string{
"push",
repo.RemoteName,
fmt.Sprintf("HEAD:%s", repo.Branch),
r.RemoteName,
fmt.Sprintf("HEAD:%s", r.Branch),
}
cmd := execabs.Command(
gitBin,
args...,
)
cmd.Dir = repo.WorkDir
if r.ForcePush {
args = append(args, "--force")
}
if r.PushFollowTags {
args = append(args, "--follow-tags")
}
cmd := plugin_exec.Command(gitBin, args...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if repo.ForcePush {
cmd.Args = append(
cmd.Args,
"--force",
)
}
if repo.PushFollowTags {
cmd.Args = append(
cmd.Args,
"--follow-tags")
}
cmd.Dir = r.WorkDir
return cmd
}

139
git/remote_test.go Normal file
View File

@ -0,0 +1,139 @@
package git
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestRemoteRemove(t *testing.T) {
tests := []struct {
name string
repo Repository
want []string
}{
{
name: "remove remote",
repo: Repository{
WorkDir: "/path/to/repo",
RemoteName: "origin",
},
want: []string{gitBin, "remote", "rm", "origin"},
},
{
name: "remove custom remote name",
repo: Repository{
WorkDir: "/path/to/repo",
RemoteName: "upstream",
},
want: []string{gitBin, "remote", "rm", "upstream"},
},
{
name: "remove remote with empty work dir",
repo: Repository{
RemoteName: "origin",
},
want: []string{gitBin, "remote", "rm", "origin"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cmd := tt.repo.RemoteRemove()
assert.Equal(t, tt.want, cmd.Cmd.Args)
assert.Equal(t, tt.repo.WorkDir, cmd.Cmd.Dir)
})
}
}
func TestRemoteAdd(t *testing.T) {
tests := []struct {
name string
repo Repository
want []string
}{
{
name: "add remote with valid inputs",
repo: Repository{
WorkDir: "/path/to/repo",
RemoteName: "origin",
RemoteURL: "https://example.com/repo.git",
},
want: []string{gitBin, "remote", "add", "origin", "https://example.com/repo.git"},
},
{
name: "add remote with empty work dir",
repo: Repository{
RemoteName: "origin",
RemoteURL: "https://example.com/repo.git",
},
want: []string{gitBin, "remote", "add", "origin", "https://example.com/repo.git"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cmd := tt.repo.RemoteAdd()
assert.Equal(t, tt.want, cmd.Cmd.Args)
assert.Equal(t, tt.repo.WorkDir, cmd.Cmd.Dir)
})
}
}
func TestRemotePush(t *testing.T) {
tests := []struct {
name string
repo Repository
want []string
forcePush bool
followTags bool
}{
{
name: "push with default options",
repo: Repository{
WorkDir: "/path/to/repo",
RemoteName: "origin",
Branch: "main",
},
want: []string{gitBin, "push", "origin", "HEAD:main"},
},
{
name: "push with force option",
repo: Repository{
WorkDir: "/path/to/repo",
RemoteName: "origin",
Branch: "main",
ForcePush: true,
},
want: []string{gitBin, "push", "origin", "HEAD:main", "--force"},
forcePush: true,
},
{
name: "push with follow tags option",
repo: Repository{
WorkDir: "/path/to/repo",
RemoteName: "origin",
Branch: "main",
PushFollowTags: true,
},
want: []string{gitBin, "push", "origin", "HEAD:main", "--follow-tags"},
followTags: true,
},
{
name: "push with empty work dir",
repo: Repository{
RemoteName: "origin",
Branch: "main",
},
want: []string{gitBin, "push", "origin", "HEAD:main"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cmd := tt.repo.RemotePush()
assert.Equal(t, tt.want, cmd.Cmd.Args)
assert.Equal(t, tt.repo.WorkDir, cmd.Cmd.Dir)
})
}
}

View File

@ -1,44 +0,0 @@
package git
import (
"bytes"
"os"
"github.com/rs/zerolog/log"
"golang.org/x/sys/execabs"
)
func Status(repo Repository) *execabs.Cmd {
cmd := execabs.Command(
gitBin,
"status",
"--porcelain",
)
cmd.Dir = repo.WorkDir
cmd.Stderr = os.Stderr
return cmd
}
func IsDirty(repo Repository) bool {
res := bytes.NewBufferString("")
cmd := Status(repo)
cmd.Dir = repo.WorkDir
cmd.Stderr = os.Stderr
cmd.Stdout = res
cmd.Stderr = res
err := runCommand(cmd)
if err != nil {
return false
}
if res.Len() > 0 {
log.Debug().Msg(res.String())
return true
}
return false
}

View File

@ -1,28 +0,0 @@
package git
const gitBin = "/usr/bin/git"
type Author struct {
Name string
Email string
}
type Repository struct {
RemoteName string
RemoteURL string
Branch string
Add string
CommitMsg string
Autocorrect string
NoVerify bool
InsecureSkipSSLVerify bool
EmptyCommit bool
PushFollowTags bool
ForcePush bool
WorkDir string
InitExists bool
Author Author
}

View File

@ -1,103 +0,0 @@
package git
import (
"fmt"
"os"
"os/user"
"path/filepath"
"github.com/thegeeklab/wp-plugin-go/trace"
"golang.org/x/sys/execabs"
)
const (
netrcFile = `
machine %s
login %s
password %s
`
configFile = `
Host *
StrictHostKeyChecking no
UserKnownHostsFile=/dev/null
`
)
const (
strictFilePerm = 0o600
strictDirPerm = 0o600
)
// WriteKey writes the SSH private key.
func WriteSSHKey(privateKey string) error {
home := "/root"
if currentUser, err := user.Current(); err == nil {
home = currentUser.HomeDir
}
sshpath := filepath.Join(home, ".ssh")
if err := os.MkdirAll(sshpath, strictDirPerm); err != nil {
return err
}
confpath := filepath.Join(sshpath, "config")
if err := os.WriteFile(
confpath,
[]byte(configFile),
strictFilePerm,
); err != nil {
return err
}
privpath := filepath.Join(sshpath, "id_rsa")
return os.WriteFile(
privpath,
[]byte(privateKey),
strictFilePerm,
)
}
// WriteNetrc writes the netrc file.
func WriteNetrc(machine, login, password string) error {
netrcContent := fmt.Sprintf(
netrcFile,
machine,
login,
password,
)
home := "/root"
if currentUser, err := user.Current(); err == nil {
home = currentUser.HomeDir
}
netpath := filepath.Join(
home,
".netrc",
)
return os.WriteFile(
netpath,
[]byte(netrcContent),
strictFilePerm,
)
}
func runCommand(cmd *execabs.Cmd) error {
if cmd.Stdout == nil {
cmd.Stdout = os.Stdout
}
if cmd.Stderr == nil {
cmd.Stderr = os.Stderr
}
trace.Cmd(cmd)
return cmd.Run()
}

20
go.mod
View File

@ -3,17 +3,18 @@ module github.com/thegeeklab/wp-git-action
go 1.22
require (
github.com/rs/zerolog v1.32.0
github.com/thegeeklab/wp-plugin-go v1.7.0
github.com/urfave/cli/v2 v2.27.1
golang.org/x/sys v0.18.0
github.com/rs/zerolog v1.33.0
github.com/stretchr/testify v1.9.0
github.com/thegeeklab/wp-plugin-go/v3 v3.0.2
github.com/urfave/cli/v2 v2.27.2
)
require (
github.com/Masterminds/goutils v1.1.1 // indirect
github.com/Masterminds/semver/v3 v3.2.1 // indirect
github.com/Masterminds/sprig/v3 v3.2.3 // indirect
github.com/cpuguy83/go-md2man/v2 v2.0.2 // indirect
github.com/cpuguy83/go-md2man/v2 v2.0.4 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/google/uuid v1.1.1 // indirect
github.com/huandu/xstrings v1.3.3 // indirect
github.com/imdario/mergo v0.3.11 // indirect
@ -22,10 +23,13 @@ require (
github.com/mattn/go-isatty v0.0.19 // indirect
github.com/mitchellh/copystructure v1.0.0 // indirect
github.com/mitchellh/reflectwalk v1.0.0 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/russross/blackfriday/v2 v2.1.0 // indirect
github.com/shopspring/decimal v1.2.0 // indirect
github.com/spf13/cast v1.3.1 // indirect
github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 // indirect
golang.org/x/crypto v0.21.0 // indirect
golang.org/x/net v0.22.0 // indirect
github.com/xrash/smetrics v0.0.0-20240312152122-5f08fbb34913 // indirect
golang.org/x/crypto v0.23.0 // indirect
golang.org/x/net v0.25.0 // indirect
golang.org/x/sys v0.20.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

33
go.sum
View File

@ -6,8 +6,8 @@ github.com/Masterminds/semver/v3 v3.2.1/go.mod h1:qvl/7zhW3nngYb5+80sSMF+FG2BjYr
github.com/Masterminds/sprig/v3 v3.2.3 h1:eL2fZNezLomi0uOLqjQoN6BfsDD+fyLtgbJMAj9n6YA=
github.com/Masterminds/sprig/v3 v3.2.3/go.mod h1:rXcFaZ2zZbLRJv/xSysmlgIM1u11eBaRMhvYXJNkGuM=
github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
github.com/cpuguy83/go-md2man/v2 v2.0.2 h1:p1EgwI/C7NhT0JmVkwCD2ZBK8j4aeHQX2pMHHBfMQ6w=
github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/cpuguy83/go-md2man/v2 v2.0.4 h1:wfIWP927BUkWJb2NmU/kNDYIBTh/ziUX91+lVfRxZq4=
github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
@ -33,8 +33,8 @@ github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINE
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
github.com/rs/zerolog v1.32.0 h1:keLypqrlIjaFsbmJOBdB/qvyF8KEtCWHwobLp5l/mQ0=
github.com/rs/zerolog v1.32.0/go.mod h1:/7mN4D5sKwJLZQ2b/znpjC3/GQWY/xaDXUM0kKWRHss=
github.com/rs/zerolog v1.33.0 h1:1cU2KZkvPxNyfgEmhHAz/1A9Bz+llsdYzklWFzgp0r8=
github.com/rs/zerolog v1.33.0/go.mod h1:/7mN4D5sKwJLZQ2b/znpjC3/GQWY/xaDXUM0kKWRHss=
github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/shopspring/decimal v1.2.0 h1:abSATXmQEYyShuxI4/vyW3tV1MrKAJzCZ/0zLUXYbsQ=
@ -46,25 +46,25 @@ github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXf
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/thegeeklab/wp-plugin-go v1.7.0 h1:YXE8WkFeoSqMhBR4WYMetlEzCp5cYwP6lZfrHH6rpIc=
github.com/thegeeklab/wp-plugin-go v1.7.0/go.mod h1:5ZCnuq/bOryxCfi9nsTPW6V+hw6L5uILVoU6OFy8E4U=
github.com/urfave/cli/v2 v2.27.1 h1:8xSQ6szndafKVRmfyeUMxkNUJQMjL1F2zmsZ+qHpfho=
github.com/urfave/cli/v2 v2.27.1/go.mod h1:8qnjx1vcq5s2/wpsqoZFndg2CE5tNFyrTvS6SinrnYQ=
github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 h1:bAn7/zixMGCfxrRTfdpNzjtPYqr8smhKouy9mxVdGPU=
github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673/go.mod h1:N3UwUGtsrSj3ccvlPHLoLsHnpR27oXr4ZE984MbSER8=
github.com/thegeeklab/wp-plugin-go/v3 v3.0.2 h1:Mv5i8S1WY+BUNjTjX6lOnB3p8S9mvM+XwfY4R98gx0g=
github.com/thegeeklab/wp-plugin-go/v3 v3.0.2/go.mod h1:ij1iJcAVgzerBTqXnmq0bu1VA+hhVVwzXKqiqfoGjjg=
github.com/urfave/cli/v2 v2.27.2 h1:6e0H+AkS+zDckwPCUrZkKX38mRaau4nL2uipkJpbkcI=
github.com/urfave/cli/v2 v2.27.2/go.mod h1:g0+79LmHHATl7DAcHO99smiR/T7uGLw84w8Y42x+4eM=
github.com/xrash/smetrics v0.0.0-20240312152122-5f08fbb34913 h1:+qGGcbkzsfDQNPPe9UDgpxAWQrhbbBXOYJFQDq/dtJw=
github.com/xrash/smetrics v0.0.0-20240312152122-5f08fbb34913/go.mod h1:4aEEwZQutDLsQv2Deui4iYQ6DWTxR14g6m8Wv88+Xqk=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.3.0/go.mod h1:hebNnKkNXi2UzZN1eVRvBB7co0a+JxK6XbPiWVs/3J4=
golang.org/x/crypto v0.21.0 h1:X31++rzVUdKhX5sWmSOFZxx8UW/ldWx55cbf08iNAMA=
golang.org/x/crypto v0.21.0/go.mod h1:0BP7YvVV9gBbVKyeTG0Gyn+gZm94bibOW5BjDEYAOMs=
golang.org/x/crypto v0.23.0 h1:dIJU/v2J8Mdglj/8rJ6UUOM3Zc9zLZxVZwwxMooUSAI=
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/net v0.2.0/go.mod h1:KqCZLdyyvdV855qA2rE3GC2aiw5xGR5TEjj8smXukLY=
golang.org/x/net v0.22.0 h1:9sGLhx7iRIHEiX0oAJ3MRZMUCElJgy7Br1nO+AMN3Tc=
golang.org/x/net v0.22.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg=
golang.org/x/net v0.25.0 h1:d/OCCoBEUq33pjydKrGQhw7IlUPI2Oylr+8qLx49kac=
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
@ -76,8 +76,8 @@ golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.18.0 h1:DBdB3niSjOA/O0blCZBqDefyWNYveAYMNF1Wum0DYQ4=
golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y=
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.2.0/go.mod h1:TVmDHMZPmdnySmBfhjOoOdhjzdE1h4u1VwSiw2l1Nuc=
@ -89,6 +89,7 @@ golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGm
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.3.0 h1:clyUAQHOM3G0M3f5vQj7LuJrETvjVot3Z5el9nffUtU=

42
internal/doc/main.go Normal file
View File

@ -0,0 +1,42 @@
//go:build generate
// +build generate
package main
import (
"context"
"flag"
"net/http"
"os"
"time"
"github.com/thegeeklab/wp-git-action/plugin"
plugin_docs "github.com/thegeeklab/wp-plugin-go/v3/docs"
plugin_template "github.com/thegeeklab/wp-plugin-go/v3/template"
)
func main() {
tmpl := "https://raw.githubusercontent.com/thegeeklab/woodpecker-plugins/main/templates/docs-data.yaml.tmpl"
client := http.Client{
Timeout: 30 * time.Second,
}
p := plugin.New(nil)
out, err := plugin_template.Render(context.Background(), client, tmpl, plugin_docs.GetTemplateData(p.App))
if err != nil {
panic(err)
}
outputFile := flag.String("output", "", "Output file path")
flag.Parse()
if *outputFile == "" {
panic("no output file specified")
}
err = os.WriteFile(*outputFile, []byte(out), 0o644)
if err != nil {
panic(err)
}
}

View File

@ -7,7 +7,11 @@ import (
"os"
"path/filepath"
"github.com/thegeeklab/wp-git-action/git"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
plugin_exec "github.com/thegeeklab/wp-plugin-go/v3/exec"
plugin_file "github.com/thegeeklab/wp-plugin-go/v3/file"
plugin_util "github.com/thegeeklab/wp-plugin-go/v3/util"
)
var (
@ -20,6 +24,13 @@ var (
ErrGitCloneDestintionNotValid = errors.New("destination not valid")
)
const (
GitActionClone GitAction = "clone"
GitActionCommit GitAction = "commit"
GitActionPush GitAction = "push"
GitActionPages GitAction = "pages"
)
//nolint:revive
func (p *Plugin) run(ctx context.Context) error {
if err := p.Validate(); err != nil {
@ -39,27 +50,26 @@ func (p *Plugin) Validate() error {
p.Settings.Repo.Autocorrect = "never"
p.Settings.Repo.RemoteName = "origin"
p.Settings.Repo.Add = ""
if p.Settings.Repo.WorkDir == "" {
p.Settings.Repo.WorkDir, err = os.Getwd()
if err != nil {
return fmt.Errorf("failed to get working directory: %w", err)
}
}
if err != nil {
return err
}
for _, action := range p.Settings.Action.Value() {
for _, actionStr := range p.Settings.Action.Value() {
action := GitAction(actionStr)
switch action {
case "clone":
case GitActionClone:
continue
case "commit":
case GitActionCommit:
continue
case "push":
case GitActionPush:
if p.Settings.SSHKey == "" && p.Settings.Netrc.Password == "" {
return ErrAuthSourceNotSet
}
case "pages":
case GitActionPages:
p.Settings.Pages.Directory = filepath.Join(p.Settings.Repo.WorkDir, p.Settings.Pages.Directory)
p.Settings.Repo.WorkDir = filepath.Join(p.Settings.Repo.WorkDir, ".tmp")
@ -83,7 +93,7 @@ func (p *Plugin) Validate() error {
return ErrPagesActionNotExclusive
}
default:
return fmt.Errorf("%w: %s", ErrActionUnknown, action)
return fmt.Errorf("%w: %s", ErrActionUnknown, actionStr)
}
}
@ -91,7 +101,13 @@ func (p *Plugin) Validate() error {
}
// Execute provides the implementation of the plugin.
//
//nolint:gocognit
func (p *Plugin) Execute() error {
var err error
homeDir := plugin_util.GetUserHomeDir()
batchCmd := make([]*plugin_exec.Cmd, 0)
gitEnv := []string{
"GIT_AUTHOR_NAME",
"GIT_AUTHOR_EMAIL",
@ -103,147 +119,152 @@ func (p *Plugin) Execute() error {
for _, env := range gitEnv {
if err := os.Unsetenv(env); err != nil {
return err
return fmt.Errorf("failed to unset git env vars '%s': %w", env, err)
}
}
if err := os.Setenv("GIT_TERMINAL_PROMPT", "0"); err != nil {
return err
}
if err := p.handleInit(); err != nil {
return err
}
if err := git.ConfigAutocorrect(p.Settings.Repo).Run(); err != nil {
return err
}
if err := git.ConfigUserName(p.Settings.Repo).Run(); err != nil {
return err
}
if err := git.ConfigUserEmail(p.Settings.Repo).Run(); err != nil {
return err
}
if err := git.ConfigSSLVerify(p.Settings.Repo).Run(); err != nil {
return err
return fmt.Errorf("failed to git env var': %w", err)
}
// Write SSH key and netrc file.
if p.Settings.SSHKey != "" {
if err := git.WriteSSHKey(p.Settings.SSHKey); err != nil {
return err
}
batchCmd = append(batchCmd, p.Settings.Repo.ConfigSSHCommand(p.Settings.SSHKey))
}
if err := git.WriteNetrc(p.Settings.Netrc.Machine, p.Settings.Netrc.Login, p.Settings.Netrc.Password); err != nil {
netrc := p.Settings.Netrc
if err := WriteNetrc(homeDir, netrc.Machine, netrc.Login, netrc.Password); err != nil {
return err
}
for _, action := range p.Settings.Action.Value() {
// Handle repo initialization.
if err := os.MkdirAll(p.Settings.Repo.WorkDir, os.ModePerm); err != nil {
return fmt.Errorf("failed to create working directory: %w", err)
}
defer os.RemoveAll(p.Settings.Repo.WorkDir)
p.Settings.Repo.IsEmpty, err = plugin_file.IsDirEmpty(p.Settings.Repo.WorkDir)
if err != nil {
return fmt.Errorf("failed to check working directory: %w", err)
}
isDir, err := plugin_file.IsDir(filepath.Join(p.Settings.Repo.WorkDir, ".git"))
if err != nil {
return fmt.Errorf("failed to check working directory: %w", err)
}
if !isDir {
batchCmd = append(batchCmd, p.Settings.Repo.Init())
}
// Handle repo configuration.
batchCmd = append(batchCmd, p.Settings.Repo.ConfigAutocorrect())
batchCmd = append(batchCmd, p.Settings.Repo.ConfigUserName())
batchCmd = append(batchCmd, p.Settings.Repo.ConfigUserEmail())
batchCmd = append(batchCmd, p.Settings.Repo.ConfigSSLVerify(p.Network.InsecureSkipVerify))
if err := ExecBatch(batchCmd); err != nil {
return err
}
for _, actionStr := range p.Settings.Action.Value() {
action := GitAction(actionStr)
switch action {
case "clone":
case GitActionClone:
log.Debug().Msg("Compose action cmd: clone")
if err := p.handleClone(); err != nil {
return err
}
case "commit":
case GitActionCommit:
log.Debug().Msg("Compose action cmd: commit")
if err := p.handleCommit(); err != nil {
return err
}
case "push":
case GitActionPush:
log.Debug().Msg("Compose action cmd: push")
if err := p.handlePush(); err != nil {
return err
}
case "pages":
case GitActionPages:
log.Debug().Msg("Compose action cmd: pages")
if err := p.handleClone(); err != nil {
return err
}
if err := p.handlePages(); err != nil {
return err
}
if err := p.handleCommit(); err != nil {
return err
}
if err := p.handlePush(); err != nil {
return err
}
}
}
return nil
}
// handleInit initializes the repository.
func (p *Plugin) handleInit() error {
path := filepath.Join(p.Settings.Repo.WorkDir, ".git")
if err := os.MkdirAll(p.Settings.Repo.WorkDir, os.ModePerm); err != nil {
return err
}
if _, err := os.Stat(path); !os.IsNotExist(err) {
p.Settings.Repo.InitExists = true
return nil
}
return execute(git.Init(p.Settings.Repo))
}
// HandleClone clones remote.
// handleClone clones the remote repository into the configured working directory.
// If the working directory is not empty, it returns an error.
func (p *Plugin) handleClone() error {
if p.Settings.Repo.InitExists {
var batchCmd []*plugin_exec.Cmd
if !p.Settings.Repo.IsEmpty {
return fmt.Errorf("%w: %s exists and not empty", ErrGitCloneDestintionNotValid, p.Settings.Repo.WorkDir)
}
if p.Settings.Repo.RemoteURL != "" {
if err := execute(git.RemoteAdd(p.Settings.Repo)); err != nil {
return err
}
batchCmd = append(batchCmd, p.Settings.Repo.RemoteAdd())
}
if err := execute(git.FetchSource(p.Settings.Repo)); err != nil {
return err
}
batchCmd = append(batchCmd, p.Settings.Repo.FetchSource())
batchCmd = append(batchCmd, p.Settings.Repo.CheckoutHead())
return execute(git.CheckoutHead(p.Settings.Repo))
return ExecBatch(batchCmd)
}
// HandleCommit commits changes locally.
func (p *Plugin) handleCommit() error {
if err := execute(git.Add(p.Settings.Repo)); err != nil {
if err := p.Settings.Repo.Add().Run(); err != nil {
return err
}
if err := execute(git.TestCleanTree(p.Settings.Repo)); err != nil {
if err := execute(git.ForceCommit(p.Settings.Repo)); err != nil {
return err
if err := p.Settings.Repo.IsCleanTree().Run(); err == nil {
if !p.Settings.Repo.EmptyCommit {
log.Debug().Msg("Commit skipped: no changes")
return nil
}
}
if p.Settings.Repo.EmptyCommit {
if err := execute(git.EmptyCommit(p.Settings.Repo)); err != nil {
return err
}
}
return nil
return p.Settings.Repo.Commit().Run()
}
// HandlePush pushs changes to remote.
func (p *Plugin) handlePush() error {
return execute(git.RemotePush(p.Settings.Repo))
return p.Settings.Repo.RemotePush().Run()
}
// HandlePages syncs, commits and pushes the changes from the pages directory to the pages branch.
func (p *Plugin) handlePages() error {
defer os.RemoveAll(p.Settings.Repo.WorkDir)
log.Debug().
Str("src", p.Settings.Pages.Directory).
Str("dest", p.Settings.Repo.WorkDir).
Msg("handlePages")
if err := p.handleClone(); err != nil {
return err
}
if err := execute(
rsyncDirectories(p.Settings.Pages, p.Settings.Repo),
); err != nil {
return err
}
if err := p.handleCommit(); err != nil {
return err
}
return p.handlePush()
return SyncDirectories(
p.Settings.Pages.Exclude.Value(),
p.Settings.Pages.Delete,
p.Settings.Pages.Directory,
p.Settings.Repo.WorkDir,
(zerolog.GlobalLevel() == zerolog.DebugLevel),
).Run()
}

View File

@ -1,14 +1,18 @@
package plugin
import (
"fmt"
"github.com/thegeeklab/wp-git-action/git"
wp "github.com/thegeeklab/wp-plugin-go/plugin"
plugin_base "github.com/thegeeklab/wp-plugin-go/v3/plugin"
"github.com/urfave/cli/v2"
)
//go:generate go run ../internal/doc/main.go -output=../docs/data/data-raw.yaml
// Plugin implements provide the plugin.
type Plugin struct {
*wp.Plugin
*plugin_base.Plugin
Settings *Settings
}
@ -34,13 +38,181 @@ type Pages struct {
Delete bool
}
func New(options wp.Options, settings *Settings) *Plugin {
p := &Plugin{}
type GitAction string
options.Execute = p.run
func New(e plugin_base.ExecuteFunc, build ...string) *Plugin {
p := &Plugin{
Settings: &Settings{},
}
p.Plugin = wp.New(options)
p.Settings = settings
options := plugin_base.Options{
Name: "wp-git-action",
Description: "Perform git actions",
Flags: Flags(p.Settings, plugin_base.FlagsPluginCategory),
Execute: p.run,
HideWoodpeckerFlags: true,
}
if len(build) > 0 {
options.Version = build[0]
}
if len(build) > 1 {
options.VersionMetadata = fmt.Sprintf("date=%s", build[1])
}
if e != nil {
options.Execute = e
}
p.Plugin = plugin_base.New(options)
return p
}
// Flags returns a slice of CLI flags for the plugin.
func Flags(settings *Settings, category string) []cli.Flag {
return []cli.Flag{
&cli.StringSliceFlag{
Name: "action",
Usage: "git action to execute",
EnvVars: []string{"PLUGIN_ACTION"},
Destination: &settings.Action,
Required: true,
Category: category,
},
&cli.StringFlag{
Name: "author-name",
Usage: "git author name",
EnvVars: []string{"PLUGIN_AUTHOR_NAME", "CI_COMMIT_AUTHOR"},
Destination: &settings.Repo.Author.Name,
Required: true,
Category: category,
},
&cli.StringFlag{
Name: "author-email",
Usage: "git author email",
EnvVars: []string{"PLUGIN_AUTHOR_EMAIL", "CI_COMMIT_AUTHOR_EMAIL"},
Destination: &settings.Repo.Author.Email,
Required: true,
Category: category,
},
&cli.StringFlag{
Name: "netrc.machine",
Usage: "netrc remote machine name",
EnvVars: []string{"PLUGIN_NETRC_MACHINE", "CI_NETRC_MACHINE"},
Destination: &settings.Netrc.Machine,
Value: "github.com",
Category: category,
},
&cli.StringFlag{
Name: "netrc.username",
Usage: "netrc login user on the remote machine",
EnvVars: []string{"PLUGIN_NETRC_USERNAME", "CI_NETRC_USERNAME"},
Destination: &settings.Netrc.Login,
Value: "token",
Category: category,
},
&cli.StringFlag{
Name: "netrc.password",
Usage: "netrc login password on the remote machine",
EnvVars: []string{"PLUGIN_NETRC_PASSWORD", "CI_NETRC_PASSWORD"},
Destination: &settings.Netrc.Password,
Category: category,
},
&cli.StringFlag{
Name: "ssh-key",
Usage: "ssh private key for the remote repository",
EnvVars: []string{"PLUGIN_SSH_KEY"},
Destination: &settings.SSHKey,
Category: category,
},
&cli.StringFlag{
Name: "remote-url",
Usage: "url of the remote repository",
EnvVars: []string{"PLUGIN_REMOTE_URL", "CI_REPO_CLONE_URL"},
Destination: &settings.Repo.RemoteURL,
Category: category,
},
&cli.StringFlag{
Name: "branch",
Usage: "name of the git source branch",
EnvVars: []string{"PLUGIN_BRANCH"},
Destination: &settings.Repo.Branch,
Value: "main",
Category: category,
},
&cli.StringFlag{
Name: "path",
Usage: "path to clone git repository",
EnvVars: []string{"PLUGIN_PATH"},
Destination: &settings.Repo.WorkDir,
Category: category,
},
&cli.StringFlag{
Name: "commit-message",
Usage: "commit message",
EnvVars: []string{"PLUGIN_MESSAGE"},
Destination: &settings.Repo.CommitMsg,
Value: "[skip ci] commit dirty state",
Category: category,
},
&cli.BoolFlag{
Name: "force-push",
Usage: "enable force push to remote repository",
EnvVars: []string{"PLUGIN_FORCE"},
Destination: &settings.Repo.ForcePush,
Value: false,
Category: category,
},
&cli.BoolFlag{
Name: "followtags",
Usage: "follow tags for pushes to remote repository",
EnvVars: []string{"PLUGIN_FOLLOWTAGS"},
Destination: &settings.Repo.PushFollowTags,
Value: false,
Category: category,
},
&cli.BoolFlag{
Name: "empty-commit",
Usage: "allow empty commits",
EnvVars: []string{"PLUGIN_EMPTY_COMMIT"},
Destination: &settings.Repo.EmptyCommit,
Value: false,
Category: category,
},
&cli.BoolFlag{
Name: "no-verify",
Usage: "bypass the pre-commit and commit-msg hooks",
EnvVars: []string{"PLUGIN_NO_VERIFY"},
Destination: &settings.Repo.NoVerify,
Value: false,
Category: category,
},
&cli.StringFlag{
Name: "pages.directory",
Usage: "source directory to be synchronized with the pages banch",
EnvVars: []string{"PLUGIN_PAGES_DIRECTORY"},
Destination: &settings.Pages.Directory,
Value: "docs/",
Category: category,
},
&cli.StringSliceFlag{
Name: "pages.exclude",
Usage: "files or directories to exclude from the pages rsync command",
EnvVars: []string{"PLUGIN_PAGES_EXCLUDE"},
Destination: &settings.Pages.Exclude,
Category: category,
},
&cli.BoolFlag{
Name: "pages.delete",
Usage: "add delete flag to pages rsync command",
EnvVars: []string{"PLUGIN_PAGES_DELETE"},
Destination: &settings.Pages.Delete,
Value: true,
Category: category,
},
}
}

50
plugin/rsync.go Normal file
View File

@ -0,0 +1,50 @@
package plugin
import (
"os"
plugin_exec "github.com/thegeeklab/wp-plugin-go/v3/exec"
)
func SyncDirectories(exclude []string, del bool, src, dest string, debug bool) *plugin_exec.Cmd {
args := []string{
"-r",
"--exclude",
".git",
}
for _, item := range exclude {
args = append(
args,
"--exclude",
item,
)
}
if del {
args = append(
args,
"--delete",
)
}
if debug {
args = append(
args,
"--stats",
)
}
args = append(
args,
".",
dest,
)
cmd := plugin_exec.Command("rsync", args...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Dir = src
return cmd
}

58
plugin/rsync_test.go Normal file
View File

@ -0,0 +1,58 @@
package plugin
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestSyncDirectories(t *testing.T) {
tests := []struct {
name string
exclude []string
del bool
debug bool
src string
dest string
want []string
}{
{
name: "exclude .git and other patterns",
exclude: []string{"*.log", "temp/"},
del: false,
debug: false,
src: "/path/to/src",
dest: "/path/to/dest",
want: []string{
"rsync", "-r", "--exclude", ".git", "--exclude", "*.log",
"--exclude", "temp/", ".", "/path/to/dest",
},
},
{
name: "delete enabled",
exclude: []string{},
del: true,
debug: false,
src: "/path/to/src",
dest: "/path/to/dest",
want: []string{"rsync", "-r", "--exclude", ".git", "--delete", ".", "/path/to/dest"},
},
{
name: "debug output enabled",
exclude: []string{},
del: false,
debug: true,
src: "/path/to/src",
dest: "/path/to/dest",
want: []string{"rsync", "-r", "--exclude", ".git", "--stats", ".", "/path/to/dest"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cmd := SyncDirectories(tt.exclude, tt.del, tt.src, tt.dest, tt.debug)
assert.Equal(t, tt.want, cmd.Cmd.Args)
assert.Equal(t, tt.src, cmd.Cmd.Dir)
})
}
}

45
plugin/util.go Normal file
View File

@ -0,0 +1,45 @@
package plugin
import (
"fmt"
"os"
"path/filepath"
plugin_exec "github.com/thegeeklab/wp-plugin-go/v3/exec"
)
const (
netrcFile = `machine %s
login %s
password %s
`
)
const strictFilePerm = 0o600
// WriteNetrc writes the netrc file.
func WriteNetrc(path, machine, login, password string) error {
netrcPath := filepath.Join(path, ".netrc")
netrcContent := fmt.Sprintf(netrcFile, machine, login, password)
if err := os.WriteFile(netrcPath, []byte(netrcContent), strictFilePerm); err != nil {
return fmt.Errorf("failed to create .netrc file: %w", err)
}
return nil
}
// ExecBatch executes a batch of commands. If any command in the batch fails, the function will return the error.
func ExecBatch(batchCmd []*plugin_exec.Cmd) error {
for _, cmd := range batchCmd {
if cmd == nil {
continue
}
if err := cmd.Run(); err != nil {
return err
}
}
return nil
}

53
plugin/util_test.go Normal file
View File

@ -0,0 +1,53 @@
package plugin
import (
"fmt"
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
)
func TestWriteNetrc(t *testing.T) {
tests := []struct {
name string
path string
machine string
login string
password string
wantErr bool
}{
{
name: "valid input",
path: t.TempDir(),
machine: "example.com",
login: "user",
password: "pass",
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := WriteNetrc(tt.path, tt.machine, tt.login, tt.password)
if tt.wantErr {
assert.Error(t, err)
return
}
assert.NoError(t, err)
netrcPath := filepath.Join(tt.path, ".netrc")
_, err = os.Stat(netrcPath)
assert.NoError(t, err)
content, err := os.ReadFile(netrcPath)
assert.NoError(t, err)
expected := fmt.Sprintf("machine %s\nlogin %s\npassword %s\n", tt.machine, tt.login, tt.password)
assert.Equal(t, expected, string(content))
})
}
}

View File

@ -1,58 +0,0 @@
package plugin
import (
"os"
"strings"
"github.com/rs/zerolog/log"
"github.com/thegeeklab/wp-git-action/git"
"golang.org/x/sys/execabs"
)
// helper function to simply wrap os execte command.
func execute(cmd *execabs.Cmd) error {
log.Debug().Msgf("+ %s", strings.Join(cmd.Args, " "))
cmd.Env = os.Environ()
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
return cmd.Run()
}
func rsyncDirectories(pages Pages, repo git.Repository) *execabs.Cmd {
args := []string{
"-r",
"--exclude",
".git",
}
for _, item := range pages.Exclude.Value() {
args = append(
args,
"--exclude",
item,
)
}
if pages.Delete {
args = append(
args,
"--delete",
)
}
args = append(
args,
".",
repo.WorkDir,
)
cmd := execabs.Command(
"rsync",
args...,
)
cmd.Dir = pages.Directory
return cmd
}