diff --git a/.ai-docs/bilingual-comparison.md b/.ai-docs/bilingual-comparison.md index 2b82b3d..f517af2 100644 --- a/.ai-docs/bilingual-comparison.md +++ b/.ai-docs/bilingual-comparison.md @@ -5,7 +5,7 @@ uses libopenapi's strict YAML/JSON parser once, checks the root version marker, and transfers the parsed AsyncAPI tree to libasyncapi. Mixed formats, ambiguous markers, unsupported AsyncAPI versions and partial AsyncAPI models fail clearly. -The stack uses libopenapi v0.42.0. Its default YAML alias expansion limit remains +The stack uses libopenapi v0.42.3. Its default YAML alias expansion limit remains enabled for both formats. Excessive alias expansion fails during loading; normal aliases retain bounded HTML previews. Doctor tests opt in to trusted excessive aliases through libasyncapi to exercise graph bounds independently of this limit. @@ -93,8 +93,8 @@ change. Use the locked public npm package when rebuilding these assets. ## Verification -Keep the canonical petstore totals unchanged: summary 42 changes / 18 breaking; -components summary 9/2 and raw JSON 10/3. Run cmd and full Go suites, race checks +Keep the canonical petstore totals unchanged: summary 45 changes / 19 breaking; +components 10/3 in both summary and raw JSON. Run cmd and full Go suites, race checks on dispatch/policy/history, and command smoke checks. Compare `BenchmarkOpenAPIReport` against the base branch with the same Go toolchain and hardware; use `-benchmem` and multiple samples. The model-window test verifies diff --git a/.ai-docs/compact-report.md b/.ai-docs/compact-report.md index 74d340c..9a4795c 100644 --- a/.ai-docs/compact-report.md +++ b/.ai-docs/compact-report.md @@ -16,7 +16,7 @@ The report contains the total and breaking change counts, up to eight semantic breaking highlights from Doctor, and a link to the public Doctor page. Each highlight is limited to 300 characters. If Doctor supplies no highlight for a whole-object removal, the report shows its changed path and property. Spec text cannot inject Markdown links, -HTML, or mentions. Counts use the same JSONPath + property deduplication as +HTML, or mentions. Counts use the same deduplication as `summary`. Existing detailed Markdown and raw JSON reports do not change. A successful comparison always writes the compact report, including when no @@ -28,7 +28,7 @@ The optional `--result-file` requires `--compact`. It writes this JSON only afte the comparison and Markdown write succeed: ```json -{"total":42,"breaking":18} +{"total":45,"breaking":19} ``` Use a fresh result path for each run and require command success before reading diff --git a/.ai-docs/component-report-identity.md b/.ai-docs/component-report-identity.md index 0574f77..f46c979 100644 --- a/.ai-docs/component-report-identity.md +++ b/.ai-docs/component-report-identity.md @@ -2,7 +2,9 @@ `summary`, `markdown-report`, and `html-report` use the shared `internal/changecounts.Deduplicate` helper for their counts and change lists. -The helper keeps one change per semantic JSONPath and property. +The helper keeps one change per semantic edit: the JSONPath, property, change +type, and values together. Two edits to one property, such as an enum addition +and removal, stay separate so a breaking change is never hidden. Doctor reports component additions and removals at `$.components`, with the category in `property` and the component name in `new` or `original`. Before @@ -15,6 +17,6 @@ list use this same list. The raw doctor tree remains intact for the document view and the separate explorer graph. Machine-readable `report` output is unchanged and retains the original engine paths. -The canonical petstore fixture still has 42 deduplicated changes, including 18 +The canonical petstore fixture has 45 deduplicated changes, including 19 breaking changes. `cmd/component_report_test.go` covers additions and removals across component categories through HTML, summary, and Markdown reports. diff --git a/AGENTS.md b/AGENTS.md index 09a6715..55eb1dd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -56,7 +56,7 @@ All `cmd/` implementation files use their canonical names (e.g., `cmd/summary.go ### Counts and semantics - `summary` is the semantic human report. -- `summary` headline, highlights, and visible summary counts are deduplicated by `JSONPath + property`. +- `summary` headline, highlights, and visible summary counts count each edit once, matching on JSONPath, property, change type, and values. - `markdown-report` top summary and object stats are also deduplicated. - `report` is the machine-readable JSON interface and should prefer stable semantic identity over renderer-local structure. @@ -139,20 +139,20 @@ After running `summary` on the petstore fixtures, the deduplicated counts must b | Document Element | Total Changes | Breaking Changes | |---|---|---| -| components | 9 | 2 | +| components | 10 | 3 | | info | 4 | 0 | -| paths | 28 | 16 | +| paths | 30 | 16 | | tags | 1 | 0 | **Summary totals (deduplicated):** -- 42 total changes, 18 breaking -- Additions: 12, Modifications: 20, Removals: 10 -- Breaking Modifications: 8, Breaking Removals: 10 +- 45 total changes, 19 breaking +- Additions: 14, Modifications: 20, Removals: 11 +- Breaking Modifications: 8, Breaking Removals: 11 **Report JSON totals (raw, not deduplicated):** - Components: 10 total / 3 breaking -The `report` JSON numbers are intentionally higher than `summary` because summary deduplicates by `JSONPath + property`. This difference is correct behavior, not a bug. If these counts drift after a change, the change broke semantics. +`summary` only removes repeats of one edit, matching on JSONPath, property, change type, and values. `report` JSON keeps every occurrence, so it can be higher when a shared reference repeats an edit; for petstore the two match. Never deduplicate on JSONPath and property alone: an enum addition and removal share both, and that key hid breaking changes, including the removal of `Pet.name`. If these counts drift after a change, the change broke semantics. ## Validation Workflow diff --git a/Dockerfile b/Dockerfile index d0c48e0..af143d6 100644 --- a/Dockerfile +++ b/Dockerfile @@ -6,7 +6,7 @@ COPY html-report/ui/src ./src RUN npm ci RUN npm run build -FROM --platform=$BUILDPLATFORM golang:1.26.9-bookworm AS builder +FROM --platform=$BUILDPLATFORM golang:1.26.10-bookworm AS builder ARG TARGETPLATFORM ARG BUILDPLATFORM diff --git a/README.md b/README.md index 37c47b2..624719b 100644 --- a/README.md +++ b/README.md @@ -20,9 +20,15 @@ It can render the same semantic change model as: - a markdown report - a self-contained offline HTML report -The same commands accept both formats, including git history and revision-scoped -references. Each comparison must use the same format on both sides. AsyncAPI 2.x -and mixed OpenAPI/AsyncAPI comparisons are rejected. +It works well for local exploration, CI/CD checks, release notes, and API review workflows. + +--- + +## AsyncAPI has landed + +Event-driven APIs break too. They just do it quietly, in a consumer nobody remembers subscribing to that topic. + +`openapi-changes` now speaks **AsyncAPI 3.x** natively. Same commands, same reports, same time machine. ```sh openapi-changes summary previous-asyncapi.yaml asyncapi.yaml @@ -30,8 +36,10 @@ openapi-changes report HEAD~1:asyncapi.yaml HEAD:asyncapi.yaml openapi-changes html-report --report-file changes.html previous-asyncapi.yaml asyncapi.yaml ``` -Existing breaking-rule files retain their OpenAPI meaning. To configure both -engines, use named sections: +The format is detected from the document, including across git history and revision-scoped references. Both sides of +a comparison must use the same format, and AsyncAPI 2.x is not supported. + +Existing rule files keep their OpenAPI meaning. To configure both engines, use named sections: ```yaml openapiRules: @@ -41,21 +49,14 @@ openapiRules: asyncapiRules: channel: address: - modified: true - multiFormatSchema: - modified: true + modified: false schemaRules: schema: - description: + type: modified: false ``` -`schemaRules` applies to JSON Schemas in AsyncAPI. Foreign schema languages are -compared as opaque content; changing their format or content is breaking by -default. JSON and HTML report items include format and version metadata in -`specification`. Human counts remain deduplicated; JSON retains raw changes. - -It works well for local exploration, CI/CD checks, release notes, and API review workflows. +**[Read the AsyncAPI docs >](https://pb33f.io/openapi-changes/asyncapi/)** ## How is it the 'most powerful and complete?'? @@ -194,6 +195,7 @@ multi-file specs with `$ref` references resolved from the same revision. Full docs: https://pb33f.io/openapi-changes/ - [Installing openapi-changes](https://pb33f.io/openapi-changes/installing/) +- [Comparing AsyncAPI specifications](https://pb33f.io/openapi-changes/asyncapi/) - [Configuring breaking changes](https://pb33f.io/openapi-changes/configuring/) - [Command arguments](https://pb33f.io/openapi-changes/command-arguments/) - Commands: @@ -210,7 +212,7 @@ Full docs: https://pb33f.io/openapi-changes/ ## Build from source -`openapi-changes` currently requires Go `1.26.9+`. The npm installer requires Node.js `20+`. +`openapi-changes` currently requires Go `1.26.10+`. The npm installer requires Node.js `20+`. The report UI uses Node.js `24.15+` in the Node 24 release line. Run `npm ci`, `npm run typecheck`, `npm test`, and `npm run build` in `html-report/ui` after diff --git a/cmd/compact_report.go b/cmd/compact_report.go index 24c521e..f3faa83 100644 --- a/cmd/compact_report.go +++ b/cmd/compact_report.go @@ -87,7 +87,7 @@ func renderCompactMarkdown(outcome compactOutcome, highlights []string) []byte { default: fmt.Fprintf(&sb, "**Total changes: %d. Breaking changes: %d.**\n\n", outcome.Total, outcome.Breaking) } - sb.WriteString("Counts are deduplicated by JSONPath + property.\n\n") + sb.WriteString("Repeats of the same change are counted once.\n\n") if len(highlights) > 0 { sb.WriteString("### Breaking highlights\n\n") for _, item := range highlights { diff --git a/cmd/compact_report_test.go b/cmd/compact_report_test.go index d91060c..fb59028 100644 --- a/cmd/compact_report_test.go +++ b/cmd/compact_report_test.go @@ -20,8 +20,8 @@ func TestCompactReportPetstore(t *testing.T) { require.NoError(t, err) report, outcome, err := generateCompactMarkdown(commits, nil) require.NoError(t, err) - assert.Equal(t, compactOutcome{Total: 42, Breaking: 18}, outcome) - assert.Contains(t, string(report), "**Total changes: 42. Breaking changes: 18.**") + assert.Equal(t, compactOutcome{Total: 45, Breaking: 19}, outcome) + assert.Contains(t, string(report), "**Total changes: 45. Breaking changes: 19.**") assert.Contains(t, string(report), "### Breaking highlights") assert.Contains(t, string(report), "https://pb33f.io/doctor/") assert.NotContains(t, string(report), "Commit") @@ -100,7 +100,7 @@ func TestCompactReportCommandBreakingHasCompletedOutcome(t *testing.T) { require.NoError(t, command.Execute()) data, err := os.ReadFile(result) require.NoError(t, err) - assert.JSONEq(t, `{"total":42,"breaking":18}`, string(data)) + assert.JSONEq(t, `{"total":45,"breaking":19}`, string(data)) } func TestCompactReportRejectsAliasedOutputs(t *testing.T) { diff --git a/cmd/enum_dedup_test.go b/cmd/enum_dedup_test.go new file mode 100644 index 0000000..720e7cf --- /dev/null +++ b/cmd/enum_dedup_test.go @@ -0,0 +1,64 @@ +// Copyright 2023-2026 Princess Beef Heavy Industries, LLC / Dave Shanley +// SPDX-License-Identifier: Apache-2.0 + +package cmd + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "github.com/pb33f/testify/assert" + "github.com/pb33f/testify/require" +) + +func TestEnumEditKeepsItsBreakingRemoval(t *testing.T) { + for name, spec := range map[string]string{ + "asyncapi": `asyncapi: 3.0.0 +info: + title: enum + version: 1.0.0 +channels: + orders: + address: orders + messages: + created: + payload: + type: string + enum: [a, b] +`, + "openapi": `openapi: 3.1.0 +info: + title: enum + version: 1.0.0 +paths: {} +components: + schemas: + Status: + type: string + enum: [a, b] +`, + } { + t.Run(name, func(t *testing.T) { + assertEnumEdit(t, spec) + }) + } +} + +func assertEnumEdit(t *testing.T, spec string) { + t.Helper() + dir := t.TempDir() + left := filepath.Join(dir, "left.yaml") + right := filepath.Join(dir, "right.yaml") + require.NoError(t, os.WriteFile(left, []byte(spec), 0o644)) + require.NoError(t, os.WriteFile(right, []byte(strings.Replace(spec, "[a, b]", "[a, c]", 1)), 0o644)) + + commits, err := loadLeftRightCommits(left, right, summaryOpts{noColor: true}) + require.NoError(t, err) + _, outcome, err := generateCompactMarkdown(commits, nil) + require.NoError(t, err) + + assert.Equal(t, 2, outcome.Total) + assert.Equal(t, 1, outcome.Breaking) +} diff --git a/cmd/markdown_report.go b/cmd/markdown_report.go index 1093482..3357a8c 100644 --- a/cmd/markdown_report.go +++ b/cmd/markdown_report.go @@ -88,7 +88,7 @@ func generateMarkdownReport(commits []*model.Commit, breakingConfig *whatChanged successCount := 0 comparedCount := 0 var renderErrors []error - headerWritten := false + apiLabel := "" includeCommitMetadata := true for i, commit := range commits { @@ -105,13 +105,7 @@ func generateMarkdownReport(commits []*model.Commit, breakingConfig *whatChanged continue } - // Write header on first success - if !headerWritten { - sb.WriteString("# " + commit.APILabel() + " Changes Report\n\n") - sb.WriteString(fmt.Sprintf("*Generated: %s*\n\n", time.Now().Format(time.RFC3339))) - headerWritten = true - } - + apiLabel = mergeAPILabel(apiLabel, commit.APILabel()) successCount++ if successCount == 1 { includeCommitMetadata = !isSyntheticLeftRightCommit(commit) @@ -156,7 +150,17 @@ func generateMarkdownReport(commits []*model.Commit, breakingConfig *whatChanged if successCount == 0 { return nil, nil } - return []byte(sb.String()), nil + // The title waits for every commit because history can change format between revisions. + header := fmt.Sprintf("# %s Changes Report\n\n*Generated: %s*\n\n", apiLabel, time.Now().Format(time.RFC3339)) + return []byte(header + sb.String()), nil +} + +// mergeAPILabel keeps a shared format label and falls back to a neutral one when formats mix. +func mergeAPILabel(current, next string) string { + if current == "" || current == next { + return next + } + return "API" } func GetMarkdownReportCommand() *cobra.Command { diff --git a/cmd/markdown_report_label_test.go b/cmd/markdown_report_label_test.go new file mode 100644 index 0000000..4210003 --- /dev/null +++ b/cmd/markdown_report_label_test.go @@ -0,0 +1,30 @@ +// Copyright 2023-2026 Princess Beef Heavy Industries, LLC / Dave Shanley +// SPDX-License-Identifier: Apache-2.0 + +package cmd + +import ( + "strings" + "testing" + + "github.com/pb33f/testify/assert" + "github.com/pb33f/testify/require" +) + +func TestMergeAPILabel(t *testing.T) { + assert.Equal(t, "OpenAPI", mergeAPILabel("", "OpenAPI")) + assert.Equal(t, "AsyncAPI", mergeAPILabel("AsyncAPI", "AsyncAPI")) + assert.Equal(t, "API", mergeAPILabel("OpenAPI", "AsyncAPI")) + assert.Equal(t, "API", mergeAPILabel("API", "OpenAPI")) +} + +func TestMarkdownReportTitleForMixedFormats(t *testing.T) { + openapi, err := loadLeftRightCommits("../sample-specs/petstorev3-original.json", "../sample-specs/petstorev3.json", summaryOpts{noColor: true}) + require.NoError(t, err) + asyncapi, err := loadLeftRightCommits("../sample-specs/asyncapi-original.yaml", "../sample-specs/asyncapi.yaml", summaryOpts{noColor: true}) + require.NoError(t, err) + + report, err := generateMarkdownReport(append(openapi, asyncapi...), nil, false) + require.NoError(t, err) + assert.True(t, strings.HasPrefix(string(report), "# API Changes Report\n"), "got: %.40s", report) +} diff --git a/cmd/markdown_report_test.go b/cmd/markdown_report_test.go index 5fe5c24..1a98495 100644 --- a/cmd/markdown_report_test.go +++ b/cmd/markdown_report_test.go @@ -110,7 +110,7 @@ func TestMarkdownReport_SingleCommitLeftRight(t *testing.T) { content := string(report) assert.True(t, strings.HasPrefix(content, "# OpenAPI Changes Report")) assert.NotContains(t, content, "## Commit 1:") - assert.Contains(t, content, "**42** changes detected, **18** are **(💔 breaking)**.") + assert.Contains(t, content, "**45** changes detected, **19** are **(💔 breaking)**.") } func TestMarkdownReport_UsesDeduplicatedCounts(t *testing.T) { @@ -127,10 +127,10 @@ func TestMarkdownReport_UsesDeduplicatedCounts(t *testing.T) { require.NotNil(t, report) content := string(report) - assert.Contains(t, content, "**42** changes detected, **18** are **(💔 breaking)**.") - assert.Contains(t, content, "- Additions: **12**") + assert.Contains(t, content, "**45** changes detected, **19** are **(💔 breaking)**.") + assert.Contains(t, content, "- Additions: **14**") assert.Contains(t, content, "- Modifications: **20**") - assert.Contains(t, content, "- Removals: **10**") + assert.Contains(t, content, "- Removals: **11**") } func TestMarkdownReport_UsesDeduplicatedObjectStats(t *testing.T) { @@ -150,8 +150,8 @@ func TestMarkdownReport_UsesDeduplicatedObjectStats(t *testing.T) { assert.Contains(t, content, "| Operation | 5 | 2 |") assert.Contains(t, content, "| PathItem | 9 | 5 |") assert.Contains(t, content, "| Responses | 3 | 2 |") - assert.Contains(t, content, "| Schema | 10 | 4 |") - assert.Contains(t, content, "| Tag | 3 | 1 |") + assert.Contains(t, content, "| Schema | 11 | 5 |") + assert.Contains(t, content, "| Tag | 5 | 1 |") assert.NotContains(t, content, "| Operation | 9 |") assert.NotContains(t, content, "| PathItem | 9 | 6 |") } @@ -174,7 +174,7 @@ func TestMarkdownReport_LeftRightOmitsSyntheticCommitMetadata(t *testing.T) { assert.NotContains(t, content, "- **Hash**:") assert.NotContains(t, content, "- **Author**:") assert.NotContains(t, content, "- **Date**:") - assert.Contains(t, content, "**42** changes detected, **18** are **(💔 breaking)**.") + assert.Contains(t, content, "**45** changes detected, **19** are **(💔 breaking)**.") } func TestMarkdownReport_PartialFailureReturnsPartialResults(t *testing.T) { diff --git a/cmd/petstore_regression_test.go b/cmd/petstore_regression_test.go index e7c2df9..c00c4d5 100644 --- a/cmd/petstore_regression_test.go +++ b/cmd/petstore_regression_test.go @@ -53,11 +53,11 @@ func TestPetstoreRegressionCounts(t *testing.T) { counts := changecounts.FromChanges(deduped) - assert.Equal(t, 42, counts.Total, "total deduplicated changes") - assert.Equal(t, 18, counts.Breaking, "breaking changes") - assert.Equal(t, 12, counts.Additions, "additions") + assert.Equal(t, 45, counts.Total, "total deduplicated changes") + assert.Equal(t, 19, counts.Breaking, "breaking changes") + assert.Equal(t, 14, counts.Additions, "additions") assert.Equal(t, 20, counts.Modifications, "modifications") - assert.Equal(t, 10, counts.Removals, "removals") + assert.Equal(t, 11, counts.Removals, "removals") assert.Equal(t, 8, counts.BreakingModifications, "breaking modifications") - assert.Equal(t, 10, counts.BreakingRemovals, "breaking removals") + assert.Equal(t, 11, counts.BreakingRemovals, "breaking removals") } diff --git a/cmd/summary.go b/cmd/summary.go index 92d45ac..5421842 100644 --- a/cmd/summary.go +++ b/cmd/summary.go @@ -114,7 +114,7 @@ func summarizeTopLevelElement(path string) string { } func renderDedupedCountsNote(markdown bool, styles summaryStyles) string { - note := "Counts are deduplicated by JSONPath + property." + note := "Repeats of the same change are counted once." if markdown { return note + "\n\n" } diff --git a/cmd/summary_test.go b/cmd/summary_test.go index 49e7ee9..0875ef5 100644 --- a/cmd/summary_test.go +++ b/cmd/summary_test.go @@ -379,7 +379,7 @@ func TestRenderSummary_UsesDoctorEngineWhenLegacyChangesMissing(t *testing.T) { assert.True(t, hasChanges) assert.NotEmpty(t, output) assert.Contains(t, output, "Breaking Highlights") - assert.Contains(t, output, "Counts are deduplicated by JSONPath + property.") + assert.Contains(t, output, "Repeats of the same change are counted once.") assert.Contains(t, output, "Document Element") assert.Contains(t, output, "paths") assert.Contains(t, output, "components") @@ -707,15 +707,15 @@ func TestRenderSummary_UsesDeduplicatedHeadlineCounts(t *testing.T) { ) require.NoError(t, err) - assert.Contains(t, output, "❌ 18 Breaking changes out of 42") - assert.Contains(t, output, "Counts are deduplicated by JSONPath + property.") - assert.Contains(t, output, "│ components │ 9 │ 2 │") - assert.Contains(t, output, "│ paths │ 28 │ 16 │") - assert.Contains(t, output, " Additions: 12") + assert.Contains(t, output, "❌ 19 Breaking changes out of 45") + assert.Contains(t, output, "Repeats of the same change are counted once.") + assert.Contains(t, output, "│ components │ 10 │ 3 │") + assert.Contains(t, output, "│ paths │ 30 │ 16 │") + assert.Contains(t, output, " Additions: 14") assert.Contains(t, output, " Modifications: 20") - assert.Contains(t, output, " Removals: 10") + assert.Contains(t, output, " Removals: 11") assert.Contains(t, output, " Breaking Modifications: 8") - assert.Contains(t, output, " Breaking Removals: 10") + assert.Contains(t, output, " Breaking Removals: 11") } func TestRenderSummary_WithLinesIncludesSourceLocations(t *testing.T) { diff --git a/git/history_root_test.go b/git/history_root_test.go new file mode 100644 index 0000000..be15e10 --- /dev/null +++ b/git/history_root_test.go @@ -0,0 +1,31 @@ +// Copyright 2023-2026 Princess Beef Heavy Industries, LLC / Dave Shanley +// SPDX-License-Identifier: Apache-2.0 + +package git + +import ( + "os" + "path/filepath" + "testing" + + "github.com/pb33f/testify/assert" + "github.com/pb33f/testify/require" +) + +// macOS temp directories are symlinks, so one is forced here for other platforms. +func TestHistoryRootPathsRewriteRelativeToRepo(t *testing.T) { + dir, err := filepath.EvalSymlinks(t.TempDir()) + require.NoError(t, err) + target := filepath.Join(dir, "target") + link := filepath.Join(dir, "link") + require.NoError(t, os.Mkdir(target, 0o755)) + if err := os.Symlink(target, link); err != nil { + t.Skipf("symlinks are unavailable: %v", err) + } + t.Setenv("TMPDIR", link) + + root := historyRoot() + rewrite := NewRepoRelativeDocumentPathRewriter(root, root) + + assert.Equal(t, "specs/asyncapi.yaml", rewrite(filepath.Join(root, "specs", "asyncapi.yaml"))) +} diff --git a/git/history_sources.go b/git/history_sources.go index 2b5840e..d10ec34 100644 --- a/git/history_sources.go +++ b/git/history_sources.go @@ -7,6 +7,16 @@ import ( "path/filepath" ) +// historyRoot returns the canonical virtual root, because the path rewriter compares +// canonical paths and macOS temp directories are symlinks. +func historyRoot() string { + root := filepath.Join(os.TempDir(), "openapi-changes-history") + if canonical, err := CanonicalizePath(root); err == nil { + return canonical + } + return root +} + // buildHistorySources defers model construction to the consumer's two-document // window. Source bytes and revision-scoped configurations remain available for // interactive navigation without retaining every document graph. @@ -40,7 +50,7 @@ func buildHistorySources(commits []*model.Commit, opts HistoryOptions) (*History config := cloneDocumentConfiguration(base) config.SpecFilePath = commits[0].FilePath if opts.ReadRevision != nil { - root := filepath.Join(os.TempDir(), "openapi-changes-history") + root := historyRoot() config.BasePath = root config.SpecFilePath = filepath.Join(root, commits[0].FilePath) config.AllowFileReferences = true @@ -87,7 +97,7 @@ func buildHistorySources(commits []*model.Commit, opts HistoryOptions) (*History commit.DocumentRewriters = []model.DocumentPathRewriter{context.DocumentRewriter} } if context == nil && opts.ReadRevision != nil { - root := filepath.Join(os.TempDir(), "openapi-changes-history") + root := historyRoot() commit.DocumentRewriters = []model.DocumentPathRewriter{NewRepoRelativeDocumentPathRewriter(root, root)} } previous = source diff --git a/go.mod b/go.mod index 4aa5eed..8a68ef2 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/pb33f/openapi-changes -go 1.26.9 +go 1.26.10 require ( charm.land/bubbles/v2 v2.2.1 @@ -14,10 +14,10 @@ require ( github.com/charmbracelet/x/term v0.2.2 github.com/google/uuid v1.6.0 github.com/mattn/go-runewidth v0.0.31 - github.com/pb33f/doctor v0.0.86 + github.com/pb33f/doctor v0.0.87 github.com/pb33f/go-yaml v0.1.1 - github.com/pb33f/libasyncapi v0.0.6 - github.com/pb33f/libopenapi v0.42.0 + github.com/pb33f/libasyncapi v0.0.7 + github.com/pb33f/libopenapi v0.42.3 github.com/pb33f/testify v0.1.1 github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 github.com/spf13/cobra v1.10.2 diff --git a/go.sum b/go.sum index f9fb4b4..6106a8b 100644 --- a/go.sum +++ b/go.sum @@ -99,18 +99,18 @@ github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELU github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo= github.com/ncruces/go-strftime v1.1.0 h1:vtPmPWMkb539RGV9WpWT9EwJGvrOCKvMNI4obWL47Hk= github.com/ncruces/go-strftime v1.1.0/go.mod h1:yVaq7iwCN09vHRrKBrrflXT0M9tTMG2KmZ9Fj7xeG/g= -github.com/pb33f/doctor v0.0.86 h1:MDXxWkalkQr8quhXTJVCedmPWYFjPOWwXU7T4Qe3Wtw= -github.com/pb33f/doctor v0.0.86/go.mod h1:9TCfRtf+g+WJArC1jga31KP2fzCggg0W0RrVWryh9Vc= +github.com/pb33f/doctor v0.0.87 h1:4PQgjs+sjYDL8VxnUJhZLHDWl0+zYcCgfsVD/m7231c= +github.com/pb33f/doctor v0.0.87/go.mod h1:9TCfRtf+g+WJArC1jga31KP2fzCggg0W0RrVWryh9Vc= github.com/pb33f/go-yaml v0.1.1 h1:yWGmhVdwzionRnSc/hEJwcfq6PaZL2QdYzyReXBbX7Q= github.com/pb33f/go-yaml v0.1.1/go.mod h1:QvWdkHP5VjFYAeHMQUkaPQqREaQnBNOXmWzAjNrnSdo= github.com/pb33f/jsonpath v0.8.4 h1:Yx7fxsKl8scgERL22WhKDs2c6gYNNUonPSWEG8Y194s= github.com/pb33f/jsonpath v0.8.4/go.mod h1:eO6mgdhw5RgzCxm/bXTi75VUs0/cCYJzdGjMCCUEI6M= github.com/pb33f/jsonschema/v6 v6.0.3 h1:TMIkE1xCmnF8Cy+anIBs+r4ASfGtwzfFxYsrrIn0wSU= github.com/pb33f/jsonschema/v6 v6.0.3/go.mod h1:cYPShw+w1Jrs0YgpE2rk1FLdIAsKfWcotv/54G6ddFo= -github.com/pb33f/libasyncapi v0.0.6 h1:csDUT7D9RyStvgPnenvbIi5BOBT/uTKRRicPttMdffY= -github.com/pb33f/libasyncapi v0.0.6/go.mod h1:OcM42Lo3J4F9Tz55RZIOxcAubOv1BGRg9gy8Sp36skk= -github.com/pb33f/libopenapi v0.42.0 h1:BVxy2OIeEJRIVVL2//AU2TKs1JjZv/wKmD/8uFI8lzI= -github.com/pb33f/libopenapi v0.42.0/go.mod h1:IlfeXtmcY38KEnGJ4OMWFA8I62BCNamuQa8omLnk6R0= +github.com/pb33f/libasyncapi v0.0.7 h1:0CTUZwjQm4Fya6Znb7q/1kBWvp/92v5CaB9T55zJMiA= +github.com/pb33f/libasyncapi v0.0.7/go.mod h1:OcM42Lo3J4F9Tz55RZIOxcAubOv1BGRg9gy8Sp36skk= +github.com/pb33f/libopenapi v0.42.3 h1:0VXnFgz04LtWjIsmCqGYA5E2Mx0DOZcOTjy5KHYw88k= +github.com/pb33f/libopenapi v0.42.3/go.mod h1:IlfeXtmcY38KEnGJ4OMWFA8I62BCNamuQa8omLnk6R0= github.com/pb33f/ordered-map/v2 v2.3.2 h1:wDyaZ2Pv9QLh64X4utCeD5Zoi9nIv2aW3lwv172O5PQ= github.com/pb33f/ordered-map/v2 v2.3.2/go.mod h1:1OhFrXu3OYw3kM+FXF+Ug3ugmmZ9LE8z0JfQMLvtV0w= github.com/pb33f/testify v0.1.1 h1:mnHe7uxKt8dyNYEGUspow72VjD264DB5rOJq4bz5tJw= diff --git a/internal/changecounts/deduplicate.go b/internal/changecounts/deduplicate.go index f6b478f..1f0bc9e 100644 --- a/internal/changecounts/deduplicate.go +++ b/internal/changecounts/deduplicate.go @@ -9,11 +9,28 @@ import ( wcModel "github.com/pb33f/libopenapi/what-changed/model" ) -// Deduplicate keeps one change per semantic JSONPath and property. Component -// additions and removals use the component name, since doctor reports those -// changes at the shared $.components path. The input changes are not modified. +// identity separates distinct edits to one property, such as an enum addition and +// removal, so a repeat is only ever a second report of the same edit. +type identity struct { + path, property, original, modified string + originalEncoded, newEncoded, reference string + changeType int + breaking bool + // Changes without a semantic path are identified by their source position, or + // by the change itself when that is unknown too. + position sourcePosition + unlocated *wcModel.Change +} + +type sourcePosition struct { + document string + originalLine, originalColumn, newLine, newColumn int +} + +// Deduplicate keeps one change per semantic edit. Component additions and removals +// use the component name, since doctor reports those changes at the shared +// $.components path. The input changes are not modified. func Deduplicate(changes []*wcModel.Change) []*wcModel.Change { - type identity struct{ path, property string } seen := make(map[identity]struct{}, len(changes)) result := make([]*wcModel.Change, 0, len(changes)) for _, change := range changes { @@ -21,7 +38,18 @@ func Deduplicate(changes []*wcModel.Change) []*wcModel.Change { continue } path := componentPath(change) - key := identity{path, change.Property} + key := identity{ + path: path, property: change.Property, original: change.Original, modified: change.New, + originalEncoded: change.OriginalEncoded, newEncoded: change.NewEncoded, + reference: change.Reference, changeType: change.ChangeType, breaking: change.Breaking, + } + if path == "" { + if position, ok := changePosition(change.Context); ok { + key.position = position + } else { + key.unlocated = change + } + } if _, ok := seen[key]; ok { continue } @@ -36,6 +64,25 @@ func Deduplicate(changes []*wcModel.Change) []*wcModel.Change { return result } +func changePosition(context *wcModel.ChangeContext) (sourcePosition, bool) { + if context == nil || (context.OriginalLine == nil && context.NewLine == nil) { + return sourcePosition{}, false + } + value := func(number *int) int { + if number == nil { + return -1 + } + return *number + } + return sourcePosition{ + document: context.DocumentLocation, + originalLine: value(context.OriginalLine), + originalColumn: value(context.OriginalColumn), + newLine: value(context.NewLine), + newColumn: value(context.NewColumn), + }, true +} + func componentPath(change *wcModel.Change) string { if change.Path != "$.components" { return change.Path diff --git a/internal/changecounts/deduplicate_test.go b/internal/changecounts/deduplicate_test.go index de5d5bc..e96b7a6 100644 --- a/internal/changecounts/deduplicate_test.go +++ b/internal/changecounts/deduplicate_test.go @@ -44,6 +44,18 @@ func TestDeduplicate_PreservesPropertyIdentity(t *testing.T) { assert.Same(t, changes[3], result[2]) } +func TestDeduplicate_KeepsDistinctEditsToOneProperty(t *testing.T) { + addition := &wcModel.Change{Path: "$.components.schemas['S'].enum", Property: "enum", ChangeType: wcModel.PropertyAdded, New: "c"} + removal := &wcModel.Change{Path: "$.components.schemas['S'].enum", Property: "enum", ChangeType: wcModel.PropertyRemoved, Original: "b", Breaking: true} + repeat := *removal + + result := Deduplicate([]*wcModel.Change{addition, removal, &repeat}) + + require.Len(t, result, 2) + assert.Same(t, addition, result[0]) + assert.Same(t, removal, result[1]) +} + func TestDeduplicate_ComponentPathBoundaries(t *testing.T) { for _, tt := range []struct { name string diff --git a/internal/changecounts/deduplicate_unlocated_test.go b/internal/changecounts/deduplicate_unlocated_test.go new file mode 100644 index 0000000..0762329 --- /dev/null +++ b/internal/changecounts/deduplicate_unlocated_test.go @@ -0,0 +1,29 @@ +// Copyright 2023-2026 Princess Beef Heavy Industries, LLC / Dave Shanley +// SPDX-License-Identifier: Apache-2.0 + +package changecounts + +import ( + "testing" + + wcModel "github.com/pb33f/libopenapi/what-changed/model" + "github.com/pb33f/testify/assert" + "github.com/pb33f/testify/require" +) + +func TestDeduplicate_UnlocatedChangesUseSourcePosition(t *testing.T) { + line, column, otherLine := 21, 43, 30 + first := &wcModel.Change{Property: "enum", ChangeType: wcModel.PropertyAdded, New: "c", + Context: &wcModel.ChangeContext{NewLine: &line, NewColumn: &column}} + repeat := *first + repeat.Context = &wcModel.ChangeContext{NewLine: &line, NewColumn: &column} + elsewhere := *first + elsewhere.Context = &wcModel.ChangeContext{NewLine: &otherLine, NewColumn: &column} + noContext := &wcModel.Change{Property: "enum", ChangeType: wcModel.PropertyAdded, New: "c"} + noContextAgain := *noContext + + result := Deduplicate([]*wcModel.Change{first, &repeat, &elsewhere, noContext, &noContextAgain}) + + require.Len(t, result, 4, "a repeat at one position collapses; positions and unknowns stay apart") + assert.Same(t, first, result[0]) +}