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 += "\n
\nUnified Diff\n\n" + fence := diffFence(diff) + markdown += fence + "diff\n" + diff + fence + "\n\n
\n" + } + } return markdown, nil } -// generateUnifiedDiff produces a unified diff between original and modified strings. -func generateUnifiedDiff(original, modified string) string { - diff := difflib.UnifiedDiff{ - A: difflib.SplitLines(original), - B: difflib.SplitLines(modified), - FromFile: "Original", - ToFile: "Modified", - Context: 3, +// Choose a fence that can contain the entire authored diff. +func diffFence(diff string) string { + width, run := 3, 0 + for _, ch := range diff { + if ch == '`' { + run++ + width = max(width, run) + } else { + run = 0 + } + } + return strings.Repeat("`", width+1) +} + +func comparisonDiff(commit *model.Commit, result *changeratorResult) string { + if result.originalSchema == nil { + return generateUnifiedDiff("Original", "Modified", commit.OldData, commit.Data) + } + type filePair struct{ original, modified string } + old, newer := result.originalSchema, result.modifiedSchema + filesByID := func(doc *jsonschema.Document) map[string]string { + m := make(map[string]string, len(doc.Resources)) + for _, r := range doc.Resources { + m[r.ID] = r.Source.Name + } + return m + } + oldFiles, newFiles := filesByID(old), filesByID(newer) + pairs := make(map[filePair]struct{}) + for _, change := range result.DocChanges.GetAllChanges() { + from, to := oldFiles[change.SchemaResource], newFiles[change.SchemaResource] + if ctx := change.Context; ctx != nil { + if ctx.OriginalDocument != "" { + from = ctx.OriginalDocument + } + if ctx.ModifiedDocument != "" { + to = ctx.ModifiedDocument + } + } + if from == "" && old.Sources[to] != nil { + from = to + } + if to == "" && newer.Sources[from] != nil { + to = from + } + if old.Root != nil && newer.Root != nil { + if from == "" && to == newer.Root.Source.Name { + from = old.Root.Source.Name + } + if to == "" && from == old.Root.Source.Name { + to = newer.Root.Source.Name + } + } + pairs[filePair{from, to}] = struct{}{} + } + sorted := make([]filePair, 0, len(pairs)) + for pair := range pairs { + sorted = append(sorted, pair) + } + slices.SortFunc(sorted, func(a, b filePair) int { + return cmp.Or(strings.Compare(a.original, b.original), strings.Compare(a.modified, b.modified)) + }) + var diffs strings.Builder + for _, pair := range sorted { + var a, b []byte + if f := old.Sources[pair.original]; f != nil { + a = f.Data + } + if f := newer.Sources[pair.modified]; f != nil { + b = f.Data + } + from, to := pair.original, pair.modified + if from == "" { + from = "/dev/null" + } + if to == "" { + to = "/dev/null" + } + diffs.WriteString(generateUnifiedDiff(from, to, a, b)) + } + return diffs.String() +} + +func generateUnifiedDiff(from, to string, original, modified []byte) string { + if bytes.Equal(original, modified) { + return "" + } + lines := func(data []byte) []string { + if len(data) == 0 { + return nil + } + return difflib.SplitLines(string(data)) } - text, err := difflib.GetUnifiedDiffString(diff) + text, err := difflib.GetUnifiedDiffString(difflib.UnifiedDiff{A: lines(original), B: lines(modified), FromFile: from, ToFile: to, Context: 3}) if err != nil { fmt.Fprintf(os.Stderr, "warning: failed to generate diff: %s\n", err) return "" @@ -92,7 +189,7 @@ func generateMarkdownReport(commits []*model.Commit, breakingConfig *whatChanged includeCommitMetadata := true for i, commit := range commits { - markdown, err := renderCommitMarkdown(commit, breakingConfig) + markdown, err := renderCommitMarkdown(commit, breakingConfig, includeDiff) if err != nil { emitCommitWarning(commit, err) renderErrors = append(renderErrors, wrapCommitError(commit, err)) @@ -126,18 +223,6 @@ func generateMarkdownReport(commits []*model.Commit, breakingConfig *whatChanged sb.WriteString(content) sb.WriteString("\n") - if includeDiff && len(commit.OldData) > 0 && len(commit.Data) > 0 { - diffText := generateUnifiedDiff(string(commit.OldData), string(commit.Data)) - if diffText != "" { - sb.WriteString("
\n") - sb.WriteString("Unified Diff\n\n") - sb.WriteString("````diff\n") - sb.WriteString(diffText) - sb.WriteString("````\n\n") - sb.WriteString("
\n\n") - } - } - sb.WriteString("---\n\n") } @@ -168,14 +253,15 @@ func GetMarkdownReportCommand() *cobra.Command { SilenceUsage: true, Use: "markdown-report", Short: "Generate a markdown report", - Long: "Generate a detailed markdown report of API changes rendered as markdown", + Long: "Generate a detailed Markdown change report", Example: "openapi-changes markdown-report HEAD~1:openapi.yaml ./openapi.yaml", RunE: func(cmd *cobra.Command, args []string) error { compact, _ := cmd.Flags().GetBool("compact") resultFile, _ := cmd.Flags().GetString("result-file") reportFile, _ := cmd.Flags().GetString("report-file") includeDiff, _ := cmd.Flags().GetBool("include-diff") - if err := validateCompactOptions(args, compact, includeDiff, reportFile, resultFile); err != nil { + schema, _ := cmd.Flags().GetBool("schema") + if err := validateCompactOptions(args, compact, includeDiff, schema, reportFile, resultFile); err != nil { return err } input, err := prepareCommandRun(cmd, args, printMarkdownReportUsage) @@ -185,6 +271,7 @@ func GetMarkdownReportCommand() *cobra.Command { if input == nil { return nil } + defer input.releaseDirectInputs() styles := commandStylesFor(input.Opts.palette) if compact { @@ -225,7 +312,7 @@ func GetMarkdownReportCommand() *cobra.Command { return cmd } -func validateCompactOptions(args []string, compact, includeDiff bool, reportFile, resultFile string) error { +func validateCompactOptions(args []string, compact, includeDiff, schema bool, reportFile, resultFile string) error { if resultFile != "" && !compact { return errors.New("--result-file requires --compact") } @@ -235,7 +322,7 @@ func validateCompactOptions(args []string, compact, includeDiff bool, reportFile if len(args) != 2 { return errors.New("--compact requires two direct comparison inputs; history is not supported") } - if info, err := os.Stat(args[0]); err == nil && info.IsDir() { + if comparisonMode(args, schema) == localHistory { return errors.New("--compact does not support repository history") } if includeDiff { diff --git a/cmd/report.go b/cmd/report.go index 61fcdb8..5d004d1 100644 --- a/cmd/report.go +++ b/cmd/report.go @@ -86,6 +86,7 @@ func runLeftRightReport(left, right string, opts summaryOpts, breakingConfig *wh if err != nil { return nil, err } + defer releaseDirectInputs(commit) result, err := changerateCommit(commit, breakingConfig) if err != nil { return nil, err @@ -212,7 +213,7 @@ func GetReportCommand() *cobra.Command { if len(args) == 0 { maybePrintBanner(cmd, opts.palette) printCommandUsage("report", - "The report command generates a machine-readable JSON report of all API changes\nusing the doctor changerator engine.", + "The report command generates a machine-readable JSON report of document changes\nusing the doctor changerator engine.", opts.palette) return nil } @@ -244,28 +245,19 @@ func GetReportCommand() *cobra.Command { return printReportJSON(flat) } - if !isHTTPURL(args[0]) { - if _, _, ok := parseGitRef(args[0]); ok { - return printReportJSONOrNoChanges(args, opts, breakingConfig, reproducible) + if comparisonMode(args, opts.schema) == localHistory { + flat, err := runGitHistoryReport(args[0], args[1], opts, breakingConfig) + if err != nil { + return err } - f, statErr := os.Stat(args[0]) - if statErr == nil && f.IsDir() { - flat, reportErr := runGitHistoryReport(args[0], args[1], opts, breakingConfig) - if reportErr != nil { - return reportErr - } - if flat == nil { - printNoChangesJSON() - return nil - } - if reproducible { - makeReportOutputReproducible(flat) - } - return printReportJSON(flat) + if flat == nil { + printNoChangesJSON() + return nil } - if _, _, ok := parseGitRef(args[1]); ok { - return printReportJSONOrNoChanges(args, opts, breakingConfig, reproducible) + if reproducible { + makeReportOutputReproducible(flat) } + return printReportJSON(flat) } return printReportJSONOrNoChanges(args, opts, breakingConfig, reproducible) diff --git a/cmd/report_common.go b/cmd/report_common.go index 951457f..e214c80 100644 --- a/cmd/report_common.go +++ b/cmd/report_common.go @@ -20,9 +20,12 @@ func createReport(commit *model.Commit) *model.Report { } summary := make(map[string]*reports.Changed) for _, change := range commit.AllChanges().GetAllChanges() { - name := strings.TrimPrefix(change.Path, "$.") - if i := strings.IndexAny(name, ".["); i >= 0 { - name = name[:i] + name := change.SchemaResource + if name == "" { + name = strings.TrimPrefix(change.Path, "$.") + if i := strings.IndexAny(name, ".["); i >= 0 { + name = name[:i] + } } if summary[name] == nil { summary[name] = &reports.Changed{} diff --git a/cmd/root.go b/cmd/root.go index 158aeba..6366c7d 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -19,9 +19,9 @@ var ( rootCmd = &cobra.Command{ SilenceUsage: true, Use: "openapi-changes", - Short: "Detect and explore changes between OpenAPI and AsyncAPI specifications.", - Long: `openapi-changes detects changes within OpenAPI or AsyncAPI 3.x specifications. - it can compare between two files, or a single file, over time. + Short: "Compare OpenAPI, AsyncAPI and JSON Schema documents.", + Long: `Compare OpenAPI, AsyncAPI 3.x and JSON Schema Draft 2020-12 documents. + Supply two files or compare revisions of a file in Git. The comparison and reporting commands use the current doctor-based engine.`, RunE: func(cmd *cobra.Command, args []string) error { @@ -74,6 +74,7 @@ func init() { rootCmd.AddCommand(GetReportCommand()) rootCmd.AddCommand(GetSummaryCommand()) rootCmd.AddCommand(GetVersionCommand()) + rootCmd.PersistentFlags().Bool("schema", false, "Compare JSON Schema Draft 2020-12 inputs, including unmarked schemas and directory collections") rootCmd.PersistentFlags().BoolP("top", "t", false, "Only show latest changes (last git revision against HEAD)") rootCmd.PersistentFlags().IntP("limit", "l", 5, "Limit history to number of revisions (default is 5)") rootCmd.PersistentFlags().BoolP("global-revisions", "R", false, "Consider all revisions in limit, not just the ones for the file") diff --git a/cmd/schema_collection_test.go b/cmd/schema_collection_test.go new file mode 100644 index 0000000..9d8dff8 --- /dev/null +++ b/cmd/schema_collection_test.go @@ -0,0 +1,221 @@ +// Copyright 2026 Princess Beef Heavy Industries, LLC / Dave Shanley +// SPDX-License-Identifier: Apache-2.0 + +package cmd + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "strings" + "testing" + + tea "charm.land/bubbletea/v2" + "github.com/charmbracelet/x/ansi" + v3 "github.com/pb33f/doctor/model/high/v3" + wc "github.com/pb33f/libopenapi/what-changed/model" + "github.com/pb33f/openapi-changes/model" + tui "github.com/pb33f/openapi-changes/tui/v2" + "github.com/pb33f/testify/require" +) + +const collectionFixture = "../sample-specs/json-schema/collections/" + +func TestSchemaCollectionAcrossCommands(t *testing.T) { + before, after := collectionFixture+"before", collectionFixture+"after" + const money = "https://schemas.example.test/money" + report := testRootCmd(GetReportCommand(), "--schema", "--reproducible", before, after) + data := captureStdout(t, func() { require.NoError(t, report.Execute()) }) + var flat model.FlatReport + require.NoError(t, json.Unmarshal([]byte(data), &flat)) + require.Nil(t, flat.Commit) + require.Len(t, flat.Changes, 1) + change := flat.Changes[0] + require.Equal(t, money, change.SchemaResource) + require.Equal(t, "$.properties.currency.minLength", change.Path) + require.Equal(t, "2", change.Original) + require.Equal(t, "3", change.New) + require.Equal(t, 1, flat.Summary[money].Breaking) + require.Equal(t, "money.json", change.Context.ModifiedDocument) + require.Equal(t, 9, *change.Context.NewLine) + summary := testRootCmd(GetSummaryCommand(), "--schema", "--no-logo", "--no-color", "--with-lines", before, after) + rendered := captureStdout(t, func() { require.ErrorContains(t, summary.Execute(), "breaking changes discovered") }) + require.Contains(t, rendered, "Money") + require.Contains(t, rendered, "minLength") + reverse := testRootCmd(GetSummaryCommand(), "--schema", "--no-logo", "--error-on-diff", after, before) + captureStdout(t, func() { require.ErrorContains(t, reverse.Execute(), "differences discovered") }) + + dir := t.TempDir() + md, outcome := filepath.Join(dir, "report.md"), filepath.Join(dir, "result.json") + compact := testRootCmd(GetMarkdownReportCommand(), "--schema", "--compact", "--report-file", md, "--result-file", outcome, before, after) + captureStdout(t, func() { require.NoError(t, compact.Execute()) }) + counts, err := os.ReadFile(outcome) + require.NoError(t, err) + require.JSONEq(t, `{"total":1,"breaking":1}`, string(counts)) + commits, err := loadCommitsFromArgs([]string{before, after}, summaryOpts{schema: true}, nil) + require.NoError(t, err) + require.Len(t, commits, 1) + t.Cleanup(func() { releaseDirectInputs(commits[0]) }) + markdown, err := generateMarkdownReport(commits, nil, true) + require.NoError(t, err) + require.Contains(t, string(markdown), "Money") + require.Contains(t, string(markdown), "--- money.json\n+++ money.json") + require.NotContains(t, string(markdown), "--- invoice.json") + items, err := buildHTMLReportItems(commits, nil) + require.NoError(t, err) + require.Len(t, items, 1) + item := items[0] + require.Equal(t, 1, item.Summary.TotalChanges) + require.Equal(t, 1, item.Summary.BreakingChanges) + require.Len(t, item.ModifiedSources, 3) + require.Contains(t, item.ModifiedSources["money.json"], `"minLength": 3`) + for _, raw := range []json.RawMessage{item.Graph.Edges, item.ExplorerGraph.Edges} { + var edges []v3.Edge + require.NoError(t, json.Unmarshal(raw, &edges)) + var references []v3.Edge + for _, e := range edges { + if e.Ref == money { + references = append(references, e) + } + } + require.Len(t, references, 2) + require.Equal(t, references[0].Targets, references[1].Targets) + require.NotEqual(t, references[0].Sources, references[1].Sources) + } + view := openSchemaConsoleChange(t, commits, false) + require.Contains(t, view, "RECENTER") + require.Regexp(t, `9[│ ┃]*"minLength": 3`, view) +} + +func openSchemaConsoleChange(t *testing.T, commits []*model.Commit, last bool) string { + t.Helper() + var console tea.Model = tui.NewConsoleModel(commits, nil, false, "", bridgeRunChangerator) + console, _ = console.Update(tea.WindowSizeMsg{Width: 140, Height: 44}) + key := tea.KeyHome + if last { + key = tea.KeyEnd + } + console, _ = console.Update(tea.KeyPressMsg{Code: key}) + console, _ = console.Update(tea.KeyPressMsg{Code: tea.KeyEnter}) + view := ansi.Strip(console.View().Content) + console, _ = console.Update(tea.KeyPressMsg{Code: tea.KeyEscape}) + _, quit := console.Update(tea.KeyPressMsg{Code: 'q', Text: "q"}) + require.NotNil(t, quit) + require.IsType(t, tea.QuitMsg{}, quit()) + return view +} + +func TestSchemaCollectionCandidatesAndIdentity(t *testing.T) { + before, after := t.TempDir(), t.TempDir() + for i, dir := range []string{after, before} { + for _, file := range []string{"deeper/second.YML", "first.YAML"} { + writeSchemaFile(t, dir, file, fmt.Sprintf("title: %s\nminLength: %d\n", filepath.Base(file), 3-i)) + } + writeSchemaFile(t, dir, ".git/ignored.json", "[") + writeSchemaFile(t, dir, "readme.txt", "[") + require.NoError(t, os.Symlink(filepath.Join(dir, "deeper"), filepath.Join(dir, "linked"))) + require.NoError(t, os.Symlink(filepath.Join(dir, ".git/ignored.json"), filepath.Join(dir, "linked.json"))) + } + opts := summaryOpts{schema: true} + flat, err := runLeftRightReport(before, after, opts, nil) + require.NoError(t, err) + require.Len(t, flat.Changes, 2) + a, b := flat.Changes[0], flat.Changes[1] + require.Equal(t, a.Path, b.Path) + require.Equal(t, *a.Context.NewLine, *b.Context.NewLine) + require.Equal(t, *a.Context.NewColumn, *b.Context.NewColumn) + require.NotEqual(t, a.ChangeHash, b.ChangeHash) + require.Equal(t, "deeper/second.YML", a.SchemaResource) + require.Equal(t, "first.YAML", b.SchemaResource) + changes := []*wc.Change{a.Change, b.Change} + grouped := buildElementSummaries(changes, map[string]string{a.SchemaResource: "Price", b.SchemaResource: "Price"}) + require.Equal(t, "Price (deeper/second.YML)", grouped[0].name) + require.Equal(t, "Price (first.YAML)", grouped[1].name) + commits, err := loadLeftRightCommits(before, after, opts) + require.NoError(t, err) + t.Cleanup(func() { releaseDirectInputs(commits[0]) }) + body, err := generateMarkdownReport(commits, nil, true) + require.NoError(t, err) + require.Equal(t, 2, strings.Count(string(body), "\n+++ ")) + require.Contains(t, string(body), "+++ deeper/second.YML") + require.Contains(t, string(body), "+++ first.YAML") + first, last := openSchemaConsoleChange(t, commits, false), openSchemaConsoleChange(t, commits, true) + require.Contains(t, first, "second.YML") + require.Contains(t, last, "first.YAML") + require.NotEqual(t, first, last) +} + +func TestSchemaCollectionEmptyAndInvalidMembers(t *testing.T) { + empty, other, members := t.TempDir(), t.TempDir(), t.TempDir() + opts := summaryOpts{schema: true} + flat, err := runLeftRightReport(empty, other, opts, nil) + require.NoError(t, err) + require.Nil(t, flat) + cmd := testRootCmd(GetSummaryCommand(), "--schema", "--no-logo", empty, other) + none := captureStdout(t, func() { require.NoError(t, cmd.Execute()) }) + require.Contains(t, strings.ToLower(none), "no changes found") + require.NotContains(t, none, "prior comparable") + mdPath, resultPath := filepath.Join(t.TempDir(), "compact.md"), filepath.Join(t.TempDir(), "result.json") + cmd = testRootCmd(GetMarkdownReportCommand(), "--schema", "--compact", "--no-logo", "--report-file", mdPath, "--result-file", resultPath, empty, other) + captureStdout(t, func() { require.NoError(t, cmd.Execute()) }) + counts, err := os.ReadFile(resultPath) + require.NoError(t, err) + require.JSONEq(t, `{"total":0,"breaking":0}`, string(counts)) + writeSchemaFile(t, members, "resource.json", `{"title":"ArchivedSchema","type":"integer"}`) + flat, err = runLeftRightReport(empty, members, opts, nil) + require.NoError(t, err) + require.Len(t, flat.Changes, 1) + require.False(t, flat.Changes[0].Breaking) + commits, err := loadLeftRightCommits(members, empty, opts) + require.NoError(t, err) + t.Cleanup(func() { releaseDirectInputs(commits[0]) }) + require.Contains(t, openSchemaConsoleChange(t, commits, false), "ArchivedSchema") + body, err := generateMarkdownReport(commits, nil, true) + require.NoError(t, err) + require.Contains(t, string(body), "--- resource.json\n+++ /dev/null") + writeSchemaFile(t, members, "bad.yaml", "type: [") + _, err = runLeftRightReport(empty, members, opts, nil) + require.ErrorContains(t, err, "modified") + require.ErrorContains(t, err, "bad.yaml") + writeSchemaFile(t, members, "bad.yaml", "$id: urn:duplicate") + writeSchemaFile(t, members, "resource.json", `{"$id":"urn:duplicate"}`) + _, err = runLeftRightReport(empty, members, opts, nil) + require.ErrorContains(t, err, "urn:duplicate") +} + +func TestSchemaCollectionModePreservesNamedFileHistory(t *testing.T) { + left, right := t.TempDir(), t.TempDir() + require.Equal(t, schemaDirectories, comparisonMode([]string{left, right}, true)) + require.Equal(t, localHistory, comparisonMode([]string{left, right}, false)) + require.Equal(t, localHistory, comparisonMode([]string{left, "schemas/customer.json"}, true)) + require.Equal(t, githubHistory, comparisonMode([]string{"https://github.com/owner/repo/blob/main/schema.json"}, true)) + require.Equal(t, directInputs, comparisonMode([]string{"HEAD~1:schema.json", "HEAD:schema.json"}, true)) + _, err := loadCommitsFromArgs([]string{left, right}, summaryOpts{}, nil) + require.ErrorContains(t, err, "are both directories; pass --schema") +} + +func TestSchemaDirectorySkipsToolingAndExplainsStrayFiles(t *testing.T) { + before, after := t.TempDir(), t.TempDir() + opts := summaryOpts{schema: true} + for dir, value := range map[string]string{before: "2", after: "3"} { + writeSchemaFile(t, dir, "money.json", `{"minLength":`+value+`}`) + writeSchemaFile(t, dir, "node_modules/dep/package.json", `{"version":"`+value+`.0.0"}`) + writeSchemaFile(t, dir, ".github/workflows/ci.yml", "on: push\nretries: "+value+"\n") + } + flat, err := runLeftRightReport(before, after, opts, nil) + require.NoError(t, err) + require.Len(t, flat.Changes, 1) + require.Equal(t, "money.json", flat.Changes[0].SchemaResource) + + stray := writeSchemaFile(t, after, "package.json", `{"dependencies":{"a":"1"}}`) + _, err = runLeftRightReport(before, after, opts, nil) + require.ErrorContains(t, err, "package.json does not look like a JSON Schema") + require.ErrorContains(t, err, "move it out of the directory") + + require.NoError(t, os.Remove(stray)) + writeSchemaFile(t, after, "order.json", `{"$ref":"missing.json"}`) + _, err = runLeftRightReport(before, after, opts, nil) + require.ErrorContains(t, err, "missing.json") + require.NotContains(t, err.Error(), "does not look like") +} diff --git a/cmd/summary.go b/cmd/summary.go index 5421842..2f94a0e 100644 --- a/cmd/summary.go +++ b/cmd/summary.go @@ -49,7 +49,7 @@ type elementSummary struct { breaking int } -func buildElementSummaries(changes []*whatChangedModel.Change) []elementSummary { +func buildElementSummaries(changes []*whatChangedModel.Change, labels map[string]string) []elementSummary { if len(changes) == 0 { return nil } @@ -64,6 +64,9 @@ func buildElementSummaries(changes []*whatChangedModel.Change) []elementSummary continue } name := summarizeTopLevelElement(change.Path) + if change.SchemaResource != "" { + name = change.SchemaResource + } if name == "" { name = "document" } @@ -76,8 +79,20 @@ func buildElementSummaries(changes []*whatChangedModel.Change) []elementSummary } } + labelCount := make(map[string]int) + if len(labels) > 0 { + for id := range grouped { + labelCount[labels[id]]++ + } + } summaries := make([]elementSummary, 0, len(grouped)) for name, stats := range grouped { + if label := labels[name]; label != "" && label != name { + if labelCount[label] > 1 { + label += " (" + name + ")" + } + name = label + } summaries = append(summaries, elementSummary{name: name, total: stats.total, breaking: stats.breaking}) } sort.Slice(summaries, func(i, j int) bool { @@ -369,7 +384,7 @@ func renderSummaryWithTheme( } sb.WriteString(renderDedupedCountsNote(markdown, styles)) - sb.WriteString(renderElementSummaryTable(buildElementSummaries(deduplicatedChanges), markdown, styles)) + sb.WriteString(renderElementSummaryTable(buildElementSummaries(deduplicatedChanges, result.Changerator.SchemaLabels), markdown, styles)) counts := changecounts.FromChanges(deduplicatedChanges) breaking := counts.Breaking @@ -487,16 +502,14 @@ func GetSummaryCommand() *cobra.Command { if input == nil { return nil } + defer input.releaseDirectInputs() input.Opts.markdown, _ = cmd.Flags().GetBool("markdown") input.Opts.errorOnDiff, _ = cmd.Flags().GetBool("error-on-diff") styles := summaryStylesForPalette(input.Opts.palette) - if len(input.Commits) == 0 && len(args) == 2 { - firstArgInfo, statErr := os.Stat(args[0]) - if statErr == nil && firstArgInfo.IsDir() { - printNoPriorVersionText() - return nil - } + if len(input.Commits) == 0 && comparisonMode(args, input.Opts.schema) == localHistory { + printNoPriorVersionText() + return nil } output, hasBreaking, hasChanges, renderErr := renderSummaryWithTheme( diff --git a/git/github.go b/git/github.go index 0269e7b..e5c108f 100644 --- a/git/github.go +++ b/git/github.go @@ -124,10 +124,13 @@ func ProcessGithubRepoDetailed(username, repo, filePath string, } svc := newGitHubService() - config := doctorgithub.DefaultSessionConfig() - config.Timeout = 60 * time.Second + newSession := func() *doctorgithub.GitHubSession { + config := doctorgithub.DefaultSessionConfig() + config.Timeout = 60 * time.Second + return svc.CreateSessionWithOptionalToken(os.Getenv(GithubToken), config) + } - session := svc.CreateSessionWithOptionalToken(os.Getenv(GithubToken), config) + session := newSession() if session == nil { err := errors.New("failed to create GitHub session") model.SendProgressError("git", err.Error(), errorChan) @@ -158,12 +161,11 @@ func ProcessGithubRepoDetailed(username, repo, filePath string, fmt.Sprintf("fetched %d github revisions", len(revisions)), true, progressChan) opts.ReadRevision = func(_, revision, path string) ([]byte, error) { - service := newGitHubService() - files, ok := service.(doctorgithub.FileService) + files, ok := svc.(doctorgithub.FileService) if !ok { return nil, fmt.Errorf("GitHub service cannot read revision references") } - session := service.CreateSessionWithOptionalToken(os.Getenv(GithubToken), config) + session := newSession() if session == nil { return nil, fmt.Errorf("failed to create GitHub reference session") } diff --git a/git/history_sources.go b/git/history_sources.go index d10ec34..f86891d 100644 --- a/git/history_sources.go +++ b/git/history_sources.go @@ -43,7 +43,7 @@ func buildHistorySources(commits []*model.Commit, opts HistoryOptions) (*History base.IgnorePolymorphicCircularReferences = true window := new(model.HistoryWindow) makeSource := func(data []byte, revision string) *model.HistorySource { - return &model.HistorySource{Data: data, Revision: revision, Config: func() (*datamodel.DocumentConfiguration, error) { + return &model.HistorySource{Schema: opts.Schema, SchemaBasePath: basePath, Data: data, Revision: revision, Config: func() (*datamodel.DocumentConfiguration, error) { if context != nil { return BuildRevisionDocumentConfiguration(context, revision, base) } @@ -75,7 +75,7 @@ func buildHistorySources(commits []*model.Commit, opts HistoryOptions) (*History break } candidate := makeSource(bits, revision) - _, _, release, err := window.Acquire(candidate) + _, release, err := window.AcquireInput(candidate) if err != nil { continue } diff --git a/git/options.go b/git/options.go index 7ff4c1e..ef96afc 100644 --- a/git/options.go +++ b/git/options.go @@ -9,6 +9,7 @@ import "github.com/pb33f/openapi-changes/model" // BreakingConfig is intentionally kept as a separate parameter in function // signatures — it controls comparison semantics, not history traversal. type HistoryOptions struct { + Schema bool ReadRevision func(repo, revision, path string) ([]byte, error) // optional hosted revision reader Lazy bool // prepare sources now and retain only the active model window Base string diff --git a/git/schema_history_test.go b/git/schema_history_test.go new file mode 100644 index 0000000..84f4af5 --- /dev/null +++ b/git/schema_history_test.go @@ -0,0 +1,65 @@ +// Copyright 2026 Princess Beef Heavy Industries, LLC / Dave Shanley +// SPDX-License-Identifier: Apache-2.0 + +package git + +import ( + "context" + "fmt" + "testing" + "time" + + doctorgithub "github.com/pb33f/doctor/github" + "github.com/pb33f/libopenapi/jsonschema" + "github.com/pb33f/testify/require" +) + +type schemaFileHistory struct { + stubGitHubService + doctorgithub.FileService + requests map[string][]string +} + +func (s *schemaFileHistory) GetFileContent(_ context.Context, _ *doctorgithub.GitHubSession, owner, repo, path, ref string) (*doctorgithub.FileContent, error) { + s.requests[ref] = append(s.requests[ref], owner+"/"+repo+"/"+path) + switch ref { + case "a0a0a0": + return &doctorgithub.FileContent{Content: "minLength: 2\n"}, nil + case "b1b1b1": + return &doctorgithub.FileContent{Content: "minLength: 3\n"}, nil + default: + return nil, fmt.Errorf("unexpected revision %q", ref) + } +} + +func TestGitHubSchemaHistoryReadsSiblingFromOwningRevision(t *testing.T) { + factory := newGitHubService + t.Cleanup(func() { newGitHubService = factory }) + initial, latest := "a0a0a0", "b1b1b1" + data := []byte("$ref: money.yaml\n") + mock := &schemaFileHistory{requests: make(map[string][]string)} + mock.createSessionWithOptionalToken = func(_ string, cfg *doctorgithub.SessionConfig) *doctorgithub.GitHubSession { + return doctorgithub.NewAnonymousGitHubSession(cfg) + } + mock.getFileHistory = func(_ context.Context, _ *doctorgithub.GitHubSession, owner, repo, path string, _ *doctorgithub.FileHistoryOptions) ([]*doctorgithub.FileRevision, error) { + require.Equal(t, "schemas/customer.yaml", path) + return []*doctorgithub.FileRevision{makeDoctorRevision(latest, "tighten", time.Now(), data), makeDoctorRevision(initial, "original", time.Now().Add(-time.Hour), data)}, nil + } + newGitHubService = func() githubHistoryService { return mock } + ch, errsCh := progressChans() + result, errs := ProcessGithubRepoDetailed("owner", "repo", "schemas/customer.yaml", ch, errsCh, HistoryOptions{Schema: true, Lazy: true, LimitTime: -1}, nil) + require.Empty(t, errs) + require.Len(t, result.Commits, 2) + t.Cleanup(result.Commits[0].Window.Close) + commit, release, err := result.Commits[0].PrepareHistory() + require.NoError(t, err) + defer release() + diff, err := jsonschema.Compare(commit.OldSchemaDocument, commit.SchemaDocument, nil) + require.NoError(t, err) + require.NotNil(t, diff) + require.Len(t, diff.GetAllChanges(), 1) + change := diff.GetAllChanges()[0] + require.Equal(t, "2", change.Original) + require.Equal(t, "3", change.New) + require.Equal(t, map[string][]string{initial: {"owner/repo/schemas/money.yaml"}, latest: {"owner/repo/schemas/money.yaml"}}, mock.requests) +} diff --git a/go.mod b/go.mod index d1f236b..01d3bda 100644 --- a/go.mod +++ b/go.mod @@ -9,15 +9,16 @@ require ( charm.land/lipgloss/v2 v2.0.6 github.com/alecthomas/chroma/v2 v2.27.0 github.com/araddon/dateparse v0.0.0-20210429162001-6b43995a97de + github.com/buger/jsonparser v1.6.1 github.com/charmbracelet/colorprofile v0.4.3 github.com/charmbracelet/x/ansi v0.11.9 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.88 - github.com/pb33f/go-yaml v0.1.1 + github.com/pb33f/doctor v0.0.90-0.20261126200916-3c7eb54b1d55 + github.com/pb33f/go-yaml v0.2.0 github.com/pb33f/libasyncapi v0.0.7 - github.com/pb33f/libopenapi v0.42.6-0.20261114224705-db27aae96380 + github.com/pb33f/libopenapi v0.44.1-0.20261126200719-18eb8107c9d0 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 @@ -29,7 +30,6 @@ require ( github.com/a-h/templ v0.3.1070 // indirect github.com/aymerick/douceur v0.2.0 // indirect github.com/bahlo/generic-list-go v0.2.0 // indirect - github.com/buger/jsonparser v1.6.1 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/charmbracelet/harmonica v0.2.0 // indirect github.com/charmbracelet/ultraviolet v0.0.0-20261008173134-6b8d4baf91b4 // indirect diff --git a/go.sum b/go.sum index eb19a2d..4074b7f 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.88 h1:4hX+P2jxFyF/lfGKw9imOUC2c44exVYDcD5T6r6Zq4I= -github.com/pb33f/doctor v0.0.88/go.mod h1:kFgQgvAm9ESjpaQAzyn82NzQpqpM+zwjZdovS2IeX/Q= -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/doctor v0.0.90-0.20261126200916-3c7eb54b1d55 h1:XqVckMXQIBbjBtNdPH7o0DUp/6wtig7EUhhUXvSbiqo= +github.com/pb33f/doctor v0.0.90-0.20261126200916-3c7eb54b1d55/go.mod h1:TLCxdC54h68wiDM+H4XTAcHoOG7LG1a196b+NPIfZLY= +github.com/pb33f/go-yaml v0.2.0 h1:t9fYMVk2BGlBIu6L07gryB+gOWt8rjEJO7e/jdBSqCo= +github.com/pb33f/go-yaml v0.2.0/go.mod h1:QvWdkHP5VjFYAeHMQUkaPQqREaQnBNOXmWzAjNrnSdo= github.com/pb33f/jsonpath v0.8.5 h1:wsbwJbz6MPUTy5fAtiIlOyQb3oblaa5M7qjtdz6orPw= github.com/pb33f/jsonpath v0.8.5/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.7 h1:0CTUZwjQm4Fya6Znb7q/1kBWvp/92v5CaB9T55zJMiA= github.com/pb33f/libasyncapi v0.0.7/go.mod h1:OcM42Lo3J4F9Tz55RZIOxcAubOv1BGRg9gy8Sp36skk= -github.com/pb33f/libopenapi v0.42.6-0.20261114224705-db27aae96380 h1:KZ9Ezi5+sBKrzD3PUIMnCw3vtF1NoW98DmFx2sYJ2lk= -github.com/pb33f/libopenapi v0.42.6-0.20261114224705-db27aae96380/go.mod h1:fzngW6SBMO7ggf7prvQlEB3qY6Rqu5dTGMbUZcy4Ybg= +github.com/pb33f/libopenapi v0.44.1-0.20261126200719-18eb8107c9d0 h1:lUcE10S2w8hrmcu7KPqjvKHcubrcsUfxFQfL9Ic2vVQ= +github.com/pb33f/libopenapi v0.44.1-0.20261126200719-18eb8107c9d0/go.mod h1:jp2ZQ3ZpilsMDSwhPSFgwlq0+xvrYE3+9mjS/rYNDDo= 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/html-report/generator.go b/html-report/generator.go index 53c4663..d53948a 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,19 @@ 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"` + // Highlighted lines for each extra source, keyed like the source maps. + OriginalSourcesHighlighted map[string]map[int]string `json:"originalSourcesHighlighted,omitempty"` + ModifiedSourcesHighlighted map[string]map[int]string `json:"modifiedSourcesHighlighted,omitempty"` +} + +// highlightSources highlights every extra source under its own name. +func highlightSources(sources map[string]string) map[string]map[int]string { + highlighted := make(map[string]map[int]string, len(sources)) + for name, text := range sources { + highlighted[name] = highlightSpecLines(text) + } + return highlighted } // highlightSpecLines uses Chroma to syntax-highlight each line of a spec, @@ -171,7 +185,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 +270,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, @@ -271,8 +286,10 @@ func BuildReportItem( if rightDrDoc != nil { graphMap = rightDrDoc.BuildGraphMap() } else { + // The map is keyed by line alone, so only the root file can use it. + // A collection has no root and gets no line-to-node lookup. 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 +314,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,12 +335,16 @@ 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, } + item.OriginalSourcesHighlighted = highlightSources(item.OriginalSources) + item.ModifiedSourcesHighlighted = highlightSources(item.ModifiedSources) return item, nil } @@ -381,6 +405,7 @@ func buildChangeExplorerGraph( rootCopy := cloneNodeTree(rootNode) changeResult := changerator.NewChangerator(result.Config) + changeResult.ChangedEdges = result.ChangedEdges changeResult.PrepareChangeViewGraph(rootCopy) filteredEdges := filterEdgesForNodes(result.ChangedEdges, changeResult.ChangedNodes) drModel.SanitizeGraph(changeResult.ChangedNodes, nil) @@ -459,6 +484,11 @@ func cloneNodeTree(node *v3.Node) *v3.Node { } func buildCommitInfo(commit *model.Commit) *CommitInfo { + // Only native schema reports drop the synthetic commit. Direct OpenAPI and + // AsyncAPI reports keep theirs, because their payload contract is unchanged. + 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 +502,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..27e829a 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,116 @@ 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.Contains(t, item.OriginalSourcesHighlighted["money.yaml"][1], "minLength") + require.Contains(t, item.ModifiedSourcesHighlighted["money.yaml"][1], "minLength") + 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 TestCollectionReportKeepsBothReferencesToMovedSchemaWithRemovedConstraint(t *testing.T) { + load := func(name, money string) *jsonschema.Document { + doc, err := jsonschema.LoadCollection(map[string][]byte{ + "order.yaml": []byte("title: Order\nproperties:\n total:\n $ref: urn:money\n"), + "invoice.yaml": []byte("title: Invoice\nproperties:\n amount:\n $ref: urn:money\n"), + name: []byte(money), + }, t.TempDir(), nil) + require.NoError(t, err) + t.Cleanup(doc.Release) + return doc + } + const money = "$id: urn:money\ntitle: Money\nproperties:\n currency:\n type: string\n" + left, right := load("a/money.yaml", money+" minLength: 3\n"), load("b/money.yaml", money) + result, err := changerator.CompareJSONSchema(left, right, nil) + require.NoError(t, err) + require.NotNil(t, result) + t.Cleanup(result.Release) + commit := &model.Commit{ + Synthetic: true, Specification: &model.ComparisonSpecification{Kind: "jsonschema"}, + 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.Removals) + require.Empty(t, item.OriginalSpec) + require.Empty(t, item.ModifiedSpec) + require.Len(t, item.OriginalSources, 3) + require.Len(t, item.ModifiedSources, 3) + require.Len(t, item.OriginalSourcesHighlighted, 3) + require.Len(t, item.ModifiedSourcesHighlighted, 3) + require.Equal(t, money+" minLength: 3\n", item.OriginalSources["a/money.yaml"]) + require.Equal(t, money, item.ModifiedSources["b/money.yaml"]) + + for _, graph := range []*GraphData{item.Graph, item.ExplorerGraph} { + require.NotNil(t, graph) + type graphNode struct { + ID, Label, Origin string + Timeline []*whatChangedModel.Change + } + var nodes []graphNode + require.NoError(t, json.Unmarshal(graph.Nodes, &nodes)) + byID := make(map[string]graphNode, len(nodes)) + var edits []*whatChangedModel.Change + for _, node := range nodes { + byID[node.ID] = node + edits = append(edits, node.Timeline...) + } + require.Equal(t, "Schemas", byID["root"].Label) + require.Len(t, edits, 1) + require.Equal(t, "a/money.yaml", edits[0].Context.OriginalDocument) + require.Equal(t, "b/money.yaml", edits[0].Context.ModifiedDocument) + require.Equal(t, 6, *edits[0].Context.OriginalLine) + require.Nil(t, edits[0].Context.NewLine) + var edges []v3.Edge + require.NoError(t, json.Unmarshal(graph.Edges, &edges)) + var uses []string + for _, edge := range edges { + if edge.Ref == "urn:money" { + require.Len(t, edge.Sources, 1) + require.Len(t, edge.Targets, 1) + use := byID[edge.Sources[0]] + require.Empty(t, use.Timeline) + require.Equal(t, "Money", byID[edge.Targets[0]].Label) + uses = append(uses, use.Origin) + } + } + require.ElementsMatch(t, []string{"order.yaml", "invoice.yaml"}, uses) + } +} + 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 - + - +