From 51c3d1642b963e065c5f42d517dcdab00bcc5f1f Mon Sep 17 00:00:00 2001 From: Don Date: Mon, 9 Nov 2020 14:32:14 -0800 Subject: [PATCH 1/2] Update to latest plugin library --- .dockeringore => .dockerignore | 0 .drone.star | 358 +++++++++++++++++++++++++++ .drone.starlark | 399 ------------------------------ .drone.yml | 16 -- .github/settings.yml | 6 +- .gitignore | 5 +- LICENSE | 1 - cmd/drone-webhook/config.go | 70 ++++++ cmd/drone-webhook/main.go | 70 ++++++ docker/Dockerfile.linux.amd64 | 2 +- docker/Dockerfile.linux.arm | 2 +- docker/Dockerfile.linux.arm64 | 2 +- docker/Dockerfile.windows.1909 | 10 + docker/Dockerfile.windows.2004 | 10 + docker/manifest.tmpl | 18 +- go.mod | 18 +- go.sum | 90 ++++--- helper.go | 12 - main.go | 201 --------------- plugin.go | 177 ------------- plugin/helper.go | 20 ++ plugin/impl.go | 133 ++++++++++ plugin/impl_test.go | 18 ++ plugin/plugin.go | 26 ++ plugin/plugin_test.go | 14 ++ template.go => plugin/template.go | 7 +- renovate.json | 26 ++ 27 files changed, 836 insertions(+), 875 deletions(-) rename .dockeringore => .dockerignore (100%) create mode 100644 .drone.star delete mode 100644 .drone.starlark delete mode 100644 .drone.yml create mode 100644 cmd/drone-webhook/config.go create mode 100644 cmd/drone-webhook/main.go create mode 100644 docker/Dockerfile.windows.1909 create mode 100644 docker/Dockerfile.windows.2004 delete mode 100644 helper.go delete mode 100644 main.go delete mode 100644 plugin.go create mode 100644 plugin/helper.go create mode 100644 plugin/impl.go create mode 100644 plugin/impl_test.go create mode 100644 plugin/plugin.go create mode 100644 plugin/plugin_test.go rename template.go => plugin/template.go (64%) create mode 100644 renovate.json diff --git a/.dockeringore b/.dockerignore similarity index 100% rename from .dockeringore rename to .dockerignore diff --git a/.drone.star b/.drone.star new file mode 100644 index 0000000..9cf7c4c --- /dev/null +++ b/.drone.star @@ -0,0 +1,358 @@ +def main(ctx): + before = testing(ctx) + + stages = [ + linux(ctx, 'amd64'), + linux(ctx, 'arm64'), + linux(ctx, 'arm'), + windows(ctx, '1909'), + windows(ctx, '1903'), + windows(ctx, '1809'), + ] + + after = manifest(ctx) + gitter(ctx) + + for b in before: + for s in stages: + s['depends_on'].append(b['name']) + + for s in stages: + for a in after: + a['depends_on'].append(s['name']) + + return before + stages + after + +def testing(ctx): + return [{ + 'kind': 'pipeline', + 'type': 'docker', + 'name': 'testing', + 'platform': { + 'os': 'linux', + 'arch': 'amd64', + }, + 'steps': [ + { + 'name': 'staticcheck', + 'image': 'golang:1.15', + 'pull': 'always', + 'commands': [ + 'go run honnef.co/go/tools/cmd/staticcheck ./...', + ], + 'volumes': [ + { + 'name': 'gopath', + 'path': '/go', + }, + ], + }, + { + 'name': 'lint', + 'image': 'golang:1.15', + 'pull': 'always', + 'commands': [ + 'go run golang.org/x/lint/golint -set_exit_status ./...', + ], + 'volumes': [ + { + 'name': 'gopath', + 'path': '/go', + }, + ], + }, + { + 'name': 'vet', + 'image': 'golang:1.15', + 'pull': 'always', + 'commands': [ + 'go vet ./...', + ], + 'volumes': [ + { + 'name': 'gopath', + 'path': '/go', + }, + ], + }, + { + 'name': 'test', + 'image': 'golang:1.15', + 'pull': 'always', + 'commands': [ + 'go test -cover ./...', + ], + 'volumes': [ + { + 'name': 'gopath', + 'path': '/go', + }, + ], + }, + ], + 'volumes': [ + { + 'name': 'gopath', + 'temp': {}, + }, + ], + 'trigger': { + 'ref': [ + 'refs/heads/master', + 'refs/tags/**', + 'refs/pull/**', + ], + }, + }] + +def linux(ctx, arch): + docker = { + 'dockerfile': 'docker/Dockerfile.linux.%s' % (arch), + 'repo': 'plugins/webhook', + 'username': { + 'from_secret': 'docker_username', + }, + 'password': { + 'from_secret': 'docker_password', + }, + } + + if ctx.build.event == 'pull_request': + docker.update({ + 'dry_run': True, + 'tags': 'linux-%s' % (arch), + }) + else: + docker.update({ + 'auto_tag': True, + 'auto_tag_suffix': 'linux-%s' % (arch), + }) + + if ctx.build.event == 'tag': + build = [ + 'go build -v -ldflags "-X main.version=%s" -a -tags netgo -o release/linux/%s/drone-webhook ./cmd/drone-webhook' % (ctx.build.ref.replace("refs/tags/v", ""), arch), + ] + else: + build = [ + 'go build -v -ldflags "-X main.version=%s" -a -tags netgo -o release/linux/%s/drone-webhook ./cmd/drone-webhook' % (ctx.build.commit[0:8], arch), + ] + + return { + 'kind': 'pipeline', + 'type': 'docker', + 'name': 'linux-%s' % (arch), + 'platform': { + 'os': 'linux', + 'arch': arch, + }, + 'steps': [ + { + 'name': 'environment', + 'image': 'golang:1.15', + 'pull': 'always', + 'environment': { + 'CGO_ENABLED': '0', + }, + 'commands': [ + 'go version', + 'go env', + ], + }, + { + 'name': 'build', + 'image': 'golang:1.15', + 'pull': 'always', + 'environment': { + 'CGO_ENABLED': '0', + }, + 'commands': build, + }, + { + 'name': 'executable', + 'image': 'golang:1.15', + 'pull': 'always', + 'commands': [ + './release/linux/%s/drone-webhook --help' % (arch), + ], + }, + { + 'name': 'docker', + 'image': 'plugins/docker', + 'pull': 'always', + 'settings': docker, + }, + ], + 'depends_on': [], + 'trigger': { + 'ref': [ + 'refs/heads/master', + 'refs/tags/**', + 'refs/pull/**', + ], + }, + } + +def windows(ctx, version): + docker = [ + 'echo $env:PASSWORD | docker login --username $env:USERNAME --password-stdin', + ] + + if ctx.build.event == 'tag': + build = [ + 'go build -v -ldflags "-X main.version=%s" -a -tags netgo -o release/windows/amd64/drone-webhook.exe ./cmd/drone-webhook' % (ctx.build.ref.replace("refs/tags/v", "")), + ] + + docker = docker + [ + 'docker build --pull -f docker/Dockerfile.windows.%s -t plugins/webhook:%s-windows-%s-amd64 .' % (version, ctx.build.ref.replace("refs/tags/v", ""), version), + 'docker run --rm plugins/webhook:%s-windows-%s-amd64 --help' % (ctx.build.ref.replace("refs/tags/v", ""), version), + 'docker push plugins/webhook:%s-windows-%s-amd64' % (ctx.build.ref.replace("refs/tags/v", ""), version), + ] + else: + build = [ + 'go build -v -ldflags "-X main.version=%s" -a -tags netgo -o release/windows/amd64/drone-webhook.exe ./cmd/drone-webhook' % (ctx.build.commit[0:8]), + ] + + docker = docker + [ + 'docker build --pull -f docker/Dockerfile.windows.%s -t plugins/webhook:windows-%s-amd64 .' % (version, version), + 'docker run --rm plugins/webhook:windows-%s-amd64 --help' % (version), + 'docker push plugins/webhook:windows-%s-amd64' % (version), + ] + + return { + 'kind': 'pipeline', + 'type': 'ssh', + 'name': 'windows-%s' % (version), + 'platform': { + 'os': 'windows', + }, + 'server': { + 'host': { + 'from_secret': 'windows_server_%s' % (version), + }, + 'user': { + 'from_secret': 'windows_username', + }, + 'password': { + 'from_secret': 'windows_password', + }, + }, + 'steps': [ + { + 'name': 'environment', + 'environment': { + 'CGO_ENABLED': '0', + }, + 'commands': [ + 'go version', + 'go env', + ], + }, + { + 'name': 'build', + 'environment': { + 'CGO_ENABLED': '0', + }, + 'commands': build, + }, + { + 'name': 'executable', + 'commands': [ + './release/windows/amd64/drone-webhook.exe --help', + ], + }, + { + 'name': 'docker', + 'environment': { + 'USERNAME': { + 'from_secret': 'docker_username', + }, + 'PASSWORD': { + 'from_secret': 'docker_password', + }, + }, + 'commands': docker, + }, + ], + 'depends_on': [], + 'trigger': { + 'ref': [ + 'refs/heads/master', + 'refs/tags/**', + ], + }, + } + +def manifest(ctx): + return [{ + 'kind': 'pipeline', + 'type': 'docker', + 'name': 'manifest', + 'steps': [ + { + 'name': 'manifest', + 'image': 'plugins/manifest', + 'pull': 'always', + 'settings': { + 'auto_tag': 'true', + 'username': { + 'from_secret': 'docker_username', + }, + 'password': { + 'from_secret': 'docker_password', + }, + 'spec': 'docker/manifest.tmpl', + 'ignore_missing': 'true', + }, + }, + { + 'name': 'microbadger', + 'image': 'plugins/webhook', + 'pull': 'always', + 'settings': { + 'urls': { + 'from_secret': 'microbadger_url', + }, + }, + }, + ], + 'depends_on': [], + 'trigger': { + 'ref': [ + 'refs/heads/master', + 'refs/tags/**', + ], + }, + }] + +def gitter(ctx): + return [{ + 'kind': 'pipeline', + 'type': 'docker', + 'name': 'gitter', + 'clone': { + 'disable': True, + }, + 'steps': [ + { + 'name': 'gitter', + 'image': 'plugins/gitter', + 'pull': 'always', + 'settings': { + 'webhook': { + 'from_secret': 'gitter_webhook', + } + }, + }, + ], + 'depends_on': [ + 'manifest', + ], + 'trigger': { + 'ref': [ + 'refs/heads/master', + 'refs/tags/**', + ], + 'status': [ + 'failure', + ], + }, + }] diff --git a/.drone.starlark b/.drone.starlark deleted file mode 100644 index 2445c7a..0000000 --- a/.drone.starlark +++ /dev/null @@ -1,399 +0,0 @@ -def main(ctx): - before = testing() - - stages = [ - linux('amd64'), - linux('arm64'), - linux('arm'), - windows('1903'), - windows('1809'), - ] - - after = manifest() + gitter() - - for b in before: - for s in stages: - s['depends_on'].append(b['name']) - - for s in stages: - for a in after: - a['depends_on'].append(s['name']) - - return before + stages + after - -def testing(): - return [{ - 'kind': 'pipeline', - 'type': 'docker', - 'name': 'testing', - 'platform': { - 'os': 'linux', - 'arch': 'amd64', - }, - 'steps': [ - { - 'name': 'vet', - 'image': 'golang:1.12', - 'pull': 'always', - 'commands': [ - 'go vet ./...' - ], - 'volumes': [ - { - 'name': 'gopath', - 'path': '/go' - } - ] - }, - { - 'name': 'lint', - 'image': 'golang:1.12', - 'pull': 'always', - 'commands': [ - 'go run golang.org/x/lint/golint -set_exit_status ./...' - ], - 'volumes': [ - { - 'name': 'gopath', - 'path': '/go' - } - ] - }, - { - 'name': 'staticcheck', - 'image': 'golang:1.12', - 'pull': 'always', - 'commands': [ - 'go run honnef.co/go/tools/cmd/staticcheck ./...' - ], - 'volumes': [ - { - 'name': 'gopath', - 'path': '/go' - } - ] - }, - { - 'name': 'test', - 'image': 'golang:1.12', - 'pull': 'always', - 'commands': [ - 'go test -cover ./...' - ], - 'volumes': [ - { - 'name': 'gopath', - 'path': '/go' - } - ] - } - ], - 'volumes': [ - { - 'name': 'gopath', - 'temp': {} - } - ], - 'trigger': { - 'ref': [ - 'refs/heads/master', - 'refs/tags/**', - 'refs/pull/**' - ] - } - }] - -def linux(arch): - return { - 'kind': 'pipeline', - 'type': 'docker', - 'name': 'linux-%s' % arch, - 'platform': { - 'os': 'linux', - 'arch': arch, - }, - 'steps': [ - { - 'name': 'build-push', - 'image': 'golang:1.12', - 'pull': 'always', - 'environment': { - 'CGO_ENABLED': '0' - }, - 'commands': [ - 'go build -v -ldflags "-X main.version=${DRONE_COMMIT_SHA:0:8}" -a -tags netgo -o release/linux/%s/drone-webhook' % arch - ], - 'when': { - 'event': { - 'exclude': [ - 'tag' - ] - } - } - }, - { - 'name': 'build-tag', - 'image': 'golang:1.12', - 'pull': 'always', - 'environment': { - 'CGO_ENABLED': '0' - }, - 'commands': [ - 'go build -v -ldflags "-X main.version=${DRONE_TAG##v}" -a -tags netgo -o release/linux/%s/drone-webhook' % arch - ], - 'when': { - 'event': [ - 'tag' - ] - } - }, - { - 'name': 'executable', - 'image': 'golang:1.12', - 'pull': 'always', - 'commands': [ - './release/linux/%s/drone-webhook --help' % arch - ] - }, - { - 'name': 'dryrun', - 'image': 'plugins/docker', - 'pull': 'always', - 'settings': { - 'dry_run': True, - 'tags': 'linux-%s' % arch, - 'dockerfile': 'docker/Dockerfile.linux.%s' % arch, - 'repo': 'plugins/webhook', - 'username': { - 'from_secret': 'docker_username' - }, - 'password': { - 'from_secret': 'docker_password' - } - }, - 'when': { - 'event': [ - 'pull_request' - ] - } - }, - { - 'name': 'publish', - 'image': 'plugins/docker', - 'pull': 'always', - 'settings': { - 'auto_tag': True, - 'auto_tag_suffix': 'linux-%s' % arch, - 'dockerfile': 'docker/Dockerfile.linux.%s' % arch, - 'repo': 'plugins/webhook', - 'username': { - 'from_secret': 'docker_username' - }, - 'password': { - 'from_secret': 'docker_password' - } - }, - 'when': { - 'event': { - 'exclude': [ - 'pull_request' - ] - } - } - } - ], - 'depends_on': [], - 'trigger': { - 'ref': [ - 'refs/heads/master', - 'refs/tags/**', - 'refs/pull/**' - ] - } - } - -def windows(version): - return { - 'kind': 'pipeline', - 'type': 'ssh', - 'name': 'windows-%s' % version, - 'platform': { - 'os': 'windows' - }, - 'server': { - 'host': { - 'from_secret': 'windows_server_%s' % version - }, - 'user': { - 'from_secret': 'windows_username' - }, - 'password': { - 'from_secret': 'windows_password' - }, - }, - 'steps': [ - { - 'name': 'build-push', - 'environment': { - 'CGO_ENABLED': '0' - }, - 'commands': [ - 'go build -v -ldflags "-X main.version=${DRONE_COMMIT_SHA:0:8}" -a -tags netgo -o release/windows/amd64/drone-webhook.exe', - ], - 'when': { - 'event': { - 'exclude': [ - 'tag' - ] - } - } - }, - { - 'name': 'build-tag', - 'environment': { - 'CGO_ENABLED': '0' - }, - 'commands': [ - 'go build -v -ldflags "-X main.version=${DRONE_TAG##v}" -a -tags netgo -o release/windows/amd64/drone-webhook.exe', - ], - 'when': { - 'event': [ - 'tag' - ] - } - }, - { - 'name': 'executable', - 'commands': [ - './release/windows/amd64/drone-webhook.exe --help', - ] - }, - { - 'name': 'latest', - 'environment': { - 'USERNAME': { - 'from_secret': 'docker_username' - }, - 'PASSWORD': { - 'from_secret': 'docker_password' - }, - }, - 'commands': [ - 'echo $env:PASSWORD | docker login --username $env:USERNAME --password-stdin', - 'docker build --pull -f docker/Dockerfile.windows.%s -t plugins/webhook:windows-%s-amd64 .' % (version, version), - 'docker run --rm plugins/webhook:windows-%s-amd64 --help' % version, - 'docker push plugins/webhook:windows-%s-amd64' % version, - ], - 'when': { - 'ref': [ - 'refs/heads/master', - ] - } - }, - { - 'name': 'tagged', - 'environment': { - 'USERNAME': { - 'from_secret': 'docker_username' - }, - 'PASSWORD': { - 'from_secret': 'docker_password' - }, - }, - 'commands': [ - 'echo $env:PASSWORD | docker login --username $env:USERNAME --password-stdin', - 'docker build --pull -f docker/Dockerfile.windows.%s -t plugins/webhook:${DRONE_TAG##v}-windows-%s-amd64 .' % (version, version), - 'docker run --rm plugins/webhook:${DRONE_TAG##v}-windows-%s-amd64 --help' % version, - 'docker push plugins/webhook:${DRONE_TAG##v}-windows-%s-amd64' % version, - ], - 'when': { - 'ref': [ - 'refs/tags/**', - ] - } - } - ], - 'depends_on': [], - 'trigger': { - 'ref': [ - 'refs/heads/master', - 'refs/tags/**', - ] - } - } - -def manifest(): - return [{ - 'kind': 'pipeline', - 'type': 'docker', - 'name': 'manifest', - 'steps': [ - { - 'name': 'manifest', - 'image': 'plugins/manifest', - 'pull': 'always', - 'settings': { - 'auto_tag': 'true', - 'username': { - 'from_secret': 'docker_username' - }, - 'password': { - 'from_secret': 'docker_password' - }, - 'spec': 'docker/manifest.tmpl', - 'ignore_missing': 'true', - }, - }, - { - 'name': 'microbadger', - 'image': 'plugins/webhook', - 'pull': 'always', - 'settings': { - 'urls': { - 'from_secret': 'microbadger_url' - } - }, - } - ], - 'depends_on': [], - 'trigger': { - 'ref': [ - 'refs/heads/master', - 'refs/tags/**' - ] - } - }] - -def gitter(): - return [{ - 'kind': 'pipeline', - 'type': 'docker', - 'name': 'gitter', - 'clone': { - 'disable': True - }, - 'steps': [ - { - 'name': 'gitter', - 'image': 'plugins/gitter', - 'pull': 'always', - 'settings': { - 'webhook': { - 'from_secret': 'gitter_webhook' - } - }, - }, - ], - 'depends_on': [ - 'manifest' - ], - 'trigger': { - 'ref': [ - 'refs/heads/master', - 'refs/tags/**' - ], - 'status': [ - 'failure' - ] - } - }] diff --git a/.drone.yml b/.drone.yml deleted file mode 100644 index 3e7dd08..0000000 --- a/.drone.yml +++ /dev/null @@ -1,16 +0,0 @@ ---- -{"kind": "pipeline", "type": "docker", "name": "testing", "platform": {"os": "linux", "arch": "amd64"}, "steps": [{"name": "vet", "image": "golang:1.12", "pull": "always", "commands": ["go vet ./..."], "volumes": [{"name": "gopath", "path": "/go"}]}, {"name": "lint", "image": "golang:1.12", "pull": "always", "commands": ["go run golang.org/x/lint/golint -set_exit_status ./..."], "volumes": [{"name": "gopath", "path": "/go"}]}, {"name": "staticcheck", "image": "golang:1.12", "pull": "always", "commands": ["go run honnef.co/go/tools/cmd/staticcheck ./..."], "volumes": [{"name": "gopath", "path": "/go"}]}, {"name": "test", "image": "golang:1.12", "pull": "always", "commands": ["go test -cover ./..."], "volumes": [{"name": "gopath", "path": "/go"}]}], "volumes": [{"name": "gopath", "temp": {}}], "trigger": {"ref": ["refs/heads/master", "refs/tags/**", "refs/pull/**"]}} ---- -{"kind": "pipeline", "type": "docker", "name": "linux-amd64", "platform": {"os": "linux", "arch": "amd64"}, "steps": [{"name": "build-push", "image": "golang:1.12", "pull": "always", "environment": {"CGO_ENABLED": "0"}, "commands": ["go build -v -ldflags \"-X main.version=${DRONE_COMMIT_SHA:0:8}\" -a -tags netgo -o release/linux/amd64/drone-webhook"], "when": {"event": {"exclude": ["tag"]}}}, {"name": "build-tag", "image": "golang:1.12", "pull": "always", "environment": {"CGO_ENABLED": "0"}, "commands": ["go build -v -ldflags \"-X main.version=${DRONE_TAG##v}\" -a -tags netgo -o release/linux/amd64/drone-webhook"], "when": {"event": ["tag"]}}, {"name": "executable", "image": "golang:1.12", "pull": "always", "commands": ["./release/linux/amd64/drone-webhook --help"]}, {"name": "dryrun", "image": "plugins/docker", "pull": "always", "settings": {"dry_run": true, "tags": "linux-amd64", "dockerfile": "docker/Dockerfile.linux.amd64", "repo": "plugins/webhook", "username": {"from_secret": "docker_username"}, "password": {"from_secret": "docker_password"}}, "when": {"event": ["pull_request"]}}, {"name": "publish", "image": "plugins/docker", "pull": "always", "settings": {"auto_tag": true, "auto_tag_suffix": "linux-amd64", "dockerfile": "docker/Dockerfile.linux.amd64", "repo": "plugins/webhook", "username": {"from_secret": "docker_username"}, "password": {"from_secret": "docker_password"}}, "when": {"event": {"exclude": ["pull_request"]}}}], "depends_on": ["testing"], "trigger": {"ref": ["refs/heads/master", "refs/tags/**", "refs/pull/**"]}} ---- -{"kind": "pipeline", "type": "docker", "name": "linux-arm64", "platform": {"os": "linux", "arch": "arm64"}, "steps": [{"name": "build-push", "image": "golang:1.12", "pull": "always", "environment": {"CGO_ENABLED": "0"}, "commands": ["go build -v -ldflags \"-X main.version=${DRONE_COMMIT_SHA:0:8}\" -a -tags netgo -o release/linux/arm64/drone-webhook"], "when": {"event": {"exclude": ["tag"]}}}, {"name": "build-tag", "image": "golang:1.12", "pull": "always", "environment": {"CGO_ENABLED": "0"}, "commands": ["go build -v -ldflags \"-X main.version=${DRONE_TAG##v}\" -a -tags netgo -o release/linux/arm64/drone-webhook"], "when": {"event": ["tag"]}}, {"name": "executable", "image": "golang:1.12", "pull": "always", "commands": ["./release/linux/arm64/drone-webhook --help"]}, {"name": "dryrun", "image": "plugins/docker", "pull": "always", "settings": {"dry_run": true, "tags": "linux-arm64", "dockerfile": "docker/Dockerfile.linux.arm64", "repo": "plugins/webhook", "username": {"from_secret": "docker_username"}, "password": {"from_secret": "docker_password"}}, "when": {"event": ["pull_request"]}}, {"name": "publish", "image": "plugins/docker", "pull": "always", "settings": {"auto_tag": true, "auto_tag_suffix": "linux-arm64", "dockerfile": "docker/Dockerfile.linux.arm64", "repo": "plugins/webhook", "username": {"from_secret": "docker_username"}, "password": {"from_secret": "docker_password"}}, "when": {"event": {"exclude": ["pull_request"]}}}], "depends_on": ["testing"], "trigger": {"ref": ["refs/heads/master", "refs/tags/**", "refs/pull/**"]}} ---- -{"kind": "pipeline", "type": "docker", "name": "linux-arm", "platform": {"os": "linux", "arch": "arm"}, "steps": [{"name": "build-push", "image": "golang:1.12", "pull": "always", "environment": {"CGO_ENABLED": "0"}, "commands": ["go build -v -ldflags \"-X main.version=${DRONE_COMMIT_SHA:0:8}\" -a -tags netgo -o release/linux/arm/drone-webhook"], "when": {"event": {"exclude": ["tag"]}}}, {"name": "build-tag", "image": "golang:1.12", "pull": "always", "environment": {"CGO_ENABLED": "0"}, "commands": ["go build -v -ldflags \"-X main.version=${DRONE_TAG##v}\" -a -tags netgo -o release/linux/arm/drone-webhook"], "when": {"event": ["tag"]}}, {"name": "executable", "image": "golang:1.12", "pull": "always", "commands": ["./release/linux/arm/drone-webhook --help"]}, {"name": "dryrun", "image": "plugins/docker", "pull": "always", "settings": {"dry_run": true, "tags": "linux-arm", "dockerfile": "docker/Dockerfile.linux.arm", "repo": "plugins/webhook", "username": {"from_secret": "docker_username"}, "password": {"from_secret": "docker_password"}}, "when": {"event": ["pull_request"]}}, {"name": "publish", "image": "plugins/docker", "pull": "always", "settings": {"auto_tag": true, "auto_tag_suffix": "linux-arm", "dockerfile": "docker/Dockerfile.linux.arm", "repo": "plugins/webhook", "username": {"from_secret": "docker_username"}, "password": {"from_secret": "docker_password"}}, "when": {"event": {"exclude": ["pull_request"]}}}], "depends_on": ["testing"], "trigger": {"ref": ["refs/heads/master", "refs/tags/**", "refs/pull/**"]}} ---- -{"kind": "pipeline", "type": "ssh", "name": "windows-1903", "platform": {"os": "windows"}, "server": {"host": {"from_secret": "windows_server_1903"}, "user": {"from_secret": "windows_username"}, "password": {"from_secret": "windows_password"}}, "steps": [{"name": "build-push", "environment": {"CGO_ENABLED": "0"}, "commands": ["go build -v -ldflags \"-X main.version=${DRONE_COMMIT_SHA:0:8}\" -a -tags netgo -o release/windows/amd64/drone-webhook.exe"], "when": {"event": {"exclude": ["tag"]}}}, {"name": "build-tag", "environment": {"CGO_ENABLED": "0"}, "commands": ["go build -v -ldflags \"-X main.version=${DRONE_TAG##v}\" -a -tags netgo -o release/windows/amd64/drone-webhook.exe"], "when": {"event": ["tag"]}}, {"name": "executable", "commands": ["./release/windows/amd64/drone-webhook.exe --help"]}, {"name": "latest", "environment": {"USERNAME": {"from_secret": "docker_username"}, "PASSWORD": {"from_secret": "docker_password"}}, "commands": ["echo $env:PASSWORD | docker login --username $env:USERNAME --password-stdin", "docker build --pull -f docker/Dockerfile.windows.1903 -t plugins/webhook:windows-1903-amd64 .", "docker run --rm plugins/webhook:windows-1903-amd64 --help", "docker push plugins/webhook:windows-1903-amd64"], "when": {"ref": ["refs/heads/master"]}}, {"name": "tagged", "environment": {"USERNAME": {"from_secret": "docker_username"}, "PASSWORD": {"from_secret": "docker_password"}}, "commands": ["echo $env:PASSWORD | docker login --username $env:USERNAME --password-stdin", "docker build --pull -f docker/Dockerfile.windows.1903 -t plugins/webhook:${DRONE_TAG##v}-windows-1903-amd64 .", "docker run --rm plugins/webhook:${DRONE_TAG##v}-windows-1903-amd64 --help", "docker push plugins/webhook:${DRONE_TAG##v}-windows-1903-amd64"], "when": {"ref": ["refs/tags/**"]}}], "depends_on": ["testing"], "trigger": {"ref": ["refs/heads/master", "refs/tags/**"]}} ---- -{"kind": "pipeline", "type": "ssh", "name": "windows-1809", "platform": {"os": "windows"}, "server": {"host": {"from_secret": "windows_server_1809"}, "user": {"from_secret": "windows_username"}, "password": {"from_secret": "windows_password"}}, "steps": [{"name": "build-push", "environment": {"CGO_ENABLED": "0"}, "commands": ["go build -v -ldflags \"-X main.version=${DRONE_COMMIT_SHA:0:8}\" -a -tags netgo -o release/windows/amd64/drone-webhook.exe"], "when": {"event": {"exclude": ["tag"]}}}, {"name": "build-tag", "environment": {"CGO_ENABLED": "0"}, "commands": ["go build -v -ldflags \"-X main.version=${DRONE_TAG##v}\" -a -tags netgo -o release/windows/amd64/drone-webhook.exe"], "when": {"event": ["tag"]}}, {"name": "executable", "commands": ["./release/windows/amd64/drone-webhook.exe --help"]}, {"name": "latest", "environment": {"USERNAME": {"from_secret": "docker_username"}, "PASSWORD": {"from_secret": "docker_password"}}, "commands": ["echo $env:PASSWORD | docker login --username $env:USERNAME --password-stdin", "docker build --pull -f docker/Dockerfile.windows.1809 -t plugins/webhook:windows-1809-amd64 .", "docker run --rm plugins/webhook:windows-1809-amd64 --help", "docker push plugins/webhook:windows-1809-amd64"], "when": {"ref": ["refs/heads/master"]}}, {"name": "tagged", "environment": {"USERNAME": {"from_secret": "docker_username"}, "PASSWORD": {"from_secret": "docker_password"}}, "commands": ["echo $env:PASSWORD | docker login --username $env:USERNAME --password-stdin", "docker build --pull -f docker/Dockerfile.windows.1809 -t plugins/webhook:${DRONE_TAG##v}-windows-1809-amd64 .", "docker run --rm plugins/webhook:${DRONE_TAG##v}-windows-1809-amd64 --help", "docker push plugins/webhook:${DRONE_TAG##v}-windows-1809-amd64"], "when": {"ref": ["refs/tags/**"]}}], "depends_on": ["testing"], "trigger": {"ref": ["refs/heads/master", "refs/tags/**"]}} ---- -{"kind": "pipeline", "type": "docker", "name": "manifest", "steps": [{"name": "manifest", "image": "plugins/manifest", "pull": "always", "settings": {"auto_tag": "true", "username": {"from_secret": "docker_username"}, "password": {"from_secret": "docker_password"}, "spec": "docker/manifest.tmpl", "ignore_missing": "true"}}, {"name": "microbadger", "image": "plugins/webhook", "pull": "always", "settings": {"urls": {"from_secret": "microbadger_url"}}}], "depends_on": ["linux-amd64", "linux-arm64", "linux-arm", "windows-1903", "windows-1809"], "trigger": {"ref": ["refs/heads/master", "refs/tags/**"]}} ---- -{"kind": "pipeline", "type": "docker", "name": "gitter", "clone": {"disable": true}, "steps": [{"name": "gitter", "image": "plugins/gitter", "pull": "always", "settings": {"webhook": {"from_secret": "gitter_webhook"}}}], "depends_on": ["manifest", "linux-amd64", "linux-arm64", "linux-arm", "windows-1903", "windows-1809"], "trigger": {"ref": ["refs/heads/master", "refs/tags/**"], "status": ["failure"]}} diff --git a/.github/settings.yml b/.github/settings.yml index 078a0de..fa726f2 100644 --- a/.github/settings.yml +++ b/.github/settings.yml @@ -69,5 +69,9 @@ branches: - continuous-integration/drone/pr enforce_admins: false restrictions: + apps: + - renovate users: [] - teams: [] + teams: + - Admins + - Maintainers diff --git a/.gitignore b/.gitignore index 941db6f..12d4187 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ -release/ +/release/ +/drone-webhook* coverage.out -drone-webhook +.drone.yml diff --git a/LICENSE b/LICENSE index 8f71f43..8dada3e 100644 --- a/LICENSE +++ b/LICENSE @@ -199,4 +199,3 @@ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. - diff --git a/cmd/drone-webhook/config.go b/cmd/drone-webhook/config.go new file mode 100644 index 0000000..84d95aa --- /dev/null +++ b/cmd/drone-webhook/config.go @@ -0,0 +1,70 @@ +// Copyright (c) 2020, the Drone Plugins project authors. +// Please see the AUTHORS file for details. All rights reserved. +// Use of this source code is governed by an Apache 2.0 license that can be +// found in the LICENSE file. + +package main + +import ( + "github.com/drone-plugins/drone-webhook/plugin" + "github.com/urfave/cli/v2" +) + +// settingsFlags has the cli.Flags for the plugin.Settings. +func settingsFlags(settings *plugin.Settings) []cli.Flag { + // Replace below with all the flags required for the plugin. + // Use Destination within the cli.Flags to populate settings + return []cli.Flag{ + &cli.StringFlag{ + Name: "method", + Usage: "webhook method", + Value: "POST", + EnvVars: []string{"PLUGIN_METHOD"}, + Destination: &settings.Method, + }, + &cli.StringFlag{ + Name: "username", + Usage: "username for basic auth", + EnvVars: []string{"PLUGIN_USERNAME", "WEBHOOK_USERNAME"}, + Destination: &settings.Username, + }, + &cli.StringFlag{ + Name: "password", + Usage: "password for basic auth", + EnvVars: []string{"PLUGIN_PASSWORD", "WEBHOOK_PASSWORD"}, + Destination: &settings.Password, + }, + &cli.StringFlag{ + Name: "content-type", + Usage: "content type", + Value: "application/json", + EnvVars: []string{"PLUGIN_CONTENT_TYPE"}, + Destination: &settings.ContentType, + }, + &cli.StringFlag{ + Name: "template", + Usage: "custom template for webhook", + EnvVars: []string{"PLUGIN_TEMPLATE"}, + Destination: &settings.Template, + }, + &cli.StringSliceFlag{ + Name: "headers", + Usage: "custom headers key map", + EnvVars: []string{"PLUGIN_HEADERS"}, + Destination: &settings.Headers, + }, + &cli.StringSliceFlag{ + Name: "urls", + Usage: "list of urls to perform the action on", + EnvVars: []string{"PLUGIN_URLS", "PLUGIN_URL", "WEBHOOK_URLS", "WEBHOOK_URL"}, + Destination: &settings.URLs, + }, + // Should be an IntSliceFlag but that doesn't have a Destination field + &cli.StringSliceFlag{ + Name: "valid-response-codes", + Usage: "list of valid http response codes", + EnvVars: []string{"PLUGIN_VALID_RESPONSE_CODES"}, + Destination: &settings.ValidCodes, + }, + } +} diff --git a/cmd/drone-webhook/main.go b/cmd/drone-webhook/main.go new file mode 100644 index 0000000..159077c --- /dev/null +++ b/cmd/drone-webhook/main.go @@ -0,0 +1,70 @@ +// Copyright (c) 2020, the Drone Plugins project authors. +// Please see the AUTHORS file for details. All rights reserved. +// Use of this source code is governed by an Apache 2.0 license that can be +// found in the LICENSE file. + +// DO NOT MODIFY THIS FILE DIRECTLY + +package main + +import ( + "os" + + "github.com/drone-plugins/drone-plugin-lib/errors" + "github.com/drone-plugins/drone-plugin-lib/urfave" + "github.com/drone-plugins/drone-webhook/plugin" + "github.com/joho/godotenv" + "github.com/urfave/cli/v2" +) + +var version = "unknown" + +func main() { + settings := &plugin.Settings{} + + if _, err := os.Stat("/run/drone/env"); err == nil { + godotenv.Overload("/run/drone/env") + } + + app := &cli.App{ + Name: "drone-webhook", + Usage: "trigger webhooks", + Version: version, + Flags: append(settingsFlags(settings), urfave.Flags()...), + Action: run(settings), + } + + if err := app.Run(os.Args); err != nil { + errors.HandleExit(err) + } +} + +func run(settings *plugin.Settings) cli.ActionFunc { + return func(ctx *cli.Context) error { + urfave.LoggingFromContext(ctx) + + plugin := plugin.New( + *settings, + urfave.PipelineFromContext(ctx), + urfave.NetworkFromContext(ctx), + ) + + if err := plugin.Validate(); err != nil { + if e, ok := err.(errors.ExitCoder); ok { + return e + } + + return errors.ExitMessagef("validation failed: %w", err) + } + + if err := plugin.Execute(); err != nil { + if e, ok := err.(errors.ExitCoder); ok { + return e + } + + return errors.ExitMessagef("execution failed: %w", err) + } + + return nil + } +} diff --git a/docker/Dockerfile.linux.amd64 b/docker/Dockerfile.linux.amd64 index 5131f36..f498a09 100644 --- a/docker/Dockerfile.linux.amd64 +++ b/docker/Dockerfile.linux.amd64 @@ -6,4 +6,4 @@ LABEL maintainer="Drone.IO Community " \ org.label-schema.schema-version="1.0" ADD release/linux/amd64/drone-webhook /bin/ -ENTRYPOINT ["/bin/drone-webhook"] +ENTRYPOINT [ "/bin/drone-webhook" ] diff --git a/docker/Dockerfile.linux.arm b/docker/Dockerfile.linux.arm index 39faeda..98d2d9c 100644 --- a/docker/Dockerfile.linux.arm +++ b/docker/Dockerfile.linux.arm @@ -6,4 +6,4 @@ LABEL maintainer="Drone.IO Community " \ org.label-schema.schema-version="1.0" ADD release/linux/arm/drone-webhook /bin/ -ENTRYPOINT ["/bin/drone-webhook"] +ENTRYPOINT [ "/bin/drone-webhook" ] diff --git a/docker/Dockerfile.linux.arm64 b/docker/Dockerfile.linux.arm64 index 253ff71..6de6983 100644 --- a/docker/Dockerfile.linux.arm64 +++ b/docker/Dockerfile.linux.arm64 @@ -6,4 +6,4 @@ LABEL maintainer="Drone.IO Community " \ org.label-schema.schema-version="1.0" ADD release/linux/arm64/drone-webhook /bin/ -ENTRYPOINT ["/bin/drone-webhook"] +ENTRYPOINT [ "/bin/drone-webhook" ] diff --git a/docker/Dockerfile.windows.1909 b/docker/Dockerfile.windows.1909 new file mode 100644 index 0000000..fd32a79 --- /dev/null +++ b/docker/Dockerfile.windows.1909 @@ -0,0 +1,10 @@ +# escape=` +FROM plugins/base:windows-1909-amd64 + +LABEL maintainer="Drone.IO Community " ` + org.label-schema.name="Drone Webhook" ` + org.label-schema.vendor="Drone.IO Community" ` + org.label-schema.schema-version="1.0" + +ADD release/windows/amd64/drone-webhook.exe C:/bin/drone-webhook.exe +ENTRYPOINT [ "C:\\bin\\drone-webhook.exe" ] diff --git a/docker/Dockerfile.windows.2004 b/docker/Dockerfile.windows.2004 new file mode 100644 index 0000000..af342a7 --- /dev/null +++ b/docker/Dockerfile.windows.2004 @@ -0,0 +1,10 @@ +# escape=` +FROM plugins/base:windows-2004-amd64 + +LABEL maintainer="Drone.IO Community " ` + org.label-schema.name="Drone Webhook" ` + org.label-schema.vendor="Drone.IO Community" ` + org.label-schema.schema-version="1.0" + +ADD release/windows/amd64/drone-webhook.exe C:/bin/drone-webhook.exe +ENTRYPOINT [ "C:\\bin\\drone-webhook.exe" ] diff --git a/docker/manifest.tmpl b/docker/manifest.tmpl index ba5a877..dc48277 100644 --- a/docker/manifest.tmpl +++ b/docker/manifest.tmpl @@ -1,10 +1,12 @@ image: plugins/webhook:{{#if build.tag}}{{trimPrefix "v" build.tag}}{{else}}latest{{/if}} + {{#if build.tags}} tags: {{#each build.tags}} - {{this}} {{/each}} {{/if}} + manifests: - image: plugins/webhook:{{#if build.tag}}{{trimPrefix "v" build.tag}}-{{/if}}linux-amd64 platform: @@ -14,17 +16,29 @@ manifests: platform: architecture: arm64 os: linux + variant: v8 - image: plugins/webhook:{{#if build.tag}}{{trimPrefix "v" build.tag}}-{{/if}}linux-arm platform: architecture: arm os: linux - - image: plugins/webhook:{{#if build.tag}}{{trimPrefix "v" build.tag}}-{{/if}}windows-1809-amd64 + variant: v7 + - image: plugins/webhook:{{#if build.tag}}{{trimPrefix "v" build.tag}}-{{/if}}windows-2004-amd64 platform: architecture: amd64 os: windows - version: 1809 + version: 2004 + - image: plugins/webhook:{{#if build.tag}}{{trimPrefix "v" build.tag}}-{{/if}}windows-1909-amd64 + platform: + architecture: amd64 + os: windows + version: 1909 - image: plugins/webhook:{{#if build.tag}}{{trimPrefix "v" build.tag}}-{{/if}}windows-1903-amd64 platform: architecture: amd64 os: windows version: 1903 + - image: plugins/webhook:{{#if build.tag}}{{trimPrefix "v" build.tag}}-{{/if}}windows-1809-amd64 + platform: + architecture: amd64 + os: windows + version: 1809 diff --git a/go.mod b/go.mod index e901a36..69e0fb9 100644 --- a/go.mod +++ b/go.mod @@ -1,16 +1,10 @@ module github.com/drone-plugins/drone-webhook +go 1.15 + require ( - bou.ke/monkey v1.0.1 // indirect - github.com/aymerick/raymond v2.0.2+incompatible // indirect - github.com/drone-plugins/drone-plugin-lib v0.0.0-20190916204527-6b33d765aca4 - github.com/drone/drone-template-lib v0.0.0-20181004051823-4019baa6c594 - github.com/jackspirou/syscerts v0.0.0-20160531025014-b68f5469dff1 - github.com/pkg/errors v0.8.1 // indirect - github.com/sirupsen/logrus v1.4.2 - github.com/stretchr/testify v1.3.0 // indirect - github.com/tkuchiki/faketime v0.1.1 // indirect - github.com/urfave/cli v1.21.0 - golang.org/x/lint v0.0.0-20190909230951-414d861bb4ac // indirect - honnef.co/go/tools v0.0.1-2019.2.3 // indirect + github.com/drone-plugins/drone-plugin-lib v0.4.0 + github.com/drone/drone-template-lib v1.0.0 + github.com/joho/godotenv v1.3.0 + github.com/urfave/cli/v2 v2.3.0 ) diff --git a/go.sum b/go.sum index 732bb7b..29f2a1b 100644 --- a/go.sum +++ b/go.sum @@ -1,64 +1,58 @@ -bou.ke/monkey v1.0.1 h1:zEMLInw9xvNakzUUPjfS4Ds6jYPqCFx3m7bRmG5NH2U= -bou.ke/monkey v1.0.1/go.mod h1:FgHuK96Rv2Nlf+0u1OOVDpCMdsWyOFmeeketDHE7LIg= -github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/Masterminds/goutils v1.1.0 h1:zukEsf/1JZwCMgHiK3GZftabmxiCw4apj3a28RPBiVg= +github.com/Masterminds/goutils v1.1.0/go.mod h1:8cTjp+g8YejhMuvIA5y2vz3BpJxksy863GQaJW2MFNU= +github.com/Masterminds/semver v1.4.2 h1:WBLTQ37jOCzSLtXNdoo8bNM8876KhNqOKvrlGITgsTc= +github.com/Masterminds/semver v1.4.2/go.mod h1:MB6lktGJrhw8PrUyiEoblNEGEQ+RzHPF078ddwwvV3Y= +github.com/Masterminds/sprig v2.18.0+incompatible h1:QoGhlbC6pter1jxKnjMFxT8EqsLuDE6FEcNbWEpw+lI= +github.com/Masterminds/sprig v2.18.0+incompatible/go.mod h1:y6hNFY5UBTIWBxnzTeuNhlNS5hqE0NB0E6fgfo2Br3o= github.com/aymerick/raymond v2.0.2+incompatible h1:VEp3GpgdAnv9B2GFyTvqgcKvY+mfKMjPOA3SbKLtnU0= github.com/aymerick/raymond v2.0.2+incompatible/go.mod h1:osfaiScAUVup+UC9Nfq76eWqDhXlp+4UYaA8uhTBO6g= -github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= -github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/bouk/monkey v1.0.0/go.mod h1:PG/63f4XEUlVyW1ttIeOJmJhhe1+t9EC/je3eTjvFhE= +github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d h1:U+s90UTSYgptZMwQh2aRr3LuazLJIa+Pg3Kc1ylSYVY= +github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/drone-plugins/drone-plugin-lib v0.0.0-20190905223702-0352df680f17 h1:x441B4/1FGRHg92xWAithZQUhsUysY+hZca3Wo6fuTQ= -github.com/drone-plugins/drone-plugin-lib v0.0.0-20190916204527-6b33d765aca4 h1:CxEkk5WIstHlmg+locKHxTnJ/rzk08P3FE5W1hFCEBk= -github.com/drone-plugins/drone-plugin-lib v0.0.0-20190916204527-6b33d765aca4/go.mod h1:Jd/3DVk8GYEuFXhOZ2UZ3D7iwoXIfZXdIQ1BaBpBBls= -github.com/drone/drone-template-lib v0.0.0-20181004051823-4019baa6c594 h1:zPRVfiHpXeGt1XGpK2TQcaj2lRydiGdVz1AoHkaC554= -github.com/drone/drone-template-lib v0.0.0-20181004051823-4019baa6c594/go.mod h1:u34woe41m58Whrf21iH6z/xLOIRM3650LhWAyUc7Oik= -github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= -github.com/jackspirou/syscerts v0.0.0-20160531025014-b68f5469dff1 h1:9Xm8CKtMZIXgcopfdWk/qZ1rt0HjMgfMR9nxxSeK6vk= -github.com/jackspirou/syscerts v0.0.0-20160531025014-b68f5469dff1/go.mod h1:zuHl3Hh+e9P6gmBPvcqR1HjkaWHC/csgyskg6IaFKFo= -github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= -github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= -github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= -github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= -github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/drone-plugins/drone-plugin-lib v0.4.0 h1:qywEYGhquUuid6zNLmKia8CWY1TUa8jPQQ/G9ozfAmc= +github.com/drone-plugins/drone-plugin-lib v0.4.0/go.mod h1:EgqogX38GoJFtckeSQyhBJYX8P+KWBPhdprAVvyRxF8= +github.com/drone/drone-template-lib v1.0.0 h1:PNBBfUhifRnrPCoWBlTitk3jipXdv8u8WLbIf7h7j00= +github.com/drone/drone-template-lib v1.0.0/go.mod h1:Hqy1tgqPH5mtbFOZmow19l4jOkZvp+WZ00cB4W3MJhg= +github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/uuid v1.1.0 h1:Jf4mxPC/ziBnoPIdpQdPJ9OeiomAUHLvxmPRSPH9m4s= +github.com/google/uuid v1.1.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/huandu/xstrings v1.2.0 h1:yPeWdRnmynF7p+lLYz0H2tthW9lqhMJrQV/U7yy4wX0= +github.com/huandu/xstrings v1.2.0/go.mod h1:DvyZB1rfVYsBIigL8HwpZgxHwXozlTgGqn63UyNX5k4= +github.com/imdario/mergo v0.3.7 h1:Y+UAYTZ7gDEuOfhxKWy+dvb5dRQ6rJjFSdX2HZY1/gI= +github.com/imdario/mergo v0.3.7/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA= +github.com/joho/godotenv v1.3.0 h1:Zjp+RcGpHhGlrMbJzXTrZZPrWj+1vfm90La1wgB6Bhc= +github.com/joho/godotenv v1.3.0/go.mod h1:7hK45KPybAkOC6peb+G5yklZfMxEjkZhHbwpqxOKXbg= +github.com/konsorten/go-windows-terminal-sequences v1.0.3 h1:CE8S1cTafDpPvMhIxNJKvHsGVBgn1xWYf1NbHQhywc8= +github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I= github.com/pkg/errors v0.8.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/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= -github.com/sirupsen/logrus v1.4.2 h1:SPIRibHv4MatM3XXNO2BJeFLZwZ2LvZgfQ5+UNI2im4= -github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= -github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/russross/blackfriday/v2 v2.0.1 h1:lPqVAte+HuHNfhJ/0LC98ESWRz8afy9tM/0RK8m9o+Q= +github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/shurcooL/sanitized_anchor_name v1.0.0 h1:PdmoCO6wvbs+7yrJyMORt4/BmY5IYyJwS/kOiWx8mHo= +github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= +github.com/sirupsen/logrus v1.6.0 h1:UBcNElsrwanuuMsnGSlYmtmgbb23qDR5dG+6X6Oo89I= +github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88= +github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= -github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q= -github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= -github.com/tkuchiki/faketime v0.1.1 h1:UZjBlktFAi23wo+jWuHuNoHUpLnB0j/5B62bl5nCPls= -github.com/tkuchiki/faketime v0.1.1/go.mod h1:RXY/TXAwGGL36IKDjrHFMcjpUrEiyWSEtLhFPw3UWF0= -github.com/urfave/cli v1.20.0 h1:fDqGv3UG/4jbVl/QkFwEdddtEDjh/5Ov6X+0B/3bPaw= -github.com/urfave/cli v1.20.0/go.mod h1:70zkFmudgCuE/ngEzBv17Jvp/497gISqfk5gWijbERA= -github.com/urfave/cli v1.21.0 h1:wYSSj06510qPIzGSua9ZqsncMmWE3Zr55KBERygyrxE= -github.com/urfave/cli v1.21.0/go.mod h1:lxDj6qX9Q6lWQxIrbrT0nwecwUtRnhVZAJjJZrVUZZQ= +github.com/tkuchiki/faketime v0.0.0-20170607100027-a4500a4f4643/go.mod h1:RXY/TXAwGGL36IKDjrHFMcjpUrEiyWSEtLhFPw3UWF0= +github.com/urfave/cli v1.22.5 h1:lNq9sAHXK2qfdI8W+GRItjCEkI+2oR4d+MEHy1CKXoU= +github.com/urfave/cli/v2 v2.2.0/go.mod h1:SE9GqnLQmjVa0iPEY0f1w3ygNIYcIJ0OKPMoW2caLfQ= +github.com/urfave/cli/v2 v2.3.0 h1:qph92Y649prgesehzOrQjdWyxFOp/QVM+6imKHad91M= +github.com/urfave/cli/v2 v2.3.0/go.mod h1:LJmUH05zAU44vOAcrfzZQKsZbVcdbOG8rtL3/XcUArI= +golang.org/x/crypto v0.0.0-20190211182817-74369b46fc67/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2 h1:VklqNMn3ovrHsnt90PveolxSbWFaJdECFbxSq0Mqo2M= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/lint v0.0.0-20190909230951-414d861bb4ac h1:8R1esu+8QioDxo4E4mX6bFztO+dMTM49DNAaWfO5OeY= -golang.org/x/lint v0.0.0-20190909230951-414d861bb4ac/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/sync v0.0.0-20190423024810-112230192c58/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-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190422165155-953cdadca894 h1:Cz4ceDQGXuKRnVBDTS23GTn/pU5OE2C0WrNTOYK1Uuc= golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac h1:MQEvx39qSf8vyrx3XRaOe+j1UDIzKwkYOVObRgGPVqI= -golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +golang.org/x/tools v0.0.0-20190624222133-a101b041ded4/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= -gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -honnef.co/go/tools v0.0.1-2019.2.3 h1:3JgtbtFHMiCmsznwGVTUWbgGov+pVqnlf1dEJTNAXeM= -honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= +gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gotest.tools/v3 v3.0.2/go.mod h1:3SzNCllyD9/Y+b5r9JIKQ474KzkZyqLqEfYqMsX94Bk= diff --git a/helper.go b/helper.go deleted file mode 100644 index 12f6c77..0000000 --- a/helper.go +++ /dev/null @@ -1,12 +0,0 @@ -package main - -// intInSlice checks if int is in slice of ints -func intInSlice(s []int, e int) bool { - for _, a := range s { - if a == e { - return true - } - } - - return false -} diff --git a/main.go b/main.go deleted file mode 100644 index c8ef24a..0000000 --- a/main.go +++ /dev/null @@ -1,201 +0,0 @@ -package main - -import ( - "os" - - "github.com/drone-plugins/drone-plugin-lib/pkg/urfave" - log "github.com/sirupsen/logrus" - "github.com/urfave/cli" -) - -var ( - version = "unknown" -) - -const ( - // MethodFlag defines the method flag name - MethodFlag = "method" - - // MethodEnvVar defines the method env var - MethodEnvVar = "PLUGIN_METHOD" - - // UsernameFlag defines the username flag name - UsernameFlag = "username" - - // UsernameEnvVar defines the username env var - UsernameEnvVar = "PLUGIN_USERNAME,WEBHOOK_USERNAME" - - // PasswordFlag defines the password flag name - PasswordFlag = "password" - - // PasswordEnvVar defines the password env var - PasswordEnvVar = "PLUGIN_PASSWORD,WEBHOOK_PASSWORD" - - // ContentTypeFlag defines the content type flag name - ContentTypeFlag = "content-type" - - // ContentTypeEnvVar defines the content type env var - ContentTypeEnvVar = "PLUGIN_CONTENT_TYPE" - - // TemplateFlag defines the template flag name - TemplateFlag = "template" - - // TemplateEnvVar defines the template env var - TemplateEnvVar = "PLUGIN_TEMPLATE" - - // HeadersFlag defines the headers flag name - HeadersFlag = "headers" - - // HeadersEnvVar defines the headers env var - HeadersEnvVar = "PLUGIN_HEADERS" - - // URLsFlag defines the urls flag name - URLsFlag = "urls" - - // URLsEnvVar defines the urls env var - URLsEnvVar = "PLUGIN_URLS,PLUGIN_URL,WEBHOOK_URLS,WEBHOOK_URL" - - // ValidResponseCodesFlag defines the valid response codes flag name - ValidResponseCodesFlag = "valid-response-codes" - - // ValidResponseCodesEnvVar defines the valid response codes env var - ValidResponseCodesEnvVar = "PLUGIN_VALID_RESPONSE_CODES" - - // DebugFlag defines the debug flag name - DebugFlag = "debug" - - // DebugEnvVar defines the debug env var - DebugEnvVar = "PLUGIN_DEBUG" - - // SkipVerifyFlag defines the skip verify flag name - SkipVerifyFlag = "skip-verify" - - // SkipVerifyEnvVar defines the skip verify env var - SkipVerifyEnvVar = "PLUGIN_SKIP_VERIFY" -) - -func main() { - app := cli.NewApp() - app.Name = "webhook plugin" - app.Usage = "webhook plugin" - app.Action = run - app.Version = version - app.Flags = []cli.Flag{ - cli.StringFlag{ - Name: MethodFlag, - Usage: "webhook method", - EnvVar: MethodEnvVar, - Value: "POST", - }, - cli.StringFlag{ - Name: UsernameFlag, - Usage: "username for basic auth", - EnvVar: UsernameEnvVar, - }, - cli.StringFlag{ - Name: PasswordFlag, - Usage: "password for basic auth", - EnvVar: PasswordEnvVar, - }, - cli.StringFlag{ - Name: ContentTypeFlag, - Usage: "content type", - EnvVar: ContentTypeEnvVar, - Value: "application/json", - }, - cli.StringFlag{ - Name: TemplateFlag, - Usage: "custom template for webhook", - EnvVar: TemplateEnvVar, - }, - cli.StringSliceFlag{ - Name: HeadersFlag, - Usage: "custom headers key map", - EnvVar: HeadersEnvVar, - }, - cli.StringSliceFlag{ - Name: URLsFlag, - Usage: "list of urls to perform the action on", - EnvVar: URLsEnvVar, - }, - cli.IntSliceFlag{ - Name: ValidResponseCodesFlag, - Usage: "list of valid http response codes", - EnvVar: ValidResponseCodesEnvVar, - }, - cli.BoolFlag{ - Name: DebugFlag, - Usage: "enable debug information", - EnvVar: DebugEnvVar, - }, - cli.BoolFlag{ - Name: SkipVerifyFlag, - Usage: "skip ssl verification", - EnvVar: SkipVerifyEnvVar, - }, - } - - flags := [][]cli.Flag{ - urfave.BuildFlags(), - urfave.RepoFlags(), - urfave.CommitFlags(), - urfave.StageFlags(), - urfave.StepFlags(), - urfave.SemVerFlags(), - } - - for _, flagz := range flags { - app.Flags = append( - app.Flags, - flagz..., - ) - } - - if err := app.Run(os.Args); err != nil { - os.Exit(1) - } -} - -func run(c *cli.Context) error { - plugin := Plugin{ - Build: urfave.BuildFromContext(c), - Repo: urfave.RepoFromContext(c), - Commit: urfave.CommitFromContext(c), - Stage: urfave.StageFromContext(c), - Step: urfave.StepFromContext(c), - SemVer: urfave.SemVerFromContext(c), - - Config: Config{ - Method: c.String(MethodFlag), - Username: c.String(UsernameFlag), - Password: c.String(PasswordFlag), - ContentType: c.String(ContentTypeFlag), - Template: c.String(TemplateFlag), - Headers: c.StringSlice(HeadersFlag), - URLs: c.StringSlice(URLsFlag), - ValidCodes: c.IntSlice(ValidResponseCodesFlag), - Debug: c.Bool(DebugFlag), - SkipVerify: c.Bool(SkipVerifyFlag), - }, - } - - if plugin.Config.Debug { - log.SetLevel(log.DebugLevel) - } - - if len(plugin.Config.URLs) == 0 { - log.Fatal("You must provide at least one url") - } - - return plugin.Exec() -} - -func init() { - log.SetFormatter(&log.TextFormatter{ - DisableColors: true, - DisableTimestamp: true, - }) - - log.SetOutput(os.Stdout) - log.SetLevel(log.InfoLevel) -} diff --git a/plugin.go b/plugin.go deleted file mode 100644 index 4647ba0..0000000 --- a/plugin.go +++ /dev/null @@ -1,177 +0,0 @@ -package main - -import ( - "bytes" - "crypto/tls" - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "net/url" - "strings" - - "github.com/drone-plugins/drone-plugin-lib/pkg/plugin" - "github.com/drone/drone-template-lib/template" - "github.com/jackspirou/syscerts" - log "github.com/sirupsen/logrus" -) - -type ( - // Config provides the pugin configuration. - Config struct { - Method string - Username string - Password string - ContentType string - Template string - Headers []string - URLs []string - ValidCodes []int - Debug bool - SkipVerify bool - } - - // Plugin provides all required attributes. - Plugin struct { - Build plugin.Build - Repo plugin.Repo - Commit plugin.Commit - Stage plugin.Stage - Step plugin.Step - SemVer plugin.SemVer - Config Config - } -) - -// Exec provides the concrete plugin handler. -func (p Plugin) Exec() error { - b, err := p.payload() - - if err != nil { - return err - } - - for i, raw := range p.Config.URLs { - uri, err := url.Parse(raw) - - if err != nil { - log.WithFields(log.Fields{ - "error": err, - }).Error("Failed to parse hook URL") - - return err - } - - req, err := http.NewRequest(p.Config.Method, uri.String(), bytes.NewReader(b)) - - if err != nil { - log.WithFields(log.Fields{ - "error": err, - }).Error("Failed to create HTTP request") - - return err - } - - req.Header.Set("Content-Type", p.Config.ContentType) - - for _, value := range p.Config.Headers { - header := strings.SplitN(value, "=", 2) - req.Header.Set(header[0], header[1]) - } - - if p.Config.Username != "" && p.Config.Password != "" { - req.SetBasicAuth(p.Config.Username, p.Config.Password) - } - - client := &http.Client{ - Transport: &http.Transport{ - Proxy: http.ProxyFromEnvironment, - TLSClientConfig: &tls.Config{ - RootCAs: syscerts.SystemRootsPool(), - InsecureSkipVerify: p.Config.SkipVerify, - }, - }, - } - - resp, err := client.Do(req) - - if err != nil { - log.WithFields(log.Fields{ - "error": err, - }).Error("Failed to execute HTTP request") - - return err - } - - defer resp.Body.Close() - - if p.Config.Debug || resp.StatusCode >= http.StatusBadRequest { - body, err := ioutil.ReadAll(resp.Body) - - if err != nil { - log.WithFields(log.Fields{ - "error": err, - }).Error("Failed to parse HTTP response") - } - - output, err := template.RenderTrim(result, webhook{ - Debug: p.Config.Debug, - Number: i, - URL: req.URL.String(), - Method: req.Method, - Header: req.Header, - Status: resp.Status, - Request: string(b), - Response: string(body), - }) - - if err != nil { - log.WithFields(log.Fields{ - "error": err, - }).Error("Failed to parse debug template") - - return err - } - - fmt.Println(output) - } - - if len(p.Config.ValidCodes) > 0 && !intInSlice(p.Config.ValidCodes, resp.StatusCode) { - log.WithFields(log.Fields{ - "code": resp.StatusCode, - }).Error("Valid response code not found") - - return fmt.Errorf("valid response code not found") - } - } - - return nil -} - -func (p Plugin) payload() ([]byte, error) { - if p.Config.Template == "" { - res, err := json.Marshal(&p) - - if err != nil { - log.WithFields(log.Fields{ - "error": err, - }).Error("Failed to generate JSON response") - - return []byte{}, err - } - - return res, nil - } - - res, err := template.RenderTrim(p.Config.Template, p) - - if err != nil { - log.WithFields(log.Fields{ - "error": err, - }).Error("Failed to parse response template") - - return []byte{}, err - } - - return []byte(res), nil -} diff --git a/plugin/helper.go b/plugin/helper.go new file mode 100644 index 0000000..2bcb196 --- /dev/null +++ b/plugin/helper.go @@ -0,0 +1,20 @@ +// Copyright (c) 2020, the Drone Plugins project authors. +// Please see the AUTHORS file for details. All rights reserved. +// Use of this source code is governed by an Apache 2.0 license that can be +// found in the LICENSE file. + +package plugin + +import "fmt" + +// intInSlice checks if int is in slice of ints +func intInSlice(s []string, e int) bool { + eStr := fmt.Sprintf("%d", e) + for _, a := range s { + if a == eStr { + return true + } + } + + return false +} diff --git a/plugin/impl.go b/plugin/impl.go new file mode 100644 index 0000000..f6e9cd0 --- /dev/null +++ b/plugin/impl.go @@ -0,0 +1,133 @@ +// Copyright (c) 2020, the Drone Plugins project authors. +// Please see the AUTHORS file for details. All rights reserved. +// Use of this source code is governed by an Apache 2.0 license that can be +// found in the LICENSE file. + +package plugin + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "io/ioutil" + "net/http" + "net/url" + "strings" + + "github.com/drone/drone-template-lib/template" + "github.com/urfave/cli/v2" +) + +// Settings for the plugin. +type Settings struct { + Method string + Username string + Password string + ContentType string + Template string + Headers cli.StringSlice + URLs cli.StringSlice + ValidCodes cli.StringSlice +} + +// Validate handles the settings validation of the plugin. +func (p *Plugin) Validate() error { + if len(p.settings.URLs.Value()) == 0 { + return errors.New("must provide at least one webhook url") + } + + for _, raw := range p.settings.URLs.Value() { + _, err := url.Parse(raw) + if err != nil { + return err + } + } + + return nil +} + +// Execute provides the implementation of the plugin. +func (p *Plugin) Execute() error { + b, err := p.payload() + + if err != nil { + return err + } + + for i, raw := range p.settings.URLs.Value() { + uri, _ := url.Parse(raw) + + req, err := http.NewRequest(p.settings.Method, uri.String(), bytes.NewReader(b)) + if err != nil { + return fmt.Errorf("failed to create http request: %w", err) + } + + req.Header.Set("Content-Type", p.settings.ContentType) + for _, value := range p.settings.Headers.Value() { + header := strings.SplitN(value, "=", 2) + req.Header.Set(header[0], header[1]) + } + + if p.settings.Username != "" && p.settings.Password != "" { + req.SetBasicAuth(p.settings.Username, p.settings.Password) + } + + resp, err := p.network.Client.Do(req) + if err != nil { + return fmt.Errorf("failed to execute http request: %w", err) + } + + defer resp.Body.Close() + + if /*p.settings.Debug ||*/ resp.StatusCode >= http.StatusBadRequest { + body, err := ioutil.ReadAll(resp.Body) + + if err != nil { + return fmt.Errorf("failed to parse http response: %w", err) + } + + output, err := template.RenderTrim(result, webhook{ + Debug: true, //p.settings.Debug, + Number: i, + URL: req.URL.String(), + Method: req.Method, + Header: req.Header, + Status: resp.Status, + Request: string(b), + Response: string(body), + }) + if err != nil { + return fmt.Errorf("failed to parse debug template: %w", err) + } + + fmt.Println(output) + } + + validCodes := p.settings.ValidCodes.Value() + if len(validCodes) > 0 && !intInSlice(validCodes, resp.StatusCode) { + return fmt.Errorf("response of %d is not valid", resp.StatusCode) + } + } + + return nil +} + +func (p *Plugin) payload() ([]byte, error) { + if p.settings.Template == "" { + res, err := json.Marshal(&p.pipeline) + + if err != nil { + return []byte{}, fmt.Errorf("failed to generate json response: %w", err) + } + + return res, nil + } + + res, err := template.RenderTrim(p.settings.Template, p) + if err != nil { + return []byte{}, fmt.Errorf("failed to parse response template: %w", err) + } + + return []byte(res), nil +} diff --git a/plugin/impl_test.go b/plugin/impl_test.go new file mode 100644 index 0000000..badfaa0 --- /dev/null +++ b/plugin/impl_test.go @@ -0,0 +1,18 @@ +// Copyright (c) 2020, the Drone Plugins project authors. +// Please see the AUTHORS file for details. All rights reserved. +// Use of this source code is governed by an Apache 2.0 license that can be +// found in the LICENSE file. + +package plugin + +import ( + "testing" +) + +func TestValidate(t *testing.T) { + t.Skip() +} + +func TestExecute(t *testing.T) { + t.Skip() +} diff --git a/plugin/plugin.go b/plugin/plugin.go new file mode 100644 index 0000000..bb8248b --- /dev/null +++ b/plugin/plugin.go @@ -0,0 +1,26 @@ +// Copyright (c) 2020, the Drone Plugins project authors. +// Please see the AUTHORS file for details. All rights reserved. +// Use of this source code is governed by an Apache 2.0 license that can be +// found in the LICENSE file. + +package plugin + +import ( + "github.com/drone-plugins/drone-plugin-lib/drone" +) + +// Plugin implements drone.Plugin to provide the plugin implementation. +type Plugin struct { + settings Settings + pipeline drone.Pipeline + network drone.Network +} + +// New initializes a plugin from the given Settings, Pipeline, and Network. +func New(settings Settings, pipeline drone.Pipeline, network drone.Network) drone.Plugin { + return &Plugin{ + settings: settings, + pipeline: pipeline, + network: network, + } +} diff --git a/plugin/plugin_test.go b/plugin/plugin_test.go new file mode 100644 index 0000000..3cb461f --- /dev/null +++ b/plugin/plugin_test.go @@ -0,0 +1,14 @@ +// Copyright (c) 2020, the Drone Plugins project authors. +// Please see the AUTHORS file for details. All rights reserved. +// Use of this source code is governed by an Apache 2.0 license that can be +// found in the LICENSE file. + +package plugin + +import ( + "testing" +) + +func TestPlugin(t *testing.T) { + t.Skip() +} diff --git a/template.go b/plugin/template.go similarity index 64% rename from template.go rename to plugin/template.go index 219f10c..e584cee 100644 --- a/template.go +++ b/plugin/template.go @@ -1,4 +1,9 @@ -package main +// Copyright (c) 2020, the Drone Plugins project authors. +// Please see the AUTHORS file for details. All rights reserved. +// Use of this source code is governed by an Apache 2.0 license that can be +// found in the LICENSE file. + +package plugin import ( "net/http" diff --git a/renovate.json b/renovate.json new file mode 100644 index 0000000..a88a8a2 --- /dev/null +++ b/renovate.json @@ -0,0 +1,26 @@ +{ + "extends": [ + "config:base", + ":automergeMinor", + ":automergeDigest" + ], + "enabledManagers": [ + "dockerfile", + "gomod" + ], + "dockerfile": { + "fileMatch": [ + "docker/Dockerfile\\.linux\\.(arm|arm64|amd64|multiarch)", + "docker/Dockerfile\\.windows\\.(1809|1903|1909|2004)" + ], + "pinDigests": true + }, + "gomod": { + "postUpdateOptions": [ + "gomodTidy" + ] + }, + "labels": [ + "renovate" + ] +} From c61f34433b705f0e5c8a9339e61f1ff0048d8403 Mon Sep 17 00:00:00 2001 From: Don Date: Mon, 9 Nov 2020 15:06:33 -0800 Subject: [PATCH 2/2] Move payload function into validate --- plugin/impl.go | 47 ++++++++++++++++++++--------------------------- 1 file changed, 20 insertions(+), 27 deletions(-) diff --git a/plugin/impl.go b/plugin/impl.go index f6e9cd0..7f71c2d 100644 --- a/plugin/impl.go +++ b/plugin/impl.go @@ -29,6 +29,7 @@ type Settings struct { Headers cli.StringSlice URLs cli.StringSlice ValidCodes cli.StringSlice + payload []byte } // Validate handles the settings validation of the plugin. @@ -44,21 +45,32 @@ func (p *Plugin) Validate() error { } } + if p.settings.Template == "" { + res, err := json.Marshal(&p.pipeline) + + if err != nil { + return fmt.Errorf("failed to generate json response: %w", err) + } + + p.settings.payload = res + } else { + res, err := template.RenderTrim(p.settings.Template, p) + if err != nil { + return fmt.Errorf("failed to parse response template: %w", err) + } + + p.settings.payload = []byte(res) + } + return nil } // Execute provides the implementation of the plugin. func (p *Plugin) Execute() error { - b, err := p.payload() - - if err != nil { - return err - } - for i, raw := range p.settings.URLs.Value() { uri, _ := url.Parse(raw) - req, err := http.NewRequest(p.settings.Method, uri.String(), bytes.NewReader(b)) + req, err := http.NewRequest(p.settings.Method, uri.String(), bytes.NewReader(p.settings.payload)) if err != nil { return fmt.Errorf("failed to create http request: %w", err) } @@ -94,7 +106,7 @@ func (p *Plugin) Execute() error { Method: req.Method, Header: req.Header, Status: resp.Status, - Request: string(b), + Request: string(p.settings.payload), Response: string(body), }) if err != nil { @@ -112,22 +124,3 @@ func (p *Plugin) Execute() error { return nil } - -func (p *Plugin) payload() ([]byte, error) { - if p.settings.Template == "" { - res, err := json.Marshal(&p.pipeline) - - if err != nil { - return []byte{}, fmt.Errorf("failed to generate json response: %w", err) - } - - return res, nil - } - - res, err := template.RenderTrim(p.settings.Template, p) - if err != nil { - return []byte{}, fmt.Errorf("failed to parse response template: %w", err) - } - - return []byte(res), nil -}