diff --git a/.ai-docs/bilingual-comparison.md b/.ai-docs/bilingual-comparison.md
index d359243..efc4e30 100644
--- a/.ai-docs/bilingual-comparison.md
+++ b/.ai-docs/bilingual-comparison.md
@@ -1,6 +1,6 @@
-# OpenAPI and AsyncAPI comparisons
+# Document and schema comparisons
-One command family supports OpenAPI and AsyncAPI 3.x. `model.ParseSpecification`
+One command family supports OpenAPI, AsyncAPI 3.x, and standalone JSON Schema Draft 2020-12. `model.ParseSpecification`
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.
@@ -19,7 +19,7 @@ available; `Commit.AllChanges` selects the additive neutral report when present.
Existing unscoped rule files remain OpenAPI-only. A combined file has optional
`openapiRules`, `asyncapiRules`, and `schemaRules` sections. The last section
-configures JSON Schemas embedded in AsyncAPI; it does not change OpenAPI policy.
+configures standalone JSON Schemas and schemas embedded in AsyncAPI; it does not change OpenAPI policy.
Unknown sections are rejected. Rules are merged into fresh defaults. The CLI's
shared breakingrules lock covers the entire delegated comparison and restores
defaults afterwards, including comparisons without a custom policy.
@@ -102,3 +102,50 @@ 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
that 30 adjacent revisions parse once each and retain at most two idle models.
+
+## Standalone JSON Schema
+
+All five commands accept Draft 2020-12 JSON Schemas. A root with the supported `$schema` declaration selects
+this engine automatically. `--schema` also accepts unmarked JSON and YAML objects, `true`, and `false`.
+Both sides must have the same native format. Unsupported dialects, unresolved references, duplicate resource IDs,
+and unsupported dynamic references return errors with source details.
+
+`model.ParseInput` and `HistoryWindow.AcquireInput` carry a single native model through direct comparisons and history.
+The Git and GitHub loaders give each schema its revision filesystem. Equal root bytes can still have different
+referenced content. The global `schemaRules` policy lock covers the native comparison. Explicit property rules
+override the default widening and narrowing classification. `libasyncapi` continues to compare embedded payloads.
+
+A schema change has a defining `schemaResource`, a resource-relative JSONPath, and available source locations in
+`context.originalDocument` and `context.modifiedDocument`. Matched resources carry both filenames, including when a file moves.
+Line and column coordinates identify only the sides where the edited value exists. The console and HTML views
+use the filenames for source lookup. The schema hash uses semantic fields, including the resource, so line movement alone
+does not change it. The root source is stored once per side. Additional files use the optional `originalSources`
+and `modifiedSources` report maps. Renderers request those source views while the result is pinned. Flat reports
+retain change values and copied coordinates. The console keeps per-file line tables in its bounded result cache.
+
+For the Customer fixture, the required-list addition has `path = $.required`, `property = required`, and `new = id`.
+The human reports show the Customer title, and the flat report groups by its canonical resource ID.
+`markdown-report --include-diff` includes the physical file pair that owns the edit.
+
+## JSON Schema collections
+
+`cmd.comparisonMode` selects a direct comparison when both arguments are local directories and `--schema` is set.
+The existing repository and file path form selects local Git history. The one-URL GitHub history form is unchanged.
+
+The directory loader enumerates regular `.json`, `.yaml`, and `.yml` files, including uppercase extensions,
+using slash-separated relative names. It skips symlinks, `node_modules`, and dot-directories such as `.git`. Every
+other member is read as a schema, so a directory should hold schemas only. The library registers every member before
+resolving references and matching resources by ID, then by relative file and embedded pointer. Either directory may
+be empty. A malformed member aborts that direct comparison with its side and filename. When that member has no
+Draft 2020-12 `$schema` declaration, the error also says it does not look like a JSON Schema.
+
+Two directories without `--schema` still select local Git history. That loader reports both arguments as
+directories and suggests `--schema`.
+
+A collection produces one report item. The graph has a `Schemas` root. Source lookup keys are the physical member
+names, and change paths are local to the resource in `schemaResource`. The summary, compact counts, and Markdown
+use the same resource-aware identity as the console and the HTML views. `--include-diff` includes one unified
+diff per changed file pair. A moved resource can have different original and modified filenames.
+
+Selecting a reference site in either HTML report shows edits authored at the site and in the definitions reached
+through its unchanged references. A changed `$ref` or `$dynamicRef` shows the edit to that keyword at its source.
diff --git a/.ai-docs/compact-report.md b/.ai-docs/compact-report.md
index 9a4795c..1c616be 100644
--- a/.ai-docs/compact-report.md
+++ b/.ai-docs/compact-report.md
@@ -1,7 +1,8 @@
# Compact Markdown reports
`markdown-report --compact` compares two direct inputs and writes a short report.
-Inputs can be files, URLs, or git revision paths. Repository history is not
+Inputs can be files, URLs, or git revision paths for OpenAPI, AsyncAPI, or JSON Schema.
+Use `--schema` for unmarked Draft 2020-12 inputs or a pair of local schema directories. Repository history is not
supported in this mode. `--include-diff` cannot be used with `--compact`.
Example:
diff --git a/AGENTS.md b/AGENTS.md
index 55eb1dd..4c245c0 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -10,7 +10,7 @@ Public documentation:
## What This Repo Is
-`openapi-changes` is a Go CLI for comparing OpenAPI specifications across:
+`openapi-changes` is a Go CLI for comparing OpenAPI, AsyncAPI 3.x, and JSON Schema Draft 2020-12 documents across:
- direct left/right file, URL, or git-revision comparison
- local git history for a file in a repository
@@ -62,6 +62,7 @@ All `cmd/` implementation files use their canonical names (e.g., `cmd/summary.go
### Machine-readable JSON
+- Standalone schema edits carry a resource-relative `path` and a `schemaResource`. Include both in count and hash identity.
- `report` should emit semantic `path` values whenever possible.
- If semantic normalization rewrites an engine path, preserve the original path in `rawPath`.
- Parameter identity must not depend on array index positions when a stable semantic name exists.
@@ -124,6 +125,17 @@ All `cmd/` implementation files use their canonical names (e.g., `cmd/summary.go
- The residual `tui/` package still exists in-repo, but it is not the canonical console implementation. The canonical console is `tui/v2/` (Bubbletea).
- **Dependency version sensitivity**: `doctor` and `libopenapi` version bumps can silently change comparison output, count semantics, or tree structure. After upgrading either dependency, always re-run the petstore regression fixtures and verify counts match expectations.
+## JSON Schema inputs
+
+`model.ParseInput` dispatches the parsed document by its native format. The shared `--schema` flag enables
+unmarked schemas, including booleans. `libopenapi/jsonschema` owns schema resources and reference resolution.
+Doctor attaches edits to its native schema graph. The CLI uses the same report and console paths as the API formats.
+Use `sample-specs/json-schema/{before,after}/customer.json` to check one breaking addition at `$.required`.
+
+With `--schema`, two local directories select a direct collection comparison. A repository and a file path still select file history.
+Use `sample-specs/json-schema/collections/{before,after}` to verify one edit at `$.properties.currency.minLength` in `money.json`,
+two incoming references, and source selection in both the console and the offline HTML report.
+
## Regression Fixtures
Use these files whenever you change semantics, counts, report rendering, or UI payload shape:
diff --git a/README.md b/README.md
index 624719b..b2b7b2c 100644
--- a/README.md
+++ b/README.md
@@ -9,7 +9,7 @@
## The world's **_most powerful and complete_** OpenAPI diff tool.
-`openapi-changes` lets you inspect what changed in an OpenAPI or AsyncAPI 3.x specification between two files,
+`openapi-changes` lets you inspect what changed in an OpenAPI, AsyncAPI 3.x, or JSON Schema Draft 2020-12 document between two files,
between git revisions of the same file, across local git history, or directly from a GitHub-hosted file URL.
It can render the same semantic change model as:
@@ -24,6 +24,37 @@ It works well for local exploration, CI/CD checks, release notes, and API review
---
+## Compare JSON Schemas
+
+Supply a pair of schemas to any of the five commands. A Draft 2020-12 `$schema` declaration selects the schema engine.
+Pass `--schema` for an unmarked object or boolean.
+
+```sh
+openapi-changes summary sample-specs/json-schema/before/customer.json sample-specs/json-schema/after/customer.json
+openapi-changes report --schema HEAD~1:schemas/customer.yaml HEAD:schemas/customer.yaml
+```
+
+The Customer example adds `id` to `required`. The report records one breaking change at `$.required`.
+The `schemaResource` field identifies the defining schema. The console and the offline HTML report open the source
+that owns the change, including referenced files. Use the `schemaRules` configuration section for schema policy.
+
+### Compare schema collections
+
+Pass two local directories with `--schema`. The CLI reads JSON and YAML files recursively and registers each
+resource before resolving references. It skips symbolic links, `node_modules`, and any directory whose name starts
+with a dot. Every other JSON or YAML file is read as a schema, so keep the directory to schemas only. An empty
+directory is a valid snapshot.
+
+```sh
+openapi-changes html-report --schema --report-file changes.html \
+ sample-specs/json-schema/collections/before sample-specs/json-schema/collections/after
+```
+
+Order and Invoice both reference Money in this example. Raising the minimum currency length from 2 to 3 produces
+one breaking change at `$.properties.currency.minLength`. The graph shows both references. The source view
+opens line 9 of `money.json`. Run the same pair with `report` for JSON or `markdown-report --include-diff`
+for the file diff.
+
## AsyncAPI has landed
Event-driven APIs break too. They just do it quietly, in a consumer nobody remembers subscribing to that topic.
diff --git a/cmd/asyncapi_test.go b/cmd/asyncapi_test.go
index 3c3a03b..35b3c96 100644
--- a/cmd/asyncapi_test.go
+++ b/cmd/asyncapi_test.go
@@ -173,11 +173,11 @@ func TestAsyncAPIAllReports(t *testing.T) {
require.Len(t, items, 1)
require.Contains(t, items[0].HtmlReport, `icon="channel"`)
require.Contains(t, items[0].HtmlReport, `id="channels"`)
- ctr, root, release, err := bridgeRunChangerator(commits[0], nil)
+ comparison, err := bridgeRunChangerator(commits[0], nil)
require.NoError(t, err)
- require.NotNil(t, root)
- defer release()
- require.Len(t, ctr.DeduplicateChanges(), 2)
+ require.NotNil(t, comparison.Root)
+ defer comparison.Release()
+ require.Len(t, comparison.Changerator.DeduplicateChanges(), 2)
}
func TestAsyncAPIUnchangedHistoryWithMalformedRevision(t *testing.T) {
diff --git a/cmd/common.go b/cmd/common.go
index bd69b48..e163840 100644
--- a/cmd/common.go
+++ b/cmd/common.go
@@ -24,6 +24,7 @@ const (
// summaryOpts holds the flags shared by the current doctor-based command family.
type summaryOpts struct {
+ schema bool
rules *model.ComparisonRules
noColor bool
tektronix bool
@@ -111,6 +112,7 @@ func readCommonFlags(cmd *cobra.Command) (opts summaryOpts, configFlag string, e
opts.limitTime, _ = cmd.Flags().GetInt("limit-time")
opts.base, _ = cmd.Flags().GetString("base")
opts.baseCommit, _ = cmd.Flags().GetString("base-commit")
+ opts.schema, _ = cmd.Flags().GetBool("schema")
opts.remote, _ = cmd.Flags().GetBool("remote")
opts.extRefs, _ = cmd.Flags().GetBool("ext-refs")
opts.globalRevisions, _ = cmd.Flags().GetBool("global-revisions")
@@ -222,27 +224,42 @@ func prepareCommandRun(
}, nil
}
-// loadCommitsFromArgs dispatches to the appropriate commit loader based on argument types.
-// Expects len(args) to be 1 or 2 (caller must validate arg count).
-func loadCommitsFromArgs(args []string, opts summaryOpts, breakingConfig *whatChangedModel.BreakingRulesConfig) ([]*model.Commit, error) {
+type inputMode uint8
+
+const (
+ directInputs inputMode = iota
+ schemaDirectories
+ localHistory
+ githubHistory
+)
+
+// comparisonMode distinguishes a directory pair from the repository/file form used by history.
+func comparisonMode(args []string, schema bool) inputMode {
if len(args) == 1 {
- return loadGitHubCommits(args[0], opts, breakingConfig)
- }
- if isHTTPURL(args[0]) {
- return loadLeftRightCommits(args[0], args[1], opts)
+ return githubHistory
}
- if _, _, ok := parseGitRef(args[0]); ok {
- return loadLeftRightCommits(args[0], args[1], opts)
+ if len(args) != 2 || isHTTPURL(args[0]) {
+ return directInputs
}
- f, statErr := os.Stat(args[0])
- if statErr == nil && f.IsDir() {
- return loadGitHistoryCommits(args[0], args[1], opts, breakingConfig)
+ first, err := os.Stat(args[0])
+ if err != nil || !first.IsDir() {
+ return directInputs
}
- if _, _, ok := parseGitRef(args[1]); ok {
- return loadLeftRightCommits(args[0], args[1], opts)
+ if schema {
+ second, err := os.Stat(args[1])
+ if err == nil && second.IsDir() {
+ return schemaDirectories
+ }
}
- if statErr != nil {
- return nil, fmt.Errorf("cannot open file/repository: '%s'", args[0])
+ return localHistory
+}
+
+func loadCommitsFromArgs(args []string, opts summaryOpts, breakingConfig *whatChangedModel.BreakingRulesConfig) ([]*model.Commit, error) {
+ switch comparisonMode(args, opts.schema) {
+ case githubHistory:
+ return loadGitHubCommits(args[0], opts, breakingConfig)
+ case localHistory:
+ return loadGitHistoryCommits(args[0], args[1], opts, breakingConfig)
}
return loadLeftRightCommits(args[0], args[1], opts)
}
@@ -263,6 +280,8 @@ func printCommandUsage(commandName, description string, palette terminal.Palette
fmt.Println()
fmt.Println("Examples:")
fmt.Printf(" %s\n", cmdStyle.Render("openapi-changes "+commandName+" ./specs/old.yaml ./specs/new.yaml"))
+ fmt.Printf(" %s\n", cmdStyle.Render("openapi-changes "+commandName+" --schema before/customer.json after/customer.json"))
+ fmt.Printf(" %s\n", cmdStyle.Render("openapi-changes "+commandName+" --schema before/schemas after/schemas"))
fmt.Printf(" %s\n", cmdStyle.Render("openapi-changes "+commandName+" HEAD~1:openapi.yaml ./openapi.yaml"))
fmt.Printf(" %s\n", cmdStyle.Render("openapi-changes "+commandName+" https://github.com/user/repo/blob/main/openapi.yaml"))
fmt.Printf(" %s\n", cmdStyle.Render("openapi-changes "+commandName+" /path/to/git/repo path/to/openapi.yaml"))
diff --git a/cmd/common_test.go b/cmd/common_test.go
index 0ff94c8..07cc7fc 100644
--- a/cmd/common_test.go
+++ b/cmd/common_test.go
@@ -8,14 +8,15 @@ import (
"testing"
"github.com/pb33f/doctor/terminal"
- "github.com/spf13/cobra"
"github.com/pb33f/testify/assert"
"github.com/pb33f/testify/require"
+ "github.com/spf13/cobra"
)
// testRootCmd creates a root command with standard persistent flags and a subcommand for testing.
func testRootCmd(sub *cobra.Command, args ...string) *cobra.Command {
root := &cobra.Command{Use: "openapi-changes"}
+ root.PersistentFlags().Bool("schema", false, "")
root.PersistentFlags().BoolP("no-logo", "b", false, "")
root.PersistentFlags().BoolP("top", "t", false, "")
root.PersistentFlags().IntP("limit", "l", 5, "")
diff --git a/cmd/compact_report.go b/cmd/compact_report.go
index f3faa83..7d0c12c 100644
--- a/cmd/compact_report.go
+++ b/cmd/compact_report.go
@@ -20,7 +20,7 @@ import (
// compactOutcome is written only after a complete direct comparison.
// Counts use the same semantic identity as the human summary.
type compactOutcome struct {
- async bool
+ label string
Total int `json:"total"`
Breaking int `json:"breaking"`
}
@@ -31,7 +31,9 @@ func generateCompactMarkdown(commits []*model.Commit, config *whatChangedModel.B
return nil, outcome, errors.New("compact report requires one complete direct comparison")
}
result, err := runChangerator(commits[0], config)
- outcome.async = commits[0].APILabel() == "AsyncAPI"
+ if label := commits[0].APILabel(); label != "OpenAPI" {
+ outcome.label = label
+ }
if err != nil {
return nil, outcome, err
}
@@ -75,8 +77,8 @@ func generateCompactMarkdown(commits []*model.Commit, config *whatChangedModel.B
func renderCompactMarkdown(outcome compactOutcome, highlights []string) []byte {
var sb strings.Builder
label := "OpenAPI"
- if outcome.async {
- label = "AsyncAPI"
+ if outcome.label != "" {
+ label = outcome.label
}
sb.WriteString("## " + label + " changes\n\n")
switch {
@@ -97,7 +99,11 @@ func renderCompactMarkdown(outcome compactOutcome, highlights []string) []byte {
}
sb.WriteString("\nUp to 8 highlights are shown. See the full report for all changes.\n\n")
}
- sb.WriteString("Use [OpenAPI Doctor](https://pb33f.io/doctor/) for workspace history, diagnostics, and pipeline controls.\n")
+ product := "OpenAPI Doctor"
+ if outcome.label == "JSON Schema" {
+ product = "Doctor"
+ }
+ sb.WriteString("Use [" + product + "](https://pb33f.io/doctor/) for workspace history, diagnostics, and pipeline controls.\n")
return []byte(sb.String())
}
diff --git a/cmd/compact_report_test.go b/cmd/compact_report_test.go
index fb59028..5724743 100644
--- a/cmd/compact_report_test.go
+++ b/cmd/compact_report_test.go
@@ -108,7 +108,7 @@ func TestCompactReportRejectsAliasedOutputs(t *testing.T) {
report, result := filepath.Join(dir, "report"), filepath.Join(dir, "result")
require.NoError(t, os.WriteFile(report, []byte("existing"), 0600))
require.NoError(t, os.Link(report, result))
- require.Error(t, validateCompactOptions([]string{"a", "b"}, true, false, report, result))
+ require.Error(t, validateCompactOptions([]string{"a", "b"}, true, false, false, report, result))
}
func TestCompactReportHighlightsRemovedPath(t *testing.T) {
diff --git a/cmd/component_report_test.go b/cmd/component_report_test.go
index df5f83e..98d7b28 100644
--- a/cmd/component_report_test.go
+++ b/cmd/component_report_test.go
@@ -69,7 +69,7 @@ func TestComponentReports_PreserveEachComponent(t *testing.T) {
assert.Contains(t, item.HtmlReport, "8 changes detected")
assert.Contains(t, string(item.Graph.NodeChangeTree), "$.components")
- markdown, err := renderCommitMarkdown(commits[0], nil)
+ markdown, err := renderCommitMarkdown(commits[0], nil, false)
require.NoError(t, err)
assert.Contains(t, markdown, "**8** changes detected")
assert.Contains(t, markdown, "| Component | 8 |")
diff --git a/cmd/console.go b/cmd/console.go
index 1266bfd..b3a0185 100644
--- a/cmd/console.go
+++ b/cmd/console.go
@@ -5,11 +5,8 @@ package cmd
import (
"fmt"
- "os"
tea "charm.land/bubbletea/v2"
- "github.com/pb33f/doctor/changerator"
- v3 "github.com/pb33f/doctor/model/high/v3"
"github.com/pb33f/doctor/terminal"
whatChangedModel "github.com/pb33f/libopenapi/what-changed/model"
"github.com/pb33f/openapi-changes/model"
@@ -19,13 +16,13 @@ import (
func printConsoleUsage(palette terminal.Palette) {
printCommandUsage("console",
- "The console command renders an interactive terminal user interface.\nExplore OpenAPI and AsyncAPI contract changes in your terminal.",
+ "The console command renders an interactive terminal user interface.\nExplore OpenAPI, AsyncAPI and JSON Schema changes in your terminal.",
palette)
}
// bridgeRunChangerator adapts cmd.runChangerator to the v2tui.RunChangeratorFn signature
// to avoid import cycles between cmd and tui/v2 packages.
-func bridgeRunChangerator(commit *model.Commit, breakingConfig *whatChangedModel.BreakingRulesConfig) (*changerator.Changerator, *v3.Node, func(), error) {
+func bridgeRunChangerator(commit *model.Commit, breakingConfig *whatChangedModel.BreakingRulesConfig) (*v2tui.Comparison, error) {
comparison := commit
if commit.Source != nil {
copy := *commit
@@ -36,15 +33,17 @@ func bridgeRunChangerator(commit *model.Commit, breakingConfig *whatChangedModel
commit.OldData = comparison.OldData
commit.Specification = comparison.Specification
commit.OriginalRevision = comparison.OriginalRevision
- if err != nil {
- return nil, nil, nil, err
+ if err != nil || result == nil {
+ return nil, err
}
- if result == nil {
- return nil, nil, nil, nil
- }
- root := result.root()
- releaseFn := func() { result.Release() }
- return result.Changerator, root, releaseFn, nil
+ original, modified := result.sourceViews()
+ return &v2tui.Comparison{
+ Changerator: result.Changerator,
+ Root: result.root(),
+ OriginalSources: original,
+ ModifiedSources: modified,
+ Release: result.Release,
+ }, nil
}
func hasRenderableDocuments(commits []*model.Commit) (bool, error) {
@@ -93,11 +92,11 @@ func GetConsoleCommand() *cobra.Command {
if input == nil {
return nil
}
+ defer input.releaseDirectInputs()
defer releaseHistoryWindows(input.Commits)
if len(input.Commits) == 0 {
- firstArgInfo, statErr := os.Stat(args[0])
- if len(args) == 2 && statErr == nil && firstArgInfo.IsDir() {
+ if comparisonMode(args, input.Opts.schema) == localHistory {
printNoPriorVersionText()
return nil
}
diff --git a/cmd/engine.go b/cmd/engine.go
index 6e44530..081cafe 100644
--- a/cmd/engine.go
+++ b/cmd/engine.go
@@ -14,6 +14,7 @@ import (
v3 "github.com/pb33f/doctor/model/high/v3"
"github.com/pb33f/go-yaml"
asyncRules "github.com/pb33f/libasyncapi/what-changed/model"
+ "github.com/pb33f/libopenapi/jsonschema"
whatChanged "github.com/pb33f/libopenapi/what-changed"
whatChangedModel "github.com/pb33f/libopenapi/what-changed/model"
"github.com/pb33f/openapi-changes/internal/breakingrules"
@@ -25,15 +26,25 @@ import (
// Callers must call Release() exactly once when they are done reading Changerator,
// DocChanges, and the doctor document tree.
type changeratorResult struct {
- releaseSources func()
- Changerator *changerator.Changerator
- DocChanges whatChanged.Changed
- AsyncResult *changerator.AsyncAPIResult
- RightDrDoc *drModel.DrDocument
- LeftDrDoc *drModel.DrDocument
+ originalSchema, modifiedSchema *jsonschema.Document
+ releaseSources func()
+ Changerator *changerator.Changerator
+ DocChanges whatChanged.Changed
+ SchemaResult *changerator.SchemaResult
+ AsyncResult *changerator.AsyncAPIResult
+ RightDrDoc *drModel.DrDocument
+ LeftDrDoc *drModel.DrDocument
+}
+
+// sourceViews shares bytes only with renderers that navigate to source files.
+func (r *changeratorResult) sourceViews() (*model.SchemaSources, *model.SchemaSources) {
+ return model.NewSchemaSources(r.originalSchema), model.NewSchemaSources(r.modifiedSchema)
}
func (r *changeratorResult) root() *v3.Node {
+ if r.SchemaResult != nil {
+ return r.SchemaResult.Right.Root
+ }
if r.AsyncResult != nil {
return r.AsyncResult.Right.Root
}
@@ -41,10 +52,14 @@ func (r *changeratorResult) root() *v3.Node {
}
func (r *changeratorResult) Release() {
+ r.originalSchema, r.modifiedSchema = nil, nil
if r.releaseSources != nil {
defer r.releaseSources()
r.releaseSources = nil
}
+ if r.SchemaResult != nil {
+ r.SchemaResult.Release()
+ }
if r.AsyncResult != nil {
r.AsyncResult.Release()
}
@@ -77,6 +92,25 @@ func runChangerator(commit *model.Commit, breakingConfig *whatChangedModel.Break
}
return result, err
}
+ if commit.SchemaDocument != nil && commit.OldSchemaDocument != nil {
+ var rules *whatChangedModel.BreakingRulesConfig
+ if commit.Rules != nil {
+ if commit.Rules.Legacy {
+ return nil, fmt.Errorf("use schemaRules to configure standalone JSON Schema")
+ }
+ rules = commit.Rules.Schema
+ }
+ release := breakingrules.Acquire(rules)
+ defer release()
+ result, err := changerator.CompareJSONSchema(commit.OldSchemaDocument, commit.SchemaDocument, rules)
+ if err != nil || result == nil {
+ return nil, err
+ }
+ return &changeratorResult{
+ Changerator: result.Changerator, DocChanges: result.Changes, SchemaResult: result,
+ originalSchema: commit.OldSchemaDocument, modifiedSchema: commit.SchemaDocument,
+ }, nil
+ }
if commit.AsyncDocument != nil && commit.OldAsyncDocument != nil {
if commit.Rules != nil && commit.Rules.Legacy {
return nil, fmt.Errorf("legacy OpenAPI rules cannot configure AsyncAPI; use asyncapiRules and schemaRules sections")
diff --git a/cmd/flag_surface_test.go b/cmd/flag_surface_test.go
index 666e108..b180b40 100644
--- a/cmd/flag_surface_test.go
+++ b/cmd/flag_surface_test.go
@@ -79,5 +79,6 @@ func TestRootPersistentFlagsRemainAvailable(t *testing.T) {
"ext-refs": true,
"config": true,
"global-revisions": true,
+ "schema": true,
}, names)
}
diff --git a/cmd/flatten_report.go b/cmd/flatten_report.go
index a2f647c..2724129 100644
--- a/cmd/flatten_report.go
+++ b/cmd/flatten_report.go
@@ -114,6 +114,15 @@ func cloneChange(change *wcModel.Change) *wcModel.Change {
cloned := *change
if change.Context != nil {
ctx := *change.Context
+ // A line pointer can refer to a YAML node. Flat history outlives its parser.
+ copyPosition := func(value *int) *int {
+ if value == nil {
+ return nil
+ }
+ return new(*value)
+ }
+ ctx.OriginalLine, ctx.OriginalColumn = copyPosition(ctx.OriginalLine), copyPosition(ctx.OriginalColumn)
+ ctx.NewLine, ctx.NewColumn = copyPosition(ctx.NewLine), copyPosition(ctx.NewColumn)
cloned.Context = &ctx
}
return &cloned
@@ -133,6 +142,11 @@ func sortFlatReportChanges(changes []*model.HashedChange) {
}
func compareHashedChanges(left, right *model.HashedChange) int {
+ if left != nil && right != nil && left.Change != nil && right.Change != nil {
+ if diff := cmp.Compare(left.SchemaResource, right.SchemaResource); diff != 0 {
+ return diff
+ }
+ }
if diff := cmp.Compare(changePath(left), changePath(right)); diff != 0 {
return diff
}
diff --git a/cmd/history_cleanup.go b/cmd/history_cleanup.go
index 1ea2e08..4edfa13 100644
--- a/cmd/history_cleanup.go
+++ b/cmd/history_cleanup.go
@@ -11,3 +11,21 @@ func releaseHistoryWindows(commits []*model.Commit) {
}
}
}
+
+// Direct inputs have no history window. Their parsed models live until all command views finish.
+func releaseDirectInputs(commit *model.Commit) {
+ if commit == nil || !commit.Synthetic {
+ return
+ }
+ model.ParsedSpecification{OpenAPI: commit.OldDocument, AsyncAPI: commit.OldAsyncDocument, Schema: commit.OldSchemaDocument}.Release()
+ model.ParsedSpecification{OpenAPI: commit.Document, AsyncAPI: commit.AsyncDocument, Schema: commit.SchemaDocument}.Release()
+ commit.OldDocument, commit.Document = nil, nil
+ commit.OldAsyncDocument, commit.AsyncDocument = nil, nil
+ commit.OldSchemaDocument, commit.SchemaDocument = nil, nil
+}
+
+func (input *commandInput) releaseDirectInputs() {
+ for _, commit := range input.Commits {
+ releaseDirectInputs(commit)
+ }
+}
diff --git a/cmd/html_report.go b/cmd/html_report.go
index 993137a..f234367 100644
--- a/cmd/html_report.go
+++ b/cmd/html_report.go
@@ -22,7 +22,7 @@ import (
func printHTMLReportUsage(palette terminal.Palette) {
printCommandUsage("html-report",
- "Generates an interactive HTML report of API changes.\nThe report is fully self-contained and works offline.",
+ "Generates an interactive HTML change report.\nThe report is fully self-contained and works offline.",
palette)
}
@@ -50,9 +50,11 @@ func buildHTMLReportItems(commits []*model.Commit, breakingConfig *whatChangedMo
continue
}
+ renderCommit := *commit
+ renderCommit.OriginalSchemas, renderCommit.ModifiedSchemas = result.sourceViews()
changeId := strconv.Itoa(i)
item, err := htmlReport.BuildReportItem(
- commit,
+ &renderCommit,
result.Changerator,
result.DocChanges,
result.RightDrDoc,
@@ -151,6 +153,7 @@ func GetHTMLReportCommand() *cobra.Command {
if input == nil {
return nil
}
+ defer input.releaseDirectInputs()
reportFile, _ := cmd.Flags().GetString("report-file")
noExplorer, _ := cmd.Flags().GetBool("no-explorer")
styles := commandStylesFor(input.Opts.palette)
diff --git a/cmd/json_schema_test.go b/cmd/json_schema_test.go
new file mode 100644
index 0000000..e76ceda
--- /dev/null
+++ b/cmd/json_schema_test.go
@@ -0,0 +1,331 @@
+// Copyright 2026 Princess Beef Heavy Industries, LLC / Dave Shanley
+// SPDX-License-Identifier: Apache-2.0
+
+package cmd
+
+import (
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/pb33f/libopenapi/jsonschema"
+ "github.com/pb33f/openapi-changes/model"
+ "github.com/pb33f/testify/require"
+)
+
+func writeSchemaFile(t *testing.T, dir, name, body string) string {
+ t.Helper()
+ file := filepath.Join(dir, name)
+ require.NoError(t, os.MkdirAll(filepath.Dir(file), 0700))
+ require.NoError(t, os.WriteFile(file, []byte(body), 0600))
+ return file
+}
+
+func TestJSONSchemaSingleRootCommands(t *testing.T) {
+ left := "../sample-specs/json-schema/before/customer.json"
+ right := "../sample-specs/json-schema/after/customer.json"
+ commits, err := loadLeftRightCommits(left, right, summaryOpts{})
+ require.NoError(t, err)
+ require.Len(t, commits, 1)
+ t.Cleanup(func() { releaseDirectInputs(commits[0]) })
+ flat, err := runLeftRightReport(left, right, summaryOpts{}, nil)
+ require.NoError(t, err)
+ require.Nil(t, flat.Commit)
+ require.Equal(t, &model.ComparisonSpecification{Kind: "jsonschema", OriginalVersion: jsonschema.Dialect, ModifiedVersion: jsonschema.Dialect}, flat.Specification)
+ require.Len(t, flat.Changes, 1)
+ ch := flat.Changes[0]
+ require.Equal(t, "$.required", ch.Path)
+ require.Equal(t, "required", ch.Property)
+ require.Equal(t, "id", ch.New)
+ require.True(t, ch.Breaking)
+ require.Equal(t, "https://schemas.example.test/customer", ch.SchemaResource)
+ require.Equal(t, "customer.json", ch.Context.ModifiedDocument)
+ require.Equal(t, 12, *ch.Context.NewLine)
+ require.NotEmpty(t, ch.ChangeHash)
+ require.Equal(t, 1, flat.Summary[ch.SchemaResource].Breaking)
+
+ summary, breaking, changed, err := renderSummary(commits, nil, false, true, false, summaryStyles{})
+ require.NoError(t, err)
+ require.True(t, breaking)
+ require.True(t, changed)
+ require.Contains(t, summary, "Customer")
+ text, err := generateMarkdownReport(commits, nil, true)
+ require.NoError(t, err)
+ require.Contains(t, string(text), "# JSON Schema Changes Report")
+ require.Contains(t, string(text), "Customer")
+ require.Contains(t, string(text), "+++ customer.json")
+ items, err := buildHTMLReportItems(commits, nil)
+ require.NoError(t, err)
+ require.Len(t, items, 1)
+ require.Equal(t, "jsonschema", items[0].Specification.Kind)
+ require.Equal(t, 1, items[0].Summary.TotalChanges)
+ require.Empty(t, items[0].OriginalSources)
+ require.Empty(t, items[0].ModifiedSources)
+ comparison, err := bridgeRunChangerator(commits[0], nil)
+ require.NoError(t, err)
+ defer comparison.Release()
+ require.Equal(t, "root", comparison.Root.Id)
+ require.Equal(t, "Customer", comparison.Root.Label)
+ require.Len(t, comparison.Changerator.DeduplicateChanges(), 1)
+}
+
+func TestJSONSchemaExplicitAndConfig(t *testing.T) {
+ dir := t.TempDir()
+ old := writeSchemaFile(t, dir, "before.json", "false")
+ after := writeSchemaFile(t, dir, "after.json", "true")
+ _, err := runLeftRightReport(old, after, summaryOpts{}, nil)
+ require.Error(t, err)
+ flat, err := runLeftRightReport(old, after, summaryOpts{schema: true}, nil)
+ require.NoError(t, err)
+ require.Equal(t, "$", flat.Changes[0].Path)
+ require.False(t, flat.Changes[0].Breaking)
+ writeSchemaFile(t, dir, "before.json", `{"minLength":3}`)
+ writeSchemaFile(t, dir, "after.json", `{"minLength":2}`)
+ cfg := writeSchemaFile(t, dir, "policy.yaml", "schemaRules:\n schema:\n minLength: {modified: true}\n")
+ md, result := filepath.Join(dir, "out.md"), filepath.Join(dir, "result.json")
+ cmd := testRootCmd(GetMarkdownReportCommand(), "--schema", "--compact", "--config", cfg, "--no-logo", "--report-file", md, "--result-file", result, old, after)
+ require.NoError(t, cmd.Execute())
+ data, err := os.ReadFile(result)
+ require.NoError(t, err)
+ require.JSONEq(t, `{"total":1,"breaking":1}`, string(data))
+ data, err = os.ReadFile(md)
+ require.NoError(t, err)
+ require.Contains(t, string(data), "## JSON Schema changes")
+ flat, err = runLeftRightReport(old, after, summaryOpts{schema: true}, nil)
+ require.NoError(t, err)
+ require.False(t, flat.Changes[0].Breaking)
+}
+
+func TestConsoleBridgeReportsUnchangedSchema(t *testing.T) {
+ schema := "../sample-specs/json-schema/before/customer.json"
+ commits, err := loadLeftRightCommits(schema, schema, summaryOpts{})
+ require.NoError(t, err)
+ require.Len(t, commits, 1)
+ t.Cleanup(func() { releaseDirectInputs(commits[0]) })
+ comparison, err := bridgeRunChangerator(commits[0], nil)
+ require.NoError(t, err)
+ require.Nil(t, comparison)
+}
+
+func TestUnmarkedInputNamesEverySupportedFormat(t *testing.T) {
+ unmarked := writeSchemaFile(t, t.TempDir(), "after.json", `{"type":"string"}`)
+ _, err := runLeftRightReport("../sample-specs/json-schema/before/customer.json", unmarked, summaryOpts{}, nil)
+ require.ErrorIs(t, err, model.ErrUnrecognizedInput)
+ require.ErrorContains(t, err, "unable to parse modified document")
+}
+
+func TestJSONSchemaGitSourcesAndPartialHistory(t *testing.T) {
+ root := "type: object\nproperties:\n price:\n $ref: money.yaml\n"
+ repo := t.TempDir()
+ runGitInDir(t, repo, "init")
+ runGitInDir(t, repo, "config", "user.name", "Fixture")
+ runGitInDir(t, repo, "config", "user.email", "fixture@example.test")
+ save := func(message string) { runGitInDir(t, repo, "add", "."); runGitInDir(t, repo, "commit", "-m", message) }
+ writeSchemaFile(t, repo, "schemas/customer.yaml", root)
+ writeSchemaFile(t, repo, "schemas/money.yaml", "type: string\nminLength: 2\n")
+ save("original")
+ writeSchemaFile(t, repo, "schemas/customer.yaml", "type: [\n")
+ save("invalid")
+ skipped := gitOutputInDir(t, repo, "rev-parse", "--short", "HEAD")
+ writeSchemaFile(t, repo, "schemas/customer.yaml", root)
+ writeSchemaFile(t, repo, "schemas/money.yaml", "type: string\nminLength: 3\n")
+ save("tighten")
+ writeSchemaFile(t, repo, "schemas/money.yaml", "type: string\nminLength: 99\n")
+ t.Chdir(repo)
+ opts := summaryOpts{schema: true, globalRevisions: true, limitTime: -1}
+ before, after := "HEAD~2:schemas/customer.yaml", "HEAD:schemas/customer.yaml"
+ check := func(flat *model.FlatReport) {
+ t.Helper()
+ require.NotNil(t, flat)
+ require.Len(t, flat.Changes, 1)
+ ch := flat.Changes[0]
+ require.Equal(t, "money.yaml", ch.SchemaResource)
+ require.Equal(t, "$.minLength", ch.Path)
+ require.Equal(t, "2", ch.Original)
+ require.Equal(t, "3", ch.New)
+ require.Equal(t, "money.yaml", ch.Context.OriginalDocument)
+ require.Equal(t, "money.yaml", ch.Context.ModifiedDocument)
+ require.True(t, ch.Breaking)
+ }
+ flat, err := runLeftRightReport(before, after, opts, nil)
+ require.NoError(t, err)
+ check(flat)
+ history, err := runGitHistoryReport(repo, "schemas/customer.yaml", opts, nil)
+ require.NoError(t, err)
+ require.NotNil(t, history)
+ require.True(t, history.MetaData.Partial)
+ require.Equal(t, []string{skipped}, history.MetaData.SkippedCommits)
+ require.Len(t, history.Reports, 1)
+ check(history.Reports[0])
+
+ commits, err := loadGitHistoryCommits(repo, "schemas/customer.yaml", opts, nil)
+ require.NoError(t, err)
+ items, err := buildHTMLReportItems(commits, nil)
+ require.NoError(t, err)
+ require.Len(t, items, 1)
+ require.Contains(t, items[0].ModifiedSources["money.yaml"], "minLength: 3")
+ for _, c := range commits {
+ require.Nil(t, c.OriginalSchemas)
+ require.Nil(t, c.ModifiedSchemas)
+ }
+ markdown, err := generateMarkdownReport(commits, nil, true)
+ require.NoError(t, err)
+ require.Contains(t, string(markdown), "--- money.yaml")
+ require.Contains(t, string(markdown), "+minLength: 3")
+ require.NotContains(t, string(markdown), "minLength: 99")
+}
+
+func TestJSONSchemaInputBoundaries(t *testing.T) {
+ left := "../sample-specs/json-schema/before/customer.json"
+ dir := t.TempDir()
+ for _, tc := range []struct{ name, source, message string }{
+ {"unsupported", `{"$schema":"https://schemas.example.test/application"}`, "https://schemas.example.test/application"},
+ {"conflict", `{"$schema":"https://json-schema.org/draft/2020-12/schema","asyncapi":"3.0.0"}`, "conflicting"},
+ {"mixed", `{"openapi":"3.1.0","info":{"title":"API","version":"1"},"paths":{}}`, "cannot compare JSON Schema and OpenAPI"},
+ {"malformed", `{"$schema":`, "unable to parse modified document"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ file := writeSchemaFile(t, dir, tc.name+".json", tc.source)
+ _, err := runLeftRightReport(left, file, summaryOpts{}, nil)
+ require.ErrorContains(t, err, tc.message)
+ })
+ }
+}
+
+func TestJSONSchemaReportStableOrderingAndHash(t *testing.T) {
+ left := "../sample-specs/json-schema/before/customer.json"
+ right := "../sample-specs/json-schema/after/customer.json"
+ report := func() string {
+ t.Helper()
+ cmd := testRootCmd(GetReportCommand(), "--reproducible", left, right)
+ return captureStdout(t, func() { require.NoError(t, cmd.Execute()) })
+ }
+ a, b := report(), report()
+ require.Equal(t, a, b)
+ require.True(t, json.Valid([]byte(a)))
+}
+
+func TestJSONSchemaConsoleOpensAuthoredLine(t *testing.T) {
+ before := "../sample-specs/json-schema/before/customer.json"
+ after := "../sample-specs/json-schema/after/customer.json"
+ for _, tc := range []struct{ name, left, right string }{
+ {"added", before, after}, {"removed", after, before},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ commits, err := loadLeftRightCommits(tc.left, tc.right, summaryOpts{})
+ require.NoError(t, err)
+ t.Cleanup(func() { releaseDirectInputs(commits[0]) })
+ view := openSchemaConsoleChange(t, commits, false)
+ require.Contains(t, view, "RECENTER")
+ require.Regexp(t, `12[│ ┃]*"id"`, view)
+ })
+ }
+}
+
+func TestJSONSchemaHTTPSources(t *testing.T) {
+ dir := t.TempDir()
+ root := "$ref: money.yaml\n"
+ for i, side := range []string{"before", "after"} {
+ writeSchemaFile(t, dir, side+"/root.yaml", root)
+ writeSchemaFile(t, dir, side+"/money.yaml", fmt.Sprintf("minLength: %d\n", i+2))
+ }
+ server := httptest.NewServer(http.FileServer(http.Dir(dir)))
+ t.Cleanup(server.Close)
+ files := []struct{ name, base string }{{"file", dir}, {"url", server.URL}}
+ for _, tc := range files {
+ t.Run(tc.name, func(t *testing.T) {
+ flat, err := runLeftRightReport(tc.base+"/before/root.yaml", tc.base+"/after/root.yaml", summaryOpts{schema: true}, nil)
+ require.NoError(t, err)
+ require.Len(t, flat.Changes, 1)
+ ch := flat.Changes[0]
+ require.Equal(t, "$.minLength", ch.Path)
+ require.Equal(t, "2", ch.Original)
+ require.Equal(t, "3", ch.New)
+ require.Contains(t, ch.Context.OriginalDocument, "money.yaml")
+ require.Contains(t, ch.Context.ModifiedDocument, "money.yaml")
+ })
+ }
+}
+
+func TestJSONSchemaCollectionUsesExternalBase(t *testing.T) {
+ root := t.TempDir()
+ common := filepath.Join(root, "common")
+ writeSchemaFile(t, common, "shared.yaml", "type: string\n")
+ writeSchemaFile(t, root, "before/root.yaml", "title: Before\n$ref: shared.yaml\n")
+ writeSchemaFile(t, root, "after/root.yaml", "title: After\n$ref: shared.yaml\n")
+ report := testRootCmd(GetReportCommand(), "--schema", "--base", common, filepath.Join(root, "before"), filepath.Join(root, "after"))
+ output := captureStdout(t, func() { require.NoError(t, report.Execute()) })
+ require.Contains(t, output, `"path": "$.title"`)
+}
+
+func TestJSONSchemaExplicitLocalBase(t *testing.T) {
+ dir := t.TempDir()
+ base := filepath.Join(dir, "shared")
+ for _, side := range []string{"before", "after"} {
+ writeSchemaFile(t, dir, side+"/root.yaml", "$schema: "+jsonschema.Dialect+"\n$ref: "+side+".yaml\n")
+ writeSchemaFile(t, dir, side+"/"+side+".yaml", "$id: urn:money\nminLength: 99\n")
+ }
+ writeSchemaFile(t, base, "before.yaml", "$id: urn:money\nminLength: 2\n")
+ writeSchemaFile(t, base, "after.yaml", "$id: urn:money\nminLength: 3\n")
+ for _, explicit := range []bool{false, true} {
+ flat, err := runLeftRightReport(filepath.Join(dir, "before/root.yaml"), filepath.Join(dir, "after/root.yaml"), summaryOpts{schema: explicit, base: base}, nil)
+ require.NoError(t, err)
+ found := false
+ for _, ch := range flat.Changes {
+ if ch.Property == "minLength" {
+ require.Equal(t, "2", ch.Original)
+ require.Equal(t, "3", ch.New)
+ found = true
+ }
+ }
+ require.True(t, found, "missing change to minLength in the explicit base directory")
+ }
+}
+
+func TestJSONSchemaPoliciesAreIsolated(t *testing.T) {
+ dir := t.TempDir()
+ left := writeSchemaFile(t, dir, "old.yaml", "minLength: 3\n")
+ right := writeSchemaFile(t, dir, "new.yaml", "minLength: 2\n")
+ for _, flag := range []bool{false, true} {
+ t.Run(fmt.Sprint(flag), func(t *testing.T) {
+ cfg := writeSchemaFile(t, dir, fmt.Sprintf("policy-%t.yaml", flag), fmt.Sprintf("schemaRules:\n schema:\n minLength: {modified: %t}\n", flag))
+ rules, err := loadComparisonRules(cfg)
+ require.NoError(t, err)
+ t.Parallel()
+ for range 5 {
+ flat, err := runLeftRightReport(left, right, summaryOpts{schema: true, rules: rules}, nil)
+ require.NoError(t, err)
+ require.Len(t, flat.Changes, 1)
+ require.Equal(t, flag, flat.Changes[0].Breaking)
+ }
+ })
+ }
+}
+
+func TestJSONSchemaPureMoveAndLineShiftPreserveIdentity(t *testing.T) {
+ before, after := t.TempDir(), t.TempDir()
+ const schema = "$id: urn:money\ntype: string\nminLength: %d\n"
+ writeSchemaFile(t, before, "old/money.yaml", fmt.Sprintf(schema, 2))
+ writeSchemaFile(t, after, "new/money.yaml", fmt.Sprintf(schema, 2))
+ opts := summaryOpts{schema: true}
+ flat, err := runLeftRightReport(before, after, opts, nil)
+ require.NoError(t, err)
+ require.Nil(t, flat)
+ writeSchemaFile(t, after, "new/money.yaml", fmt.Sprintf(schema, 3))
+ flat, err = runLeftRightReport(before, after, opts, nil)
+ require.NoError(t, err)
+ require.Len(t, flat.Changes, 1)
+ initial := flat.Changes[0]
+ require.Equal(t, "old/money.yaml", initial.Context.OriginalDocument)
+ require.Equal(t, "new/money.yaml", initial.Context.ModifiedDocument)
+ writeSchemaFile(t, after, "new/money.yaml", "\n\n"+fmt.Sprintf(schema, 3))
+ flat, err = runLeftRightReport(before, after, opts, nil)
+ require.NoError(t, err)
+ require.Len(t, flat.Changes, 1)
+ require.NotEqual(t, *initial.Context.NewLine, *flat.Changes[0].Context.NewLine)
+ require.Equal(t, initial.ChangeHash, flat.Changes[0].ChangeHash)
+}
diff --git a/cmd/left_right_sources.go b/cmd/left_right_sources.go
index 81df2e4..e1f78f2 100644
--- a/cmd/left_right_sources.go
+++ b/cmd/left_right_sources.go
@@ -4,20 +4,24 @@
package cmd
import (
+ "errors"
"fmt"
"io"
+ "io/fs"
"log/slog"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
+ "strings"
"time"
"github.com/google/uuid"
"github.com/pb33f/doctor/terminal"
"github.com/pb33f/libopenapi/datamodel"
"github.com/pb33f/libopenapi/index"
+ "github.com/pb33f/libopenapi/jsonschema"
"github.com/pb33f/openapi-changes/git"
"github.com/pb33f/openapi-changes/model"
)
@@ -25,6 +29,7 @@ import (
type comparisonSource struct {
Display string
RootBytes []byte
+ Directory string
DocConfig *datamodel.DocumentConfiguration
RewriteDocumentPath model.DocumentPathRewriter
Cleanup func()
@@ -65,6 +70,9 @@ func resolveLocalFileSource(raw string, opts summaryOpts) (comparisonSource, err
return comparisonSource{}, fmt.Errorf("cannot resolve file '%s': %w", raw, err)
}
bits, err := os.ReadFile(absPath)
+ if errors.Is(err, os.ErrNotExist) {
+ return comparisonSource{}, fmt.Errorf("cannot open file/repository: '%s': %w", raw, err)
+ }
if err != nil {
return comparisonSource{}, fmt.Errorf("cannot read file '%s': %w", raw, err)
}
@@ -251,22 +259,89 @@ func attachLazyLocalFS(docConfig *datamodel.DocumentConfiguration) error {
return nil
}
-func buildLeftRightCommit(left, right comparisonSource) (*model.Commit, error) {
- leftDoc, leftAsync, err := model.ParseSpecification(left.RootBytes, left.DocConfig)
+func resolveSchemaDirectory(raw string, opts summaryOpts) (comparisonSource, error) {
+ directory, err := filepath.Abs(raw)
if err != nil {
- return nil, fmt.Errorf("unable to parse original document '%s': %w", left.Display, err)
+ return comparisonSource{}, err
}
- rightDoc, rightAsync, err := model.ParseSpecification(right.RootBytes, right.DocConfig)
+ base, baseURL, err := resolveBaseOverride(opts.base)
if err != nil {
- if leftDoc != nil {
- leftDoc.Release()
+ return comparisonSource{}, err
+ }
+ config := newComparisonDocConfig(opts)
+ config.BasePath = directory
+ if base != "" {
+ config.BasePath = base
+ }
+ config.BaseURL = baseURL
+ config.AllowFileReferences = true
+ config.AllowRemoteReferences = opts.remote || baseURL != nil
+ return comparisonSource{Display: raw, Directory: directory, DocConfig: config, Cleanup: func() {}}, nil
+}
+
+func (s comparisonSource) parse(schema model.SchemaInputOptions) (model.ParsedSpecification, error) {
+ if s.Directory == "" {
+ return model.ParseInput(s.RootBytes, s.Display, s.DocConfig, schema)
+ }
+ files := os.DirFS(s.Directory)
+ members := make(map[string][]byte)
+ err := fs.WalkDir(files, ".", func(name string, entry fs.DirEntry, err error) error {
+ if err != nil {
+ return err
+ }
+ // Tooling and dependency directories hold JSON and YAML that are not schemas.
+ if entry.IsDir() && name != "." && (entry.Name() == "node_modules" || strings.HasPrefix(entry.Name(), ".")) {
+ return fs.SkipDir
+ }
+ if !entry.Type().IsRegular() {
+ return nil
+ }
+ switch strings.ToLower(path.Ext(name)) {
+ case ".json", ".yaml", ".yml":
+ data, err := fs.ReadFile(files, name)
+ if err != nil {
+ return err
+ }
+ members[name] = data
}
+ return nil
+ })
+ if err != nil {
+ return model.ParsedSpecification{}, err
+ }
+ doc, err := jsonschema.LoadCollection(members, s.Directory, s.DocConfig)
+ if err != nil {
+ return model.ParsedSpecification{}, explainCollectionMember(err, members)
+ }
+ return model.ParsedSpecification{Schema: doc}, nil
+}
+
+// explainCollectionMember adds guidance when the rejected member carries no dialect
+// declaration. A schema directory is read whole, so a stray tooling file ends up here.
+func explainCollectionMember(err error, members map[string][]byte) error {
+ var member *jsonschema.MemberError
+ if errors.As(err, &member) && !model.DeclaresSchema(members[member.Name]) {
+ return fmt.Errorf("%s does not look like a JSON Schema (it has no Draft 2020-12 $schema declaration); move it out of the directory if it is not one: %w", member.Name, err)
+ }
+ return err
+}
+
+func buildLeftRightCommit(left, right comparisonSource, schema model.SchemaInputOptions) (*model.Commit, error) {
+ original, err := left.parse(schema)
+ if err != nil {
+ return nil, fmt.Errorf("unable to parse original document '%s': %w", left.Display, err)
+ }
+ modified, err := right.parse(schema)
+ if err != nil {
+ original.Release()
return nil, fmt.Errorf("unable to parse modified document '%s': %w", right.Display, err)
}
var rewriters []model.DocumentPathRewriter
- if (leftAsync == nil) != (rightAsync == nil) {
- return nil, fmt.Errorf("cannot compare OpenAPI and AsyncAPI documents")
+ if original.Kind() != modified.Kind() {
+ original.Release()
+ modified.Release()
+ return nil, fmt.Errorf("cannot compare %s and %s documents", original.Kind(), modified.Kind())
}
if left.RewriteDocumentPath != nil {
rewriters = append(rewriters, left.RewriteDocumentPath)
@@ -281,10 +356,12 @@ func buildLeftRightCommit(left, right comparisonSource) (*model.Commit, error) {
CommitDate: time.Now(),
OldData: left.RootBytes,
Data: right.RootBytes,
- OldDocument: leftDoc,
- Document: rightDoc,
- OldAsyncDocument: leftAsync,
- AsyncDocument: rightAsync,
+ OldSchemaDocument: original.Schema,
+ SchemaDocument: modified.Schema,
+ OldDocument: original.OpenAPI,
+ Document: modified.OpenAPI,
+ OldAsyncDocument: original.AsyncAPI,
+ AsyncDocument: modified.AsyncAPI,
OriginalSource: left.Display,
ModifiedSource: right.Display,
Synthetic: true,
@@ -293,19 +370,27 @@ func buildLeftRightCommit(left, right comparisonSource) (*model.Commit, error) {
}
func buildLeftRightCommitAndSources(left, right string, opts summaryOpts) (*model.Commit, error) {
- leftSource, err := resolveComparisonSource(left, opts)
+ resolve := resolveComparisonSource
+ if opts.schema && comparisonMode([]string{left, right}, true) == schemaDirectories {
+ resolve = resolveSchemaDirectory
+ }
+ leftSource, err := resolve(left, opts)
if err != nil {
return nil, err
}
defer leftSource.Cleanup()
- rightSource, err := resolveComparisonSource(right, opts)
+ rightSource, err := resolve(right, opts)
if err != nil {
return nil, err
}
defer rightSource.Cleanup()
- commit, err := buildLeftRightCommit(leftSource, rightSource)
+ schema := model.SchemaInputOptions{Explicit: opts.schema}
+ if opts.base != "" && !isHTTPURL(opts.base) {
+ schema.BasePath = leftSource.DocConfig.BasePath
+ }
+ commit, err := buildLeftRightCommit(leftSource, rightSource, schema)
if err != nil {
return nil, err
}
diff --git a/cmd/loaders.go b/cmd/loaders.go
index 68715f5..fb32096 100644
--- a/cmd/loaders.go
+++ b/cmd/loaders.go
@@ -136,6 +136,7 @@ func loadGitHubCommitsDetailed(rawURL string, opts summaryOpts, breakingConfig *
d := makeProgressDrainer()
result, errs := processGithubRepoDetailed(user, repo, filePath,
d.ProgressChan, d.ErrorChan, git.HistoryOptions{
+ Schema: opts.schema,
Lazy: true,
BaseCommit: opts.baseCommit,
Limit: opts.limit,
@@ -184,11 +185,15 @@ func loadGitHistoryCommitsDetailed(gitPath, filePath string, opts summaryOpts, b
}
_, err = os.Stat(filepath.Join(repo, filePath))
if err != nil {
+ if info, statErr := os.Stat(filePath); statErr == nil && info.IsDir() {
+ return nil, fmt.Errorf("'%s' and '%s' are both directories; pass --schema to compare them as JSON Schema collections", gitPath, filePath)
+ }
return nil, fmt.Errorf("cannot open file: '%s'", filePath)
}
extractDrainer := makeProgressDrainer()
extractOpts := git.HistoryOptions{
+ Schema: opts.schema,
BaseCommit: opts.baseCommit,
GlobalRevisions: opts.globalRevisions,
Limit: opts.limit,
@@ -206,6 +211,7 @@ func loadGitHistoryCommitsDetailed(gitPath, filePath string, opts summaryOpts, b
populateDrainer := makeProgressDrainer()
result, errs := populateHistoryDetailed(commits,
populateDrainer.ProgressChan, populateDrainer.ErrorChan, git.HistoryOptions{
+ Schema: opts.schema,
LimitTime: opts.limitTime,
Base: opts.base,
Remote: opts.remote,
diff --git a/cmd/markdown_report.go b/cmd/markdown_report.go
index 3357a8c..c7a1137 100644
--- a/cmd/markdown_report.go
+++ b/cmd/markdown_report.go
@@ -4,16 +4,20 @@
package cmd
import (
+ "bytes"
+ "cmp"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
+ "slices"
"strings"
"time"
"github.com/pb33f/doctor/changerator/renderer"
"github.com/pb33f/doctor/terminal"
+ "github.com/pb33f/libopenapi/jsonschema"
whatChangedModel "github.com/pb33f/libopenapi/what-changed/model"
"github.com/pb33f/openapi-changes/internal/changecounts"
"github.com/pb33f/openapi-changes/model"
@@ -23,13 +27,13 @@ import (
func printMarkdownReportUsage(palette terminal.Palette) {
printCommandUsage("markdown-report",
- "Generates a detailed markdown report of API changes using the doctor changerator engine.",
+ "Generates a detailed Markdown change report using the doctor changerator engine.",
palette)
}
// renderCommitMarkdown runs the doctor changerator on a single commit and returns markdown.
// Returns (markdown, nil) on success, ("", nil) for no changes, ("", err) for failures.
-func renderCommitMarkdown(commit *model.Commit, breakingConfig *whatChangedModel.BreakingRulesConfig) (string, error) {
+func renderCommitMarkdown(commit *model.Commit, breakingConfig *whatChangedModel.BreakingRulesConfig, includeDiff bool) (string, error) {
result, err := runChangerator(commit, breakingConfig)
if err != nil {
return "", err
@@ -42,6 +46,7 @@ func renderCommitMarkdown(commit *model.Commit, breakingConfig *whatChangedModel
markdown, err := renderer.NewHTMLRenderer(renderer.DefaultRenderConfig()).RenderMarkdown(&renderer.RenderInput{
ChangeReport: result.DocChanges,
+ SchemaLabels: result.Changerator.SchemaLabels,
Doctor: result.RightDrDoc,
RightDocContent: commit.Data,
DeduplicatedChanges: deduplicatedChanges,
@@ -50,19 +55,111 @@ func renderCommitMarkdown(commit *model.Commit, breakingConfig *whatChangedModel
if err != nil {
return "", err
}
+ if includeDiff {
+ diff := comparisonDiff(commit, result)
+ if diff != "" {
+ markdown += "\nUnified Diff
\n\n"
+ fence := diffFence(diff)
+ markdown += fence + "diff\n" + diff + fence + "\n\nUnified Diff
\n\n")
- sb.WriteString("````diff\n")
- sb.WriteString(diffText)
- sb.WriteString("````\n\n")
- sb.WriteString("