From 25ded9f68a4fbb111f0e18b40f066f6019adaae7 Mon Sep 17 00:00:00 2001 From: quobix Date: Wed, 25 Nov 2026 11:04:23 -0500 Subject: [PATCH 01/24] Plan native JSON Schema comparisons and shared-reference collections --- ...1-25-json-schema-comparisons-plan-crush.md | 52 +++++++++++ plans/2026-11-25-json-schema-comparisons.md | 86 +++++++++++++++++++ 2 files changed, 138 insertions(+) create mode 100644 plans/2026-11-25-json-schema-comparisons-plan-crush.md create mode 100644 plans/2026-11-25-json-schema-comparisons.md diff --git a/plans/2026-11-25-json-schema-comparisons-plan-crush.md b/plans/2026-11-25-json-schema-comparisons-plan-crush.md new file mode 100644 index 0000000..2a0e517 --- /dev/null +++ b/plans/2026-11-25-json-schema-comparisons-plan-crush.md @@ -0,0 +1,52 @@ + + +# Plan-crush review of native JSON Schema comparisons + +This review challenged the first draft's single-schema path, collection matching, and release order against the dependencies selected by CLI `f9f73e7`. The [implementation plan](2026-11-25-json-schema-comparisons.md) incorporates the findings below. + +## [P1] Standalone breaking rules can change existing API reports + +The single-schema draft extended `CompareSchemas` with new compatibility defaults. AsyncAPI calls that function for embedded schemas. A direct probe also showed that the existing comparator marks both boolean transitions as breaking, misses a rename of `$anchor`, and misses an edit or addition confined to unreferenced `$defs`. The low model already reads and hashes both keywords. A global policy change would affect existing users and still leave the missing traversal. [Shared entry point](https://github.com/pb33f/libopenapi/blob/db27aae96380883740653c3658a79b4110ea35ff/what-changed/model/schema.go#L415) and [AsyncAPI caller](https://github.com/pb33f/libasyncapi/blob/v0.0.7/what-changed/model/schema.go#L15) + +Add a standalone entry to the same comparator, expose the missing edits there, and carry explicit overrides into it. The existing API entry keeps its contract. Prove directional defaults with both boolean transitions, an isolated string bound, a negation case, and an annotation. Prove address changes with an unused definition and an anchor. Run embedded API cases with and without overrides. Confidence is high for the observed gaps. Composition behavior needs its own fixtures before a directional rule applies. + +## [P1] Two independent definitions can become one edit + +The collection draft retained the resource name for display but did not require it in count or hash identity. I constructed two native changes with equal paths, coordinates, old and new values, and different `context.document` values. Doctor returned **one** after deduplication. The CLI produced **identical hashes**. Its human counter also uses file position only when the path is empty. A display label cannot repair records that have already collapsed. [Doctor edit key](https://github.com/pb33f/doctor/blob/v0.0.88/changerator/renderer/asyncapi_report.go#L130), [CLI edit key](../internal/changecounts/deduplicate.go), and [hash input](../model/report.go#L52) + +Carry the owning `schemaResource` with each native edit. Use it in the schema count key, graph node ID, hash, and sort, with the path relative to that resource. Verify two independent edits yield two counts and hashes, while two uses of one changed definition yield one human edit and two reference edges. This preserves the raw machine report and avoids a second deduplication pass. Confidence is high from the reproduced collision. + +## [P1] First-wins ID registration can select the wrong target + +The collection draft relied on Rolodex registration to reject an ambiguous collection. I registered distinct origins with the same resolved `$id` through `RegisterSchemaId`. Both calls returned success, and lookup retained the first origin. By the time the public registry is enumerated, the other declaration has been lost. [Registration result](https://github.com/pb33f/libopenapi/blob/db27aae96380883740653c3658a79b4110ea35ff/index/schema_id_registry.go#L18) and [public registration](https://github.com/pb33f/libopenapi/blob/db27aae96380883740653c3658a79b4110ea35ff/index/spec_index_accessors.go#L381) + +Surface the duplicate outcome at registration for schema comparisons. Reuse the index for lookup. Treat a second visit to the same authored declaration as one origin. Register all declared resources on a side before resolving its references. Reverse enumeration order and require the same two-origin diagnostic. Also verify a forward reference to a local canonical ID with network lookup disabled. Confidence is high from the registration probe. + +## [P1] A rendered change list does not supply an interactive tree + +The single-schema draft connected `SchemaChanges` to the renderer. In a probe, Doctor produced Markdown and HTML for a newly required `Customer.id` and Diagramatron drew the Customer class. The native edit's path was empty. Doctor's `BuildNodeChangeTree` returns immediately when a neutral `ChangeReport` is set. The CLI explorer also filters out edges whose endpoints were dropped. [Native tree handling](https://github.com/pb33f/doctor/blob/v0.0.88/changerator/cleaner.go#L63), [working AsyncAPI adapter](https://github.com/pb33f/doctor/blob/v0.0.88/changerator/asyncapi.go#L37), and [explorer construction](../html-report/generator.go) + +Have Doctor attach edits to a prepared native node tree before invoking existing renderers. Keep authored reference edges and original-side removals. For collections, retain each immediate use site of a changed definition and its ancestors when selecting explorer nodes. Verify connected graph endpoints, navigation from both uses, and one edit on the defining node. Confidence is high for the code paths. The new interactive behavior remains a milestone test. + +## [P1] A line number can open the wrong file + +The source-navigation draft carried a resource name alongside a path. The existing HTML item supplies one original string and one modified string, its graph line map is keyed by line alone, and the terminal source helper declines any change with an external document location. Two schemas in one file can also share source bytes. A copy of the whole source per node would multiply payload size without resolving which side owns a removal. [HTML source contract](../html-report/generator.go#L87), [console lookup](../tui/v2/diff.go#L47), and [Cowboy focused diff](https://github.com/pb33f/cowboy-components/blob/v0.16.0/src/components/diff-viewer/diff-focus.ts#L45) + +Introduce file selection in milestone 1 when a single root first reaches a sibling. Store source text once per file and side and use that same lookup for collections. Verify different files at the same line, a stable-ID move with an edit, and a deletion available only on the original side. Open the HTML offline and drive the console code view. Confidence is high for the current limitation. + +## [P2] Directory dispatch differs by command + +The directory draft added collection loading at the shared CLI loader. The JSON command has a separate directory-to-history branch. Compact Markdown rejects a directory before loading it. Summary and console also inspect the first argument to choose their empty-history message. Implementing collection routing at only one site would give different meanings to the same two paths. [Shared loader](../cmd/common.go#L227), [JSON route](../cmd/report.go#L252), [compact validation](../cmd/markdown_report.go#L238), [summary](../cmd/summary.go#L496), and [console](../cmd/console.go#L100) + +Use one argument-mode decision across these sites. Two local directories under `--schema` select a collection. A repository and file select named-file history. Verify all five normal commands, compact Markdown, two empty collections, and the existing history syntax. Confidence is high from inspection of all five directory checks. + +## Crushed plan + +1. Deliver the `Customer` fixture through the five public commands. Reuse the comparator, index, renderer, and UI. Add only schema input, scoped compatibility, native edit locations, and source selection. This removes the need for an API envelope, a comparison registry, or separate report implementations. +2. After that gate, add per-side member discovery and matching. Put each edit on its definition and retain its incoming references. Accept the collection stage only when the shared-Money and independent-edit fixtures both pass. +3. Keep the initial scope to Draft 2020-12, named-file history, and explicit local directory pairs. Additional dialects, directory history, and a general schema-containment solver have separate requirements. + +The existing Petstore count, AsyncAPI reports, external references, graph connectivity, partial history, and reproducible JSON tests passed on the CLI baseline. The same six focused tests passed with an isolated libopenapi `v0.44.0` pin. That checks a dependency integration risk. The two milestone gates are future implementation work. diff --git a/plans/2026-11-25-json-schema-comparisons.md b/plans/2026-11-25-json-schema-comparisons.md new file mode 100644 index 0000000..c1c8ac4 --- /dev/null +++ b/plans/2026-11-25-json-schema-comparisons.md @@ -0,0 +1,86 @@ + + +# Native JSON Schema comparisons + +Give `summary`, `report`, `markdown-report`, `html-report`, and `console` a JSON Schema as their comparison root. Ship a working single-root comparison through all five commands first. Then give those same commands a collection root named **Schemas**. A change to a shared definition belongs to its defining resource. The graph shows each place that uses it. + +This plan incorporates the [plan-crush findings](2026-11-25-json-schema-comparisons-plan-crush.md). The CLI baseline is `f9f73e7`. It selects Doctor `v0.0.88`, libopenapi `db27aae9`, libasyncapi `v0.0.7`, and Cowboy Components `0.16.0`. [Go dependencies](../go.mod) and [report UI dependencies](../html-report/ui/package.json) + +## Milestone 1. One schema root on each side + +```sh +openapi-changes summary before/customer.schema.json after/customer.schema.json +openapi-changes report --schema --reproducible before.json after.json +openapi-changes console --schema HEAD~1:schemas/customer.json HEAD:schemas/customer.json +``` + +A supported `$schema` declaration selects JSON Schema automatically. Use `--schema` for an unmarked object, `{}`, or a boolean. The initial dialect is Draft 2020-12. Under explicit schema mode, use that dialect when the declaration is absent. Name the file, side, and declared URI when a dialect is unsupported. Accept JSON and its JSON-compatible YAML representation. Keep API version markers on the existing OpenAPI and AsyncAPI routes. Reject conflicting kinds, invalid roots, malformed syntax, and duplicate mapping keys. A `$schema` pointing to an application's validation schema is insufficient for automatic selection. [JSON Schema roots and dialects](https://json-schema.org/draft/2020-12/json-schema-core#section-8.1.1) + +| Order and owner | Work and completion condition | +| --- | --- | +| 1. `pb33f/libopenapi` | Add a standalone schema loader around the existing parsed node, `base.SchemaProxy`, index, and Rolodex. Retain the authored node, effective dialect, retrieval source, and resolver for the lifetime of the comparison. Share strict decoding with the document loader. Accept boolean roots and preserve coordinates, base URIs, and reference siblings. Reject duplicate IDs from distinct declarations in a single root or its dependencies at registration. Add a standalone entry to the existing schema comparator. Scope its compatibility rules to this entry. Finish with the semantic fixtures below and tests for existing embedded callers. | +| 2. `pb33f/doctor` | Add a schema entry to Changerator. Take the native change report and indexed inputs from libopenapi. Reuse the existing node, edge, location lookup, and change attachment code where it works for a schema. Return a prepared root with ID `root`, the raw tree, reference edges, and source locations on both sides. Supply removed branches from the original tree. The generic Markdown and HTML renderers already accept `SchemaChanges`. Use the native root and member names for human headings. Escape unusual property names when deriving machine paths. Verify the semantic tree, raw graph, and filtered explorer graph. | +| 3. `pb33f/cowboy-components` | Let the document card and tree display Doctor's schema root label. Prefer the title, then the resource name or source filename, then `Schema`. Reuse the existing schema nodes and icon. Extend the static-report TypeScript contract and focused diff input for a selected source on each side. A root-only report still uses its existing pair of source strings. Render a titled schema, a boolean root, and a removed field. Exercise existing OpenAPI and AsyncAPI cards with the same build. | +| 4. `pb33f/openapi-changes` | Add the shared `--schema` flag, native input dispatch, and schema branch in `runChangerator`. Carry the selected kind through the direct loader, history window, config, compact Markdown, and report metadata. Supply schema labels for help, HTML metadata, and summary grouping. Connect the Doctor root to the existing Bubble Tea and static HTML views. Pin matching Go and npm versions, rebuild both embedded bundles, and update the README, AGENTS.md, and `.ai-docs/` with the new contract. Run the five-command gate. | +| 5. `pb33f/pb33f.io` | Add a JSON Schema guide beside the AsyncAPI guide. Update command arguments and `schemaRules` examples. Use the actual CLI fixture, output, and first released version. Extend the same page after the collection milestone. [Public documentation source](https://github.com/pb33f/pb33f.io/tree/f4444304932d8c1e07f8c8b19f81f83069a6b210/content/openapi-changes) | + +`pb33f/libasyncapi` is a regression consumer in both milestones. Its JSON Schema payloads already delegate to `CompareSchemas`. Keep that entry's behavior, including foreign payload handling and AsyncAPI configuration. Run its schema and external-reference tests against the proposed libopenapi pin. [AsyncAPI schema comparison](https://github.com/pb33f/libasyncapi/blob/v0.0.7/what-changed/model/schema.go#L15) + +### Comparison and reporting contract + +- **Compatibility.** The original schema is the published contract. Mark a change as breaking when it can reject previously accepted data or remove a published address. For the default policy, `true` to `false` breaks, `false` to `true` widens, adding a required field breaks, and raising `minLength` on a plain string breaks. Lowering it widens. Apply these directional rules only in contexts where they hold. Negation can reverse the effect, and `oneOf` can make it ambiguous. Use conservative classification where direction cannot be established. Apply an explicitly supplied `schemaRules` property override before defaults. Keep the original override distinct from the merged defaults so an explicit `true` takes effect on a widening edit. +- **Published definitions.** Compare `$defs` keys and their contents even when the root never refers to them. Include `$id` and static `$anchor` edits. An address removal or rename breaks references to the old address. A `$defs` entry is a named subschema and can introduce a resource with its own `$id`. Resolve `$ref` siblings and nested bases by the declared dialect. Test `$dynamicRef` with `$dynamicAnchor` against its evaluation scope. Give a specific unsupported-feature error for a case the resolver cannot represent. Exercise `prefixItems` order and metadata-only edits. A description edit is visible and nonbreaking by default. Diagnose unresolved references and unsupported required vocabularies before returning an unchanged result. [JSON Schema resource and reference rules](https://json-schema.org/draft/2020-12/json-schema-core#section-8.2) +- **Machine identity.** Use `specification.kind = "jsonschema"` and the effective dialect URI in `originalVersion` and `modifiedVersion`. On schema changes, carry an additive `schemaResource` key alongside the native resource-relative JSONPath. For a required-list addition, `path` is `$.required`, `property` is `required`, and `new` is the member name. Whole-root changes use `$`. Use the canonical `$id` when it is independent of the checkout. Express IDs derived from a snapshot file base in that snapshot's relative namespace. Use the normalized source-relative name for an anonymous resource. Match directly supplied roots by argument position even if their names differ. Choose the modified resource key if its owner survives, and the original key if the resource is removed. Keep `rawPath` for a rewritten engine path. +- **Counts and hashes.** Include the resource key in the existing semantic edit identity used by Doctor and the CLI. Pass each original change through flat JSON. Derive human counts from the existing deduplicator. Use the same schema identity fields for grouping and deterministic sorting. For schema `changeHash`, hash an unambiguous encoding of resource, native path, property, change type, and old/new values, including structured values and reference targets. Coordinates serve navigation. Keep the existing hash algorithm for API formats. Test the custom `Change.MarshalJSON` and the flattened output. [CLI deduplication](../internal/changecounts/deduplicate.go) and [flat report hash](../model/report.go) +- **Sources and history.** One root may refer to another file. Use each side's existing file, URL, or revision configuration and its remote-reference policy. For Git and GitHub, a sibling comes from the same revision as its root. Equal root bytes permit a shortcut only after reachable dependencies are accounted for. Reuse the bounded history window and console cache. Preserve public `ParseSpecification` and `HistoryWindow.Acquire` callers with thin adapters over the native input path. Keep distinct outcomes for an unchanged pair, a first revision, a failed direct comparison, and mixed history with `metaData.partial` and `skippedCommits`. Direct reports omit synthetic commit details. [Source loading](../cmd/left_right_sources.go) and [history ownership](../model/history_source.go) +- **Source navigation.** Use existing root buffers for a self-contained pair. For multi-file inputs add an optional source table to each report item, keyed by side and source. Store each required file once per side. Optional `context.originalDocument` and `context.modifiedDocument` select the file for the existing line and column on that side. Keep `context.document` for existing consumers. Key line maps by side and file. Use the original for removals and modified for additions. A modification can display both, including after a move. The console uses the same lookup and its existing cache. HTML must work offline. Use the loader's sanitized display locations in exported sources. Keep the raw document tree and generate the explorer view from a copy. [HTML payload and explorer](../html-report/generator.go) and [terminal source selection](../tui/v2/diff.go) + +Scope standalone defaults and `schemaRules` to the schema comparison. Reuse the CLI's existing `breakingrules.Acquire` guard for any reads of libopenapi's active policy and release it on error. A legacy unscoped rule file receives the existing format-specific diagnostic. Test custom rules followed by a default run and concurrent runs with opposing rules. [Rules configuration](../cmd/comparison_rules.go) and [policy guard](../internal/breakingrules/config.go) + +### Gate before collection work + +Use one small `Customer` fixture pair throughout. Both sides declare the same `$id` and define `id` as a string. Add `id` to the modified root's `required` list. Keep the added member on a known source line. + +| Command | Required observation | +| --- | --- | +| `summary` | One addition and one breaking change. The highlight and tree identify `Customer / required / id`. `--with-lines` points at the added member. Check the existing breaking and `--error-on-diff` exit behavior with this fixture and a widening edit. | +| `report` | One raw record with the expected resource, path, property, member, breaking flag, and coordinate. Two `--reproducible` runs produce identical JSON. | +| `markdown-report` | Full and compact output identify the schema and agree on one breaking change. `--include-diff` uses the authored file pair. Check the compact result file and the existing unchanged result. | +| `html-report` | Open the offline artifact. Select the change in the document tree and explorer and verify the highlighted line. Check the full build and the lite build's available views. | +| `console` | Start through the normal CLI path in a pseudo-terminal. Select the leaf, open the code/diff view, verify the displayed source, and quit. Drive the same interaction in a model test for CI. | + +Run the reverse/removal interaction, a `$defs`-only edit, a boolean pair, and an identical pair. Add a changed sibling behind byte-identical roots. Run it through file, HTTP, and Git-revision loaders, including a working-tree copy that conflicts with the revision. Repeat a named-file history lookup through a mocked GitHub file service pinned to the commit SHA. Check a malformed revision between valid revisions and a mixed-kind pair. These cases also exercise source release on success and failure. Complete this gate with the real CLI and embedded assets before starting milestone 2. + +## Milestone 2. Collections with shared references + +```sh +openapi-changes html-report --schema --report-file changes.html ./before/schemas ./after/schemas +``` + +Two explicitly supplied local directories are snapshots and produce one comparison item. Recursively enumerate regular `.json`, `.yaml`, and `.yml` files in stable relative-path order. These directories are curated schema sets, so unmarked schemas and arbitrary filenames work. Skip Git metadata and directory symlinks. A single `$defs` bundle continues to use the file route. Named-file history retains its existing `repo file` and GitHub file-URL syntax. + +| Order and owner | Work and completion condition | +| --- | --- | +| 1. `libopenapi` | Use one Rolodex per side. Add each member's existing file index and register its resources before resolving cross-file references. Traverse schema-bearing positions, including embedded `$id` resources. Treat `examples`, `default`, and `const` values as instance data. Surface an error with both origins for duplicate resolved IDs in schema mode. Resolve local members by ID before any permitted external lookup. Compare each matched pair of authored definitions once. Preserve distinct use-site targets when dynamic scopes differ. A `$ref` retarget or sibling edit belongs to the reference site. A definition edit belongs to its nearest resource. Reuse this ownership during recursion and across roots. | +| 2. `doctor` | Assemble one `Schemas` root from those results. Give each member a resource-qualified node ID and keep its JSONPath local. Build one definition subtree and an edge from each authored reference site. Retain old nodes and origins for removals. In the explorer, keep incoming references to changed definitions and the containment paths needed to reach their source nodes. Usage nodes contribute zero edits for an edit authored at the target. | +| 3. `cowboy-components` and `openapi-changes` | Cowboy consumes the collection root and the source lookup from milestone 1. The CLI owns directory enumeration, existing argument routing, and one result across all five commands. Use one mode decision for `report`, shared loading, compact Markdown, and empty-result messages. Group summaries by resource. For `--include-diff`, label unified diffs by changed physical file pair. Select the correct resource for the graph, document tree, console, and offline source view. | +| 4. `pb33f.io` | Publish the shared-reference example, file selection and identity rules, and expected JSON, counts, and source navigation for the released CLI. | + +**Matching.** First match equal resolved `$id` values. Project file-derived URIs under each snapshot onto its relative namespace for identity, output, and hashing, so different checkout directories compare consistently. Resolve actual references against their real base on each side. Pair remaining resources at the same unambiguous relative file and embedded pointer. This exposes an ID rename at the same location as an ID change. A pure move with a stable absolute ID and equivalent references retains identity and adds zero semantic edits. Remaining original and modified members are removals and additions. Order output by resource and local path. Fail a direct snapshot pair clearly on an ambiguous, unreadable, or malformed member. An empty snapshot is valid and can represent every member being added or removed. + +**Acceptance fixture.** `order.json` and `invoice.json` both reference the canonical ID of `money.json`. Only `Money.properties.currency.minLength` changes, from `2` to `3`. All five commands must expose one breaking definition edit. The graph must contain both incoming edges, and selection from either use must open the modified money file. The flat report must identify Money at `$.properties.currency.minLength`. Reverse the edit to verify widening. Remove a member to verify original-side navigation. + +Add a counterexample with identical edits at the same path, line, and column in two independent resources. Expect two changes, two hashes, and two selectable files. Also cover a stable-ID move and edit, an anonymous resource, a duplicate ID, a nested relative ID, a retargeted reference, a recursive reference, and shuffled enumeration order. A shared-reference fan-out benchmark must observe one comparison of the target pair and one source body per file and side as the number of incoming edges grows. + +## Integration and validation + +Use a clean worktree and a fresh, nontracking branch in each changed repository. For each milestone, integrate libopenapi into Doctor, then consume Doctor and Cowboy in the CLI. Develop with a local Go workspace and a local Cowboy package build. Pin published module and npm versions in the consuming changes. Rebuild both CLI bundles from the lockfile. Keep each tested change in a focused commit and record the selected versions and benchmark results with the integration change. + +- In libopenapi run `go test ./datamodel/... ./index ./what-changed/...`. In Doctor run `go test ./model/... ./changerator/...`. Run `go test ./what-changed/...` in libasyncapi with the integration pins. Include focused race tests for shared references and policy isolation. +- In Cowboy run `npm test` and `npm run build`. In the CLI report UI run `npm ci`, `npm run typecheck`, `npm test`, and `npm run build`. Verify the released public examples in the Hugo site build. +- In the CLI run `go test ./cmd -count=1` and `go test ./... -count=1`, with focused race checks on history release. Verify help and Petstore through the existing commands, then run the AsyncAPI reports, graph, and history fixtures. Compare `BenchmarkOpenAPIReport` and `BenchmarkAsyncAPIReport` with `-benchmem` on the same toolchain. + +At the target CLI revision the executable Petstore test expects **45 total and 19 breaking**. The older checkout instructions quote 42 and 18. Use the tested target as the comparison baseline. [Petstore regression](../cmd/petstore_regression_test.go) and [existing benchmarks](../cmd/bilingual_benchmark_test.go) From 6c4aa65e0beb72255746d1cce45743026901d561 Mon Sep 17 00:00:00 2001 From: quobix Date: Wed, 25 Nov 2026 11:54:14 -0500 Subject: [PATCH 02/24] Render native schema comparisons in full and lite HTML reports --- html-report/generator.go | 47 +- html-report/generator_test.go | 42 + html-report/templates/header.gohtml | 4 +- html-report/ui/build/static/bundle-lite.js | 114 +-- html-report/ui/build/static/bundle.js | 846 +++++++++--------- .../ui/src/components/report-shell-base.ts | 8 +- html-report/ui/src/components/report-shell.ts | 2 + html-report/ui/test/fixtures.ts | 2 +- .../ui/test/report-shell-render.test.ts | 17 + 9 files changed, 587 insertions(+), 495 deletions(-) diff --git a/html-report/generator.go b/html-report/generator.go index 53c4663..fd4e3f0 100644 --- a/html-report/generator.go +++ b/html-report/generator.go @@ -80,11 +80,13 @@ type ReportPayload struct { OriginalPath string `json:"originalPath,omitempty"` ModifiedPath string `json:"modifiedPath,omitempty"` Items []*ReportItem `json:"items"` - History *HistoryData `json:"history"` + History *HistoryData `json:"history,omitempty"` } // ReportItem represents a single commit/comparison in the report. type ReportItem struct { + OriginalSources map[string]string `json:"originalSources,omitempty"` + ModifiedSources map[string]string `json:"modifiedSources,omitempty"` Specification *model.ComparisonSpecification `json:"specification,omitempty"` ChangeId string `json:"changeId"` Graph *GraphData `json:"graph"` @@ -95,7 +97,7 @@ type ReportItem struct { ModifiedSpec string `json:"modifiedSpec"` OriginalHighlighted map[int]string `json:"originalHighlighted,omitempty"` ModifiedHighlighted map[int]string `json:"modifiedHighlighted,omitempty"` - Commit *CommitInfo `json:"commit"` + Commit *CommitInfo `json:"commit,omitempty"` } // highlightSpecLines uses Chroma to syntax-highlight each line of a spec, @@ -171,7 +173,7 @@ type GraphData struct { // SummaryData mirrors the cowboy-components SpecSummary interface (no vacuum fields). type SummaryData struct { ChangeId string `json:"changeId"` - Created string `json:"created"` + Created string `json:"created,omitempty"` TotalChanges int `json:"totalChanges"` BreakingChanges int `json:"breakingChanges"` Additions int `json:"additions"` @@ -256,6 +258,7 @@ func BuildReportItem( htmlRenderer := renderer.NewHTMLRenderer(htmlConfig) htmlReport, err := htmlRenderer.RenderHTML(&renderer.RenderInput{ ChangeReport: docChanges, + SchemaLabels: result.SchemaLabels, Doctor: rightDrDoc, RightDocContent: commit.Data, Config: htmlConfig, @@ -272,7 +275,7 @@ func BuildReportItem( graphMap = rightDrDoc.BuildGraphMap() } else { for _, node := range result.ChangedNodes { - if node.ValueLine > 0 { + if node.ValueLine > 0 && (commit.ModifiedSchemas == nil || commit.ModifiedSchemas.Root == node.OriginLocation) { graphMap[node.ValueLine] = node.Id } } @@ -297,15 +300,18 @@ func BuildReportItem( summary := &SummaryData{ ChangeId: changeId, - Created: commit.CommitDate.Format(time.RFC3339), TotalChanges: counts.Total, BreakingChanges: counts.Breaking, Additions: counts.Additions, Modifications: counts.Modifications, Removals: counts.Removals, - GitCommitSha: commit.Hash, - GitAuthor: commit.Author, - GitMessage: commit.Message, + } + commitInfo := buildCommitInfo(commit) + if commitInfo != nil { + summary.Created = commit.CommitDate.Format(time.RFC3339) + summary.GitCommitSha = commit.Hash + summary.GitAuthor = commit.Author + summary.GitMessage = commit.Message } item := &ReportItem{ @@ -315,11 +321,13 @@ func BuildReportItem( ExplorerGraph: explorerGraph, Summary: summary, HtmlReport: htmlReport, + OriginalSources: commit.OriginalSchemas.Extra(), + ModifiedSources: commit.ModifiedSchemas.Extra(), OriginalSpec: string(commit.OldData), ModifiedSpec: string(commit.Data), OriginalHighlighted: highlightSpecLines(string(commit.OldData)), ModifiedHighlighted: highlightSpecLines(string(commit.Data)), - Commit: buildCommitInfo(commit), + Commit: commitInfo, } return item, nil @@ -459,6 +467,9 @@ func cloneNodeTree(node *v3.Node) *v3.Node { } func buildCommitInfo(commit *model.Commit) *CommitInfo { + if commit.Synthetic && commit.Specification != nil && commit.Specification.Kind == "jsonschema" { + return nil + } return &CommitInfo{ Hash: commit.Hash, Date: commit.CommitDate.Format(time.RFC3339), @@ -472,15 +483,27 @@ func buildCommitInfo(commit *model.Commit) *CommitInfo { // for the history line charts. Items are reversed so the chart reads // oldest (left) to newest (right). func BuildHistoryData(items []*ReportItem) *HistoryData { - n := len(items) + n := 0 + for _, item := range items { + if item.Commit != nil { + n++ + } + } + if n == 0 && len(items) > 0 { + return nil + } labels := make([]string, n) additions := make([]float64, n) modifications := make([]float64, n) removals := make([]float64, n) changeIds := make([]string, n) - for i, item := range items { - j := n - 1 - i + j := n + for _, item := range items { + if item.Commit == nil { + continue + } + j-- labels[j] = item.Commit.Date additions[j] = float64(item.Summary.Additions) modifications[j] = float64(item.Summary.Modifications) diff --git a/html-report/generator_test.go b/html-report/generator_test.go index 879fd79..b6d4f9c 100644 --- a/html-report/generator_test.go +++ b/html-report/generator_test.go @@ -4,10 +4,15 @@ package html_report import ( + "encoding/json" "testing" + "testing/fstest" "time" + "github.com/pb33f/doctor/changerator" v3 "github.com/pb33f/doctor/model/high/v3" + "github.com/pb33f/libopenapi/datamodel" + "github.com/pb33f/libopenapi/jsonschema" whatChangedModel "github.com/pb33f/libopenapi/what-changed/model" "github.com/pb33f/openapi-changes/model" "github.com/pb33f/testify/assert" @@ -86,6 +91,43 @@ func TestNewReportData_Lite(t *testing.T) { assert.NotEqual(t, bundledJS, rd.BundledJS, "lite should use the lite bundle") } +func TestStandaloneSchemaReportItem(t *testing.T) { + root := []byte("{\"title\":\"Order\",\"properties\":{\"amount\":{\"$ref\":\"money.yaml\"}}}") + load := func(body string) *jsonschema.Document { + cfg := datamodel.NewDocumentConfiguration() + cfg.BasePath = "/snapshot" + cfg.LocalFS = fstest.MapFS{"money.yaml": {Data: []byte(body)}} + doc, err := jsonschema.Load(root, "order.json", cfg, true) + require.NoError(t, err) + t.Cleanup(doc.Release) + return doc + } + left, right := load("minLength: 2"), load("minLength: 3") + result, err := changerator.CompareJSONSchema(left, right, nil) + require.NoError(t, err) + require.NotNil(t, result) + defer result.Release() + commit := &model.Commit{OldData: root, Data: root, Synthetic: true, Hash: "synthetic", Message: "placeholder", + Specification: &model.ComparisonSpecification{Kind: "jsonschema", OriginalVersion: jsonschema.Dialect, ModifiedVersion: jsonschema.Dialect}, + OriginalSchemas: model.NewSchemaSources(left), ModifiedSchemas: model.NewSchemaSources(right)} + item, err := BuildReportItem(commit, result.Changerator, result.Changes, nil, "0") + require.NoError(t, err) + require.Equal(t, 1, item.Summary.TotalChanges) + require.Equal(t, 1, item.Summary.BreakingChanges) + require.Equal(t, string(root), item.OriginalSpec) + require.Equal(t, string(root), item.ModifiedSpec) + require.Equal(t, map[string]string{"money.yaml": "minLength: 2"}, item.OriginalSources) + require.Equal(t, map[string]string{"money.yaml": "minLength: 3"}, item.ModifiedSources) + require.Nil(t, item.Commit) + require.Nil(t, BuildHistoryData([]*ReportItem{item})) + encoded, err := json.Marshal(item) + require.NoError(t, err) + assert.NotContains(t, string(encoded), "\"commit\":") + assert.NotContains(t, string(encoded), "gitCommitSha") + assert.Contains(t, string(item.Graph.Nodes), "\"documentKind\":\"jsonschema\"") + assert.Contains(t, string(item.Graph.Nodes), "\"modifiedDocument\":\"money.yaml\"") +} + func TestBuildHistoryData(t *testing.T) { items := []*ReportItem{ { diff --git a/html-report/templates/header.gohtml b/html-report/templates/header.gohtml index 1e86980..836bcc7 100644 --- a/html-report/templates/header.gohtml +++ b/html-report/templates/header.gohtml @@ -3,10 +3,10 @@ OPENAPI-CHANGES: Full Change Report - + - +