| 1 | package cmd |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "fmt" |
| 7 | "os" |
| 8 | "strings" |
| 9 | |
| 10 | "the-valley/flow/internal/config" |
| 11 | "the-valley/flow/internal/github" |
| 12 | "the-valley/flow/internal/project" |
| 13 | "github.com/spf13/cobra" |
| 14 | ) |
| 15 | |
| 16 | // webhookEvents is the set of GitHub events the webhook subscribes to. |
| 17 | var webhookEvents = []string{ |
| 18 | "push", |
| 19 | "check_run", |
| 20 | "check_suite", |
| 21 | "pull_request", |
| 22 | "pull_request_review", |
| 23 | "issue_comment", |
| 24 | } |
| 25 | |
| 26 | // ghHook represents a GitHub repository webhook from the API. |
| 27 | type ghHook struct { |
| 28 | ID int64 `json:"id"` |
| 29 | Active bool `json:"active"` |
| 30 | Events []string `json:"events"` |
| 31 | Config struct { |
| 32 | URL string `json:"url"` |
| 33 | ContentType string `json:"content_type"` |
| 34 | } `json:"config"` |
| 35 | } |
| 36 | |
| 37 | // webhookStatus holds the check result for a single project. |
| 38 | type webhookStatus struct { |
| 39 | Project string |
| 40 | Owner string |
| 41 | Repo string |
| 42 | HookID int64 // 0 means not found |
| 43 | Error string // non-empty on failure |
| 44 | } |
| 45 | |
| 46 | // WebhookDeps holds injectable dependencies for webhook commands. |
| 47 | type WebhookDeps struct { |
| 48 | ListHooks func(owner, repo string) ([]ghHook, error) |
| 49 | CreateHook func(owner, repo, relayURL, secret string) error |
| 50 | ResolveRepo func(dir string) (string, string, error) |
| 51 | LoadConfig func() (config.Config, error) |
| 52 | LoadRegistry func() (*project.Registry, error) |
| 53 | ReadFile func(name string) ([]byte, error) |
| 54 | } |
| 55 | |
| 56 | // DefaultWebhookDeps returns WebhookDeps wired to real implementations. |
| 57 | func DefaultWebhookDeps() WebhookDeps { |
| 58 | return WebhookDeps{ |
| 59 | ListHooks: listRepoHooks, |
| 60 | CreateHook: createRepoHook, |
| 61 | ResolveRepo: func(dir string) (string, string, error) { |
| 62 | return github.NewGHCLIClient("").GetRepoOwnerAndNameFromDir(context.TODO(), dir) |
| 63 | }, |
| 64 | LoadConfig: func() (config.Config, error) { return config.Load("") }, |
| 65 | LoadRegistry: project.Load, |
| 66 | ReadFile: os.ReadFile, |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | var webhookCmd = &cobra.Command{ |
| 71 | Use: "webhook", |
| 72 | Short: "Manage GitHub webhooks for registered projects", |
| 73 | Long: `Check and configure GitHub webhooks for registered projects. |
| 74 | |
| 75 | Webhooks allow Klaus to receive push notifications from GitHub via github-relay |
| 76 | instead of polling. Each project's repo needs a webhook pointing at the relay URL. |
| 77 | |
| 78 | Configure relay_url and secret_file in your klaus config webhook section: |
| 79 | |
| 80 | { |
| 81 | "webhook": { |
| 82 | "relay_url": "https://example.ts.net", |
| 83 | "secret_file": "/path/to/webhook-secret" |
| 84 | } |
| 85 | }`, |
| 86 | } |
| 87 | |
| 88 | var webhookCheckCmd = &cobra.Command{ |
| 89 | Use: "check", |
| 90 | Short: "Check if webhooks are configured for registered projects", |
| 91 | Args: cobra.NoArgs, |
| 92 | RunE: func(cmd *cobra.Command, args []string) error { |
| 93 | return runWebhookCheck(cmd, args, DefaultWebhookDeps()) |
| 94 | }, |
| 95 | } |
| 96 | |
| 97 | var webhookSetupCmd = &cobra.Command{ |
| 98 | Use: "setup [project-name]", |
| 99 | Short: "Create missing webhooks for registered projects", |
| 100 | Long: `Create GitHub webhooks for projects that don't have one configured. |
| 101 | |
| 102 | With no arguments, checks all registered projects and creates webhooks for any |
| 103 | that are missing. With a project name, sets up the webhook for that project only. |
| 104 | |
| 105 | Requires relay_url and secret_file in the webhook config.`, |
| 106 | Args: cobra.MaximumNArgs(1), |
| 107 | RunE: func(cmd *cobra.Command, args []string) error { |
| 108 | return runWebhookSetup(cmd, args, DefaultWebhookDeps()) |
| 109 | }, |
| 110 | } |
| 111 | |
| 112 | func runWebhookCheck(cmd *cobra.Command, _ []string, deps WebhookDeps) error { |
| 113 | cfg, err := deps.LoadConfig() |
| 114 | if err != nil { |
| 115 | return err |
| 116 | } |
| 117 | if cfg.Webhook == nil || cfg.Webhook.RelayURL == "" { |
| 118 | return fmt.Errorf("webhook.relay_url is not configured; add it to your klaus config") |
| 119 | } |
| 120 | |
| 121 | statuses, err := checkAllProjects(cfg.Webhook.RelayURL, deps) |
| 122 | if err != nil { |
| 123 | return err |
| 124 | } |
| 125 | |
| 126 | if len(statuses) == 0 { |
| 127 | fmt.Fprintln(cmd.OutOrStdout(), "No projects registered. Use 'klaus project add' to register one.") |
| 128 | return nil |
| 129 | } |
| 130 | |
| 131 | for _, s := range statuses { |
| 132 | if s.Error != "" { |
| 133 | fmt.Fprintf(cmd.OutOrStdout(), "%-20s %s/%s error: %s\n", s.Project, s.Owner, s.Repo, s.Error) |
| 134 | } else if s.HookID != 0 { |
| 135 | fmt.Fprintf(cmd.OutOrStdout(), "%-20s %s/%s โ configured (hook %d)\n", s.Project, s.Owner, s.Repo, s.HookID) |
| 136 | } else { |
| 137 | fmt.Fprintf(cmd.OutOrStdout(), "%-20s %s/%s โ missing\n", s.Project, s.Owner, s.Repo) |
| 138 | } |
| 139 | } |
| 140 | return nil |
| 141 | } |
| 142 | |
| 143 | func runWebhookSetup(cmd *cobra.Command, args []string, deps WebhookDeps) error { |
| 144 | cfg, err := deps.LoadConfig() |
| 145 | if err != nil { |
| 146 | return err |
| 147 | } |
| 148 | if cfg.Webhook == nil || cfg.Webhook.RelayURL == "" { |
| 149 | return fmt.Errorf("webhook.relay_url is not configured; add it to your klaus config") |
| 150 | } |
| 151 | if cfg.Webhook.SecretFile == "" { |
| 152 | return fmt.Errorf("webhook.secret_file is not configured; add it to your klaus config") |
| 153 | } |
| 154 | |
| 155 | secretBytes, err := deps.ReadFile(cfg.Webhook.SecretFile) |
| 156 | if err != nil { |
| 157 | return fmt.Errorf("reading webhook secret: %w", err) |
| 158 | } |
| 159 | secret := strings.TrimSpace(string(secretBytes)) |
| 160 | if secret == "" { |
| 161 | return fmt.Errorf("webhook secret file is empty: %s", cfg.Webhook.SecretFile) |
| 162 | } |
| 163 | |
| 164 | reg, err := deps.LoadRegistry() |
| 165 | if err != nil { |
| 166 | return err |
| 167 | } |
| 168 | projects := reg.List() |
| 169 | if len(projects) == 0 { |
| 170 | fmt.Fprintln(cmd.OutOrStdout(), "No projects registered. Use 'klaus project add' to register one.") |
| 171 | return nil |
| 172 | } |
| 173 | |
| 174 | // If a specific project was requested, filter to just that one. |
| 175 | if len(args) == 1 { |
| 176 | name := args[0] |
| 177 | path, ok := projects[name] |
| 178 | if !ok { |
| 179 | return fmt.Errorf("project %q is not registered", name) |
| 180 | } |
| 181 | projects = map[string]string{name: path} |
| 182 | } |
| 183 | |
| 184 | relayURL := cfg.Webhook.RelayURL |
| 185 | var created, skipped, errored int |
| 186 | |
| 187 | for name, localPath := range projects { |
| 188 | owner, repo, err := deps.ResolveRepo(localPath) |
| 189 | if err != nil { |
| 190 | fmt.Fprintf(cmd.OutOrStdout(), "%-20s error resolving repo: %v\n", name, err) |
| 191 | errored++ |
| 192 | continue |
| 193 | } |
| 194 | |
| 195 | hookID, err := findMatchingHookWith(deps, owner, repo, relayURL) |
| 196 | if err != nil { |
| 197 | fmt.Fprintf(cmd.OutOrStdout(), "%-20s %s/%s error checking hooks: %v\n", name, owner, repo, err) |
| 198 | errored++ |
| 199 | continue |
| 200 | } |
| 201 | if hookID != 0 { |
| 202 | fmt.Fprintf(cmd.OutOrStdout(), "%-20s %s/%s already configured (hook %d)\n", name, owner, repo, hookID) |
| 203 | skipped++ |
| 204 | continue |
| 205 | } |
| 206 | |
| 207 | if err := deps.CreateHook(owner, repo, relayURL, secret); err != nil { |
| 208 | fmt.Fprintf(cmd.OutOrStdout(), "%-20s %s/%s error creating webhook: %v\n", name, owner, repo, err) |
| 209 | errored++ |
| 210 | continue |
| 211 | } |
| 212 | fmt.Fprintf(cmd.OutOrStdout(), "%-20s %s/%s โ webhook created\n", name, owner, repo) |
| 213 | created++ |
| 214 | } |
| 215 | |
| 216 | fmt.Fprintf(cmd.OutOrStdout(), "\nDone: %d created, %d already configured, %d errors\n", created, skipped, errored) |
| 217 | return nil |
| 218 | } |
| 219 | |
| 220 | // checkAllProjects checks webhook status for all registered projects. |
| 221 | func checkAllProjects(relayURL string, deps WebhookDeps) ([]webhookStatus, error) { |
| 222 | reg, err := deps.LoadRegistry() |
| 223 | if err != nil { |
| 224 | return nil, err |
| 225 | } |
| 226 | projects := reg.List() |
| 227 | |
| 228 | var statuses []webhookStatus |
| 229 | for name, localPath := range projects { |
| 230 | s := webhookStatus{Project: name} |
| 231 | |
| 232 | owner, repo, err := deps.ResolveRepo(localPath) |
| 233 | if err != nil { |
| 234 | s.Error = fmt.Sprintf("resolving repo: %v", err) |
| 235 | statuses = append(statuses, s) |
| 236 | continue |
| 237 | } |
| 238 | s.Owner = owner |
| 239 | s.Repo = repo |
| 240 | |
| 241 | hookID, err := findMatchingHookWith(deps, owner, repo, relayURL) |
| 242 | if err != nil { |
| 243 | s.Error = fmt.Sprintf("listing hooks: %v", err) |
| 244 | statuses = append(statuses, s) |
| 245 | continue |
| 246 | } |
| 247 | s.HookID = hookID |
| 248 | statuses = append(statuses, s) |
| 249 | } |
| 250 | return statuses, nil |
| 251 | } |
| 252 | |
| 253 | // findMatchingHookWith checks if a repo has a webhook whose URL matches the relay URL. |
| 254 | // Returns the hook ID if found, 0 if not. |
| 255 | func findMatchingHookWith(deps WebhookDeps, owner, repo, relayURL string) (int64, error) { |
| 256 | hooks, err := deps.ListHooks(owner, repo) |
| 257 | if err != nil { |
| 258 | return 0, err |
| 259 | } |
| 260 | return matchHook(hooks, relayURL), nil |
| 261 | } |
| 262 | |
| 263 | // matchHook returns the ID of the first hook whose config URL starts with the |
| 264 | // relay URL, or 0 if none match. |
| 265 | func matchHook(hooks []ghHook, relayURL string) int64 { |
| 266 | // Normalize: ensure relayURL doesn't have trailing slash for comparison. |
| 267 | relayURL = strings.TrimRight(relayURL, "/") |
| 268 | for _, h := range hooks { |
| 269 | hookURL := strings.TrimRight(h.Config.URL, "/") |
| 270 | if hookURL == relayURL || strings.HasPrefix(hookURL, relayURL+"/") { |
| 271 | return h.ID |
| 272 | } |
| 273 | } |
| 274 | return 0 |
| 275 | } |
| 276 | |
| 277 | // listRepoHooks fetches webhooks for a repository via the GitHub API. |
| 278 | func listRepoHooks(owner, repo string) ([]ghHook, error) { |
| 279 | client := github.NewGHCLIClient("") |
| 280 | data, err := client.APIGet(context.TODO(), fmt.Sprintf("repos/%s/%s/hooks", owner, repo)) |
| 281 | if err != nil { |
| 282 | return nil, err |
| 283 | } |
| 284 | var hooks []ghHook |
| 285 | if err := json.Unmarshal(data, &hooks); err != nil { |
| 286 | return nil, fmt.Errorf("parsing hooks response: %w", err) |
| 287 | } |
| 288 | return hooks, nil |
| 289 | } |
| 290 | |
| 291 | // createRepoHook creates a webhook on a GitHub repository. |
| 292 | func createRepoHook(owner, repo, relayURL, secret string) error { |
| 293 | client := github.NewGHCLIClient("") |
| 294 | body := map[string]interface{}{ |
| 295 | "name": "web", |
| 296 | "active": true, |
| 297 | "events": webhookEvents, |
| 298 | "config": map[string]string{ |
| 299 | "url": relayURL, |
| 300 | "content_type": "json", |
| 301 | "secret": secret, |
| 302 | }, |
| 303 | } |
| 304 | _, err := client.APIPostJSON(context.TODO(), fmt.Sprintf("repos/%s/%s/hooks", owner, repo), body) |
| 305 | return err |
| 306 | } |
| 307 | |
| 308 | func init() { |
| 309 | webhookCmd.AddCommand(webhookCheckCmd) |
| 310 | webhookCmd.AddCommand(webhookSetupCmd) |
| 311 | rootCmd.AddCommand(webhookCmd) |
| 312 | } |