Compare commits

...

2 Commits

14 changed files with 467 additions and 267 deletions

View File

@ -19,7 +19,6 @@ GOLANGCI_LINT_PACKAGE ?= github.com/golangci/golangci-lint/cmd/golangci-lint@$(G
XGO_PACKAGE ?= src.techknowlogick.com/xgo@latest
GOTESTSUM_PACKAGE ?= gotest.tools/gotestsum@latest
GENERATE ?=
XGO_VERSION := go-1.22.x
XGO_TARGETS ?= linux/amd64,linux/arm-6,linux/arm-7,linux/arm64
@ -65,7 +64,7 @@ lint: golangci-lint
.PHONY: generate
generate:
$(GO) generate $(GENERATE)
$(GO) generate $(PACKAGES)
.PHONY: generate-docs
generate-docs:

View File

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

View File

@ -1,61 +0,0 @@
package main
import (
"github.com/thegeeklab/wp-github-comment/plugin"
"github.com/urfave/cli/v2"
)
// settingsFlags has the cli.Flags for the plugin.Settings.
//
//go:generate go run docs.go flags.go
func settingsFlags(settings *plugin.Settings, category string) []cli.Flag {
return []cli.Flag{
&cli.StringFlag{
Name: "api-key",
EnvVars: []string{"PLUGIN_API_KEY", "GITHUB_COMMENT_API_KEY"},
Usage: "personal access token to access the GitHub API",
Destination: &settings.APIKey,
Category: category,
Required: true,
},
&cli.StringFlag{
Name: "base-url",
EnvVars: []string{"PLUGIN_BASE_URL", "GITHUB_COMMENT_BASE_URL"},
Usage: "API URL",
Value: "https://api.github.com/",
Destination: &settings.BaseURL,
Category: category,
},
&cli.StringFlag{
Name: "key",
EnvVars: []string{"PLUGIN_KEY", "GITHUB_COMMENT_KEY"},
Usage: "unique identifier to assign to a comment",
Destination: &settings.Key,
Category: category,
},
&cli.StringFlag{
Name: "message",
EnvVars: []string{"PLUGIN_MESSAGE", "GITHUB_COMMENT_MESSAGE"},
Usage: "path to file or string that contains the comment text",
Destination: &settings.Message,
Category: category,
Required: true,
},
&cli.BoolFlag{
Name: "update",
EnvVars: []string{"PLUGIN_UPDATE", "GITHUB_COMMENT_UPDATE"},
Usage: "enable update of an existing comment that matches the key",
Value: false,
Destination: &settings.Update,
Category: category,
},
&cli.BoolFlag{
Name: "skip-missing",
EnvVars: []string{"PLUGIN_SKIP_MISSING", "GITHUB_COMMENT_SKIP_MISSING"},
Usage: "skip comment creation if the given message file does not exist",
Value: false,
Destination: &settings.SkipMissing,
Category: category,
},
}
}

View File

@ -1,11 +1,7 @@
package main
import (
"fmt"
"github.com/thegeeklab/wp-github-comment/plugin"
wp "github.com/thegeeklab/wp-plugin-go/plugin"
)
//nolint:gochecknoglobals
@ -15,14 +11,5 @@ var (
)
func main() {
settings := &plugin.Settings{}
options := wp.Options{
Name: "wp-github-comment",
Description: "Add comments to GitHub Issues and Pull Requests",
Version: BuildVersion,
VersionMetadata: fmt.Sprintf("date=%s", BuildDate),
Flags: settingsFlags(settings, wp.FlagsPluginCategory),
}
plugin.New(options, settings).Run()
plugin.New(nil, BuildVersion, BuildDate).Run()
}

View File

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

View File

@ -15,6 +15,13 @@ properties:
defaultValue: "https://api.github.com/"
required: false
- name: insecure_skip_verify
description: |
Skip SSL verification.
type: bool
defaultValue: false
required: false
- name: key
description: |
Unique identifier to assign to a comment.
@ -23,6 +30,13 @@ properties:
type: string
required: false
- name: log_level
description: |
Plugin log level.
type: string
defaultValue: "info"
required: false
- name: message
description: |
Path to file or string that contains the comment text.

16
go.mod
View File

@ -4,8 +4,10 @@ go 1.22
require (
github.com/google/go-github/v61 v61.0.0
github.com/migueleliasweb/go-github-mock v0.0.23
github.com/rs/zerolog v1.32.0
github.com/thegeeklab/wp-plugin-go v1.7.1
github.com/stretchr/testify v1.9.0
github.com/thegeeklab/wp-plugin-go/v2 v2.3.1
github.com/urfave/cli/v2 v2.27.2
golang.org/x/oauth2 v0.20.0
)
@ -15,8 +17,11 @@ require (
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/go-github/v59 v59.0.0 // indirect
github.com/google/go-querystring v1.1.0 // indirect
github.com/google/uuid v1.1.1 // indirect
github.com/gorilla/mux v1.8.0 // 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
@ -24,11 +29,14 @@ require (
github.com/mattn/go-isatty v0.0.19 // indirect
github.com/mitchellh/copystructure v1.0.0 // indirect
github.com/mitchellh/reflectwalk v1.0.0 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/russross/blackfriday/v2 v2.1.0 // indirect
github.com/shopspring/decimal v1.2.0 // indirect
github.com/spf13/cast v1.3.1 // indirect
github.com/xrash/smetrics v0.0.0-20240312152122-5f08fbb34913 // indirect
golang.org/x/crypto v0.22.0 // indirect
golang.org/x/net v0.24.0 // indirect
golang.org/x/sys v0.19.0 // 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
golang.org/x/time v0.3.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

25
go.sum
View File

@ -15,12 +15,16 @@ github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5x
github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/go-github/v59 v59.0.0 h1:7h6bgpF5as0YQLLkEiVqpgtJqjimMYhBkD4jT5aN3VA=
github.com/google/go-github/v59 v59.0.0/go.mod h1:rJU4R0rQHFVFDOkqGWxfLNo6vEk4dv40oDjhV/gH6wM=
github.com/google/go-github/v61 v61.0.0 h1:VwQCBwhyE9JclCI+22/7mLB1PuU9eowCXKY5pNlu1go=
github.com/google/go-github/v61 v61.0.0/go.mod h1:0WR+KmsWX75G2EbpyGsGmradjo3IiciuI4BmdVCobQY=
github.com/google/go-querystring v1.1.0 h1:AnCroh3fv4ZBgVIf1Iwtovgjaw/GiKJo8M8yD/fhyJ8=
github.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17icRSOU623lUBU=
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/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI=
github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So=
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=
@ -32,6 +36,8 @@ 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/migueleliasweb/go-github-mock v0.0.23 h1:GOi9oX/+Seu9JQ19V8bPDLqDI7M9iEOjo3g8v1k6L2c=
github.com/migueleliasweb/go-github-mock v0.0.23/go.mod h1:NsT8FGbkvIZQtDu38+295sZEX8snaUiiQgsGxi6GUxk=
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=
@ -53,8 +59,8 @@ github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXf
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/thegeeklab/wp-plugin-go v1.7.1 h1:zfR/rfNPuyVhXJu1fsLfp4+Mz2pTf6WwW/mIqw9750I=
github.com/thegeeklab/wp-plugin-go v1.7.1/go.mod h1:Ixi5plt9tpFGTu6yc/Inm5DcDpp3xPTeohfr86gf2EU=
github.com/thegeeklab/wp-plugin-go/v2 v2.3.1 h1:ARwYgTPZ5iPsmOenmqcCf8TjiEe8wBOHKO7H/Xshe48=
github.com/thegeeklab/wp-plugin-go/v2 v2.3.1/go.mod h1:0t8M8txtEFiaB6RqLX8vLrxkqAo5FT5Hx7dztN592D4=
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=
@ -63,15 +69,15 @@ github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5t
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.22.0 h1:g1v0xeRhjcugydODzvb3mEM9SQ0HGp9s/nh3COQ/C30=
golang.org/x/crypto v0.22.0/go.mod h1:vr6Su+7cTlO45qkww3VDJlzDn0ctJvRgYbC2NvXHt+M=
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.24.0 h1:1PcaxkF854Fu3+lvBIx5SYn9wRlBzzcnHZSiaFFAb0w=
golang.org/x/net v0.24.0/go.mod h1:2Q7sJY5mzlzWjKtYUEXSlBWCdyaioyXzRB2RtU8KVE8=
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/oauth2 v0.20.0 h1:4mQdhULixXKP1rwYBW0vAijoXnkTG0BLCDRzfe1idMo=
golang.org/x/oauth2 v0.20.0/go.mod h1:XYTD2NtWslqkgxebSiOHnXEap4TF09sJSc7H1sXbhtI=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
@ -85,8 +91,8 @@ golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.19.0 h1:q5f1RH2jigJ1MoAWp2KTp3gm5zAGFUTarQZ5U386+4o=
golang.org/x/sys v0.19.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=
@ -94,11 +100,14 @@ 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/time v0.3.0 h1:rg5rLMjNzMS1RkNLzCG38eapWhnYLFYXDXj2gOlr8j4=
golang.org/x/time v0.3.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
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=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.3.0 h1:clyUAQHOM3G0M3f5vQj7LuJrETvjVot3Z5el9nffUtU=

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

@ -0,0 +1,42 @@
//go:build generate
// +build generate
package main
import (
"context"
"flag"
"net/http"
"os"
"time"
"github.com/thegeeklab/wp-github-comment/plugin"
"github.com/thegeeklab/wp-plugin-go/v2/docs"
"github.com/thegeeklab/wp-plugin-go/v2/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 := template.Render(context.Background(), client, tmpl, 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

@ -1,84 +0,0 @@
package plugin
import (
"context"
"fmt"
"strings"
"github.com/google/go-github/v61/github"
)
type commentClient struct {
Message string
Update bool
Key string
Repo string
Owner string
IssueNum int
*github.Client
}
func (cc *commentClient) issueComment(ctx context.Context) error {
var (
err error
comment *github.IssueComment
resp *github.Response
)
issueComment := &github.IssueComment{
Body: &cc.Message,
}
if cc.Update {
// Append plugin comment ID to comment message so we can search for it later
message := fmt.Sprintf("%s\n<!-- id: %s -->\n", cc.Message, cc.Key)
issueComment.Body = &message
comment, err = cc.comment(ctx)
if err == nil && comment != nil {
_, resp, err = cc.Client.Issues.EditComment(ctx, cc.Owner, cc.Repo, *comment.ID, issueComment)
}
}
if err == nil && resp == nil {
_, _, err = cc.Client.Issues.CreateComment(ctx, cc.Owner, cc.Repo, cc.IssueNum, issueComment)
}
if err != nil {
return err
}
return nil
}
func (cc *commentClient) comment(ctx context.Context) (*github.IssueComment, error) {
var allComments []*github.IssueComment
opts := &github.IssueListCommentsOptions{}
for {
comments, resp, err := cc.Client.Issues.ListComments(ctx, cc.Owner, cc.Repo, cc.IssueNum, opts)
if err != nil {
return nil, err
}
allComments = append(allComments, comments...)
if resp.NextPage == 0 {
break
}
opts.Page = resp.NextPage
}
for _, comment := range allComments {
if strings.Contains(*comment.Body, fmt.Sprintf("<!-- id: %s -->", cc.Key)) {
return comment, nil
}
}
//nolint:nilnil
return nil, nil
}

96
plugin/github.go Normal file
View File

@ -0,0 +1,96 @@
package plugin
import (
"context"
"errors"
"fmt"
"strings"
"github.com/google/go-github/v61/github"
)
var ErrCommentNotFound = errors.New("no comment found")
type GithubClient struct {
Client *github.Client
Issue *GithubIssue
}
type GithubIssue struct {
*github.Client
Number int
Message string
Key string
Repo string
Owner string
Update bool
}
// Constructor function for Parent.
func NewGithubClient(client *github.Client) *GithubClient {
return &GithubClient{
Client: client,
Issue: &GithubIssue{Client: client},
}
}
// AddComment adds a new comment or updates an existing comment on a GitHub issue.
// If the Update field is true, it will append a unique identifier to the comment
// body and attempt to find and update the existing comment with that identifier.
// Otherwise, it will create a new comment on the issue.
func (i *GithubIssue) AddComment(ctx context.Context) (*github.IssueComment, error) {
issueComment := &github.IssueComment{
Body: &i.Message,
}
if i.Update {
// Append plugin comment ID to comment message so we can search for it later
*issueComment.Body = fmt.Sprintf("%s\n<!-- id: %s -->\n", i.Message, i.Key)
comment, err := i.FindComment(ctx)
if err != nil && !errors.Is(err, ErrCommentNotFound) {
return comment, err
}
if comment != nil {
comment, _, err = i.Client.Issues.EditComment(ctx, i.Owner, i.Repo, *comment.ID, issueComment)
return comment, err
}
}
comment, _, err := i.Client.Issues.CreateComment(ctx, i.Owner, i.Repo, i.Number, issueComment)
return comment, err
}
// FindComment returns the GitHub issue comment that contains the specified key, or nil if no such comment exists.
// It retrieves all comments on the issue and searches for one that contains the specified key in the comment body.
func (i *GithubIssue) FindComment(ctx context.Context) (*github.IssueComment, error) {
var allComments []*github.IssueComment
opts := &github.IssueListCommentsOptions{}
for {
comments, resp, err := i.Client.Issues.ListComments(ctx, i.Owner, i.Repo, i.Number, opts)
if err != nil {
return nil, err
}
allComments = append(allComments, comments...)
if resp.NextPage == 0 {
break
}
opts.Page = resp.NextPage
}
for _, comment := range allComments {
if strings.Contains(*comment.Body, fmt.Sprintf("<!-- id: %s -->", i.Key)) {
return comment, nil
}
}
return nil, fmt.Errorf("%w key: %s", ErrCommentNotFound, i.Key)
}

192
plugin/github_test.go Normal file
View File

@ -0,0 +1,192 @@
package plugin
import (
"context"
"fmt"
"net/http"
"testing"
"github.com/google/go-github/v61/github"
"github.com/migueleliasweb/go-github-mock/src/mock"
"github.com/stretchr/testify/assert"
)
func TestGithubIssue_FindComment(t *testing.T) {
ctx := context.Background()
key := "test-key"
keyPattern := "<!-- id: " + key + " -->"
owner := "test-owner"
repo := "test-repo"
number := 1
tests := []struct {
name string
comments []*github.IssueComment
want *github.IssueComment
wantErr error
}{
{
name: "no comments",
want: nil,
wantErr: ErrCommentNotFound,
},
{
name: "comment found",
comments: []*github.IssueComment{
{Body: github.String(keyPattern)},
},
want: &github.IssueComment{Body: github.String(keyPattern)},
},
{
name: "comment not found",
comments: []*github.IssueComment{
{Body: github.String("other comment")},
},
want: nil,
wantErr: ErrCommentNotFound,
},
{
name: "multiple comments",
comments: []*github.IssueComment{
{Body: github.String("other comment")},
{Body: github.String(keyPattern)},
{Body: github.String("another comment")},
},
want: &github.IssueComment{Body: github.String(keyPattern)},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
mockedHTTPClient := mock.NewMockedHTTPClient(
mock.WithRequestMatch(
mock.GetReposIssuesCommentsByOwnerByRepoByIssueNumber,
tt.comments,
),
)
client := github.NewClient(mockedHTTPClient)
issue := &GithubIssue{
Client: client,
Owner: owner,
Repo: repo,
Number: number,
Key: key,
}
got, err := issue.FindComment(ctx)
if tt.wantErr != nil {
assert.Error(t, err)
assert.Equal(t, tt.want, got)
return
}
assert.NoError(t, err)
assert.Equal(t, tt.want, got)
})
}
}
func TestGithubIssue_AddComment(t *testing.T) {
ctx := context.Background()
key := "test-key"
keyPattern := "<!-- id: " + key + " -->"
owner := "test-owner"
repo := "test-repo"
number := 1
message := "test message"
tests := []struct {
name string
update bool
existingKey string
comments []*github.IssueComment
want *github.IssueComment
wantErr bool
}{
{
name: "create new comment",
update: false,
want: &github.IssueComment{Body: github.String("test message\n<!-- id: test-key -->\n")},
},
{
name: "update existing comment",
update: true,
comments: []*github.IssueComment{
{ID: github.Int64(123), Body: github.String(keyPattern)},
},
want: &github.IssueComment{Body: github.String("test message\n<!-- id: test-key -->\n")},
},
{
name: "update non-existing comment",
update: true,
want: &github.IssueComment{Body: github.String("test message\n<!-- id: test-key -->\n")},
},
{
name: "create new comment with error",
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
mockedHTTPClient := mock.NewMockedHTTPClient(
mock.WithRequestMatch(
mock.GetReposIssuesCommentsByOwnerByRepoByIssueNumber,
tt.comments,
),
mock.WithRequestMatchHandler(
mock.PostReposIssuesCommentsByOwnerByRepoByIssueNumber,
http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
if tt.wantErr {
mock.WriteError(w, http.StatusInternalServerError, "internal server error")
} else {
_, _ = w.Write(mock.MustMarshal(
&github.IssueComment{
Body: github.String(fmt.Sprintf("%s\n%s\n", message, keyPattern)),
},
))
}
}),
),
mock.WithRequestMatchHandler(
mock.PatchReposIssuesCommentsByOwnerByRepoByCommentId,
http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
if tt.wantErr {
mock.WriteError(w, http.StatusInternalServerError, "internal server error")
} else {
_, _ = w.Write(mock.MustMarshal(
&github.IssueComment{
Body: github.String(fmt.Sprintf("%s\n%s\n", message, keyPattern)),
},
))
}
}),
),
)
client := github.NewClient(mockedHTTPClient)
issue := &GithubIssue{
Client: client,
Owner: owner,
Repo: repo,
Number: number,
Key: key,
Message: message,
Update: tt.update,
}
got, err := issue.AddComment(ctx)
if tt.wantErr {
assert.Error(t, err)
assert.Equal(t, tt.want, got)
return
}
assert.NoError(t, err)
assert.Equal(t, tt.want, got)
})
}
}

