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 d5a2efb..fd85b25 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -6,12 +6,14 @@ Rules for AI coding agents (and humans) working in this repo. `CLAUDE.md` import **If you add a plugin, add its row to [`docs/plugins.md`](docs/plugins.md) in the same PR. If you change a plugin's id, provider, source, what it watches, format plugin or status, update its row in the same PR. If you remove one, remove its row.** -The list of supported APIs on docs.patch-it.dev is generated from that file, so a plugin missing from it doesn't exist as far as users can tell. Then run `make plugins-json`: it regenerates [`docs/plugins.json`](docs/plugins.json) from the plugin registry and the table, and fails if a registered plugin has no row (or a row has no plugin, a wrong format or no provider page). `go test` fails while `docs/plugins.json` is out of date. The check can't tell whether a row's words are right: you are that check. Say in the PR that you compared them. +The list of supported APIs on docs.patch-it.dev is generated from that file, so a plugin missing from it doesn't exist as far as users can tell. Then run `make plugins-json`: it regenerates [`docs/plugins.json`](docs/plugins.json) from the plugin registry and the table (and the plugin count on the README's badge), and fails if a registered plugin has no row (or a row has no plugin, a wrong format or no provider page). `go test` fails while `docs/plugins.json` is out of date. The check can't tell whether a row's words are right: you are that check. Say in the PR that you compared them. Keep the table between the `` and `` markers a plain Markdown table, one row per plugin, absolute links only (the docs site copies it verbatim). ## Rule 2: this repo is public +Public text (README, docs, descriptions) follows [docs/README-template.md](docs/README-template.md): its order, its words, its layer statuses. + Everything you write here is public forever, including commit messages, branch names, PR titles and descriptions, and test data. Never write: - credentials, tokens, keys, or values from any `.env`; @@ -23,6 +25,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)`; `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. - **Precision over recall.** When unsure whether something is a change, don't emit an event. @@ -36,12 +39,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 @@ -50,6 +53,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/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/README.md b/README.md index 7346417..0fa19d7 100644 --- a/README.md +++ b/README.md @@ -1,63 +1,122 @@ +Patchy, the patch-it bot, holding up the lines it found + # patch-it-plugins -The source plugins for [patch-it](https://github.com/patch-it-dev/patch-it), the tool that turns third-party API changes into pull requests in your repo. Each plugin reads one provider's own sources (API specs, changelogs, deprecation pages, SDK migration guides, release feeds) and turns what changed into change events. +**How patch-it notices, on its own, that something your code depends on changed.** Each plugin watches one provider's own source (an API spec, a changelog, a shutdown notice, a release feed) and turns what changed into a change event, with the source linked and quoted. -> **Just moved.** The plugins were moved here from patch-it's hosted ingestion service, which imports this module at a tagged release (`v0.x.y`) and runs them every day. +**Why:** when anything your code depends on changes (APIs, packages, SDKs, runtimes, CI, AI models), [patch-it](https://patch-it.dev) finds the code that breaks and opens the pull request that fixes it. In your CI, on your key. You get the fix, not the alert. These plugins are the trigger: nobody has to assign an alert or open a ticket. -## How a plugin works +[![CI](https://github.com/patch-it-dev/patch-it-plugins/actions/workflows/CI_go.yml/badge.svg)](https://github.com/patch-it-dev/patch-it-plugins/actions/workflows/CI_go.yml) +[![Go Reference](https://pkg.go.dev/badge/github.com/patch-it-dev/patch-it-plugins.svg)](https://pkg.go.dev/github.com/patch-it-dev/patch-it-plugins) +[![Go version](https://img.shields.io/github/go-mod/go-version/patch-it-dev/patch-it-plugins)](go.mod) +[![License: Apache-2.0](https://img.shields.io/badge/license-Apache--2.0-3f5bf0)](LICENSE) +[![Plugins](https://img.shields.io/badge/plugins-20-3f5bf0)](docs/plugins.md) +[![Docs](https://img.shields.io/badge/docs-docs.patch--it.dev-3f5bf0)](https://docs.patch-it.dev) +[![Discussions](https://img.shields.io/github/discussions/patch-it-dev/patch-it-plugins)](https://github.com/patch-it-dev/patch-it-plugins/discussions) + +```mermaid +flowchart LR + A["Provider's own source
spec · changelog · shutdown notice · feed"] -->|"read daily"| B["Plugin
(this repo)"] + B -->|"what changed, quoted"| C["Change event
breaking · deprecation · date · source"] + C --> D["patch-it in your CI
finds the lines, an AI model writes the change"] + D --> E["Pull request in your repo
your tests check it, you merge it"] +``` + +## What patch-it does + +1. **It acts on its own.** A plugin here sees the change where the provider announces it, and patch-it starts from there: no alert to triage, no ticket to assign. That includes changes that never bump a version, like an AI model or an API shut down on a date. +2. **It writes the fix.** An AI model (on your own key) reads the change and the lines it affects and writes the code change. Your repo's own tests check it, and it arrives as a pull request you review and merge like any other: the code change, not just the version. +3. **Proof:** 8 pull requests opened by the early version have been merged by outside maintainers. +4. **What it covers:** + + | Layer | Status | + |---|---| + | APIs (Stripe, OpenAI, Anthropic and [more](docs/plugins.md)) | live | + | AI models (shutdowns and retirements) | live | + | Packages and SDKs (breaking major releases) | in testing | + | Runtimes (end of life) | building | + | CI (retired runners, images, actions) | planned | + +5. **Start:** [docs.patch-it.dev](https://docs.patch-it.dev) sets up the GitHub Action in your repo. To have it watch a provider it doesn't cover yet, add a plugin (below). + +## Add a provider in 15 minutes + +You need Go (the version in `go.mod`), `make` and Python 3. Pick the format that reads your provider's source ([which one](docs/writing-a-plugin.md#3-pick-the-format-plugin)), then: + +**1. Scaffold it.** + +```sh +URL=https://acme.example/changelog.xml # your provider's source +go run ./cmd/new-plugin --api acme --provider Acme --format feed --source "$URL" +``` +``` +Scaffolded acme (Acme, format feed): + docs/plugins.md + plugins/feed/acme.go (new) + plugins/feed/acme_test.go (new) + ... +Next steps (every place to fill in says TODO(new-plugin): ...) +``` + +**2. Save a real copy of the source and write the golden file.** Fill in the `TODO(new-plugin)`s: the reader in `plugins/feed/acme.go`, the saved file's row in `testdata/README.md`, and "Why this source" in `providers/acme.md`. + +```sh +curl -fsSL -o plugins/feed/testdata/acme.rss.xml "$URL" +go test ./plugins/feed -run TestAcme -update # writes testdata/golden/acme.json: read it like code +``` + +**3. Check it, the way CI will.** +```sh +make plugins-json && make check +``` ``` -provider source ──fetch──▶ plugin ──▶ change events ──▶ patch-it's change feed ──▶ your CI - (spec, page, feed) reads, diffs, (validated, each (GET /v1/changes) (patch-it opens - normalizes with a source link the PR) - and a quote) +... +make check: all passed ``` +**4. Open the pull request** (`git commit -s`, one plugin per PR). Details: [docs/writing-a-plugin.md](docs/writing-a-plugin.md). Stuck? Ask in [Discussions](https://github.com/patch-it-dev/patch-it-plugins/discussions). Looking for a first change? [Good first issues](https://github.com/patch-it-dev/patch-it-plugins/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22). + +## How a plugin works + 1. **Fetch.** The plugin asks its environment for the source (`env.Get`); it never opens connections itself. Pages that change in place are also cited through a Web Archive snapshot, so the link in an event keeps showing what the plugin read. 2. **Compare.** It compares the source to the last version it saw (the baseline): two OpenAPI specs, two versions of a deprecations page, a new release's changelog section. -3. **Emit events.** Each change becomes one event in [patch-it's change-event format](https://github.com/patch-it-dev/patch-it/tree/main/docs/contract): what changed, how bad it is (breaking, deprecation, behavior change, non-breaking), the date it takes effect, and the source URL with a quote. **No source, no event.** +3. **Emit events.** Each change becomes one event in [patch-it's change-event format](https://github.com/patch-it-dev/patch-it/tree/main/docs/contract): what changed, how bad it is (breaking, deprecation, behavior change, non-breaking), the date it takes effect, and the source URL with a quote. **No source, no event.** When unsure, a plugin emits nothing: a wrong event would become a wrong pull request. + +Most providers are an entry for a shared format plugin (`openapi`, `retirements`, `migrationguide`, `removedmembers`, `changelog`, `feed`, `apichangelog`, `catalog`), not new code. patch-it's hosted ingestion service runs every plugin daily and serves the events to the patch-it GitHub Action and CLI. -Plugins are small: most providers are an entry for a shared format plugin (`openapi`, `retirements`, `migrationguide`, `removedmembers`, `changelog`, `feed`), not new code. patch-it's hosted service runs every plugin daily and serves the events to the patch-it GitHub Action and CLI. +## Supported plugins + +**[docs/plugins.md](docs/plugins.md)** lists every plugin: provider, layer, what it watches, its source. The same list is on [docs.patch-it.dev](https://docs.patch-it.dev/supported-apis/plugins/), and as JSON in [docs/plugins.json](docs/plugins.json) (`make plugins-json`). ## Layout | Path | What's there | |---|---| | [`plugin/`](plugin/) | The `Plugin` interface, the registry (`Register`, `Lookup`, `Names`), `Env`, `Result` | -| [`plugins/`](plugins/) | The format plugins: `openapi`, `retirements`, `migrationguide`, `removedmembers`, `changelog`, `feed`. `plugins/all` imports every one | +| [`plugins/`](plugins/) | The format plugins; `plugins/all` imports every one | +| [`cmd/new-plugin/`](cmd/new-plugin/), [`cmd/list-plugins/`](cmd/list-plugins/) | The starter for a new provider; the generator of `docs/plugins.json` | | [`kit/`](kit/), [`kit/kittest/`](kit/kittest/) | What plugins share (the unchanged-page check, Wayback citing) and the test kit (in-memory store, saved pages, golden files) | | [`event/`](event/), [`migrate/`](migrate/) | The change-event types of [patch-it's contract](https://github.com/patch-it-dev/patch-it/tree/main/docs/contract), and the v1 → v2 conversion | | [`diff/`](diff/), [`normalize/`](normalize/), [`hint/`](hint/), [`adapter/`](adapter/) | The OpenAPI diff engine: compare two specs, turn the changes into events, attach changelog hints; one adapter per spec provider | | [`retire/`](retire/), [`sdkguide/`](sdkguide/), [`fetch/`](fetch/) | The deprecations-page and migration-guide readers; the HTTP fetch and cache | | [`contract/fixtures/`](contract/) | A copy of patch-it's change-event fixtures | | [`providers/`](providers/) | One page per provider: why that source, what the plugin reads | -| [`docs/`](docs/) | [The plugin list](docs/plugins.md) and [how to write a plugin](docs/writing-a-plugin.md) | - -## Supported plugins - -See **[docs/plugins.md](docs/plugins.md)**. The same list is on [docs.patch-it.dev](https://docs.patch-it.dev/supported-apis/plugins/). +| [`docs/`](docs/) | [The plugin list](docs/plugins.md), [how to write a plugin](docs/writing-a-plugin.md), the [README template](docs/README-template.md) patch-it's public repos share | -## Run the tests - -Go (the version in `go.mod`), `make` and Python 3, no other setup: +## Run the checks ```sh -make check # what CI runs: tidy, build, gofmt, vet, import and net/http guards, go test -race, leak guard +make check # what CI runs: tidy, build, gofmt, vet, import and net/http guards, go test -race, no TODO(new-plugin) left, leak guard ``` -The tests are offline: every plugin's test reads a saved copy of its source from `testdata/` and compares the events with a golden file. One package: `go test ./plugins/feed`. After an intended change to a plugin's output, `go test ./plugins/ -update` rewrites its golden files; review that diff like code. - -### Environment +The tests are offline: every plugin's test reads a saved copy of its source from `testdata/` and compares the events with a golden file. After an intended change to a plugin's output, `go test ./plugins/ -update` rewrites its golden files; review that diff like code. -| Variable | Needed | What it does | -|---|---|---| -| `GITHUB_TOKEN` | No | Optional. A GitHub token (no scopes needed) sent to the GitHub API when the `openapi` adapters look up release tags (Stripe's and Datadog's releases, GitHub's API versions). It only raises GitHub's rate limit for unauthenticated calls (60 an hour per IP); the tests never use it. | - -Nothing else is read from the environment. +`GITHUB_TOKEN` (optional, no scopes) only raises GitHub's rate limit when the `openapi` adapters look up release tags; the tests never use it. Nothing else is read from the environment. ## Releases -Every release is a `v0.x.y` tag on `main` with a [GitHub release](https://github.com/patch-it-dev/patch-it-plugins/releases) and generated notes. Maintainers make them with the manual **Release** workflow ([how](CONTRIBUTING.md#releasing)); tags are never moved or deleted, so a bad release is fixed with a new patch version. +Releases are `v0.x.y` tags on `main` with a [GitHub release](https://github.com/patch-it-dev/patch-it-plugins/releases) and generated notes. The **Release** workflow tags a patch release on its own every Monday and Thursday at 14:00 UTC when something new was merged, and maintainers can run it by hand ([how](CONTRIBUTING.md#releasing)). patch-it's hosted ingestion service runs the latest release, so a merged plugin is running within a few days. Tags are never moved or deleted. ```sh go get github.com/patch-it-dev/patch-it-plugins@latest @@ -65,9 +124,7 @@ go get github.com/patch-it-dev/patch-it-plugins@latest ## Contributing -New providers and fixes are welcome. Read [CONTRIBUTING.md](CONTRIBUTING.md) first (DCO sign-off, golden tests, adding your plugin to `docs/plugins.md`). AI coding agents: [AGENTS.md](AGENTS.md). - -User docs for patch-it itself: [docs.patch-it.dev](https://docs.patch-it.dev). +New providers and fixes are welcome: [CONTRIBUTING.md](CONTRIBUTING.md) has the rules (DCO sign-off, golden tests, the plugin list), [docs/writing-a-plugin.md](docs/writing-a-plugin.md) the how-to. AI coding agents: [AGENTS.md](AGENTS.md). Questions and ideas: [Discussions](https://github.com/patch-it-dev/patch-it-plugins/discussions). ## License diff --git a/cmd/list-plugins/main.go b/cmd/list-plugins/main.go index 9932074..55504d7 100644 --- a/cmd/list-plugins/main.go +++ b/cmd/list-plugins/main.go @@ -1,6 +1,7 @@ // Command list-plugins writes docs/plugins.json: every registered plugin // joined with its row in docs/plugins.md (id, provider, what it watches, -// format plugin, source URL, status, provider page). It fails when the +// format plugin, source URL, status, provider page), and sets the plugin +// count on the README's badge. It fails when the // registry and the table disagree. Run it from the repo root: // // go run ./cmd/list-plugins # rewrite docs/plugins.json (make plugins-json) @@ -43,13 +44,24 @@ func run(root, out string, check bool) error { _, err := os.Stdout.Write(b) return err } + readmePath := filepath.Join(root, pluginlist.Readme) + readme, err := os.ReadFile(readmePath) + if err != nil { + return err + } + badged, _ := pluginlist.Badge(readme, len(plugins)) path := filepath.Join(root, out) if check { have, err := os.ReadFile(path) - if err != nil || !bytes.Equal(have, b) { - return fmt.Errorf("%s is out of date: run `make plugins-json` and commit it", out) + if err != nil || !bytes.Equal(have, b) || !bytes.Equal(readme, badged) { + return fmt.Errorf("%s or the README's plugins badge is out of date: run `make plugins-json` and commit them", out) } return nil } + if !bytes.Equal(readme, badged) { + if err := os.WriteFile(readmePath, badged, 0o644); err != nil { + return err + } + } return os.WriteFile(path, b, 0o644) } 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..7e4dd1d --- /dev/null +++ b/cmd/new-plugin/main.go @@ -0,0 +1,541 @@ +// 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 |, quotes, backslashes 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 |, quotes, backslashes 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 + 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() +} + +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") || strings.Contains(c, "source"): + cells = append(cells, "TODO(new-plugin): "+source) + 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") + 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/README-template.md b/docs/README-template.md new file mode 100644 index 0000000..81d0551 --- /dev/null +++ b/docs/README-template.md @@ -0,0 +1,99 @@ +# README template for patch-it's public repos + +Every public patch-it repo's README has the same shape, so a developer landing on any of them knows in ten seconds what it is and how to try it. This repo's [README](../README.md) is the worked example. Copy the skeleton at the bottom, then fill each section using the notes. + +## The sections, in order + +| # | Section | What goes in it | +|---|---|---| +| 1 | **What** (one line, bold, under the title) | What *this repo* is, in one sentence, in the product's words. For a part of patch-it, say which part of the story it is ("how patch-it notices, on its own, that something changed"). | +| 2 | **Why** (one short paragraph) | The one-liner for patch-it: when anything your code depends on changes (APIs, packages, SDKs, runtimes, CI, AI models), patch-it finds the code that breaks and opens the pull request that fixes it. In your CI, on your key. "You get the fix, not the alert." Then one sentence on why this repo matters to that. | +| 3 | **Badges** (one line of them) | The badge set below, in that order. | +| 4 | **Visual** | One picture of the flow: a mermaid diagram (GitHub renders it) until there's a GIF or screenshot. Left to right, ending in "pull request in your repo". | +| 5 | **The story** ("What patch-it does") | In this order, one or two lines each: (1) **it acts on its own** (it watches the change itself; no one assigns an alert; also changes with no version bump, like a model or API shut down on a date); (2) **it writes the fix** (an AI model on your key writes the code change, your tests check it, you review and merge it); (3) **proof** ("8 pull requests merged by outside maintainers", no other counts); (4) **layers covered**, as a table marked `live`, `in testing`, `building` or `planned`, never ahead of the truth; (5) **how to start** (a link to docs.patch-it.dev). | +| 6 | **Quickstart** (three or four steps, one screen) | The shortest path from a clean clone to the repo's main job, each step a command that runs as written, with the output to expect. Details live in linked docs. | +| 7 | **How it works, and links** | A short "how it works", the layout if the repo has code, how to run its checks, releases, contributing (with Discussions and good first issues), license, and docs.patch-it.dev. | + +## The badge set + +In this order; drop one only if it can't be honest for the repo (no release yet: no release badge): + +1. **CI**: the main workflow's badge, `https://github.com/patch-it-dev//actions/workflows/.yml/badge.svg`. +2. **Package reference**, if it's a library: Go Reference (`https://pkg.go.dev/badge/.svg`), PyPI or npm version. +3. **Language version**: e.g. `https://img.shields.io/github/go-mod/go-version/patch-it-dev/`. +4. **Latest release**, once there is one: `https://img.shields.io/github/v/release/patch-it-dev/`. +5. **License**: `https://img.shields.io/badge/license--3f5bf0`. +6. **A count the repo is about**, only if a test keeps it right (patch-it-plugins: the plugins badge, set by `make plugins-json` and checked by `go test`). +7. **Docs**: `https://img.shields.io/badge/docs-docs.patch--it.dev-3f5bf0`. +8. **Discussions**: `https://img.shields.io/github/discussions/patch-it-dev/`. + +Static badges use the brand accent, `3f5bf0` (`accent`, light theme, in the brand tokens). + +## Words + +- Say "patch-it" (lowercase), and refer to Patchy as "Patchy" or "patch-it", never "he". +- Always list the layers; never describe patch-it as API-only. +- Use: "on its own", "writes the fix", "the code change, not just the version", "you review and merge". +- Don't name version-bump bots in headlines, the first lines or repo descriptions, and don't write "better than", "killer" or "magic". A factual comparison belongs on the docs' comparison page only. +- A public README never mentions private repos, internal services or pricing that isn't public. The service that runs plugins is "patch-it's hosted ingestion service". + +## Images + +Use only images that are already public, linked by URL, never copied in: Patchy and the wordmark from the organization profile, `https://raw.githubusercontent.com/patch-it-dev/.github/main/profile/assets/.svg` (`bot-asleep`, `bot-found-one`, `bot-merged`, `bot-excited`, `patchy-night-shift`, `wordmark-plain-on-light`, `wordmark-plain-on-dark`). Give every image alt text that says what it shows. No gradients, glows or starry skies. + +## Skeleton + +````markdown +Patchy, the patch-it bot + +# + +**** + +**Why:** when anything your code depends on changes (APIs, packages, SDKs, runtimes, CI, AI models), [patch-it](https://patch-it.dev) finds the code that breaks and opens the pull request that fixes it. In your CI, on your key. You get the fix, not the alert. + + + +```mermaid +flowchart LR + A["A dependency changes"] --> B[""] --> C["Pull request in your repo"] +``` + +## What patch-it does + +1. **It acts on its own.** ... +2. **It writes the fix.** ... +3. **Proof:** 8 pull requests opened by the early version have been merged by outside maintainers. +4. **What it covers:** + + | Layer | Status | + |---|---| + | APIs | live | + | AI models | live | + | Packages and SDKs | in testing | + | Runtimes | building | + | CI | planned | + +5. **Start:** [docs.patch-it.dev](https://docs.patch-it.dev). + +## + +## How it works + +## Contributing + +## License +```` + +Keep the layer statuses the same in every repo, and change them everywhere at once when one moves. + +## When a repo goes public + +The README is half of it. The same day, in the repo's settings: + +1. **Description**: one line in the same words (what the repo is, the layers, "You get the fix, not the alert"), under 350 characters, no version-bot names, never API-only. +2. **Website**: `https://docs.patch-it.dev` (or the page in the docs about this repo). +3. **Topics**: from `dependencies`, `breaking-changes`, `api-changes`, `api`, `sdk`, `ai-models`, `ci`, `pull-requests`, `automation`, plus the repo's language and what it is (`go`, `plugins`, `documentation`, …). +4. **Discussions** on, if people will ask questions there; keep the categories Q&A, Ideas, Show and tell and Announcements. +5. **Social preview** (Settings → General → Social preview; GitHub has no API for it): a 1280×640 PNG, dark background from the brand tokens, the plain wordmark, Patchy on a cream tile, IBM Plex, the repo's one line. No gradients or glows. +6. Check a shared link to the repo shows its own card. diff --git a/docs/README.md b/docs/README.md index 126dc8f..fbfc72d 100644 --- a/docs/README.md +++ b/docs/README.md @@ -4,6 +4,7 @@ |---|---| | [plugins.md](plugins.md) | Every supported plugin: id, provider, what it watches, source. Also published on [docs.patch-it.dev](https://docs.patch-it.dev/supported-apis/plugins/). | | [plugins.json](plugins.json) | The same list as JSON, generated by `make plugins-json` from the plugin registry and plugins.md. Don't edit by hand. | +| [README-template.md](README-template.md) | The shape every public patch-it repo's README follows: sections, badge set, words, images. | | [writing-a-plugin.md](writing-a-plugin.md) | How to add a provider: the `Plugin` interface, fetching through `env.Get` and `kit/`, saving the source, the golden test with `kittest`, the provider page and the plugin list. | | [../providers/](../providers/) | One page per provider: why that source, what the plugin reads and ignores. | diff --git a/docs/writing-a-plugin.md b/docs/writing-a-plugin.md index 241d1c5..e51b889 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)' .`), 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 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 diff --git a/internal/pluginlist/pluginlist.go b/internal/pluginlist/pluginlist.go index 92418b6..7ad543f 100644 --- a/internal/pluginlist/pluginlist.go +++ b/internal/pluginlist/pluginlist.go @@ -16,6 +16,7 @@ import ( "reflect" "regexp" "slices" + "strconv" "strings" "github.com/patch-it-dev/patch-it-plugins/plugin" @@ -208,6 +209,20 @@ func List(root string) ([]Plugin, error) { return out, nil } +// Readme is the README, relative to the repo root: its plugins badge is a +// static count that `make plugins-json` keeps right. +const Readme = "README.md" + +var badge = regexp.MustCompile(`(img\.shields\.io/badge/plugins-)(\d+)(-)`) + +// Badge is readme with its plugins badge set to n. ok is false when it has none. +func Badge(readme []byte, n int) (out []byte, ok bool) { + if !badge.Match(readme) { + return readme, false + } + return badge.ReplaceAll(readme, []byte("${1}"+strconv.Itoa(n)+"${3}")), true +} + // Marshal is docs/plugins.json for plugins, ending in a newline. func Marshal(plugins []Plugin) ([]byte, error) { var buf bytes.Buffer diff --git a/internal/pluginlist/pluginlist_test.go b/internal/pluginlist/pluginlist_test.go index 3c96ac0..895d93f 100644 --- a/internal/pluginlist/pluginlist_test.go +++ b/internal/pluginlist/pluginlist_test.go @@ -77,3 +77,33 @@ func TestListWantsARowPerPlugin(t *testing.T) { t.Errorf("err = %v, want stripe's missing row", err) } } + +// The README's plugins badge is a static number: it must be the count in +// docs/plugins.json (make plugins-json sets it), or the badge lies. +func TestReadmeBadgeCountsThePlugins(t *testing.T) { + plugins, err := List(root) + if err != nil { + t.Fatal(err) + } + readme, err := os.ReadFile(filepath.Join(root, Readme)) + if err != nil { + t.Fatal(err) + } + want, ok := Badge(readme, len(plugins)) + if !ok { + t.Fatal("README.md has no plugins badge (img.shields.io/badge/plugins--...)") + } + if !bytes.Equal(readme, want) { + t.Errorf("README.md's plugins badge doesn't say %d: run `make plugins-json`", len(plugins)) + } +} + +func TestBadge(t *testing.T) { + got, ok := Badge([]byte("[![Plugins](https://img.shields.io/badge/plugins-20-3f5bf0)](docs/plugins.md)"), 21) + if !ok || string(got) != "[![Plugins](https://img.shields.io/badge/plugins-21-3f5bf0)](docs/plugins.md)" { + t.Errorf("Badge = %s, %v", got, ok) + } + if _, ok := Badge([]byte("no badge"), 1); ok { + t.Error("found a badge in none") + } +}