Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions .github/workflows/CI_contract.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# contract/fixtures/ is a copy of patch-it's fixtures/ (the change-event contract
# patch-it owns). This fails when the two drift apart, so event/ and migrate/ test
# the same events the patch-it client does. Only top-level "_comment" fields may
# differ (scripts/check_contract.py).
#
# patch-it is cloned anonymously, with no token. While patch-it isn't public yet the
# clone can't see it, and the check passes with a notice.
name: CI_contract

on:
pull_request:
merge_group:
schedule:
- cron: "17 5 * * 1"
workflow_dispatch:

permissions:
contents: read

# A new push cancels the run it supersedes.
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true

jobs:
contract:
name: contract fixtures match patch-it
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- uses: actions/checkout@v6

- name: clone patch-it's fixtures (anonymous)
id: upstream
env:
GIT_TERMINAL_PROMPT: "0"
run: |
code=$(curl -s -o /dev/null -w '%{http_code}' https://api.github.com/repos/patch-it-dev/patch-it)
if [ "$code" = "404" ]; then
echo "::notice::patch-it-dev/patch-it isn't publicly readable yet; skipping the contract check."
echo "present=false" >> "$GITHUB_OUTPUT"
exit 0
fi
git -c credential.helper= clone --quiet --depth 1 --filter=blob:none --sparse \
https://github.com/patch-it-dev/patch-it upstream
git -C upstream sparse-checkout set fixtures
echo "present=true" >> "$GITHUB_OUTPUT"

- name: compare
if: steps.upstream.outputs.present == 'true'
run: python3 scripts/check_contract.py upstream/fixtures
2 changes: 0 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,6 @@ go test -race ./...
python3 scripts/leak_guard.py --all # the internal-names check over every tracked file
```

Until the plugin code lands there is no `go.mod`, and `CI_go` passes with a notice.

## Layout

```
Expand Down
12 changes: 10 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

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.

> **Under construction.** Plugins are being moved here from patch-it's hosted ingestion service. Until they land, this repo holds the rules, the CI and [the list of supported plugins](docs/plugins.md); the Go code follows.
> **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.

## How a plugin works

Expand All @@ -25,7 +25,7 @@ See **[docs/plugins.md](docs/plugins.md)**. The same list is on [docs.patch-it.d

## Run the tests

Once the code has landed (Go, see `go.mod`):
Go (the version in `go.mod`), no other setup:

```sh
go build ./...
Expand All @@ -36,6 +36,14 @@ go test -race ./...

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.

### Environment

| 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.

## 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).
Expand Down
33 changes: 33 additions & 0 deletions adapter/adapter.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// Package adapter defines the per-API source adapter interface and holds
// each API's adapter, starting with Stripe. An adapter only knows where its
// API's spec lives and how to fetch it — fetching mechanics live in
// fetch/, and diffing/normalizing/storing are shared, not adapter code.
package adapter

import "context"

// Spec is one fetched spec: its raw bytes, the API version it declares, and
// the pinned URL it came from. It is not yet parsed or stored — that is
// diff.Parse's and the baseline's (plugin.Spec) job, respectively.
type Spec struct {
Content []byte
Version string
SourceURL string
}

// Adapter is the shape every source adapter follows. Community and private
// adapters implement the same three methods.
type Adapter interface {
API() string // lowercase slug, e.g. "stripe"
LatestTag(ctx context.Context) (string, error) // newest release tag
Fetch(ctx context.Context, tag string) (Spec, error) // spec for that exact tag
}

// Reshaper is an adapter whose Fetch changes the spec's structure, not only its
// encoding, before the differ reads it (GitLab's inlined request bodies). A
// pointer into what the differ read may then name no node in the published
// file, so SourcePointer turns it back into one that does. It is given the
// fetched content and returns the mapping for that spec.
type Reshaper interface {
SourcePointer(content []byte) func(ptr string) string
}
84 changes: 84 additions & 0 deletions adapter/datadog.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
package adapter

import (
"context"
"encoding/json"
"fmt"

"github.com/patch-it-dev/patch-it-plugins/fetch"
"gopkg.in/yaml.v3"
)

// Variables, not constants, only so tests can point them at a local server.
var (
datadogReleasesURL = "https://api.github.com/repos/DataDog/datadog-api-client-python/releases/latest"
// datadogSpecURLTemplate is the v2 spec the Python, JS, Go, Java and Ruby
// clients are all generated from. Datadog publishes no standalone spec
// repo: the generator's output is bundled inside datadog-api-client-python
// itself, regenerated on every release.
datadogSpecURLTemplate = "https://raw.githubusercontent.com/DataDog/datadog-api-client-python/%s/.generator/schemas/v2/openapi.yaml"
)

// Datadog adapts datadog-api-client-python's bundled OpenAPI spec for the
// openapi plugin (diff.Parse expects JSON; the spec ships as YAML, converted
// in Fetch — see Fetch's comment).
type Datadog struct{}

var _ Adapter = Datadog{}

func (Datadog) API() string { return "datadog" }

// LatestTag asks GitHub for the client's newest release tag, e.g. "2.62.0".
// Datadog has no release process of its own to ask instead: the spec has no
// repo, so the client that's generated from it is the only thing that's
// tagged.
func (Datadog) LatestTag(ctx context.Context) (string, error) {
body, err := fetch.Get(ctx, datadogReleasesURL, githubHeaders())
if err != nil {
return "", fmt.Errorf("looking up datadog's latest release: %w", err)
}
var release struct {
TagName string `json:"tag_name"`
}
if err := json.Unmarshal(body, &release); err != nil {
return "", fmt.Errorf("parsing github release response: %w", err)
}
if release.TagName == "" {
return "", fmt.Errorf("github release response had no tag_name")
}
return release.TagName, nil
}

// Fetch downloads the spec pinned to tag and converts it from YAML to JSON,
// since diff.Parse only reads JSON. This changes no provenance guarantee:
// normalize's excerpt already re-serializes whatever node it quotes rather
// than slicing the original bytes, for every adapter including Stripe's.
//
// Version is the release tag, not info.version: unlike Stripe, Datadog's
// info.version is a fixed "1.0" that never moves between releases (checked
// 2026-11-13), so it can't tell two releases apart or sit in a fingerprint.
// The tag is also what a customer actually pins in requirements.txt
// (datadog-api-client==2.61.0), so the version gate can compare against it
// directly — no SDK-version-to-API-version table like Stripe's needed.
func (Datadog) Fetch(ctx context.Context, tag string) (Spec, error) {
url := fmt.Sprintf(datadogSpecURLTemplate, tag)
body, err := fetch.Get(ctx, url, nil) // raw.githubusercontent.com needs no auth
if err != nil {
return Spec{}, fmt.Errorf("fetching datadog spec %s: %w", tag, err)
}

var doc any
if err := yaml.Unmarshal(body, &doc); err != nil {
return Spec{}, fmt.Errorf("parsing datadog spec %s as yaml: %w", tag, err)
}
content, err := json.Marshal(doc)
if err != nil {
return Spec{}, fmt.Errorf("converting datadog spec %s to json: %w", tag, err)
}

return Spec{
Content: content,
Version: tag,
SourceURL: url,
}, nil
}
114 changes: 114 additions & 0 deletions adapter/datadog_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
package adapter

import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
)

// fakeDatadogGitHub serves a latest-release endpoint and specs by path, like
// fakeGitHub but under datadog's URL shape (no legacy fallback).
func fakeDatadogGitHub(t *testing.T, releaseJSON string, specs map[string]string) *httptest.Server {
t.Helper()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/releases/latest" {
w.Write([]byte(releaseJSON))
return
}
body, ok := specs[r.URL.Path]
if !ok {
http.NotFound(w, r)
return
}
w.Write([]byte(body))
}))
t.Cleanup(srv.Close)

oldRel, oldSpec := datadogReleasesURL, datadogSpecURLTemplate
datadogReleasesURL = srv.URL + "/releases/latest"
datadogSpecURLTemplate = srv.URL + "/%s/.generator/schemas/v2/openapi.yaml"
t.Cleanup(func() {
datadogReleasesURL, datadogSpecURLTemplate = oldRel, oldSpec
})
return srv
}

func TestDatadogLatestTagReadsTheReleaseTag(t *testing.T) {
fakeDatadogGitHub(t, `{"tag_name":"2.62.0"}`, nil)
tag, err := Datadog{}.LatestTag(context.Background())
if err != nil || tag != "2.62.0" {
t.Errorf("got %q, %v; want 2.62.0", tag, err)
}
}

func TestDatadogLatestTagRejectsAReleaseWithoutATag(t *testing.T) {
fakeDatadogGitHub(t, `{"name":"something"}`, nil)
if _, err := (Datadog{}).LatestTag(context.Background()); err == nil {
t.Error("release without tag_name: want an error")
}
}

// Fetch's whole job beyond downloading is converting YAML to JSON, since
// diff.Parse only reads JSON. The real spec's shape (a mapping with string
// keys throughout) is what this checks, not just that some conversion ran.
func TestDatadogFetchConvertsYAMLToJSON(t *testing.T) {
srv := fakeDatadogGitHub(t, "", map[string]string{
"/2.61.0/.generator/schemas/v2/openapi.yaml": "" +
"openapi: 3.0.0\n" +
"info:\n" +
" version: \"1.0\"\n" +
"components:\n" +
" schemas:\n" +
" TagIndexingRuleDynamicTags:\n" +
" type: object\n" +
" properties:\n" +
" exclude_not_used_in_assets:\n" +
" type: boolean\n",
})
spec, err := Datadog{}.Fetch(context.Background(), "2.61.0")
if err != nil {
t.Fatal(err)
}
if spec.SourceURL != srv.URL+"/2.61.0/.generator/schemas/v2/openapi.yaml" {
t.Errorf("source_url = %s, want the file actually fetched", spec.SourceURL)
}
want := `{"components":{"schemas":{"TagIndexingRuleDynamicTags":{"properties":{"exclude_not_used_in_assets":{"type":"boolean"}},"type":"object"}}},"info":{"version":"1.0"},"openapi":"3.0.0"}`
if string(spec.Content) != want {
t.Errorf("content = %s, want %s", spec.Content, want)
}
}

// Unlike Stripe, Version comes from the release tag: info.version inside
// datadog's spec is a fixed "1.0" that never moves between releases (checked
// 2026-11-13), so it can't be what tells two releases of events apart.
func TestDatadogFetchUsesTheTagAsVersionNotInfoVersion(t *testing.T) {
fakeDatadogGitHub(t, "", map[string]string{
"/2.61.0/.generator/schemas/v2/openapi.yaml": "info:\n version: \"1.0\"\n",
})
spec, err := Datadog{}.Fetch(context.Background(), "2.61.0")
if err != nil {
t.Fatal(err)
}
if spec.Version != "2.61.0" {
t.Errorf("version = %q, want the tag 2.61.0 (info.version is always 1.0)", spec.Version)
}
}

func TestDatadogFetchRejectsInvalidYAML(t *testing.T) {
fakeDatadogGitHub(t, "", map[string]string{
"/bad/.generator/schemas/v2/openapi.yaml": "not: [valid: yaml",
})
_, err := Datadog{}.Fetch(context.Background(), "bad")
if err == nil || !strings.Contains(err.Error(), "yaml") {
t.Errorf("got %v, want a yaml parse error", err)
}
}

func TestDatadogFetchFailsWhenSpecDoesNotExist(t *testing.T) {
fakeDatadogGitHub(t, "", nil)
if _, err := (Datadog{}).Fetch(context.Background(), "9.9.9"); err == nil {
t.Error("missing tag: want an error")
}
}
Loading
Loading