View File

@ -10,7 +10,7 @@ import (
"github.com/google/go-github/v61/github"
"github.com/rs/zerolog/log"
"github.com/thegeeklab/wp-plugin-go/file"
"github.com/thegeeklab/wp-plugin-go/v2/file"
"golang.org/x/oauth2"
)
@ -74,18 +74,16 @@ func (p *Plugin) Execute() error {
ts,
)
client := github.NewClient(tc)
client.BaseURL = p.Settings.baseURL
gh := github.NewClient(tc)
gh.BaseURL = p.Settings.baseURL
commentClient := commentClient{
Client: client,
Repo: p.Metadata.Repository.Name,
Owner: p.Metadata.Repository.Owner,
Message: p.Settings.Message,
Update: p.Settings.Update,
Key: p.Settings.Key,
IssueNum: p.Metadata.Curr.PullRequest,
}
client := NewGithubClient(gh)
client.Issue.Repo = p.Metadata.Repository.Name
client.Issue.Owner = p.Metadata.Repository.Owner
client.Issue.Message = p.Settings.Message
client.Issue.Update = p.Settings.Update
client.Issue.Key = p.Settings.Key
client.Issue.Number = p.Metadata.Curr.PullRequest
if p.Settings.SkipMissing && !p.Settings.IsFile {
log.Info().
@ -94,7 +92,7 @@ func (p *Plugin) Execute() error {
return nil
}
err := commentClient.issueComment(p.Network.Context)
_, err := client.Issue.AddComment(p.Network.Context)
if err != nil {
return fmt.Errorf("failed to create or update comment: %w", err)
}

View File

@ -1,11 +1,15 @@
package plugin
import (
"fmt"
"net/url"
wp "github.com/thegeeklab/wp-plugin-go/plugin"
wp "github.com/thegeeklab/wp-plugin-go/v2/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
@ -26,13 +30,85 @@ type Settings struct {
baseURL *url.URL
}
func New(options wp.Options, settings *Settings) *Plugin {
p := &Plugin{}
func New(e wp.ExecuteFunc, build ...string) *Plugin {
p := &Plugin{
Settings: &Settings{},
}
options.Execute = p.run
options := wp.Options{
Name: "wp-github-comment",
Description: "Add comments to GitHub Issues and Pull Requests",
Flags: Flags(p.Settings, wp.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 = wp.New(options)
p.Settings = settings
return p
}
// Flags returns a slice of CLI flags for the plugin.
func Flags(settings *Settings, category string) []cli.Flag {
return []cli.Flag{
&cli.StringFlag{
Name: "api-key",
EnvVars: []string{"PLUGIN_API_KEY", "GITHUB_COMMENT_API_KEY"},
Usage: "personal access token to access the GitHub API",
Destination: &settings.APIKey,
Category: category,
Required: true,
},
&cli.StringFlag{
Name: "base-url",
EnvVars: []string{"PLUGIN_BASE_URL", "GITHUB_COMMENT_BASE_URL"},
Usage: "API URL",
Value: "https://api.github.com/",
Destination: &settings.BaseURL,
Category: category,
},
&cli.StringFlag{
Name: "key",
EnvVars: []string{"PLUGIN_KEY", "GITHUB_COMMENT_KEY"},
Usage: "unique identifier to assign to a comment",
Destination: &settings.Key,
Category: category,
},
&cli.StringFlag{
Name: "message",
EnvVars: []string{"PLUGIN_MESSAGE", "GITHUB_COMMENT_MESSAGE"},
Usage: "path to file or string that contains the comment text",
Destination: &settings.Message,
Category: category,
Required: true,
},
&cli.BoolFlag{
Name: "update",
EnvVars: []string{"PLUGIN_UPDATE", "GITHUB_COMMENT_UPDATE"},
Usage: "enable update of an existing comment that matches the key",
Value: false,
Destination: &settings.Update,
Category: category,
},
&cli.BoolFlag{
Name: "skip-missing",
EnvVars: []string{"PLUGIN_SKIP_MISSING", "GITHUB_COMMENT_SKIP_MISSING"},
Usage: "skip comment creation if the given message file does not exist",
Value: false,
Destination: &settings.SkipMissing,
Category: category,
},
}
}