From 7768e66692bc8d510cfe399c40bd874c6bd657f1 Mon Sep 17 00:00:00 2001 From: adssib <75389300+adssib@users.noreply.github.com> Date: Thu, 19 Nov 2026 15:14:13 -0500 Subject: [PATCH 1/2] add the new-plugin starter command go run ./cmd/new-plugin --api --provider --format scaffolds a provider on any of the eight format plugins: the definition, its Register line, a registered/golden/drop test over placeholder sources, testdata rows, the provider page, the docs/plugins.md row and docs/plugins.json. It refuses a taken id and then changes nothing. Co-Authored-By: Claude Opus 5.5 Signed-off-by: adssib <75389300+adssib@users.noreply.github.com> --- .github/pull_request_template.md | 1 + AGENTS.md | 3 + CONTRIBUTING.md | 2 + cmd/new-plugin/formats.go | 534 ++++++++++++++++++++++++++++++ cmd/new-plugin/main.go | 539 +++++++++++++++++++++++++++++++ cmd/new-plugin/main_test.go | 185 +++++++++++ docs/writing-a-plugin.md | 41 ++- 7 files changed, 1295 insertions(+), 10 deletions(-) create mode 100644 cmd/new-plugin/formats.go create mode 100644 cmd/new-plugin/main.go create mode 100644 cmd/new-plugin/main_test.go diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 30b6631..f56eb72 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -12,6 +12,7 @@ - [ ] `providers/.md` written or updated from `providers/_template.md`, including **Why this source** - [ ] Fetches only through `env.Get` / `kit/` - [ ] `make check` passes locally (and `make plugins-json` was run if a plugin or its row changed) +- [ ] No `TODO(new-plugin)` left (`grep -rn 'TODO(new-plugin)' .` prints nothing) - [ ] Nothing private: no credentials, internal hosts, private links, customer names ## Notes for the reviewer diff --git a/AGENTS.md b/AGENTS.md index d5a2efb..e755f9d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -23,6 +23,8 @@ Refer to the service that runs these plugins as "patch-it's hosted ingestion ser ## Rules for plugin code +- **Start a new provider with `go run ./cmd/new-plugin --api --provider --format `**, then fill in every `TODO(new-plugin)`; none may be left when you open the PR. + - **Fetch only through the environment** (`env.Get` or `kit/`). No `net/http` outside the fetch layer, no filesystem outside `testdata/`, no database. - **Golden test + dated source quote**: a saved copy of the real source in `testdata/`, a row in `testdata/README.md` (URL, date fetched, license, quote), and `testdata/golden/.json` with the exact events. - **Precision over recall.** When unsure whether something is a change, don't emit an event. @@ -50,6 +52,7 @@ Go module `github.com/patch-it-dev/patch-it-plugins`; the only dependency is `go ``` plugin/ the Plugin interface, the registry, Env, Result, Spec (baselines) cmd/list-plugins/ writes docs/plugins.json (make plugins-json); internal/pluginlist/ is its logic +cmd/new-plugin/ scaffolds a provider on a format plugin (go run ./cmd/new-plugin --help) plugins// one package per format plugin: openapi, retirements, migrationguide, removedmembers, changelog, feed, apichangelog, catalog; plugins/all imports every one kit/ kit/kittest/ Unchanged, Cite, Wayback; the test kit (Mem, Pages, Ingest, Golden) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index d3a6435..38e63c7 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -2,6 +2,8 @@ Thanks for helping patch-it watch more APIs. This file is the rulebook; [docs/writing-a-plugin.md](docs/writing-a-plugin.md) is the how-to. +**Start a new provider with the starter:** `go run ./cmd/new-plugin --api --provider --format ` writes the definition, its registration, a test over placeholder sources, the testdata rows, the provider page and the `docs/plugins.md` row; you fill in the `TODO(new-plugin)`s ([how](docs/writing-a-plugin.md#1-scaffold-it-with-new-plugin)). + ## The rules 1. **Add your plugin to [docs/plugins.md](docs/plugins.md).** Every new plugin gets a row; every change to a plugin's id, provider, source, what it watches or status updates its row. The list on docs.patch-it.dev is built from that file, so a plugin that isn't listed is invisible to users. Then run `make plugins-json` to regenerate [`docs/plugins.json`](docs/plugins.json); it fails if the registry and the table disagree, and the tests fail while the JSON is out of date. diff --git a/cmd/new-plugin/formats.go b/cmd/new-plugin/formats.go new file mode 100644 index 0000000..e6a0b75 --- /dev/null +++ b/cmd/new-plugin/formats.go @@ -0,0 +1,534 @@ +package main + +// formatSpec is how a provider is added to one format plugin: where its +// definition goes, the line that registers it, the placeholder sources its +// test reads, and how the test runs it. +type formatSpec struct { + layer string // default layer for docs/plugins.md + defDir string // the package directory the definition goes in + def string // the definition file (template) + register string // the plugin.Register line added to plugins/'s init (template) + ref string // how the test and the Register line name the definition + pluginOf string // the plugin literal for the registered test (template) + fixtures map[string]string // placeholder sources under plugins//testdata: name (template) -> content (template) + source string // the fixture the golden test reads; the drop test reads a copy, -drop. + ingest string // the test's Ingest func and anything it needs (template) + imports []string // the test's imports besides testing and kittest + next string // a format-specific line for the next steps + drop string // the drop test, when "no event at all" can't be it (template) + dropFile string // the drop test's placeholder, when not a copy of the source's + mapEntry *mapEntry // an entry the format needs in a map elsewhere +} + +// mapEntry is a line added to a map literal in another package: the v1 -> v2 +// conversion in migrate/ knows each model retirement page and SDK guide. +type mapEntry struct { + file, varName, entry string // entry is a template +} + +const todo = "TODO(new-plugin)" + +var formats = map[string]formatSpec{ + "feed": { + layer: "API", + defDir: "plugins/feed", + def: `package feed + +// {{.Ident}} is {{.Provider}}'s feed of changes. +// +// ` + todo + `: say what the feed is and what you checked, with the date, as +// the feeds in readers.go do: RSS or Atom, how many entries it keeps, how +// {{.Provider}} marks a breaking change or a deprecation. +var {{.Ident}} = Feed{ + API: "{{.ID}}", + Vendor: "{{.Provider}}", + URL: "{{.Source}}", + Read: read{{.Ident}}, +} + +// read{{.Ident}} turns one entry of {{.Provider}}'s feed into findings. +// +// ` + todo + `: return one Finding per thing the entry says stops or is +// deprecated, with a typed Subject, the date in Version and the entry's own +// lines in Excerpt. For an entry that is marked but that you can't read for +// sure, return a Finding with only Entry and Dropped set. Return nothing for +// an entry that isn't a breaking change or a deprecation. Precision over +// recall: readCloudflareAPI in readers.go is a worked example. +func read{{.Ident}}(e Entry) []Finding { + return nil +} +`, + register: `plugin.Register(Plugin{Feed: {{.Ident}}, Archiver: kit.Wayback{}})`, + pluginOf: `Plugin{Feed: {{.Ident}}}`, + fixtures: map[string]string{"{{.File}}.rss.xml": ` + +placeholderhttps://example.com/placeholder +Placeholder entryhttps://example.com/placeholderSat, 14 Nov 2026 12:00:00 GMTNot a change. + +`}, + source: "{{.File}}.rss.xml", + ingest: `// {{.Lower}}Ingest runs the plugin over a saved copy of the feed, cited +// through a test archive that serves the same copy. +func {{.Lower}}Ingest(t *testing.T, file string) []event.EventV2 { + t.Helper() + saved := kittest.Pages{ {{.Ident}}.URL: file} + archive := &kittest.Archive{T: t, Pages: saved} + return kittest.IngestWith(t, kittest.Env(t, saved), Plugin{Feed: {{.Ident}}, Archiver: archive}) +} +`, + imports: []string{"github.com/patch-it-dev/patch-it-plugins/event"}, + }, + + "retirements": { + layer: "AI models", + defDir: "retire", + def: `package retire + +import "strings" + +// {{.Ident}} is {{.Provider}}'s model deprecations page. +// +// ` + todo + `: say what the page is and what you checked, with the date, as +// providers.go does: served as markdown, the table's columns (a "Shutdown +// date" or "Retirement date" column first, then the model and its +// replacement), how far back it goes. +var {{.Ident}} = Page{ + API: "{{.ID}}", + Vendor: "{{.Provider}}", + URL: "{{.Source}}", + // ` + todo + `: the provider's main call that takes a model name. + Operation: "POST /v1/TODO", + // ` + todo + `: keep the model names the operation above takes (text + // models, not image or embedding ones), as openAIText in providers.go does. + Keep: func(name string) bool { return strings.HasPrefix(name, "placeholder-text-") }, +} +`, + register: `plugin.Register(Plugin{Page: retire.{{.Ident}}, Archiver: kit.Wayback{}})`, + mapEntry: &mapEntry{"migrate/migrate.go", "providers", `retire.{{.Ident}}.API: "{{.Slug}}"`}, + pluginOf: `Plugin{Page: retire.{{.Ident}}}`, + fixtures: map[string]string{"{{.File}}-deprecations.md": `# Placeholder deprecations page + +` + todo + `: a placeholder. Replace it with a real copy of {{.Source}} (as markdown) and list it in README.md. + +## Placeholder + +| Shutdown date | Model | Replacement | +| ------------- | ----- | ----------- | +| November 14, 2026 | ` + "`placeholder-text-model`" + ` | ` + "`placeholder-text-model-2`" + ` | +`}, + dropFile: `# Placeholder deprecations page + +` + todo + `: a placeholder. Replace it with a real copy of {{.Source}} (as markdown) and list it in README.md. + +## Placeholder + +| Shutdown date | Model | Replacement | +| ------------- | ----- | ----------- | +| November 14, 2026 | ` + "`placeholder-text-model`" + ` | ` + "`placeholder-text-model-2`" + ` | +| November 14, 2026 | ` + "`placeholder-image-model`" + ` | ` + "`placeholder-image-model-2`" + ` | +`, + drop: `// The pinned drop test: a model the operation doesn't take (Keep says no) +// must not become an event, even with a shutdown date. +// ` + todo + `: save a page with such a row (an image, audio or embedding +// model) and name the model here. +func Test{{.Ident}}DropsANonChange(t *testing.T) { + for _, e := range {{.Lower}}Ingest(t, {{.Lower}}Drop) { + if b, _ := json.Marshal(e); strings.Contains(string(b), "placeholder-image-model") { + t.Errorf("event for placeholder-image-model, which Keep drops: %s", e.Description) + } + } +} +`, + source: "{{.File}}-deprecations.md", + ingest: `// {{.Lower}}Ingest runs the plugin over a saved copy of the page, cited +// through a test archive that serves the same copy. +func {{.Lower}}Ingest(t *testing.T, file string) []event.EventV2 { + t.Helper() + saved := kittest.Pages{retire.{{.Ident}}.URL: file} + archive := &kittest.Archive{T: t, Pages: saved} + return kittest.IngestWith(t, kittest.Env(t, saved), Plugin{Page: retire.{{.Ident}}, Archiver: archive}) +} +`, + imports: []string{"encoding/json", "strings", "github.com/patch-it-dev/patch-it-plugins/event", "github.com/patch-it-dev/patch-it-plugins/retire"}, + }, + + "migrationguide": { + layer: "SDK", + defDir: "sdkguide", + def: `package sdkguide + +// {{.Ident}} is {{.Provider}}'s SDK guide to a major release (MIGRATION.md at +// the release tag). +// +// ` + todo + `: the repo, the major release, the API operation the removed +// parameters were sent to, and the calls the guide's table names. Say what +// you checked, with the date. +var {{.Ident}} = Guide{ + API: "{{.ID}}", + Repo: "TODO-owner/TODO-repo", + Major: 1, + Operation: "POST /v1/TODO", + Methods: "` + "`TODO.create()`" + `", + Symbols: []string{"TODO.create"}, +} +`, + register: `plugin.Register(Plugin{Guide: sdkguide.{{.Ident}}})`, + mapEntry: &mapEntry{"migrate/migrate.go", "guides", `sdkguide.{{.Ident}}.API: sdkguide.{{.Ident}}`}, + pluginOf: `Plugin{Guide: sdkguide.{{.Ident}}}`, + fixtures: map[string]string{"{{.File}}-MIGRATION.md": `# Migrating to v1 + +` + todo + `: a placeholder. Replace it with a real copy of the guide at the release tag and list it in README.md. + +## Removed parameters + +| Method | Removed parameter | Use instead | +| ------ | ----------------- | ----------- | +| ` + "`TODO.create()`" + ` | ` + "`placeholder_param`" + ` | Remove it. | +`}, + dropFile: `# Migrating to v1 + +` + todo + `: a placeholder. Replace it with a real copy of the guide at the release tag and list it in README.md. + +## Removed parameters + +| Method | Removed parameter | Use instead | +| ------ | ----------------- | ----------- | +| ` + "`TODO.create()`" + ` | ` + "`placeholder_param`" + ` | Remove it. | +| ` + "`TODO.beta.create()`" + ` | ` + "`placeholder_elsewhere`" + ` | Not the plain call. | +`, + drop: `// The pinned drop test: a row about another call than Methods names must +// not become an event. +// ` + todo + `: save a guide with such a row (a beta-only method, a helper) +// and name its parameter here. +func Test{{.Ident}}DropsANonChange(t *testing.T) { + for _, e := range {{.Lower}}Ingest(t, {{.Lower}}Drop) { + if b, _ := json.Marshal(e); strings.Contains(string(b), "placeholder_elsewhere") { + t.Errorf("event for placeholder_elsewhere, a row about another call: %s", e.Description) + } + } +} +`, + source: "{{.File}}-MIGRATION.md", + ingest: `// {{.Lower}}Ingest runs the plugin over a saved copy of the guide. +func {{.Lower}}Ingest(t *testing.T, file string) []event.EventV2 { + t.Helper() + return kittest.Ingest(t, Plugin{Guide: sdkguide.{{.Ident}}}, kittest.Pages{sdkguide.{{.Ident}}.URL(): file}) +} +`, + imports: []string{"encoding/json", "strings", "github.com/patch-it-dev/patch-it-plugins/event", "github.com/patch-it-dev/patch-it-plugins/sdkguide"}, + }, + + "removedmembers": { + layer: "package", + defDir: "plugins/removedmembers", + def: `package removedmembers + +// {{.Ident}} is {{.Provider}}'s migration guide to a release, with its table +// of removed members. +// +// ` + todo + `: the package, how the guide writes the module, the release, +// the repo, the guide's path at the release tag and the heading the table is +// under. Say what you checked, with the date. +var {{.Ident}} = Guide{ + Package: "{{.ID}}", + Module: "{{.ID}}", + Release: "1.0.0", + Repo: "TODO-owner/TODO-repo", + Path: "TODO/migration_guide.rst", + Section: "Removed members", +} +`, + register: `plugin.Register(Plugin{Guide: {{.Ident}}})`, + pluginOf: `Plugin{Guide: {{.Ident}}}`, + fixtures: map[string]string{"{{.File}}-migration-guide.rst": `.. ` + todo + `: a placeholder. Replace it with a real copy of the guide at the release tag and list it in README.md. + +Removed members +--------------- + +====================== ========================== +Removed member Migration guideline +====================== ========================== +placeholder_member Use ` + "``{{.ID}}.placeholder_new``" + ` instead. +====================== ========================== +`}, + dropFile: `.. ` + todo + `: a placeholder. Replace it with a real copy of the guide and say in the test why its other table is no removal. + +Removed members +--------------- + +====================== ========================== +Removed member Migration guideline +====================== ========================== +placeholder_member Use ` + "``{{.ID}}.placeholder_new``" + ` instead. +====================== ========================== + +Other members +------------- + +====================== ========================== +Removed member Migration guideline +====================== ========================== +placeholder_elsewhere Not in the main table. +====================== ========================== +`, + drop: `// The pinned drop test: every row of the table under Section is a removal, +// so what must not become an event is a member listed anywhere else. +// ` + todo + `: save a guide with such a table (another namespace, a +// deprecation table) and name one of its members here. +func Test{{.Ident}}DropsANonChange(t *testing.T) { + for _, e := range {{.Lower}}Ingest(t, {{.Lower}}Drop) { + if slices.Contains(e.Subject.Symbols, "placeholder_elsewhere") { + t.Errorf("event for placeholder_elsewhere, which isn't under %q", {{.Ident}}.Section) + } + } +} +`, + source: "{{.File}}-migration-guide.rst", + ingest: `// {{.Lower}}Ingest runs the plugin over a saved copy of the guide. +func {{.Lower}}Ingest(t *testing.T, file string) []event.EventV2 { + t.Helper() + return kittest.Ingest(t, Plugin{Guide: {{.Ident}}}, kittest.Pages{ {{.Ident}}.URL(): file}) +} +`, + imports: []string{"slices", "github.com/patch-it-dev/patch-it-plugins/event"}, + }, + + "changelog": { + layer: "package", + defDir: "plugins/changelog", + def: `package changelog + +// {{.Ident}} is {{.Provider}}'s changelog at one release. +// +// ` + todo + `: the ecosystem, the import name, the repo, the release's tag, +// the release as the changelog heads it, and the changelog's path. Say what +// you checked, with the date, as changelog.go does for Textual and urllib3. +var {{.Ident}} = File{ + Package: "{{.ID}}", Ecosystem: "pypi", Module: "{{.ID}}", + Repo: "TODO-owner/TODO-repo", Tag: "v1.0.0", Release: "1.0.0", Path: "CHANGELOG.md", +} +`, + register: `plugin.Register(Plugin{File: {{.Ident}}})`, + pluginOf: `Plugin{File: {{.Ident}}}`, + fixtures: map[string]string{"{{.File}}-CHANGELOG.md": `# Changelog + + + +## [1.0.0] - 2026-11-14 + +### Added + +- A placeholder entry. +`}, + source: "{{.File}}-CHANGELOG.md", + ingest: `// {{.Lower}}Ingest runs the plugin over a saved copy of the changelog. +func {{.Lower}}Ingest(t *testing.T, file string) []event.EventV2 { + t.Helper() + return kittest.Ingest(t, Plugin{File: {{.Ident}}}, kittest.Pages{ {{.Ident}}.URL(): file}) +} +`, + imports: []string{"github.com/patch-it-dev/patch-it-plugins/event"}, + }, + + "apichangelog": { + layer: "API", + defDir: "plugins/apichangelog", + def: `package apichangelog + +// {{.Ident}} is {{.Provider}}'s machine-readable API changelog. +// +// ` + todo + `: the repo and the file's path, and what you checked, with the +// date, as apichangelog.go does for MongoDB Atlas. +var {{.Ident}} = Log{ + API: "{{.ID}}", Vendor: "{{.Provider}}", Name: "TODO: the API's name, for sentences", + Repo: "TODO-owner/TODO-repo", Path: "changelog/changelog.json", +} +`, + register: `plugin.Register(Plugin{Log: {{.Ident}}})`, + pluginOf: `Plugin{Log: {{.Ident}}}`, + fixtures: map[string]string{ + "{{.File}}-changelog.json": `[{"date": "2026-11-14", "paths": [{"path": "/placeholder", "httpMethod": "GET", "versions": [{"version": "2026-01-01", "changes": [{"change": "placeholder: not a life-cycle change", "changeCode": "response-property-added", "backwardCompatible": true}]}]}]}]` + "\n", + "{{.File}}-commits.json": `[{"sha": "0000000000000000000000000000000000000000"}]` + "\n", + }, + source: "{{.File}}-changelog.json", + ingest: `// {{.Lower}}Commit is the commit the saved changelog is at. +// ` + todo + `: the real commit, and its commits response saved alongside. +const {{.Lower}}Commit = "0000000000000000000000000000000000000000" + +// {{.Lower}}Ingest runs the plugin over a saved copy of the changelog. +func {{.Lower}}Ingest(t *testing.T, file string) []event.EventV2 { + t.Helper() + return kittest.Ingest(t, Plugin{Log: {{.Ident}}}, kittest.Pages{ + {{.Ident}}.CommitsURL(): "testdata/{{.File}}-commits.json", + {{.Ident}}.URL({{.Lower}}Commit): file, + }) +} +`, + imports: []string{"github.com/patch-it-dev/patch-it-plugins/event"}, + }, + + "catalog": { + layer: "runtime", + defDir: "plugins/catalog", + def: `package catalog + +// {{.Ident}} is {{.Provider}}'s catalog: one JSON object, one key per command +// or endpoint, at a git ref. +// +// ` + todo + `: the ecosystem and package for the events' subject, the repo, +// the catalog's path and the commits API URL for the newest ref. Say what you +// checked, with the date, as catalog.go does for Redis. +var {{.Ident}} = Catalog{ + API: "{{.ID}}", Ecosystem: "{{.ID}}", Package: "{{.ID}}", + Repo: "TODO-owner/TODO-repo", Path: "TODO/commands.json", + RefsURL: "https://api.github.com/repos/TODO-owner/TODO-repo/commits/main", +} +`, + register: `plugin.Register(Plugin{Catalog: {{.Ident}}})`, + pluginOf: `Plugin{Catalog: {{.Ident}}}`, + fixtures: map[string]string{ + "{{.File}}-old.json": "{\"PLACEHOLDER\": {}}\n", + "{{.File}}-new.json": "{\"PLACEHOLDER\": {}}\n", + }, + source: "{{.File}}-new.json", + ingest: `// The two refs the saved snapshots are at. +// ` + todo + `: the real commits, oldest first. +const ( + {{.Lower}}OldRef = "0000000000000000000000000000000000000000" + {{.Lower}}NewRef = "1111111111111111111111111111111111111111" +) + +// {{.Lower}}Ingest replays the saved old snapshot against file. +func {{.Lower}}Ingest(t *testing.T, file string) []event.EventV2 { + t.Helper() + env := kittest.Env(t, kittest.Pages{ + {{.Ident}}.URL({{.Lower}}OldRef): "testdata/{{.File}}-old.json", + {{.Ident}}.URL({{.Lower}}NewRef): file, + }) + sink := env.Baselines.(kittest.Sink) + p := Plugin{Catalog: {{.Ident}}} + if rejected, err := kittest.Replay(context.Background(), env, sink, p, {{.Lower}}OldRef, {{.Lower}}NewRef); err != nil || rejected { + t.Fatalf("replay: rejected=%v err=%v", rejected, err) + } + return kittest.Stored(t, sink) +} +`, + imports: []string{"context", "github.com/patch-it-dev/patch-it-plugins/event"}, + }, + + "openapi": { + layer: "API", + defDir: "adapter", + def: `package adapter + +import ( + "context" + "fmt" +) + +// {{.Ident}} adapts {{.Provider}}'s OpenAPI spec for the openapi plugin. +// +// ` + todo + `: LatestTag finds the newest release (a tag, or the commit +// that last changed the spec) and Fetch downloads the spec at it with +// fetch.Get, as supabase.go and vercel.go do. Say where the spec is +// published and what you checked, with the date. +type {{.Ident}} struct{} + +var _ Adapter = {{.Ident}}{} + +func ({{.Ident}}) API() string { return "{{.ID}}" } + +// LatestTag is the newest release of the spec. +func ({{.Ident}}) LatestTag(ctx context.Context) (string, error) { + return "", fmt.Errorf("{{.ID}}: LatestTag isn't written yet (adapter/{{.File}}.go)") +} + +// Fetch downloads the spec at tag. +func ({{.Ident}}) Fetch(ctx context.Context, tag string) (Spec, error) { + return Spec{}, fmt.Errorf("{{.ID}}: Fetch isn't written yet (adapter/{{.File}}.go)") +} +`, + register: `plugin.Register(Plugin{Adapter: adapter.{{.Ident}}{}})`, + pluginOf: `Plugin{Adapter: adapter.{{.Ident}}{}}`, + fixtures: map[string]string{ + "{{.File}}-old.json": `{"openapi": "3.0.3", "info": {"title": "placeholder", "version": "1"}, "paths": {}}` + "\n", + "{{.File}}-new.json": `{"openapi": "3.0.3", "info": {"title": "placeholder", "version": "2"}, "paths": {}}` + "\n", + }, + source: "{{.File}}-new.json", + ingest: `// {{.Lower}}Adapter serves saved copies of the spec: tag -> file. +// ` + todo + `: name the tags after the real releases you saved. +type {{.Lower}}Adapter map[string]string + +func ({{.Lower}}Adapter) API() string { return "{{.ID}}" } + +func ({{.Lower}}Adapter) LatestTag(context.Context) (string, error) { return "new", nil } + +func (a {{.Lower}}Adapter) Fetch(_ context.Context, tag string) (adapter.Spec, error) { + file, ok := a[tag] + if !ok { + return adapter.Spec{}, fmt.Errorf("no saved copy for %s", tag) + } + body, err := os.ReadFile(file) + if err != nil { + return adapter.Spec{}, err + } + return adapter.Spec{Content: body, Version: tag, SourceURL: "{{.Source}}"}, nil +} + +// {{.Lower}}Ingest replays the saved old spec against file. +func {{.Lower}}Ingest(t *testing.T, file string) []event.EventV2 { + t.Helper() + env := kittest.Env(t, nil) + sink := env.Baselines.(kittest.Sink) + p := Plugin{Adapter: {{.Lower}}Adapter{"old": "testdata/{{.File}}-old.json", "new": file}} + if rejected, err := kittest.Replay(context.Background(), env, sink, p, "old", "new"); err != nil || rejected { + t.Fatalf("replay: rejected=%v err=%v", rejected, err) + } + return kittest.Stored(t, sink) +} +`, + imports: []string{"context", "fmt", "os", "github.com/patch-it-dev/patch-it-plugins/adapter", "github.com/patch-it-dev/patch-it-plugins/event"}, + next: "Write LatestTag and Fetch in adapter/{{.File}}.go (fetch.Get only); add Diff/Keep to the Register line if the spec needs them (see vercel.go).", + }, +} + +// testFile is the generated test, the same for every format. +const testFile = `package {{.Format}} + +import ( +{{range .Imports}} "{{.}}" +{{end}}) + +// The saved sources the tests read. +// ` + todo + `: replace the placeholders with real copies, and list each in +// testdata/README.md (URL, date fetched, license, a short quote). +const ( + {{.Lower}}Source = "testdata/{{.SourceFile}}" + {{.Lower}}Drop = "testdata/{{.DropFile}}" +) + +func Test{{.Ident}}RegistersItself(t *testing.T) { + kittest.Registered(t, {{.PluginOf}}) +} + +// The golden test: the saved source in, every event out. +// ` + todo + `: once the source is real, run +// +// go test ./plugins/{{.Format}} -run Test{{.Ident}}Golden -update +// +// and read testdata/golden/{{.ID}}.json like code: every event in it is a +// pull request someone may get. +func Test{{.Ident}}Golden(t *testing.T) { + kittest.Golden(t, "testdata/golden/{{.ID}}.json", {{.Lower}}Ingest(t, {{.Lower}}Source)) +} + +{{if .Drop}}{{.Drop}}{{else}}// The pinned drop test: a realistic input that must not become an event. +// ` + todo + `: save one (an unrelated section, a behavior change written as +// prose, a product name in a sentence) and say here why it's no change. +func Test{{.Ident}}DropsANonChange(t *testing.T) { + if got := {{.Lower}}Ingest(t, {{.Lower}}Drop); len(got) != 0 { + t.Errorf("%d events from %s, want none", len(got), {{.Lower}}Drop) + } +} +{{end}} +{{.Ingest}}` diff --git a/cmd/new-plugin/main.go b/cmd/new-plugin/main.go new file mode 100644 index 0000000..d03a394 --- /dev/null +++ b/cmd/new-plugin/main.go @@ -0,0 +1,539 @@ +// Command new-plugin scaffolds a provider on one of the format plugins, so a +// contributor only fills in what is specific to the provider. Run it from the +// repo root: +// +// go run ./cmd/new-plugin --api acme --provider Acme --format openapi +// +// It writes the provider's definition in the format's package (or the reader +// package the format uses: adapter/, retire/, sdkguide/), adds its +// plugin.Register line to plugins/'s init, a test (registered, golden, +// drop) over placeholder sources with an empty golden file, a row in that +// testdata/README.md, providers/.md from providers/_template.md and a +// row in docs/plugins.md, then regenerates docs/plugins.json. `go test ./...` +// passes right after; every place to fill in says TODO(new-plugin). +// +// It changes nothing when the id is taken (registered, in docs/plugins.md, or +// a file it would write exists). +package main + +import ( + "bytes" + "flag" + "fmt" + "go/ast" + "go/format" + "go/parser" + "go/token" + "io" + "os" + "os/exec" + "path/filepath" + "regexp" + "slices" + "strings" + "text/template" + "time" + "unicode" + + "github.com/patch-it-dev/patch-it-plugins/internal/pluginlist" + "github.com/patch-it-dev/patch-it-plugins/plugin" + _ "github.com/patch-it-dev/patch-it-plugins/plugins/all" +) + +// Options are the command's flags. +type Options struct { + Root string // the repo root + API string // the plugin id: --api and every event's api + Provider string // whose API, SDK or package + Format string // the format plugin + Layer string // the docs/plugins.md layer; "" is the format's default + Source string // the provider's source URL; "" is a placeholder + Watches string // the docs/plugins.md "what it watches" cell + Page string // the provider page, providers/.md; "" is the id. An existing page is shared, not rewritten + Today time.Time + // Go runs the go command afterwards: the golden file from the placeholders + // (go test -update) and docs/plugins.json (go run ./cmd/list-plugins). + Go bool +} + +func main() { + var o Options + flag.StringVar(&o.Root, "root", ".", "the repo root") + flag.StringVar(&o.API, "api", "", "the plugin id, e.g. acme or acme-models (lowercase letters, digits, hyphens)") + flag.StringVar(&o.Provider, "provider", "", "the provider's name, e.g. Acme") + flag.StringVar(&o.Format, "format", "", "the format plugin: "+strings.Join(formatNames(), ", ")) + flag.StringVar(&o.Layer, "layer", "", "the layer in docs/plugins.md: API, SDK, package, runtime, CI or \"AI models\" (default: the format's)") + flag.StringVar(&o.Source, "source", "", "the provider's source URL (default: a placeholder to fill in)") + flag.StringVar(&o.Watches, "watches", "", "what it watches, in a few words (default: a placeholder)") + flag.StringVar(&o.Page, "page", "", "the provider page, providers/.md (default: the --api id); one page per provider, so a second plugin of a provider names the existing page") + flag.Parse() + o.Today = time.Now().UTC() + o.Go = true + if err := Run(o, os.Stdout); err != nil { + fmt.Fprintln(os.Stderr, "new-plugin:", err) + os.Exit(1) + } +} + +func formatNames() []string { + var names []string + for n := range formats { + names = append(names, n) + } + slices.Sort(names) + return names +} + +var ( + validID = regexp.MustCompile(`^[a-z][a-z0-9]*(-[a-z0-9]+)*$`) + validURL = regexp.MustCompile(`^https://[^\s|()]+$`) + cellSafe = regexp.MustCompile(`^[^|\n` + "`" + `]+$`) + goosArchs = []string{"aix", "android", "darwin", "dragonfly", "freebsd", "hurd", "illumos", "ios", "js", "linux", "nacl", "netbsd", "openbsd", "plan9", "solaris", "wasip1", "windows", "zos", + "386", "amd64", "arm", "arm64", "loong64", "mips", "mipsle", "mips64", "mips64le", "ppc64", "ppc64le", "riscv64", "s390x", "wasm", "test"} +) + +// data is what the templates fill in. +type data struct { + ID, Ident, Lower, Provider, Source, File, Format string + Slug string // the provider, lowercase: a model subject's provider + SourceFile, DropFile, PluginOf, Ingest, Drop string + Imports []string +} + +// Run scaffolds the plugin, or changes nothing and says why. +func Run(o Options, out io.Writer) error { + f, ok := formats[o.Format] + if !ok { + return fmt.Errorf("--format %q: want one of %s", o.Format, strings.Join(formatNames(), ", ")) + } + if !validID.MatchString(o.API) || o.API == "all" { + return fmt.Errorf("--api %q: want lowercase letters, digits and single hyphens, starting with a letter (acme, acme-models), and not \"all\"", o.API) + } + if o.Provider == "" || !cellSafe.MatchString(o.Provider) { + return fmt.Errorf("--provider %q: want the provider's name, without | or backticks", o.Provider) + } + if o.Layer == "" { + o.Layer = f.layer + } + if _, ok := pluginlist.Layers[o.Layer]; !ok { + return fmt.Errorf("--layer %q: want API, SDK, package, runtime, CI or \"AI models\"", o.Layer) + } + if o.Source == "" { + o.Source = "https://example.com/TODO-" + o.API + "-source" + } else if !validURL.MatchString(o.Source) { + return fmt.Errorf("--source %q: want an https URL", o.Source) + } + if o.Watches == "" { + o.Watches = "TODO: what it watches, in a few words" + } else if !cellSafe.MatchString(o.Watches) { + return fmt.Errorf("--watches: no | or backticks") + } + + sharedPage := false + if o.Page == "" { + o.Page = o.API + } else if !validID.MatchString(o.Page) { + return fmt.Errorf("--page %q: want the name of a page in providers/, without .md", o.Page) + } else if _, err := os.Stat(filepath.Join(o.Root, "providers", o.Page+".md")); err == nil { + sharedPage = true + } + + // Taken? Check everything before writing anything. + if _, ok := plugin.Lookup(o.API); ok { + return fmt.Errorf("a plugin named %q is already registered: pick another --api", o.API) + } + tablePath := filepath.Join(o.Root, pluginlist.Table) + table, err := os.ReadFile(tablePath) + if err != nil { + return fmt.Errorf("%v (run from the repo root, or pass --root)", err) + } + rows, err := pluginlist.ReadTable(table) + if err != nil { + return err + } + for _, r := range rows { + if r.ID == o.API { + return fmt.Errorf("%s already has a row for %q: pick another --api", pluginlist.Table, o.API) + } + } + + d := data{ID: o.API, Provider: o.Provider, Source: o.Source, Format: o.Format} + d.Ident = ident(o.API) + d.Lower = string(unicode.ToLower(rune(d.Ident[0]))) + d.Ident[1:] + d.File = fileBase(o.API) + d.Slug = strings.Trim(regexp.MustCompile(`[^a-z0-9]+`).ReplaceAllString(strings.ToLower(o.Provider), "-"), "-") + d.SourceFile = fill(f.source, d) + d.DropFile = dropName(d.SourceFile) + d.PluginOf = fill(f.pluginOf, d) + d.Ingest = fill(f.ingest, d) + d.Drop = fill(f.drop, d) + d.Imports = append(slices.Clone(f.imports), "testing", "github.com/patch-it-dev/patch-it-plugins/kit/kittest") + slices.Sort(d.Imports) + + pkgDir := "plugins/" + o.Format + writes := map[string][]byte{} + add := func(path string, b []byte) { writes[path] = b } + + def, err := gofmt(fill(f.def, d)) + if err != nil { + return fmt.Errorf("the %s template: %w", o.Format, err) + } + add(filepath.Join(f.defDir, d.File+".go"), def) + test, err := gofmt(fill(testFile, d)) + if err != nil { + return fmt.Errorf("the test template: %w", err) + } + add(filepath.Join(pkgDir, d.File+"_test.go"), test) + for name, content := range f.fixtures { + add(filepath.Join(pkgDir, "testdata", fill(name, d)), []byte(fill(content, d))) + } + drop := f.dropFile + if drop == "" { + drop = f.fixtures[f.source] + } + add(filepath.Join(pkgDir, "testdata", d.DropFile), []byte(fill(drop, d))) + // What the placeholders give; rewritten with -update below, and again + // once the source is real. + add(filepath.Join(pkgDir, "testdata", "golden", o.API+".json"), []byte("[]\n")) + + if !sharedPage { + page, err := providerPage(o) + if err != nil { + return err + } + add(filepath.Join("providers", o.Page+".md"), page) + } + + for path := range writes { + if _, err := os.Stat(filepath.Join(o.Root, path)); err == nil { + return fmt.Errorf("%s already exists: pick another --api, or remove what's left of an earlier run", path) + } + } + for _, dir := range []string{f.defDir, pkgDir} { + if err := identsFree(filepath.Join(o.Root, dir), d.Ident, d.Lower, "read"+d.Ident, "Test"+d.Ident+"Golden"); err != nil { + return err + } + } + + // The edits to existing files. + mainFile, registered, err := register(o.Root, pkgDir, fill(f.register, d)) + if err != nil { + return err + } + edits := map[string][]byte{mainFile: registered} + if m := f.mapEntry; m != nil { + if edits[m.file], err = addMapEntry(filepath.Join(o.Root, m.file), m.varName, fill(m.entry, d)); err != nil { + return err + } + } + readmePath := filepath.Join(pkgDir, "testdata", "README.md") + readme, err := os.ReadFile(filepath.Join(o.Root, readmePath)) + if err != nil { + return err + } + if edits[readmePath], err = readmeRows(readme, []string{d.SourceFile, d.DropFile}, o.Source); err != nil { + return fmt.Errorf("%s: %w", readmePath, err) + } + if edits[pluginlist.Table], err = tableRow(table, o, d); err != nil { + return err + } + + // Write. + var paths []string + for path, b := range writes { + full := filepath.Join(o.Root, path) + if err := os.MkdirAll(filepath.Dir(full), 0o755); err != nil { + return err + } + if err := os.WriteFile(full, b, 0o644); err != nil { + return err + } + paths = append(paths, path+" (new)") + } + for path, b := range edits { + if err := os.WriteFile(filepath.Join(o.Root, path), b, 0o644); err != nil { + return err + } + paths = append(paths, path) + } + slices.Sort(paths) + fmt.Fprintf(out, "Scaffolded %s (%s, format %s):\n", o.API, o.Provider, o.Format) + for _, p := range paths { + fmt.Fprintln(out, " "+p) + } + if o.Go { + for _, args := range [][]string{ + {"test", "./" + pkgDir, "-run", "^Test" + d.Ident + "Golden$", "-update"}, + {"run", "./cmd/list-plugins"}, + } { + cmd := exec.Command("go", args...) + cmd.Dir = o.Root + if b, err := cmd.CombinedOutput(); err != nil { + return fmt.Errorf("the files are written, but `go %s` failed: %w\n%s", strings.Join(args, " "), err, b) + } + } + fmt.Fprintf(out, " %s (from the placeholders)\n docs/plugins.json (regenerated)\n", filepath.Join(pkgDir, "testdata", "golden", o.API+".json")) + } + fmt.Fprint(out, fill(nextSteps, struct { + data + Extra, Page string + Shared bool + }{d, fill(f.next, d), o.Page, sharedPage})) + return nil +} + +const nextSteps = ` +Next steps (every place to fill in says TODO(new-plugin): grep -rn 'TODO(new-plugin)' .): + 1. Save a real copy of the source over the placeholder: + curl -fsSL -o plugins/{{.Format}}/testdata/{{.SourceFile}} '' + and a realistic input that must not become an event as plugins/{{.Format}}/testdata/{{.DropFile}}. + Fill in their rows in plugins/{{.Format}}/testdata/README.md (URL, date fetched, license, quote). + 2. Fill in the definition (the TODOs in the file next to the Register line for {{.Ident}}).{{if .Extra}} + {{.Extra}}{{end}} + 3. Write the golden file, then read it like code: + go test ./plugins/{{.Format}} -run Test{{.Ident}} -update + 4. {{if .Shared}}Add {{.ID}} to providers/{{.Page}}.md (shared with the provider's other plugins){{else}}Fill in providers/{{.Page}}.md{{end}}, above all "Why this source", and the row in docs/plugins.md + (what it watches, the source; a plugin in the code is live), then: make plugins-json + 5. make check, then open the PR (git commit -s). +` + +func fill(tmpl string, d any) string { + var b strings.Builder + template.Must(template.New("").Parse(tmpl)).Execute(&b, d) + return b.String() +} + +func gofmt(src string) ([]byte, error) { return format.Source([]byte(src)) } + +// ident is the id as a Go name: "acme-models" -> "AcmeModels". +func ident(id string) string { + var b strings.Builder + for _, part := range strings.Split(id, "-") { + b.WriteString(strings.ToUpper(part[:1]) + part[1:]) + } + return b.String() +} + +// fileBase is the id as a file name: hyphens become underscores, and a last +// part Go would read as a build constraint (_linux, _arm64, _test) gets +// "_plugin" after it. +func fileBase(id string) string { + base := strings.ReplaceAll(id, "-", "_") + parts := strings.Split(base, "_") + if len(parts) > 1 && slices.Contains(goosArchs, parts[len(parts)-1]) { + base += "_plugin" + } + return base +} + +// dropName is "x.rss.xml" -> "x-drop.rss.xml". +func dropName(name string) string { + base, ext, _ := strings.Cut(name, ".") + return base + "-drop." + ext +} + +// identsFree fails if the package in dir already declares one of names. +func identsFree(dir string, names ...string) error { + pkgs, err := parser.ParseDir(token.NewFileSet(), dir, nil, parser.SkipObjectResolution) + if err != nil { + return err + } + for _, pkg := range pkgs { + for path, file := range pkg.Files { + for _, decl := range file.Decls { + for _, n := range declNames(decl) { + if slices.Contains(names, n) { + return fmt.Errorf("%s already declares %s: pick another --api", path, n) + } + } + } + } + } + return nil +} + +func declNames(decl ast.Decl) []string { + switch d := decl.(type) { + case *ast.FuncDecl: + if d.Recv == nil { + return []string{d.Name.Name} + } + case *ast.GenDecl: + var out []string + for _, s := range d.Specs { + switch s := s.(type) { + case *ast.ValueSpec: + for _, n := range s.Names { + out = append(out, n.Name) + } + case *ast.TypeSpec: + out = append(out, s.Name.Name) + } + } + return out + } + return nil +} + +// register adds line at the end of the init func that registers pkgDir's +// plugins, next to the others. +func register(root, pkgDir, line string) (string, []byte, error) { + files, err := filepath.Glob(filepath.Join(root, pkgDir, "*.go")) + if err != nil { + return "", nil, err + } + for _, path := range files { + if strings.HasSuffix(path, "_test.go") { + continue + } + src, err := os.ReadFile(path) + if err != nil { + return "", nil, err + } + fset := token.NewFileSet() + file, err := parser.ParseFile(fset, path, src, parser.SkipObjectResolution) + if err != nil { + return "", nil, err + } + for _, decl := range file.Decls { + fn, ok := decl.(*ast.FuncDecl) + if !ok || fn.Name.Name != "init" || fn.Recv != nil || !bytes.Contains(src[fn.Pos()-1:fn.End()-1], []byte("plugin.Register(")) { + continue + } + at := fset.Position(fn.Body.Rbrace).Offset + var b bytes.Buffer + b.Write(src[:at]) + b.WriteString("\t" + line + "\n") + b.Write(src[at:]) + out, err := format.Source(b.Bytes()) + if err != nil { + return "", nil, fmt.Errorf("adding the Register line to %s: %w", path, err) + } + rel, _ := filepath.Rel(root, path) + return rel, out, nil + } + } + return "", nil, fmt.Errorf("found no init in %s that calls plugin.Register", pkgDir) +} + +// addMapEntry adds entry to the map literal varName is set to in path. +func addMapEntry(path, varName, entry string) ([]byte, error) { + src, err := os.ReadFile(path) + if err != nil { + return nil, err + } + fset := token.NewFileSet() + file, err := parser.ParseFile(fset, path, src, parser.SkipObjectResolution) + if err != nil { + return nil, err + } + var lit *ast.CompositeLit + ast.Inspect(file, func(n ast.Node) bool { + if v, ok := n.(*ast.ValueSpec); ok && len(v.Names) == 1 && v.Names[0].Name == varName && len(v.Values) == 1 { + lit, _ = v.Values[0].(*ast.CompositeLit) + } + return lit == nil + }) + if lit == nil { + return nil, fmt.Errorf("%s: no map literal %s to add %s to", path, varName, entry) + } + at := fset.Position(lit.Rbrace).Offset + var b bytes.Buffer + b.Write(src[:at]) + if len(lit.Elts) > 0 && fset.Position(lit.Elts[len(lit.Elts)-1].End()).Line == fset.Position(lit.Rbrace).Line { + b.WriteString(", " + entry) + } else { + b.WriteString("\t" + entry + ",\n") + } + b.Write(src[at:]) + return format.Source(b.Bytes()) +} + +// readmeRows adds a row per saved file to the first table of a testdata +// README whose first column is the file, with a TODO in every other column. +func readmeRows(readme []byte, files []string, source string) ([]byte, error) { + lines := strings.Split(string(readme), "\n") + header := -1 + for i, l := range lines { + if strings.HasPrefix(l, "| File") { + header = i + break + } + } + if header < 0 { + // The format's sources live with its reader package (retire/, + // sdkguide/); this package's own saved sources get a table of their own. + for len(lines) > 0 && lines[len(lines)-1] == "" { + lines = lines[:len(lines)-1] + } + lines = append(lines, "", "## Saved sources", "", "| File | URL | Saved | License | Quote |", "|---|---|---|---|---|", "") + header = len(lines) - 3 + } + end := header + 1 + for end < len(lines) && strings.HasPrefix(lines[end], "|") { + end++ + } + var cols []string + for _, c := range strings.Split(strings.Trim(lines[header], "| "), "|") { + cols = append(cols, strings.ToLower(strings.TrimSpace(c))) + } + var rows []string + for _, file := range files { + cells := []string{"`" + file + "`"} + for _, c := range cols[1:] { + switch { + case strings.Contains(c, "url"): + cells = append(cells, "TODO(new-plugin): "+source) + case strings.Contains(c, "saved") || strings.Contains(c, "date") || strings.Contains(c, "fetched"): + cells = append(cells, "TODO(new-plugin): YYYY-MM-DD") + case strings.Contains(c, "license"): + cells = append(cells, "TODO(new-plugin): the license; kept whole, or trimmed and why") + case strings.Contains(c, "quote"): + cells = append(cells, "TODO(new-plugin): a short quote of the part the plugin reads") + default: + cells = append(cells, "TODO(new-plugin)") + } + } + rows = append(rows, "| "+strings.Join(cells, " | ")+" |") + } + lines = slices.Insert(lines, end, rows...) + return []byte(strings.Join(lines, "\n")), nil +} + +// tableRow adds the plugin's row at the end of docs/plugins.md's table. +func tableRow(table []byte, o Options, d data) ([]byte, error) { + end := bytes.Index(table, []byte(pluginlist.EndMarker)) + if end < 0 { + return nil, fmt.Errorf("%s: no %s", pluginlist.Table, pluginlist.EndMarker) + } + row := fmt.Sprintf("| [`%s`](https://github.com/patch-it-dev/patch-it-plugins/blob/main/providers/%s.md) | %s | %s | %s | `%s` | [%s](%s) | live |\n", + o.API, o.Page, o.Provider, o.Layer, o.Watches, o.Format, linkText(o.Source), o.Source) + var b bytes.Buffer + b.Write(table[:end]) + b.WriteString(row) + b.Write(table[end:]) + return b.Bytes(), nil +} + +func linkText(url string) string { + if strings.Contains(url, "example.com/TODO") { + return "TODO: the source" + } + return strings.TrimPrefix(url, "https://") +} + +// providerPage is providers/_template.md for this provider. +func providerPage(o Options) ([]byte, error) { + tmpl, err := os.ReadFile(filepath.Join(o.Root, "providers", "_template.md")) + if err != nil { + return nil, err + } + s := string(tmpl) + s = strings.ReplaceAll(s, "", o.Provider) + s = strings.ReplaceAll(s, "", o.API) + s = strings.ReplaceAll(s, "``", "<"+o.Source+">") + s = strings.ReplaceAll(s, "``", o.Today.Format("2006-01-02")+" (TODO(new-plugin): the date you checked it)") + s = strings.Replace(s, "Copy this file to `providers/"+o.API+".md` and fill every section. Delete these instructions.", + "TODO(new-plugin): fill every section, then delete this line. Scaffolded by `go run ./cmd/new-plugin`.", 1) + return []byte(s), nil +} diff --git a/cmd/new-plugin/main_test.go b/cmd/new-plugin/main_test.go new file mode 100644 index 0000000..4fbbecd --- /dev/null +++ b/cmd/new-plugin/main_test.go @@ -0,0 +1,185 @@ +package main + +import ( + "bytes" + "crypto/sha256" + "io" + "io/fs" + "os" + "os/exec" + "path/filepath" + "slices" + "strings" + "testing" + "time" +) + +var today = time.Date(2026, 11, 19, 0, 0, 0, 0, time.UTC) + +// A plugin of every format, scaffolded into a copy of the repo: the copy +// builds, vets and passes its tests, and docs/plugins.json lists them all. +// Then the same command again changes nothing. +func TestScaffoldEveryFormat(t *testing.T) { + if testing.Short() { + t.Skip("runs the go command over a copy of the repo") + } + goCmd, err := exec.LookPath("go") + if err != nil { + t.Skip("no go command on PATH") + } + root := copyRepo(t) + for _, f := range formatNames() { + o := Options{Root: root, API: "acme-" + f, Provider: "Acme Corp", Format: f, Today: today, Go: true} + var out bytes.Buffer + if err := Run(o, &out); err != nil { + t.Fatalf("%s: %v\n%s", f, err, out.String()) + } + if !strings.Contains(out.String(), "Next steps") { + t.Errorf("%s: no next steps in\n%s", f, out.String()) + } + } + for _, args := range [][]string{{"build", "./..."}, {"vet", "./..."}, {"test", "-count=1", "./plugins/...", "./internal/...", "./migrate/..."}} { + cmd := exec.Command(goCmd, args...) + cmd.Dir = root + if b, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("go %s: %v\n%s", strings.Join(args, " "), err, b) + } + } + listed, err := os.ReadFile(filepath.Join(root, "docs", "plugins.json")) + if err != nil { + t.Fatal(err) + } + for _, f := range formatNames() { + if !bytes.Contains(listed, []byte(`"id": "acme-`+f+`"`)) { + t.Errorf("docs/plugins.json doesn't list acme-%s", f) + } + } + + before := tree(t, root) + err = Run(Options{Root: root, API: "acme-feed", Provider: "Acme Corp", Format: "feed", Today: today, Go: true}, io.Discard) + if err == nil || !strings.Contains(err.Error(), "already has a row") { + t.Errorf("second run: err = %v, want the id taken", err) + } + if after := tree(t, root); !slices.Equal(before, after) { + t.Error("a refused run changed files") + } +} + +// A second plugin of a provider shares its page: no new page, and the row +// links the existing one. +func TestScaffoldSharesTheProviderPage(t *testing.T) { + root := copyRepo(t) + o := Options{Root: root, API: "algolia-analytics", Provider: "Algolia", Format: "openapi", Page: "algolia", Today: today} + if err := Run(o, io.Discard); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(filepath.Join(root, "providers", "algolia-analytics.md")); err == nil { + t.Error("wrote providers/algolia-analytics.md; want the shared providers/algolia.md") + } + table, _ := os.ReadFile(filepath.Join(root, "docs", "plugins.md")) + if !bytes.Contains(table, []byte("[`algolia-analytics`](https://github.com/patch-it-dev/patch-it-plugins/blob/main/providers/algolia.md)")) { + t.Error("the row doesn't link providers/algolia.md") + } +} + +func TestRefusesBadInput(t *testing.T) { + root := copyRepo(t) + before := tree(t, root) + for name, o := range map[string]Options{ + "unknown format": {API: "acme", Provider: "Acme", Format: "graphql"}, + "uppercase id": {API: "Acme", Provider: "Acme", Format: "feed"}, + "double hyphen": {API: "acme--x", Provider: "Acme", Format: "feed"}, + "id all": {API: "all", Provider: "Acme", Format: "feed"}, + "registered id": {API: "stripe", Provider: "Stripe", Format: "openapi"}, + "no provider": {API: "acme", Format: "feed"}, + "pipe in name": {API: "acme", Provider: "Ac|me", Format: "feed"}, + "unknown layer": {API: "acme", Provider: "Acme", Format: "feed", Layer: "database"}, + "http source": {API: "acme", Provider: "Acme", Format: "feed", Source: "http://acme.example/feed"}, + "provider exists": {API: "numpy", Provider: "NumPy", Format: "changelog"}, + } { + o.Root, o.Today = root, today + if err := Run(o, io.Discard); err == nil { + t.Errorf("%s: no error", name) + } + } + if after := tree(t, root); !slices.Equal(before, after) { + t.Error("a refused run changed files") + } +} + +func TestFileBaseAvoidsBuildConstraints(t *testing.T) { + for id, want := range map[string]string{ + "acme": "acme", + "acme-models": "acme_models", + "acme-linux": "acme_linux_plugin", + "acme-arm64": "acme_arm64_plugin", + "acme-test": "acme_test_plugin", + "linux": "linux", + "acme-js-sdk2": "acme_js_sdk2", + } { + if got := fileBase(id); got != want { + t.Errorf("fileBase(%q) = %q, want %q", id, got, want) + } + } + if got := ident("acme-models-2"); got != "AcmeModels2" { + t.Errorf("ident = %q", got) + } +} + +// copyRepo copies the repo's tracked files to a temp dir. +func copyRepo(t *testing.T) string { + t.Helper() + src, err := filepath.Abs("../..") + if err != nil { + t.Fatal(err) + } + cmd := exec.Command("git", "ls-files", "-z", "--cached", "--others", "--exclude-standard") + cmd.Dir = src + list, err := cmd.Output() + if err != nil { + t.Skipf("git ls-files: %v", err) + } + dst := t.TempDir() + for _, f := range strings.Split(string(list), "\x00") { + if f == "" { + continue + } + b, err := os.ReadFile(filepath.Join(src, f)) + if err != nil { + continue // deleted in the worktree + } + if err := os.MkdirAll(filepath.Join(dst, filepath.Dir(f)), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dst, f), b, 0o644); err != nil { + t.Fatal(err) + } + } + return dst +} + +// tree is every file under root with its hash, sorted. +func tree(t *testing.T, root string) []string { + t.Helper() + var out []string + err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error { + if err != nil || d.IsDir() { + return err + } + b, err := os.ReadFile(path) + if err != nil { + return err + } + out = append(out, path+" "+hash(b)) + return nil + }) + if err != nil { + t.Fatal(err) + } + return out +} + +func hash(b []byte) string { + sum := sha256.Sum256(b) + return string(sum[:]) +} diff --git a/docs/writing-a-plugin.md b/docs/writing-a-plugin.md index 241d1c5..cd912ee 100644 --- a/docs/writing-a-plugin.md +++ b/docs/writing-a-plugin.md @@ -4,7 +4,28 @@ A plugin watches one provider source and turns what changed into change events. **Most new providers don't need new code.** They are a new entry for an existing format plugin: a new `changelog.File`, a new `retire.Page`, a new `feed.Feed` reader, a new OpenAPI adapter. Write a new format plugin only when none of them reads your source. -## 1. Pick the source +## 1. Scaffold it with `new-plugin` + +Pick the source and the format plugin that reads it (steps 2 and 3), then let the starter write everything around the provider: + +```sh +go run ./cmd/new-plugin --api acme --provider Acme --format openapi +# --format: openapi, retirements, migrationguide, removedmembers, changelog, feed, apichangelog, catalog +# optional: --source https://... (the provider's source), --watches "...", --layer API|SDK|package|runtime|CI|"AI models", +# --page acme (a second plugin of a provider shares its page in providers/) +``` + +It writes, and lists: + +- the provider's definition, in the package the format reads it from (`adapter/`, `retire/`, `sdkguide/` or `plugins//`), and its `plugin.Register` line in that format's `init` (plus the `migrate/` map entry that `retirements` and `migrationguide` need); +- `plugins//_test.go`: the registration test, a golden test and a pinned drop test, over placeholder sources in `testdata/`, with the golden file written from them; +- a row per saved file in that `testdata/README.md` (URL, date, license, quote to fill in); +- `providers/.md` from the template (or nothing, with `--page`, when the provider already has one); +- the row in `docs/plugins.md`, and `docs/plugins.json` regenerated. + +`go test ./...` passes right after; every place to fill in says `TODO(new-plugin)` (`grep -rn 'TODO(new-plugin)' .`). It refuses an id that's taken (registered, in `docs/plugins.md`, or a file it would write exists) and then changes nothing. The steps below are what you fill in. + +## 2. Pick the source Use the provider's own, most machine-readable source. In order of preference: @@ -13,9 +34,9 @@ Use the provider's own, most machine-readable source. In order of preference: 3. **An official RSS / Atom feed** of changes. Built to be machine-read. 4. **An official documentation page** (a deprecations page), ideally served as markdown. A live page changes, so events cite a Wayback Machine snapshot of it. -Never scrape what the provider's `robots.txt` or terms disallow, and never read a forum or a third-party blog. Write down what you chose and why in the provider page (step 7). +Never scrape what the provider's `robots.txt` or terms disallow, and never read a forum or a third-party blog. Write down what you chose and why in the provider page (step 8). -## 2. Pick the format plugin +## 3. Pick the format plugin | Format plugin | Reads | Add a provider by | |---|---|---| @@ -28,7 +49,7 @@ Never scrape what the provider's `robots.txt` or terms disallow, and never read | `plugins/catalog` | A flat JSON catalog, one entry per name, with no release tags to pin — a commit SHA stands in | A `catalog.Catalog`, diffed between two snapshots for names that disappeared entirely | | `plugins/apichangelog` | A vendor's machine-readable API changelog in JSON (per day, endpoint and API version, oasdiff change codes), at the commit that last changed it | An `apichangelog.Log` | -## 3. The interface +## 4. The interface A plugin implements `plugin.Plugin` (package [`plugin/`](../plugin/plugin.go)): @@ -81,14 +102,14 @@ func init() { The event format is [patch-it's change-event contract](https://github.com/patch-it-dev/patch-it/tree/main/docs/contract); `event/` is its Go binding. Every event has a typed `subject` (`api_operation`, `model`, `package_release`, `ci_runtime`), a `change_type` (`breaking`, `deprecation`, …), a `version`, a `fingerprint` (`event.FingerprintV2`), and **a `source_url` and `source_excerpt`: no source, no event**. Call `Validate()`; an invalid event goes in `Result.Rejected`, not `Events`. -## 4. Save the source +## 5. Save the source Save a real copy of what the plugin reads under your package's `testdata/` (or the reader package's, like `retire/testdata/`). Add a row to that directory's `README.md`: file, URL, date fetched, license, and a short quote of the part the plugin reads. - **Openly licensed files** (MIT, BSD, Apache, CC BY): keep them whole. - **Vendor documentation pages**: trim to what the plugin reads (the tables, the sections), copy every kept line unchanged, mark it "excerpt for testing; © the vendor", and say what you left out. -## 5. Write the golden test +## 6. Write the golden test The test kit, `kit/kittest`, runs the plugin with no network, no database and a fixed clock: @@ -105,21 +126,21 @@ func TestGolden(t *testing.T) { - `kittest.Golden` compares the stored events with the JSON file. Create or rewrite it with `go test ./plugins/ -update`, then read the diff like code: every event in it is a pull request someone may get. - A live page: build the env with `kittest.Env`, cite through `&kittest.Archive{T: t, Pages: saved}` and run with `kittest.IngestWith`. -## 6. Pin a drop test and the registration +## 7. Pin a drop test and the registration - **One drop test**: a realistic input the plugin must *not* turn into an event (an unrelated section, a behavior change written as prose, a product name in a sentence). Precision over recall: a missed change is a bug we fix later; a wrong change is a wrong pull request in someone's repo. - **`registered_test.go`**: `kittest.Registered(t, Plugin{…})` checks the package registered that plugin under that name. - **A new format plugin package**: add its blank import to [`plugins/all/all.go`](../plugins/all/all.go). `TestEveryPluginIsImported` fails until you do; the hosted service runs exactly what `plugins/all` imports. -## 7. Write the provider page +## 8. Write the provider page Copy [`providers/_template.md`](../providers/_template.md) to `providers/.md` and fill in every section: what it watches; **why this source** (the link, the date you checked it, why it's the best place this provider announces breaking changes, the alternatives you didn't use and why, one short quote); how the provider announces changes; what the plugin reads and ignores; known gaps. -## 8. Add the row to `docs/plugins.md` +## 9. Add the row to `docs/plugins.md` **Not optional** ([AGENTS.md](../AGENTS.md) rule 1). Add one row between the `plugins:start` and `plugins:end` markers: the id linked to its provider page, the provider, what it watches, the format plugin, the source, the status. Absolute links only: the docs site copies the table as it is. Changing a plugin's id, source or what it watches updates its row in the same PR. Then run `make plugins-json` to regenerate `docs/plugins.json`; it fails, naming the problem, if the registry and the table disagree. -## 9. Check and open the PR +## 10. Check and open the PR ```sh make check # what CI runs, plus the leak guard From bf08394abc17be0b66c429ce43ed75782d300203 Mon Sep 17 00:00:00 2001 From: adssib <75389300+adssib@users.noreply.github.com> Date: Thu, 19 Nov 2026 15:21:57 -0500 Subject: [PATCH 2/2] fail make check and ci on a TODO(new-plugin) left Also: quotes and backslashes refused in --provider and --watches, the openapi testdata table's Source and Checked columns get their hints. Co-Authored-By: Claude Opus 5.5 Signed-off-by: adssib <75389300+adssib@users.noreply.github.com> --- .github/pull_request_template.md | 1 - .github/workflows/CI_go.yml | 5 +++++ AGENTS.md | 6 +++--- Makefile | 14 ++++++++++++-- cmd/new-plugin/main.go | 14 ++++++++------ docs/writing-a-plugin.md | 2 +- 6 files changed, 29 insertions(+), 13 deletions(-) diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index f56eb72..30b6631 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -12,7 +12,6 @@ - [ ] `providers/.md` written or updated from `providers/_template.md`, including **Why this source** - [ ] Fetches only through `env.Get` / `kit/` - [ ] `make check` passes locally (and `make plugins-json` was run if a plugin or its row changed) -- [ ] No `TODO(new-plugin)` left (`grep -rn 'TODO(new-plugin)' .` prints nothing) - [ ] Nothing private: no credentials, internal hosts, private links, customer names ## Notes for the reviewer diff --git a/.github/workflows/CI_go.yml b/.github/workflows/CI_go.yml index 2321c5b..8f21644 100644 --- a/.github/workflows/CI_go.yml +++ b/.github/workflows/CI_go.yml @@ -74,6 +74,11 @@ jobs: if: steps.go.outputs.present == 'true' run: make nethttp + # A provider scaffolded with new-plugin, with a TODO(new-plugin) left. + - name: no TODO(new-plugin) left + if: steps.go.outputs.present == 'true' + run: make todos + # -race: the fetcher and the tests' HTTP servers run on other goroutines. # Also fails when docs/plugins.json is out of date (make plugins-json). - name: go test diff --git a/AGENTS.md b/AGENTS.md index e755f9d..c13dac5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -23,7 +23,7 @@ Refer to the service that runs these plugins as "patch-it's hosted ingestion ser ## Rules for plugin code -- **Start a new provider with `go run ./cmd/new-plugin --api --provider --format `**, then fill in every `TODO(new-plugin)`; none may be left when you open the PR. +- **Start a new provider with `go run ./cmd/new-plugin --api --provider --format `**, then fill in every `TODO(new-plugin)`; `make todos` (part of `make check` and CI_go) fails while one is left. - **Fetch only through the environment** (`env.Get` or `kit/`). No `net/http` outside the fetch layer, no filesystem outside `testdata/`, no database. - **Golden test + dated source quote**: a saved copy of the real source in `testdata/`, a row in `testdata/README.md` (URL, date fetched, license, quote), and `testdata/golden/.json` with the exact events. @@ -38,12 +38,12 @@ Refer to the service that runs these plugins as "patch-it's hosted ingestion ser **Run `make check` before you say you're done.** It runs exactly what `CI_go` runs (each CI step is a Makefile target) plus the internal-names check over every tracked file; if it passes locally, those checks pass in CI. ```sh -make check # tidy, build, gofmt, vet, the import allowlist, the net/http guard, go test -race, leak guard +make check # tidy, build, gofmt, vet, the import allowlist, the net/http guard, go test -race, no TODO(new-plugin) left, leak guard make check PATCH_IT=../patch-it # also CI_contract: contract/fixtures/ against a patch-it checkout make plugins-json # regenerate docs/plugins.json after adding or changing a plugin or its row ``` -One target at a time: `make tidy`, `make build`, `make fmt`, `make vet`, `make imports`, `make nethttp`, `make test`, `make leak-guard`, `make contract`. Use `make GO=/path/to/go check` for another Go. +One target at a time: `make tidy`, `make build`, `make fmt`, `make vet`, `make imports`, `make nethttp`, `make test`, `make todos`, `make leak-guard`, `make contract`. Use `make GO=/path/to/go check` for another Go. ## Layout diff --git a/Makefile b/Makefile index f507bd9..23ddf94 100644 --- a/Makefile +++ b/Makefile @@ -17,9 +17,9 @@ PYTHON ?= python3 MODULE := github.com/patch-it-dev/patch-it-plugins ALLOWED := ^($(MODULE)(/|$$)|gopkg\.in/yaml\.v3$$) -.PHONY: check tidy build fmt vet imports nethttp test leak-guard contract plugins-json +.PHONY: check tidy build fmt vet imports nethttp test todos leak-guard contract plugins-json -check: tidy build fmt vet imports nethttp test leak-guard contract +check: tidy build fmt vet imports nethttp test todos leak-guard contract @echo "make check: all passed" # go.mod and go.sum are tidy. @@ -62,6 +62,16 @@ nethttp: test: $(GO) test -race -count=1 ./... +# A provider started with new-plugin is done when nothing it wrote still says +# TODO(new-plugin). +TODO_DIRS := plugins adapter retire sdkguide migrate providers docs/plugins.md +todos: + @left=$$(grep -rl 'TODO(new-plugin)' $(TODO_DIRS) || true); \ + if [ -n "$$left" ]; then \ + for f in $$left; do echo "::error file=$$f::TODO(new-plugin) left: fill it in (grep -n 'TODO(new-plugin)' $$f)."; done; \ + exit 1; \ + fi + # CI_leak_guard checks only what a PR adds (plus gitleaks); this checks every # tracked file. leak-guard: diff --git a/cmd/new-plugin/main.go b/cmd/new-plugin/main.go index d03a394..7e4dd1d 100644 --- a/cmd/new-plugin/main.go +++ b/cmd/new-plugin/main.go @@ -87,7 +87,7 @@ func formatNames() []string { var ( validID = regexp.MustCompile(`^[a-z][a-z0-9]*(-[a-z0-9]+)*$`) validURL = regexp.MustCompile(`^https://[^\s|()]+$`) - cellSafe = regexp.MustCompile(`^[^|\n` + "`" + `]+$`) + cellSafe = regexp.MustCompile(`^[^|\n"\\` + "`" + `]+$`) goosArchs = []string{"aix", "android", "darwin", "dragonfly", "freebsd", "hurd", "illumos", "ios", "js", "linux", "nacl", "netbsd", "openbsd", "plan9", "solaris", "wasip1", "windows", "zos", "386", "amd64", "arm", "arm64", "loong64", "mips", "mipsle", "mips64", "mips64le", "ppc64", "ppc64le", "riscv64", "s390x", "wasm", "test"} ) @@ -110,7 +110,7 @@ func Run(o Options, out io.Writer) error { return fmt.Errorf("--api %q: want lowercase letters, digits and single hyphens, starting with a letter (acme, acme-models), and not \"all\"", o.API) } if o.Provider == "" || !cellSafe.MatchString(o.Provider) { - return fmt.Errorf("--provider %q: want the provider's name, without | or backticks", o.Provider) + return fmt.Errorf("--provider %q: want the provider's name, without |, quotes, backslashes or backticks", o.Provider) } if o.Layer == "" { o.Layer = f.layer @@ -126,7 +126,7 @@ func Run(o Options, out io.Writer) error { if o.Watches == "" { o.Watches = "TODO: what it watches, in a few words" } else if !cellSafe.MatchString(o.Watches) { - return fmt.Errorf("--watches: no | or backticks") + return fmt.Errorf("--watches: no |, quotes, backslashes or backticks") } sharedPage := false @@ -299,7 +299,9 @@ Next steps (every place to fill in says TODO(new-plugin): grep -rn 'TODO(new-plu func fill(tmpl string, d any) string { var b strings.Builder - template.Must(template.New("").Parse(tmpl)).Execute(&b, d) + if err := template.Must(template.New("").Parse(tmpl)).Execute(&b, d); err != nil { + panic(err) // the templates are constants: a failure is a bug here + } return b.String() } @@ -482,9 +484,9 @@ func readmeRows(readme []byte, files []string, source string) ([]byte, error) { cells := []string{"`" + file + "`"} for _, c := range cols[1:] { switch { - case strings.Contains(c, "url"): + case strings.Contains(c, "url") || strings.Contains(c, "source"): cells = append(cells, "TODO(new-plugin): "+source) - case strings.Contains(c, "saved") || strings.Contains(c, "date") || strings.Contains(c, "fetched"): + case strings.Contains(c, "saved") || strings.Contains(c, "date") || strings.Contains(c, "fetched") || strings.Contains(c, "checked"): cells = append(cells, "TODO(new-plugin): YYYY-MM-DD") case strings.Contains(c, "license"): cells = append(cells, "TODO(new-plugin): the license; kept whole, or trimmed and why") diff --git a/docs/writing-a-plugin.md b/docs/writing-a-plugin.md index cd912ee..e51b889 100644 --- a/docs/writing-a-plugin.md +++ b/docs/writing-a-plugin.md @@ -23,7 +23,7 @@ It writes, and lists: - `providers/.md` from the template (or nothing, with `--page`, when the provider already has one); - the row in `docs/plugins.md`, and `docs/plugins.json` regenerated. -`go test ./...` passes right after; every place to fill in says `TODO(new-plugin)` (`grep -rn 'TODO(new-plugin)' .`). It refuses an id that's taken (registered, in `docs/plugins.md`, or a file it would write exists) and then changes nothing. The steps below are what you fill in. +`go test ./...` passes right after; every place to fill in says `TODO(new-plugin)` (`grep -rn 'TODO(new-plugin)' .`), and `make check` (its `todos` step, also in CI_go) fails until none is left. It refuses an id that's taken (registered, in `docs/plugins.md`, or a file it would write exists) and then changes nothing. The steps below are what you fill in. ## 2. Pick the source