diff --git a/CHANGELOG.md b/CHANGELOG.md index 9cb6e8ac9e..414256c5d3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,9 +7,11 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ## [Unreleased] ### Added +- **`mxcli diff --format json`** — prints the report as one JSON document (`refused`, `preflight`, `execError`, `failures`, `units`, `documents`, `files`, `summary`) for a tool that has to decide on the result without parsing the diff. A script exec would refuse reports `refused` and `summary.writesNothing: true`. - **`check` and `lint` flag a decision captioned with its whole condition** (ako/mxcli#2685) — Studio Pro draws a decision's caption inside the diamond, and an `if` with no `@caption` was captioned with its full condition, so `$Stints != empty and length($Stints/json) >= 2` wrapped mid-token there and repeated the Expression field. `check` now reports an `if` or `elsif` with no `@caption` whose condition uses `and`/`or` or is longer than 40 characters (MDL-CAPTION01, info), and lint rule CONV012 reports a stored decision captioned with such a condition. A short single test is still its own caption, and `@caption ''` is not reported. The write-microflows skill and `mxcli syntax microflow.control-flow` now tell authors to caption decisions with a short phrase (`@caption 'Has stints?'`). ### Changed +- **`mxcli diff` copies, hashes and cleans up in parallel, and leaves out `packages/`** — diff spent most of its time copying the project one file at a time, hashing the files next to the model and then removing the scratch folder one file at a time. The copy of regular files and the hashing now run on a pool of workers, and the first three levels of the scratch folder are removed in parallel. `packages/` (deployment packages exported by Studio Pro, which exec never reads or writes) joins the directories the scratch copy leaves out. `MXCLI_DIFF_TIMING=1` prints the time of each stage to stderr. Measured on a project of about 3 thousand units (about 430 MB outside the skipped directories) on Windows: a one-statement script went from about 31 s to about 13 s, with the same report on the scripts tried. - **A pluggable widget's association is written `Association:`, the one spelling** (ako/mxcli#2709, upstream mendixlabs/mxcli#1995) — a combo box (or drop-down filter) bound to an association was accepted as `Attribute:` too. `describe` printed that spelling, and `check` then warned that the association was unset (MDL-WIDGET56, CE0642) on every round trip, although `exec` wrote it and the build accepted it. `describe` now prints `Association:`. **Breaking:** `check` and `exec` refuse `Attribute:` naming the association a widget's mode binds (MDL-WIDGET57), with a message naming the rewrite. The MDL-WIDGET56 hint names the MDL keyword (`set Association:`) instead of the widget's internal property name. `Association: $Param.Module.Assoc` now works without the old alias. - **An error handler ending in an `if` with one terminating branch rejoins after the failing activity** (ako/mxcli#2733, upstream mendixlabs/mxcli#2007) — if one branch ended in `raise error` or `return` and the other did not, the other branch was wired back in front of the guarded activity. The activity then ran again for as long as it kept failing, and `check`, `exec` and `mx check` reported nothing. The handler now continues at the statement after the activity, as the syntax help says and as it already did with any statement after the `end if`. **Breaking:** a script that relied on the implicit loop now builds a handler that carries on. Write the retry explicitly with `merge attempt;` before the activity and `join attempt;` in the branch, which is what `describe` prints for a retry loop. diff --git a/cmd/mxcli/cmd_diff.go b/cmd/mxcli/cmd_diff.go index 3e7de74ae8..fbce1c99be 100644 --- a/cmd/mxcli/cmd_diff.go +++ b/cmd/mxcli/cmd_diff.go @@ -35,12 +35,14 @@ the first error (--continue-on-error runs every statement). A script exec would refuse, or a statement it would stop at, is reported as Refused. The project itself is only read. The scratch copy leaves out .git, deployment, -releases and node_modules, and is deleted afterwards. +releases, packages and node_modules, and is deleted afterwards. Output Formats: unified - Traditional unified diff format (default) side - Side-by-side comparison struct - Structural changes summary + json - One JSON document: refused, preflight, execError, units, documents, + files and summary (see docs-site/src/tools/diff.md) Examples: # Unified diff (default) @@ -54,6 +56,9 @@ Examples: # With color output mxcli diff -p app.mpr changes.mdl --color + + # For a tool: the report as JSON + mxcli diff -p app.mpr changes.mdl --format json `, Args: cobra.ExactArgs(1), Run: func(cmd *cobra.Command, args []string) { @@ -67,7 +72,7 @@ Examples: continueOnError, _ := cmd.Flags().GetBool("continue-on-error") showExecOutput, _ := cmd.Flags().GetBool("exec-output") depPolicy := deprecationPolicy(cmd) - refuseJSONFlag("diff", "--format unified|side|struct") + refuseJSONFlag("diff", "--format unified|side|struct|json") if projectPath == "" { fmt.Fprintln(os.Stderr, "Error: --project (-p) is required") @@ -115,6 +120,13 @@ Examples: fmt.Fprintf(os.Stderr, "Error: %v\n", err) os.Exit(1) } + if format == "json" { + if err := report.WriteJSON(os.Stdout); err != nil { + fmt.Fprintf(os.Stderr, "Error: %v\n", err) + os.Exit(1) + } + return + } report.Write(os.Stdout, executor.DiffOptions{ Format: executor.DiffFormat(format), UseColor: useColor, diff --git a/cmd/mxcli/main.go b/cmd/mxcli/main.go index c4c36f9eed..132b41c644 100644 --- a/cmd/mxcli/main.go +++ b/cmd/mxcli/main.go @@ -460,7 +460,7 @@ func init() { "Check syntax and the no-model rules only: do not auto-detect the .mpr in the current directory (conflicts with -p, --references, --post-migration)") // Diff command flags - diffCmd.Flags().StringP("format", "f", "unified", "Output format: unified, side, struct") + diffCmd.Flags().StringP("format", "f", "unified", "Output format: unified, side, struct, json") diffCmd.Flags().BoolP("color", "", false, "Use colored output") diffCmd.Flags().IntP("width", "w", 120, "Terminal width for side-by-side format") diffCmd.Flags().Bool("no-check", false, "Skip exec's pre-flight checks, as exec --no-check does") diff --git a/docs-site/src/tools/diff.md b/docs-site/src/tools/diff.md index b2af742c38..eb517ebf5d 100644 --- a/docs-site/src/tools/diff.md +++ b/docs-site/src/tools/diff.md @@ -21,7 +21,7 @@ script's language header — and then compares the copy with the project unit by unit. What it reports is therefore exactly what `exec` would write: there is no second judgement to disagree with exec's. The project itself is only read, and the scratch copy is deleted afterwards (it leaves out `.git`, `deployment`, -`releases` and `node_modules`). +`releases`, `packages` and `node_modules`). The copy, the hashing of the files next to the model and the cleanup run in parallel; set `MXCLI_DIFF_TIMING=1` to print the time of each stage to stderr. Each unit exec would add, rewrite, move or remove is shown as the `describe` of the document before and after. A domain model is shown per entity and @@ -56,6 +56,25 @@ Modified: Microflow Shop.ACT_Apply: moved to 'Shop/Archive' Files exec writes next to the model (Java sources, theme files) are listed as `New file:` / `Modified file:`. +### JSON output + +`--format json` prints the report as one JSON document instead of text, for a +tool that has to decide on the result without parsing the diff: + +```bash +mxcli diff -p app.mpr changes.mdl --format json +``` + +| Field | Meaning | +|---|---| +| `refused` | Why exec's pre-flight or a statement would refuse the script; `""` when it runs | +| `preflight` | What exec's pre-flight printed (warnings and errors), when there is any | +| `execError` | The error exec would stop on; `""` when it would not | +| `failures` | The statement failures a `--continue-on-error` run reports | +| `units` | The units exec would add, rewrite, move or remove: `id`, `kind`, `type`, `name`, and `moved`, `rewritten`, `idChurnOnly` | +| `documents` | The units as MDL, one entry per document (per entity and association for a domain model): `objectType`, `objectName`, `kind` (`added`, `modified` or `removed`), `writes`, `current`, `proposed` | +| `files` | The files next to the model exec would write or delete: `path`, `kind` | +| `summary` | `added`, `modified`, `removed`, `units`, `files` and `writesNothing` | ### What diff no longer reports Because the verdict is exec's own, a script exec has already applied diffs as diff --git a/mdl/scriptdiff/copy.go b/mdl/scriptdiff/copy.go index a2403260f5..6252491704 100644 --- a/mdl/scriptdiff/copy.go +++ b/mdl/scriptdiff/copy.go @@ -3,10 +3,13 @@ package scriptdiff import ( + "errors" "fmt" "io" "os" "path/filepath" + "runtime" + "sync" ) // skippedDirs are directories of a project folder the scratch copy leaves out: @@ -18,6 +21,7 @@ var skippedDirs = map[string]bool{ ".svn": true, "deployment": true, "releases": true, + "packages": true, // deployment packages (.mpk) exported by Studio Pro: build output, never read or written by exec "node_modules": true, ".mendix-cache": true, ".mendix-cache2": true, @@ -40,10 +44,61 @@ func copyProject(src, dst string) error { if err != nil { return err } - return filepath.Walk(src, func(p string, info os.FileInfo, err error) error { + + // Directories and symlinks are created while walking, in walk order, so a + // file's directory always exists before the file is copied. Regular files go + // to a pool of workers: a project is thousands of small files (a unit each), + // and on Windows the per-file cost (open, create, antivirus scan) dwarfs the + // bytes, so copying them one by one was most of a diff's time. + type job struct { + from, to string + perm os.FileMode + } + workers := runtime.NumCPU() * 4 + if workers > 32 { + workers = 32 + } + if workers < 4 { + workers = 4 + } + jobs := make(chan job, 256) + var wg sync.WaitGroup + var firstErr error + var errMu sync.Mutex + setErr := func(err error) { + errMu.Lock() + if firstErr == nil { + firstErr = err + } + errMu.Unlock() + } + failed := func() bool { + errMu.Lock() + defer errMu.Unlock() + return firstErr != nil + } + for i := 0; i < workers; i++ { + wg.Add(1) + go func() { + defer wg.Done() + for j := range jobs { + if failed() { + continue // drain + } + if err := copyFile(j.from, j.to, j.perm); err != nil { + setErr(err) + } + } + }() + } + + walkErr := filepath.Walk(src, func(p string, info os.FileInfo, err error) error { if err != nil { return err } + if failed() { + return errors.New("copy failed") + } rel, err := filepath.Rel(src, p) if err != nil { return err @@ -62,11 +117,44 @@ func copyProject(src, dst string) error { } return os.MkdirAll(target, 0o755) case mode.IsRegular(): - return copyFile(p, target, mode.Perm()) + jobs <- job{from: p, to: target, perm: mode.Perm()} + return nil default: return nil // sockets, devices: nothing exec reads } }) + close(jobs) + wg.Wait() + if firstErr != nil { + return firstErr + } + return walkErr +} + +// removeAllParallel removes dir like os.RemoveAll, removing the children of the +// first `depth` levels concurrently. Anything it cannot remove that way is left +// to a final os.RemoveAll, which also reports the error. +func removeAllParallel(dir string, depth int) error { + if depth > 0 { + if entries, err := os.ReadDir(dir); err == nil { + var wg sync.WaitGroup + sem := make(chan struct{}, 32) + for _, e := range entries { + if !e.IsDir() { + continue + } + wg.Add(1) + sem <- struct{}{} + go func(p string) { + defer wg.Done() + defer func() { <-sem }() + _ = removeAllParallel(p, depth-1) + }(filepath.Join(dir, e.Name())) + } + wg.Wait() + } + } + return os.RemoveAll(dir) } func copyFile(src, dst string, perm os.FileMode) error { diff --git a/mdl/scriptdiff/json_test.go b/mdl/scriptdiff/json_test.go new file mode 100644 index 0000000000..f3f99a3e0a --- /dev/null +++ b/mdl/scriptdiff/json_test.go @@ -0,0 +1,74 @@ +// SPDX-License-Identifier: Apache-2.0 + +package scriptdiff + +import ( + "bytes" + "encoding/json" + "testing" + + "github.com/mendixlabs/mxcli/mdl/ast" + "github.com/mendixlabs/mxcli/mdl/executor" +) + +func TestWriteJSON(t *testing.T) { + r := &Report{ + Units: []UnitChange{{ID: "u1", Kind: Modified, Type: "Forms$Page", Name: "M.P", Rewritten: true}}, + Results: []executor.DiffResult{{ + ObjectType: "Page", ObjectName: ast.QualifiedName{Module: "M", Name: "P"}, + Current: "a", Proposed: "b", + }}, + Files: []FileChange{{Path: "x.txt", Kind: Added}}, + } + var buf bytes.Buffer + if err := r.WriteJSON(&buf); err != nil { + t.Fatal(err) + } + var got struct { + Refused string `json:"refused"` + Documents []struct { + ObjectType string `json:"objectType"` + ObjectName string `json:"objectName"` + Kind string `json:"kind"` + } `json:"documents"` + Files []struct{ Path, Kind string } `json:"files"` + Summary struct { + Modified int `json:"modified"` + Units int `json:"units"` + WritesNothing bool `json:"writesNothing"` + } `json:"summary"` + } + if err := json.Unmarshal(buf.Bytes(), &got); err != nil { + t.Fatalf("not valid JSON: %v\n%s", err, buf.String()) + } + if len(got.Documents) != 1 || got.Documents[0].ObjectName != "M.P" || got.Documents[0].Kind != "modified" { + t.Errorf("documents: %+v", got.Documents) + } + if got.Summary.Modified != 1 || got.Summary.Units != 1 || got.Summary.WritesNothing { + t.Errorf("summary: %+v", got.Summary) + } + if len(got.Files) != 1 || got.Files[0].Path != "x.txt" { + t.Errorf("files: %+v", got.Files) + } +} + +func TestWriteJSONRefusedWritesNothing(t *testing.T) { + r := &Report{Refused: "unresolved reference"} + var buf bytes.Buffer + if err := r.WriteJSON(&buf); err != nil { + t.Fatal(err) + } + var got struct { + Refused string `json:"refused"` + Summary struct { + WritesNothing bool `json:"writesNothing"` + } `json:"summary"` + Units []any `json:"units"` + } + if err := json.Unmarshal(buf.Bytes(), &got); err != nil { + t.Fatal(err) + } + if got.Refused == "" || !got.Summary.WritesNothing || got.Units == nil { + t.Errorf("refused report: %+v", got) + } +} diff --git a/mdl/scriptdiff/parallel_test.go b/mdl/scriptdiff/parallel_test.go new file mode 100644 index 0000000000..d9f5f91bd1 --- /dev/null +++ b/mdl/scriptdiff/parallel_test.go @@ -0,0 +1,100 @@ +// SPDX-License-Identifier: Apache-2.0 + +package scriptdiff + +import ( + "crypto/sha256" + "fmt" + "os" + "path/filepath" + "testing" +) + +// writeTree creates n files spread over nested directories under root and returns +// their paths relative to root with their contents. +func writeTree(t *testing.T, root string, n int) map[string]string { + t.Helper() + files := map[string]string{} + for i := 0; i < n; i++ { + rel := filepath.Join(fmt.Sprintf("d%d", i%7), fmt.Sprintf("e%d", i%3), fmt.Sprintf("f%d.txt", i)) + content := fmt.Sprintf("content %d", i) + full := filepath.Join(root, rel) + if err := os.MkdirAll(filepath.Dir(full), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(full, []byte(content), 0o644); err != nil { + t.Fatal(err) + } + files[rel] = content + } + return files +} + +func TestCopyProjectCopiesEveryFileAndSkipsBuildDirs(t *testing.T) { + base := t.TempDir() + src := filepath.Join(base, "src") + files := writeTree(t, src, 300) + for _, skipped := range []string{".git", "deployment", "packages", "node_modules"} { + if err := os.MkdirAll(filepath.Join(src, skipped), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(src, skipped, "big.bin"), []byte("x"), 0o644); err != nil { + t.Fatal(err) + } + } + scratch := filepath.Join(base, "scratch") + if err := os.MkdirAll(scratch, 0o755); err != nil { + t.Fatal(err) + } + dst := filepath.Join(scratch, "project") + + if err := copyProject(src, dst); err != nil { + t.Fatalf("copyProject: %v", err) + } + for rel, want := range files { + got, err := os.ReadFile(filepath.Join(dst, rel)) + if err != nil { + t.Fatalf("missing %s: %v", rel, err) + } + if string(got) != want { + t.Fatalf("%s: got %q, want %q", rel, got, want) + } + } + for _, skipped := range []string{".git", "deployment", "packages", "node_modules"} { + if _, err := os.Stat(filepath.Join(dst, skipped)); !os.IsNotExist(err) { + t.Errorf("%s was copied; it must be left out", skipped) + } + } +} + +func TestRemoveAllParallelRemovesTheTree(t *testing.T) { + dir := filepath.Join(t.TempDir(), "tree") + writeTree(t, dir, 200) + if err := removeAllParallel(dir, 3); err != nil { + t.Fatalf("removeAllParallel: %v", err) + } + if _, err := os.Stat(dir); !os.IsNotExist(err) { + t.Fatalf("%s still exists", dir) + } + if err := removeAllParallel(dir, 3); err != nil { + t.Fatalf("removing a missing folder must not fail: %v", err) + } +} + +func TestHashFileIsSHA256(t *testing.T) { + p := filepath.Join(t.TempDir(), "f") + data := []byte("hello mxcli") + if err := os.WriteFile(p, data, 0o644); err != nil { + t.Fatal(err) + } + got, err := hashFile(p) + if err != nil { + t.Fatal(err) + } + if want := sha256.Sum256(data); got != want { + t.Fatalf("got %x, want %x", got, want) + } + if _, err := hashFile(filepath.Join(t.TempDir(), "missing")); err == nil { + t.Fatal("hashing a missing file must fail") + } +} diff --git a/mdl/scriptdiff/scriptdiff.go b/mdl/scriptdiff/scriptdiff.go index 17d718cefb..44c79f6139 100644 --- a/mdl/scriptdiff/scriptdiff.go +++ b/mdl/scriptdiff/scriptdiff.go @@ -26,6 +26,7 @@ import ( "io" "os" "path/filepath" + "time" "github.com/mendixlabs/mxcli/mdl/ast" "github.com/mendixlabs/mxcli/mdl/backend" @@ -83,17 +84,31 @@ func Run(mprPath string, prog *ast.Program, opts Options) (*Report, error) { if opts.NewBackend == nil { return nil, errors.New("scriptdiff: no backend to open the scratch copy with") } + // MXCLI_DIFF_TIMING=1 prints how long each stage takes (to stderr). + timing := os.Getenv("MXCLI_DIFF_TIMING") == "1" + t0 := time.Now() + stage := func(name string) { + if timing { + fmt.Fprintf(os.Stderr, "diff-timing %-18s %6.2fs\n", name, time.Since(t0).Seconds()) + t0 = time.Now() + } + } scratch, err := NewScratch(mprPath) if err != nil { return nil, err } - defer scratch.Close() + defer func() { + scratch.Close() + stage("cleanup") + }() src, copyMpr := scratch.src, scratch.Mpr + stage("copy-project") before, err := TakeSnapshot(copyMpr) if err != nil { return nil, err } + stage("snapshot-before") rep := &Report{} var out bytes.Buffer @@ -124,6 +139,7 @@ func Run(mprPath string, prog *ast.Program, opts Options) (*Report, error) { _ = x.Execute(&ast.DisconnectStmt{}) x.Close() rep.Output = out.String() + stage("preflight+exec") if g.refused != nil { return nil, g.refused } @@ -132,14 +148,18 @@ func Run(mprPath string, prog *ast.Program, opts Options) (*Report, error) { if err != nil { return nil, err } + stage("snapshot-after") rep.Units, rep.Files = before.Compare(after) + stage("compare") if len(rep.Units) > 0 { r, err := newRenderer(src, copyMpr, before, after, opts) if err != nil { return nil, err } + stage("renderer-open") rep.Results = r.render(rep.Units) r.close() + stage("render") } return rep, nil } @@ -176,8 +196,10 @@ func NewScratch(mprPath string) (*Scratch, error) { return &Scratch{dir: dir, src: src, Mpr: filepath.Join(copyDir, filepath.Base(src))}, nil } -// Close removes the scratch folder. -func (s *Scratch) Close() error { return os.RemoveAll(s.dir) } +// Close removes the scratch folder. The folder holds thousands of small files, +// and removing them one by one is slow on Windows, so the first levels are +// removed in parallel. +func (s *Scratch) Close() error { return removeAllParallel(s.dir, 3) } // Apply executes prog against the copy as exec would — stopping at the first // error — and returns what exec printed. A statement that would act outside diff --git a/mdl/scriptdiff/snapshot.go b/mdl/scriptdiff/snapshot.go index 6567fc20f7..cd4fa6ed10 100644 --- a/mdl/scriptdiff/snapshot.go +++ b/mdl/scriptdiff/snapshot.go @@ -9,8 +9,10 @@ import ( "io" "os" "path/filepath" + "runtime" "sort" "strings" + "sync" "go.mongodb.org/mongo-driver/v2/bson" @@ -61,6 +63,11 @@ func TakeSnapshot(mprPath string) (*Snapshot, error) { dir := filepath.Dir(mprPath) mprBase := filepath.Base(mprPath) + // The files next to the model are listed first and hashed by a pool of + // workers: they are the project's heavy files (packages, libraries, widgets), + // and hashing them one after another was a good part of the snapshot's time. + type hashJob struct{ path, rel string } + var toHash []hashJob err = filepath.Walk(dir, func(p string, info os.FileInfo, err error) error { if err != nil { return err @@ -84,26 +91,68 @@ func TakeSnapshot(mprPath string) (*Snapshot, error) { if !info.Mode().IsRegular() { return nil } - f, err := os.Open(p) - if err != nil { - return err - } - defer f.Close() - h := sha256.New() - if _, err := io.Copy(h, f); err != nil { - return err - } - var sum [sha256.Size]byte - copy(sum[:], h.Sum(nil)) - s.files[filepath.ToSlash(rel)] = sum + toHash = append(toHash, hashJob{path: p, rel: filepath.ToSlash(rel)}) return nil }) if err != nil { return nil, fmt.Errorf("scan %s: %w", dir, err) } + + workers := runtime.NumCPU() * 2 + if workers < 2 { + workers = 2 + } + var ( + wg sync.WaitGroup + mu sync.Mutex + hashErr error + jobsChan = make(chan hashJob, 128) + ) + for i := 0; i < workers; i++ { + wg.Add(1) + go func() { + defer wg.Done() + for j := range jobsChan { + sum, err := hashFile(j.path) + mu.Lock() + if err != nil { + if hashErr == nil { + hashErr = err + } + } else { + s.files[j.rel] = sum + } + mu.Unlock() + } + }() + } + for _, j := range toHash { + jobsChan <- j + } + close(jobsChan) + wg.Wait() + if hashErr != nil { + return nil, fmt.Errorf("scan %s: %w", dir, hashErr) + } return s, nil } +// hashFile is the SHA-256 of one file's contents. +func hashFile(path string) ([sha256.Size]byte, error) { + var sum [sha256.Size]byte + f, err := os.Open(path) + if err != nil { + return sum, err + } + defer f.Close() + h := sha256.New() + if _, err := io.Copy(h, f); err != nil { + return sum, err + } + copy(sum[:], h.Sum(nil)) + return sum, nil +} + // isWidgetDocs reports whether rel is the folder of generated widget docs // (executor.WidgetDocsDirs) or inside it. func isWidgetDocs(rel string) bool { diff --git a/mdl/scriptdiff/write.go b/mdl/scriptdiff/write.go index 44440bdafd..7d8802484e 100644 --- a/mdl/scriptdiff/write.go +++ b/mdl/scriptdiff/write.go @@ -3,6 +3,7 @@ package scriptdiff import ( + "encoding/json" "fmt" "io" "strings" @@ -10,6 +11,91 @@ import ( "github.com/mendixlabs/mxcli/mdl/executor" ) +// jsonReport is the machine-readable form of a Report (mxcli diff --format +// json): what a tool needs to decide, without reading the text of the diff. +type jsonReport struct { + // Refused is why exec's pre-flight would refuse the script; "" when it runs. + Refused string `json:"refused"` + // Preflight is what exec's pre-flight printed (warnings and errors). + Preflight string `json:"preflight,omitempty"` + // ExecError is the error exec would stop on; "" when it would not. + ExecError string `json:"execError"` + // Failures are the statement failures a --continue-on-error run reports. + Failures string `json:"failures,omitempty"` + // Units are the units exec would add, rewrite, move or remove. + Units []jsonUnit `json:"units"` + // Documents render Units as MDL, an entry per document (per entity and + // association for a domain model). + Documents []jsonDocument `json:"documents"` + // Files are the files next to the model exec would write or delete. + Files []jsonFile `json:"files"` + Summary jsonSummary `json:"summary"` +} + +type jsonUnit struct { + ID string `json:"id"` + Kind string `json:"kind"` + Type string `json:"type"` + Name string `json:"name"` + Moved string `json:"moved,omitempty"` + Rewritten bool `json:"rewritten"` + IDChurnOnly bool `json:"idChurnOnly,omitempty"` +} + +type jsonDocument struct { + ObjectType string `json:"objectType"` + ObjectName string `json:"objectName"` + Kind string `json:"kind"` // added, modified or removed + // Writes is what is written that the MDL does not show (a move, a property + // describe does not print); "" otherwise. + Writes string `json:"writes,omitempty"` + Current string `json:"current,omitempty"` + Proposed string `json:"proposed,omitempty"` +} + +type jsonFile struct { + Path string `json:"path"` + Kind string `json:"kind"` +} + +type jsonSummary struct { + Added int `json:"added"` + Modified int `json:"modified"` + Removed int `json:"removed"` + Units int `json:"units"` + Files int `json:"files"` + WritesNothing bool `json:"writesNothing"` +} + +// WriteJSON prints the report as one JSON document. +func (r *Report) WriteJSON(w io.Writer) error { + out := jsonReport{Refused: r.Refused, Preflight: r.PreflightOutput, Failures: r.Failures, Units: []jsonUnit{}, Documents: []jsonDocument{}, Files: []jsonFile{}} + if r.ExecErr != nil { + out.ExecError = strings.TrimSpace(r.ExecErr.Error()) + } + for _, u := range r.Units { + out.Units = append(out.Units, jsonUnit{ID: u.ID, Kind: string(u.Kind), Type: u.Type, Name: u.Name, Moved: u.Moved, Rewritten: u.Rewritten, IDChurnOnly: u.IDChurnOnly}) + } + for _, res := range r.Results { + kind := "modified" + switch { + case res.IsNew: + kind = "added" + case res.IsDeleted: + kind = "removed" + } + out.Documents = append(out.Documents, jsonDocument{ObjectType: res.ObjectType, ObjectName: res.ObjectName.String(), Kind: kind, Writes: res.Writes, Current: res.Current, Proposed: res.Proposed}) + } + for _, f := range r.Files { + out.Files = append(out.Files, jsonFile{Path: f.Path, Kind: string(f.Kind)}) + } + added, modified, removed := r.Counts() + out.Summary = jsonSummary{Added: added, Modified: modified, Removed: removed, Units: len(r.Units), Files: len(r.Files), WritesNothing: r.Refused != "" || (len(r.Units) == 0 && len(r.Files) == 0)} + enc := json.NewEncoder(w) + enc.SetIndent("", " ") + return enc.Encode(out) +} + // Counts are the documents a report changes: entities and associations count // one each, as does every other document. func (r *Report) Counts() (added, modified, removed int) {