Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
16 changes: 14 additions & 2 deletions cmd/mxcli/cmd_diff.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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) {
Expand All @@ -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")
Expand Down Expand Up @@ -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,
Expand Down
2 changes: 1 addition & 1 deletion cmd/mxcli/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
21 changes: 20 additions & 1 deletion docs-site/src/tools/diff.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
92 changes: 90 additions & 2 deletions mdl/scriptdiff/copy.go
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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,
Expand All @@ -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
Expand All @@ -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 {
Expand Down
74 changes: 74 additions & 0 deletions mdl/scriptdiff/json_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
Loading
Loading