Skip to content

Commit ae2c3fe

Browse files
committed
admin: add webhook management commands
Add list, create, update and delete subcommands under "pw admin webhook". The list command optionally accepts a project linkname and defaults to showing all webhooks. Create and update support --events with bash completion and a "?" shorthand that lists valid event categories without requiring other flags. The active flag is negatable via --no-active. Signed-off-by: Robin Jarry <robin@jarry.cc>
1 parent e2af447 commit ae2c3fe

3 files changed

Lines changed: 250 additions & 0 deletions

File tree

‎cmd/pw/admin/main.go‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,5 +12,6 @@ type CLI struct {
1212
State StateCmd `cmd:"" help:"Manage states."`
1313
Maintainer MaintainerCmd `cmd:"" help:"Manage project maintainers."`
1414
DelegateRule DelegateRuleCmd `cmd:"" name:"delegate-rule" help:"Manage delegation rules."`
15+
Webhook WebhookCmd `cmd:"" help:"Manage webhooks."`
1516
Gc GcCmd `cmd:"" help:"Garbage collect stale data."`
1617
}

‎cmd/pw/admin/webhooks.go‎

Lines changed: 247 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,247 @@
1+
// Patchwork - automated patch tracking system
2+
// Copyright (C) The Patchwork Contributors (see CONTRIBUTORS)
3+
//
4+
// SPDX-License-Identifier: GPL-2.0-or-later
5+
6+
package admin
7+
8+
import (
9+
"bufio"
10+
"fmt"
11+
"os"
12+
"slices"
13+
"strings"
14+
"text/tabwriter"
15+
"time"
16+
17+
"github.com/alecthomas/kong"
18+
"github.com/uptrace/bun"
19+
20+
"github.com/getpatchwork/patchwork/cmd/pw/pw"
21+
"github.com/getpatchwork/patchwork/pkg/db"
22+
)
23+
24+
type WebhookCmd struct {
25+
List WebhookListCmd `cmd:"" help:"List webhooks for a project."`
26+
Create WebhookCreateCmd `cmd:"" help:"Create a webhook."`
27+
Update WebhookUpdateCmd `cmd:"" help:"Update a webhook."`
28+
Delete WebhookDeleteCmd `cmd:"" help:"Delete a webhook."`
29+
}
30+
31+
type WebhookListCmd struct {
32+
Project string `arg:"" default:"" help:"Project linkname (omit to list all)."`
33+
}
34+
35+
func (c *WebhookListCmd) Run(ctx *pw.Context) error {
36+
q := ctx.DB.NewSelect().Model((*db.Webhook)(nil)).
37+
OrderExpr("id ASC")
38+
39+
if c.Project != "" {
40+
var project db.Project
41+
err := ctx.DB.NewSelect().Model(&project).
42+
Where("linkname = ?", c.Project).
43+
Scan(ctx)
44+
if err != nil {
45+
return fmt.Errorf("project %q not found", c.Project)
46+
}
47+
q = q.Where("project_id = ?", project.ID)
48+
}
49+
50+
var hooks []db.Webhook
51+
if err := q.Scan(ctx, &hooks); err != nil {
52+
return err
53+
}
54+
55+
// resolve project names
56+
projIDs := make(map[int]bool)
57+
for _, h := range hooks {
58+
projIDs[h.ProjectID] = true
59+
}
60+
projMap := make(map[int]string)
61+
if len(projIDs) > 0 {
62+
var projects []db.Project
63+
ids := make([]int, 0, len(projIDs))
64+
for id := range projIDs {
65+
ids = append(ids, id)
66+
}
67+
ctx.DB.NewSelect().Model(&projects).
68+
Where("id IN ?", bun.Tuple(ids)).
69+
Scan(ctx)
70+
for _, p := range projects {
71+
projMap[p.ID] = p.Linkname
72+
}
73+
}
74+
75+
w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
76+
fmt.Fprintf(w, "ID\tPROJECT\tURL\tEVENTS\tACTIVE\n")
77+
for _, h := range hooks {
78+
fmt.Fprintf(w, "%d\t%s\t%s\t%s\t%v\n",
79+
h.ID, projMap[h.ProjectID], h.URL, h.Events, h.Active)
80+
}
81+
return w.Flush()
82+
}
83+
84+
func EventCategories() []string {
85+
events := make([]string, 0, len(db.ValidEventCategories))
86+
for e := range db.ValidEventCategories {
87+
events = append(events, e)
88+
}
89+
slices.Sort(events)
90+
return events
91+
}
92+
93+
type EventsFlag string
94+
95+
func (v *EventsFlag) Decode(ctx *kong.DecodeContext) error {
96+
tok, err := ctx.Scan.PopValue("events")
97+
if err != nil {
98+
return err
99+
}
100+
val := fmt.Sprintf("%v", tok.Value)
101+
if val == "?" {
102+
fmt.Println("Valid event categories:")
103+
for _, c := range EventCategories() {
104+
fmt.Printf(" %s\n", c)
105+
}
106+
os.Exit(0)
107+
}
108+
*v = EventsFlag(val)
109+
return nil
110+
}
111+
112+
type WebhookCreateCmd struct {
113+
Project string `required:"" help:"Project linkname."`
114+
User string `required:"" help:"Creator username."`
115+
URL string `required:"" name:"url" help:"Webhook endpoint URL."`
116+
Secret string `name:"secret" help:"Secret for HMAC signatures."`
117+
Events EventsFlag `name:"events" default:"*" completion:"csv:events" help:"Comma-separated event categories, or '*' for all (use '?' to list all supported events)."`
118+
Active bool `name:"active" default:"true" negatable:"" help:"Whether the webhook is active."`
119+
}
120+
121+
func (c *WebhookCreateCmd) Run(ctx *pw.Context) error {
122+
if err := db.ValidateEvents(string(c.Events)); err != nil {
123+
return err
124+
}
125+
126+
var project db.Project
127+
err := ctx.DB.NewSelect().Model(&project).
128+
Where("linkname = ?", c.Project).
129+
Scan(ctx)
130+
if err != nil {
131+
return fmt.Errorf("project %q not found", c.Project)
132+
}
133+
134+
var user db.User
135+
err = ctx.DB.NewSelect().Model(&user).
136+
Where("username = ?", c.User).
137+
Scan(ctx)
138+
if err != nil {
139+
return fmt.Errorf("user %q not found", c.User)
140+
}
141+
142+
hook := db.Webhook{
143+
ProjectID: project.ID,
144+
URL: c.URL,
145+
Secret: c.Secret,
146+
Events: string(c.Events),
147+
Active: c.Active,
148+
CreatorID: user.ID,
149+
Created: time.Now(),
150+
}
151+
err = db.New(ctx, ctx.DB).Insert(&hook)
152+
if err != nil {
153+
return err
154+
}
155+
156+
fmt.Printf("Created webhook (id=%d) %s\n", hook.ID, hook.URL)
157+
return nil
158+
}
159+
160+
type WebhookUpdateCmd struct {
161+
ID int `arg:"" help:"Webhook ID."`
162+
URL string `name:"url" help:"Webhook endpoint URL."`
163+
Secret string `name:"secret" help:"Secret for HMAC signatures."`
164+
Events string `name:"events" completion:"csv:events" help:"Comma-separated event categories, or '*' for all (use '?' to list all supported events)."`
165+
Active *bool `name:"active" negatable:"" help:"Whether the webhook is active."`
166+
}
167+
168+
func (c *WebhookUpdateCmd) Run(ctx *pw.Context) error {
169+
var hook db.Webhook
170+
err := ctx.DB.NewSelect().Model(&hook).
171+
Where("id = ?", c.ID).
172+
Scan(ctx)
173+
if err != nil {
174+
return fmt.Errorf("webhook %d not found", c.ID)
175+
}
176+
177+
q := ctx.DB.NewUpdate().Model(&hook).Where("id = ?", hook.ID)
178+
updated := false
179+
if c.URL != "" {
180+
q = q.Set("url = ?", c.URL)
181+
updated = true
182+
}
183+
if c.Secret != "" {
184+
q = q.Set("secret = ?", c.Secret)
185+
updated = true
186+
}
187+
if c.Events != "" {
188+
if err := db.ValidateEvents(c.Events); err != nil {
189+
return err
190+
}
191+
q = q.Set("events = ?", c.Events)
192+
updated = true
193+
}
194+
if c.Active != nil {
195+
q = q.Set("active = ?", *c.Active)
196+
updated = true
197+
}
198+
199+
if !updated {
200+
return fmt.Errorf("no fields to update")
201+
}
202+
203+
_, err = q.Exec(ctx)
204+
if err != nil {
205+
return err
206+
}
207+
208+
fmt.Printf("Updated webhook %d\n", c.ID)
209+
return nil
210+
}
211+
212+
type WebhookDeleteCmd struct {
213+
Force bool `short:"f" help:"Skip confirmation."`
214+
ID int `arg:"" help:"Webhook ID to delete."`
215+
}
216+
217+
func (c *WebhookDeleteCmd) Run(ctx *pw.Context) error {
218+
var hook db.Webhook
219+
err := ctx.DB.NewSelect().Model(&hook).
220+
Where("id = ?", c.ID).
221+
Scan(ctx)
222+
if err != nil {
223+
return fmt.Errorf("webhook %d not found", c.ID)
224+
}
225+
226+
if !c.Force {
227+
fmt.Printf("Delete webhook %d (url=%q)? [y/N] ",
228+
hook.ID, hook.URL)
229+
reader := bufio.NewReader(os.Stdin)
230+
answer, _ := reader.ReadString('\n')
231+
answer = strings.TrimSpace(strings.ToLower(answer))
232+
if answer != "y" && answer != "yes" {
233+
fmt.Println("Aborted.")
234+
return nil
235+
}
236+
}
237+
238+
_, err = ctx.DB.NewDelete().Model((*db.Webhook)(nil)).
239+
Where("id = ?", hook.ID).
240+
Exec(ctx)
241+
if err != nil {
242+
return err
243+
}
244+
245+
fmt.Printf("Deleted webhook %d\n", c.ID)
246+
return nil
247+
}

‎cmd/pw/main.go‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,8 @@ func (v VersionFlag) BeforeReset(app *kong.Kong, vars kong.Vars) error {
7878
func main() {
7979
var cli CLI
8080

81+
config.RegisterHints("events", admin.EventCategories())
82+
8183
k := config.Parse(&cli, "Patchwork runtime commands.")
8284

8385
if k.Command() == "config" {

0 commit comments

Comments
 (0)