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

Compare commits

...

90 Commits
v1.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
renovate[bot]
f5bbc9920e
fix(deps): update module github.com/thegeeklab/wp-plugin-go to v1.7.0 (#94)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2024-03-26 21:34:22 +01:00
renovate[bot]
337fd34c89 chore(deps): update dependency golangci/golangci-lint to v1.57.1 2024-03-25 03:01:20 +00:00
renovate[bot]
f83fcb549d chore(docker): update docker.io/library/golang:1.22 docker digest to 0b55ab8 2024-03-13 07:18:03 +00:00
1203a0aea6
cleanup docs and examples 2024-03-12 20:43:34 +01:00
renovate[bot]
5afc6e8105
fix(deps): update module github.com/thegeeklab/wp-plugin-go to v1.6.1 (#93)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2024-03-07 21:27:00 +01:00
renovate[bot]
1cd7d4ff26
fix(deps): update module golang.org/x/sys to v0.18.0 (#91)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2024-03-06 14:42:20 +01:00
renovate[bot]
51d15b59de chore(docker): update docker.io/library/golang:1.22 docker digest to 34ce21a 2024-03-06 03:40:16 +00:00
renovate[bot]
70f10ceec8 chore(deps): update dependency golangci/golangci-lint to v1.56.2 2024-02-19 04:21:57 +00:00
renovate[bot]
0d79893d5b chore(docker): update docker.io/library/golang:1.22 docker digest to 7b297d9 2024-02-16 03:27:40 +00:00
1a42dfab36
[skip ci] revert renovate automerge config 2024-02-15 12:19:26 +01:00
renovate[bot]
55f13ab7b4
fix(deps): update module github.com/thegeeklab/wp-plugin-go to v1.6.0 (#88)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2024-02-09 21:55:54 +01:00
renovate[bot]
49eab50c24
fix(deps): update module golang.org/x/sys to v0.17.0 (#87)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2024-02-07 22:35:27 +01:00
renovate[bot]
70941b6809
chore(deps): update docker.io/library/golang docker tag to v1.22 (#84)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
Co-authored-by: Robert Kaussow <mail@thegeeklab.de>
2024-02-07 22:33:42 +01:00
renovate[bot]
dd99d7ecb3
chore(docker): update docker.io/library/golang:1.21 docker digest to 0e1e6be (#86)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2024-02-07 12:26:31 +00:00
3c01e1862e
harmonize container image refs and use fqin 2024-02-07 09:40:37 +01:00
f3cc731f4e
run ci on renovate auto branches 2024-02-07 09:10:08 +01:00
f1fde1b71e
ci: enable ci run on renovate branches 2024-02-05 08:58:26 +01:00
renovate[bot]
51fe23e9b8
fix(deps): update module github.com/rs/zerolog to v1.32.0 (#82)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2024-02-05 08:45:15 +01:00
renovate[bot]
2578f5e0b6 chore(docker): update golang:1.21 docker digest to 7b575fe 2024-02-05 06:46:57 +00:00
renovate[bot]
27ca26eb06 chore(deps): update dependency mvdan/gofumpt to v0.6.0 2024-01-30 16:05:27 +00:00
renovate[bot]
27c8c152e9 chore(docker): update alpine:3.19 docker digest to c5b1261 2024-01-29 10:54:41 +00:00
renovate[bot]
5b626b61e4 chore(docker): update golang:1.21 docker digest to 76aadd9 2024-01-25 07:58:40 +00:00
renovate[bot]
9d34d3a110
chore(deps): update quay.io/thegeeklab/wp-docker-buildx docker tag to v3 (#78)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2024-01-22 11:27:36 +01:00
renovate[bot]
7e9f648da9 chore(docker): update golang:1.21 docker digest to 5f5d61d 2024-01-17 09:42:09 +00:00
renovate[bot]
4c0fcd94b2 chore(docker): update golang:1.21 docker digest to 6fbd2d3 2024-01-12 00:40:31 +00:00
renovate[bot]
60415eebf9 chore(docker): update golang:1.21 docker digest to 21260a4 2024-01-11 15:33:46 +00:00
renovate[bot]
62c34e8e15 chore(docker): update golang:1.21 docker digest to ffbb0b8 2024-01-11 04:43:50 +00:00
renovate[bot]
53a01a7a41 chore(docker): update golang:1.21 docker digest to 7026fb7 2024-01-10 05:03:45 +00:00
a71876c992
fix license desc in docs 2024-01-06 14:45:59 +01:00
renovate[bot]
d53921b51c
fix(deps): update module golang.org/x/sys to v0.16.0 (#72)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2024-01-04 20:33:06 +01:00
96723f4bfe
docs: fix default value property in data file 2024-01-03 23:26:13 +01:00
6865b90932
chore: cleanup docs and use cmd trace from plugin lib (#71) 2024-01-03 22:22:54 +01:00
renovate[bot]
390bf11375
fix(deps): update module github.com/thegeeklab/wp-plugin-go to v1.5.0 (#70)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2024-01-03 21:24:22 +01:00
renovate[bot]
91b490fa56
fix(deps): update module github.com/urfave/cli/v2 to v2.27.1 (#69)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2024-01-01 16:21:19 +01:00
6709777a8c
fix: fix wrong handling of insecure-skip-ssl-verify param (#68)
BREAKING CHANGE: The parameter `insecure_ssl_verify` was renamed to `insecure_skip_ssl_verify`
2023-12-24 00:17:55 +01:00
1b0b01b69e
use list style synatx and cleanup (#67) 2023-12-23 23:44:41 +01:00
renovate[bot]
b1c496e7b9
fix(deps): update module github.com/thegeeklab/wp-plugin-go to v1.3.0 (#66)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-12-21 15:21:06 +01:00
renovate[bot]
57e3effa6f chore(docker): update golang:1.21 docker digest to 672a228 2023-12-21 06:23:55 +00:00
renovate[bot]
2a11591c7e chore(docker): update golang:1.21 docker digest to fb02af5 2023-12-20 18:11:48 +00:00
renovate[bot]
44dc4f78ec chore(docker): update golang:1.21 docker digest to 1a9d253 2023-12-20 07:26:47 +00:00
renovate[bot]
5aeb95a0d2 chore(docker): update golang:1.21 docker digest to b172263 2023-12-19 15:32:46 +00:00
08849623ce
ci: add missing test group 2023-12-15 22:34:45 +01:00
renovate[bot]
f59875721d chore(docker): update golang:1.21 docker digest to 2ff79bc 2023-12-13 07:20:06 +00:00
renovate[bot]
653602671d chore(docker): update golang:1.21 docker digest to ae34fbf 2023-12-09 10:16:34 +00:00
renovate[bot]
41bd7dc2cf
chore(deps): update alpine docker tag to v3.19 (#59)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-12-08 08:40:26 +01:00
renovate[bot]
d7a7053fe7
chore(deps): update quay.io/thegeeklab/wp-docker-buildx docker tag to v2 (#58)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-12-07 08:40:08 +01:00
renovate[bot]
d1ef3c7917
fix(deps): update module github.com/thegeeklab/wp-plugin-go to v1.2.0 (#57)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-12-06 23:03:59 +01:00
fbed495725
fix: replace logrus by zerolog (#56) 2023-12-06 09:29:25 +01:00
renovate[bot]
f2730341af chore(docker): update golang:1.21 docker digest to 58e14a9 2023-12-06 04:07:16 +00:00
renovate[bot]
bcf6b7ab88
fix(deps): update module github.com/thegeeklab/wp-plugin-go to v1.1.0 (#54)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-12-05 14:37:24 +01:00
22f4a88a64
ci: exclude dockerhub from linkcheck due to rate limiting 2023-12-05 11:24:31 +01:00
renovate[bot]
19f22d8864
fix(deps): update module github.com/urfave/cli/v2 to v2.26.0 (#53)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-12-04 09:01:24 +01:00
renovate[bot]
fceff01010 chore(docker): update alpine:3.18 docker digest to 34871e7 2023-12-01 07:08:52 +00:00
renovate[bot]
725e4806d2
fix(deps): update module golang.org/x/sys to v0.15.0 (#51)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2023-11-28 09:47:04 +01:00
renovate[bot]
6664e00e1c chore(docker): update golang:1.21 docker digest to 9baee0e 2023-11-22 21:29:29 +00:00
renovate[bot]
1a2a262376 chore(docker): update golang:1.21 docker digest to daa9d10 2023-11-22 13:31:14 +00:00
renovate[bot]
be90784736 chore(docker): update golang:1.21 docker digest to 4521f9d 2023-11-22 06:57:18 +00:00
renovate[bot]
ceadccdf99 chore(docker): update golang:1.21 docker digest to 57bf74a 2023-11-16 09:11:40 +00:00
3a3e8807ce
remove deprecated go version from golangci config 2023-11-08 09:25:27 +01:00
renovate[bot]
1edb59949d chore(docker): update golang:1.21 docker digest to 81cd210 2023-11-08 00:40:21 +00:00
renovate[bot]
7ca222c99b chore(deps): update dependency golangci/golangci-lint to v1.55.2 2023-11-06 03:09:24 +00:00
39 changed files with 1497 additions and 855 deletions

1
.gitignore vendored
View File

@ -1,6 +1,7 @@
/dist
/release
/wp-git-action*
docs/data/data-raw.yaml
coverage.out
CHANGELOG.md

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
@ -86,6 +85,7 @@ linters:
# - wastedassign
- whitespace
- wsl
- zerologlint
fast: false
run:
@ -94,4 +94,3 @@ run:
linters-settings:
gofumpt:
extra-rules: true
lang-version: "1.21"

1
.lycheeignore Normal file
View File

@ -0,0 +1 @@
https://hub.docker.com/r/thegeeklab/*

View File

@ -6,8 +6,8 @@ when:
- ${CI_REPO_DEFAULT_BRANCH}
steps:
dryrun:
image: quay.io/thegeeklab/wp-docker-buildx:1
- name: dryrun
image: quay.io/thegeeklab/wp-docker-buildx:4
settings:
containerfile: Containerfile.multiarch
dry_run: true
@ -19,9 +19,9 @@ steps:
when:
- event: [pull_request]
publish-dockerhub:
- name: publish-dockerhub
image: quay.io/thegeeklab/wp-docker-buildx:4
group: container
image: quay.io/thegeeklab/wp-docker-buildx:1
settings:
auto_tag: true
containerfile: Containerfile.multiarch
@ -40,9 +40,9 @@ steps:
branch:
- ${CI_REPO_DEFAULT_BRANCH}
publish-quay:
- name: publish-quay
image: quay.io/thegeeklab/wp-docker-buildx:4
group: container
image: quay.io/thegeeklab/wp-docker-buildx:1
settings:
auto_tag: true
containerfile: Containerfile.multiarch

View File

@ -6,26 +6,25 @@ when:
- ${CI_REPO_DEFAULT_BRANCH}
steps:
build:
image: docker.io/techknowlogick/xgo:go-1.21.x
- name: build
image: docker.io/techknowlogick/xgo:go-1.22.x
commands:
- ln -s $(pwd) /source
- make release
executable:
- name: executable
image: quay.io/thegeeklab/alpine-tools
commands:
- $(find dist/ -executable -type f -iname ${CI_REPO_NAME}-linux-amd64) --help
changelog:
- name: changelog
image: quay.io/thegeeklab/git-sv
commands:
- git fetch --depth=2147483647
- git sv current-version
- git sv release-notes -t ${CI_COMMIT_TAG:-next} -o CHANGELOG.md
- cat CHANGELOG.md
publish-github:
- name: publish-github
image: docker.io/plugins/github-release
settings:
api_key:
@ -36,7 +35,7 @@ steps:
overwrite: true
title: ${CI_COMMIT_TAG}
when:
- event: [tag]
- event: [tag]
depends_on:
- test

View File

@ -6,26 +6,27 @@ when:
- ${CI_REPO_DEFAULT_BRANCH}
steps:
markdownlint:
- name: markdownlint
image: quay.io/thegeeklab/markdownlint-cli
group: test
commands:
- markdownlint 'README.md' 'CONTRIBUTING.md'
spellcheck:
- name: spellcheck
image: quay.io/thegeeklab/alpine-tools
group: test
commands:
- spellchecker --files '_docs/**/*.md' 'README.md' 'CONTRIBUTING.md' -d .dictionary -p spell indefinite-article syntax-urls
- spellchecker --files 'docs/**/*.md' 'README.md' 'CONTRIBUTING.md' -d .dictionary -p spell indefinite-article syntax-urls
environment:
FORCE_COLOR: "true"
NPM_CONFIG_LOGLEVEL: "error"
link-validation:
- name: link-validation
image: docker.io/lycheeverse/lychee
group: test
commands:
- lychee --no-progress --format detailed _docs/content README.md
- lychee --no-progress --format detailed docs/content README.md
publish:
- name: publish
image: quay.io/thegeeklab/wp-git-action
settings:
action:
@ -36,13 +37,14 @@ steps:
message: "[skip ci] auto-update documentation"
netrc_password:
from_secret: github_token
pages_directory: _docs/
pages_directory: docs/
when:
- event: [push, manual]
branch:
- ${CI_REPO_DEFAULT_BRANCH}
status: [success, failure]
pushrm-dockerhub:
- name: pushrm-dockerhub
image: docker.io/chko/docker-pushrm:1
secrets:
- source: docker_password
@ -59,7 +61,7 @@ steps:
- ${CI_REPO_DEFAULT_BRANCH}
status: [success]
pushrm-quay:
- name: pushrm-quay
image: docker.io/chko/docker-pushrm:1
secrets:
- source: quay_token

View File

@ -8,7 +8,7 @@ when:
runs_on: [success, failure]
steps:
matrix:
- name: matrix
image: quay.io/thegeeklab/wp-matrix
settings:
homeserver:

View File

@ -6,12 +6,12 @@ when:
- ${CI_REPO_DEFAULT_BRANCH}
steps:
lint:
image: docker.io/library/golang:1.21
- name: lint
image: docker.io/library/golang:1.22
commands:
- make lint
test:
image: docker.io/library/golang:1.21
- name: test
image: docker.io/library/golang:1.22
commands:
- make test

View File

@ -1,4 +1,4 @@
FROM --platform=$BUILDPLATFORM golang:1.21@sha256:b113af1e8b06f06a18ad41a6b331646dff587d7a4cf740f4852d16c49ed8ad73 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 alpine:3.18@sha256:eece025e432126ce23f223450a0326fbebde39cdf496a85d8c016293fc851978
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.5.0
GOFUMPT_PACKAGE_VERSION := v0.6.0
# renovate: datasource=github-releases depName=golangci/golangci-lint
GOLANGCI_LINT_PACKAGE_VERSION := v1.55.1
GOLANGCI_LINT_PACKAGE_VERSION := v1.59.0
EXECUTABLE := wp-git-action
@ -19,8 +19,7 @@ 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.21.x
XGO_VERSION := go-1.22.x
XGO_TARGETS ?= linux/amd64,linux/arm-6,linux/arm-7,linux/arm64
TARGETOS ?= linux
@ -65,7 +64,7 @@ lint: golangci-lint
.PHONY: generate
generate:
$(GO) generate $(GENERATE)
$(GO) generate $(PACKAGES)
.PHONY: test
test:

View File

@ -1,98 +0,0 @@
---
properties:
- name: action
description: |
Git actions to be executed. Supported actions: `clone | commit | push | pages`. Specified actions are executed in the specified order
- **clone:** Clones the repository in `remote_url` and checks out the `branch` to `path`.
- **commit:** Adds a commit to the default repository or the repository in `remote_url`.
- **push:** Pushes all commits to the default repository or the repository set in `remote_url`.
- **pages:** The `pages` action is a special action that cannot be combined with other actions. It is intended for use for
GitHub pages. It synchronizes the contents of `pages_directory` with the target `branch` using `rsync` and pushes the changes automatically.
required: true
type: list
- name: author_name
description: Git author name.
required: true
type: string
- name: author_email
description: Git author Email Address.
required: true
type: string
- name: netrc_machine
description: Netrc remote machine name.
defaultvalue: github.com
type: string
- name: netrc_username
description: Netrc login user on the remote machine.
defaultvalue: token
type: string
- name: netrc_password
description: Netrc login password on the remote machine.
type: string
- name: ssh_key
description: SSH private key for the remote repository.
type: string
- name: remote_url
description: URL of the remote repository.
type: string
- name: branch
description: Name of the git branch.
defaultvalue: main
type: string
- name: path
description: Path to clone the git repository.
type: string
- name: message
description: Commit message.
defaultvalue: "[skip ci] commit dirty state"
type: string
- name: force
description: Enable force push to remote repository.
defaultvalue: false
type: bool
- name: followtags
description: Push all the `refs` that would be pushed without this option, and also push annotated tags in `refs/tags` that are missing from the remote.
defaultvalue: false
type: bool
- name: insecure_ssl_verify
description: Configure git SSL verification of the remote machine.
defaultvalue: false
type: bool
- name: empty_commit
description: Allow empty commits. Usually recording a commit that has the exact same tree as its sole parent commit is a mistake, and those commits are not allowed by default.
defaultvalue: false
type: bool
- name: no_verify
description: Bypass the pre-commit and commit-msg hooks.
defaultvalue: false
type: bool
- name: pages_directory
description: Source directory to be synchronized with the pages `branch`.
defaultvalue: docs/
type: string
- name: pages_exclude
description: Files or directories to exclude from the rsync command.
type: list
- name: pages_delete
description: When set to `true`, the `--delete` flag is added to the rsync command to remove files from the `branch` that do not exist in the `pages_directory` either.
defaultvalue: true
type: bool

View File

@ -1,161 +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.
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-ssl-verify",
Usage: "set SSL verification of the remote machine",
EnvVars: []string{"PLUGIN_INSECURE_SSL_VERIFY"},
Destination: &settings.Repo.InsecureSSLVerify,
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 for pages sync",
EnvVars: []string{"PLUGIN_PAGES_DIRECTORY"},
Destination: &settings.Pages.Directory,
Value: "docs/",
Category: category,
},
&cli.StringSliceFlag{
Name: "pages.exclude",
Usage: "exclude flag added to pages rsnyc command",
EnvVars: []string{"PLUGIN_PAGES_EXCLUDE"},
Destination: &settings.Pages.Exclude,
Category: category,
},
&cli.BoolFlag{
Name: "pages.delete",
Usage: "delete flag added 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

@ -8,7 +8,7 @@ title: wp-git-action
[![Go Report Card](https://goreportcard.com/badge/github.com/thegeeklab/wp-git-action)](https://goreportcard.com/report/github.com/thegeeklab/wp-git-action)
[![GitHub contributors](https://img.shields.io/github/contributors/thegeeklab/wp-git-action)](https://github.com/thegeeklab/wp-git-action/graphs/contributors)
[![Source: GitHub](https://img.shields.io/badge/source-github-blue.svg?logo=github&logoColor=white)](https://github.com/thegeeklab/wp-git-action)
[![License: MIT](https://img.shields.io/github/license/thegeeklab/wp-git-action)](https://github.com/thegeeklab/wp-git-action/blob/main/LICENSE)
[![License: Apache-2.0](https://img.shields.io/github/license/thegeeklab/wp-git-action)](https://github.com/thegeeklab/wp-git-action/blob/main/LICENSE)
Woodpecker CI plugin to perform git actions.
@ -21,17 +21,14 @@ Woodpecker CI plugin to perform git actions.
## Usage
```YAML
kind: pipeline
name: default
steps:
- name: commit changelog
image: thegeeklab/wp-git-action
image: quay.io/thegeeklab/wp-git-action
settings:
action:
- commit
- push
netrc_password: ghp_3LbMg9Kncpdkhjp3bh3dMnKNXLjVMTsXk4sM
netrc_password: ghp_randomstring
author_name: octobot
author_email: octobot@example.com
message: "[skip ci] update changelog"
@ -52,21 +49,18 @@ steps:
The plugin can be used to publish GitHub pages to the pages branch. Remember that the `pages` action cannot be combined with other actions.
```YAML
kind: pipeline
name: default
steps:
- name: publish
image: thegeeklab/wp-git-action
image: quay.io/thegeeklab/wp-git-action
settings:
action:
- pages
author_email: bot@thegeeklab.de
author_name: thegeeklab-bot
author_email: bot@texample.com
author_name: octocat-bot
message: "update pages"
branch: gh-pages
pages_directory: docs/
netrc_password: ghp_3LbMg9Kncpdkhjp3bh3dMnKNXLjVMTsXk4sM
netrc_password: ghp_randomstring
```
## Build
@ -86,5 +80,12 @@ docker build --file Containerfile.multiarch --tag thegeeklab/wp-git-action .
## Test
```Shell
docker run --rm \
-e PLUGIN_ACTION=clone \
-e PLUGIN_BRANCH=master \
-e PLUGIN_AUTHOR_EMAIL=octocat@example.copm \
-e PLUGIN_AUTHOR_NAME=octocat \
-e PLUGIN_REMOTE_URL=https://github.com/octocat/Hello-World \
-w /tmp \
thegeeklab/wp-git-action
```

152
docs/data/data.yaml Normal file
View File

@ -0,0 +1,152 @@
---
properties:
- name: action
description: |
Git action to execute.
Supported actions: `clone | commit | push | pages`. Specified actions are executed in the specified order
- **clone:** Clones the repository in `remote_url` and checks out the `branch` to `path`.
- **commit:** Adds a commit to the default repository or the repository in `remote_url`.
- **push:** Pushes all commits to the default repository or the repository set in `remote_url`.
- **pages:** The `pages` action is a special action that cannot be combined with other actions. It is intended for use for
GitHub pages. It synchronizes the contents of `pages_directory` with the target `branch` using `rsync` and pushes the changes automatically.
type: list
required: true
- name: author_email
description: |
Git author email.
type: string
required: true
- name: author_name
description: |
Git author name.
type: string
required: true
- name: branch
description: |
Name of the git source branch.
type: string
defaultValue: "main"
required: false
- name: empty_commit
description: |
Allow empty commits.
Usually recording a commit that has the exact same tree as its sole parent commit is a mistake,
and those commits are not allowed by default.
type: bool
defaultValue: false
required: false
- name: followtags
description: |
Follow tags for pushes to remote repository.
Push all the `refs` that would be pushed without this option, and also push annotated tags
in `refs/tags` that are missing from the remote.
type: bool
defaultValue: false
required: false
- name: force
description: |
Enable force push to remote repository.
type: bool
defaultValue: false
required: false
- name: insecure_skip_verify
description: |
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.
type: string
defaultValue: "[skip ci] commit dirty state"
required: false
- name: netrc_machine
description: |
Netrc remote machine name.
type: string
defaultValue: "github.com"
required: false
- name: netrc_password
description: |
Netrc login password on the remote machine.
type: string
required: false
- name: netrc_username
description: |
Netrc login user on the remote machine.
type: string
defaultValue: "token"
required: false
- name: no_verify
description: |
Bypass the pre-commit and commit-msg hooks.
type: bool
defaultValue: false
required: false
- name: pages_delete
description: |
Add delete flag to pages rsync command.
When set to `true`, the `--delete` flag is added to the rsync command to remove files
from the branch that do not exist in the `pages_directory` either.
type: bool
defaultValue: true
required: false
- name: pages_directory
description: |
Source directory to be synchronized with the pages branch.
type: string
defaultValue: "docs/"
required: false
- name: pages_exclude
description: |
Files or directories to exclude from the pages rsync command.
type: list
required: false
- name: path
description: |
Path to clone git repository.
type: string
required: false
- name: remote_url
description: |
Url of the remote repository.
type: string
required: false
- name: ssh_key
description: |
Ssh private key for the remote repository.
type: string
required: false

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
}
// repoSSLVerify 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.SSLVerify),
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,29 +0,0 @@
package 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
InsecureSSLVerify bool
EmptyCommit bool
PushFollowTags bool
ForcePush bool
SSLVerify bool
WorkDir string
InitExists bool
Author Author
}
const gitBin = "/usr/bin/git"

View File

@ -1,107 +0,0 @@
package git
import (
"fmt"
"os"
"os/user"
"path/filepath"
"strings"
"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 trace(cmd *execabs.Cmd) {
fmt.Fprintf(os.Stdout, "+ %s\n", strings.Join(cmd.Args, " "))
}
func runCommand(cmd *execabs.Cmd) error {
if cmd.Stdout == nil {
cmd.Stdout = os.Stdout
}
if cmd.Stderr == nil {
cmd.Stderr = os.Stderr
}
trace(cmd)
return cmd.Run()
}

31
go.mod
View File

@ -1,20 +1,35 @@
module github.com/thegeeklab/wp-git-action
go 1.21
go 1.22
require (
github.com/rs/zerolog v1.31.0
github.com/thegeeklab/wp-plugin-go v1.0.2
github.com/urfave/cli/v2 v2.25.7
golang.org/x/sys v0.14.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/cpuguy83/go-md2man/v2 v2.0.2 // indirect
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.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
github.com/joho/godotenv v1.5.1 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
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/xrash/smetrics v0.0.0-20201216005158-039620a65673 // indirect
golang.org/x/net v0.17.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-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
)

96
go.sum
View File

@ -1,7 +1,23 @@
github.com/Masterminds/goutils v1.1.1 h1:5nUrii3FMTL5diU80unEVvNevw1nH4+ZV4DSLVJLSYI=
github.com/Masterminds/goutils v1.1.1/go.mod h1:8cTjp+g8YejhMuvIA5y2vz3BpJxksy863GQaJW2MFNU=
github.com/Masterminds/semver/v3 v3.2.0/go.mod h1:qvl/7zhW3nngYb5+80sSMF+FG2BjYrf8m9wsX0PNOMQ=
github.com/Masterminds/semver/v3 v3.2.1 h1:RN9w6+7QoMeJVGyfmbcgs28Br8cvmnucEXnY0rYXWg0=
github.com/Masterminds/semver/v3 v3.2.1/go.mod h1:qvl/7zhW3nngYb5+80sSMF+FG2BjYrf8m9wsX0PNOMQ=
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=
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/google/uuid v1.1.1 h1:Gkbcsh/GbpXz7lPftLA3P6TYMwjCLYm83jiFQZF/3gY=
github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/huandu/xstrings v1.3.3 h1:/Gcsuc1x8JVbJ9/rlye4xZnVAbEkGauT8lbebqcQws4=
github.com/huandu/xstrings v1.3.3/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE=
github.com/imdario/mergo v0.3.11 h1:3tnifQM4i+fbajXKBHXWEH+KvNHqojZ778UH75j3bGA=
github.com/imdario/mergo v0.3.11/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=
@ -9,22 +25,74 @@ github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovk
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA=
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mitchellh/copystructure v1.0.0 h1:Laisrj+bAB6b/yJwB5Bt3ITZhGJdqmxquMKeZ+mmkFQ=
github.com/mitchellh/copystructure v1.0.0/go.mod h1:SNtv71yrdKgLRyLFxmLdkAbkKEFWgYaq1OVrnRcwhnw=
github.com/mitchellh/reflectwalk v1.0.0 h1:9D+8oIskB4VJBN5SFlmc27fSlIBZaov1Wpk/IfikLNY=
github.com/mitchellh/reflectwalk v1.0.0/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
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.31.0 h1:FcTR3NnLWW+NnTwwhFWiJSZr4ECLpqCm6QsEnyvbV4A=
github.com/rs/zerolog v1.31.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/thegeeklab/wp-plugin-go v1.0.2 h1:c5yJZ8RWqEufZwa3ErP8RpnyyGjhyw05yH+oeeuJBeA=
github.com/thegeeklab/wp-plugin-go v1.0.2/go.mod h1:gAa0rupkUomiHWjM6/+CtyUrLYgk/qXiRkYtPrOG5Ik=
github.com/urfave/cli/v2 v2.25.7 h1:VAzn5oq403l5pHjc4OhD54+XGO9cdKVL/7lDjF+iKUs=
github.com/urfave/cli/v2 v2.25.7/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=
golang.org/x/net v0.17.0 h1:pVaXccu2ozPjCXewfr1S7xza/zcXTity9cCdXQYSjIM=
golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE=
github.com/shopspring/decimal v1.2.0 h1:abSATXmQEYyShuxI4/vyW3tV1MrKAJzCZ/0zLUXYbsQ=
github.com/shopspring/decimal v1.2.0/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o=
github.com/spf13/cast v1.3.1 h1:nFm6S0SMdyzrzcmThSipiEubIDy8WEXKNZ0UOgiRpng=
github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
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/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.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.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=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
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.14.0 h1:Vz7Qs629MkJkGyHxUlRHizWJRG2j8fbQKjELVSNhy7Q=
golang.org/x/sys v0.14.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=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
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=
gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

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
}