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 .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Golden JSON is compared byte-for-byte with Go's LF output on every OS.
/cmd/testdata/golden/*.json text eol=lf
15 changes: 15 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,21 @@ jobs:
- run: go vet ./...
- run: go test -race -count=1 -coverprofile=coverage.out ./...

native-test:
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [windows-latest, macos-latest]
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
with:
go-version-file: go.mod
- run: go build ./...
- run: go vet ./...
- run: go test -race -count=1 ./...

cross-compile:
runs-on: ubuntu-latest
strategy:
Expand Down
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,24 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]

### Added
- Interactive image comparison (`compare -i`) with cancellable loading, regression and size-budget results, paired layers, sortable and filterable file changes, and bounded text differences.
- PR checklist and bug report and feature request forms, with guidance for private security reports.
- Optional image-size and growth budgets in `.layerx.yaml`, with CI baseline checks and JSON/Markdown check reports.

### Fixed
- Interactive Compare now explains waste and platform differences, keeps checks and layer details available in narrow terminals, and supports exact-path text comparisons without clearing filters.
- Updated to Go 1.27.4 for standard library security fixes.
- Go patch releases get their own update PRs so security fixes can land between monthly dependency updates.
- Fix shifted comparison help keys and text line endings, reduce extraction memory use, and improve Windows cache and JSON export reliability.
- Keep comparison content tied to the analyzed image, accept 1,500-line text files, reject incomplete archives with cached analyses, and restore the terminal on hangup.
- Keep large interactive comparisons responsive, reuse Docker exports for file previews, and make long paths and preview failures easier to inspect.
- Avoid intermittent comparison cache warnings when both images share a digest on Windows.
- Reject empty YAML size limits instead of silently skipping their checks.
- Platform-pinned checks can reuse matching locally built images without trying to pull their tags from a registry.

### Changed
- Make comparison help clearer and scrollable, honor theme and background settings throughout, and preserve compact shortcuts, diff colors and file metadata.
- Redesign interactive comparisons with LayerX styling, a guided overview, directory hotspots, growth-ranked files, useful binary metadata and stable side-by-side text diffs.
- File browsing now offers folder navigation keys, a files-only size list, and a wider names view.
- Speed up image analysis and archive inspection, especially for larger images and slower filesystems.
- Remove unused review tooling and correct contributor release guidance.
Expand Down
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -467,13 +467,17 @@ layerx compare ./build/prev.tar myapp:next

# Show every diff entry instead of the top-N summary
layerx compare --mode full myapp:old myapp:new

# Browse paired layers, file changes, and bounded text differences
layerx compare -i ./build/prev.tar ./build/current.tar
```

- Reports size, efficiency, layer, file, and waste deltas in a deterministic text report with aligned columns.
- Default compact mode shows the largest deltas per section with `... and N more` counters; `--mode full` prints everything; `--mode summary` keeps the header, any warnings and the verdict.
- Last line is always machine-parseable: `verdict: ok`, `verdict: regression reason=efficiency,waste`, `verdict: noop digest=<sha256>`, or `verdict: noop reason=path-equal`.
- Text reports end with a machine-parseable line: `verdict: ok`, `verdict: regression reason=efficiency,waste`, `verdict: noop digest=<sha256>`, or `verdict: noop reason=path-equal`. Interactive mode (`-i`) emits no final report or verdict line.
- Exit codes: `0` no regression, `1` regression detected, `2` operational error.
- Live progress on stderr while resolving remote images. Pipe `2>/dev/null` to silence; stdout stays grep-clean for CI gating.
- Interactive mode opens an overview of size, waste, budgets and directory hotspots. `Enter` on a directory investigates its changed files; `Esc` clears that scope. Use `1` for layers, `2` for all files, `3` for the overview, or `Tab` to cycle. File changes rank by growth; `/` searches, `s` changes ranking, `m` shows metadata, and `Enter` opens text or metadata details. Press `?` for help. `q` exits without another report, preserving the regression exit code; `q`/`Ctrl+C` cancel loading. Requires terminal input and output.

---

Expand Down
12 changes: 6 additions & 6 deletions cmd/ci_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -250,18 +250,18 @@ path-rules:
// compareCmd one in cmd/compare_test.go.
func TestCICmd_NoArgs_ShowsUsage(t *testing.T) {
cases := []struct {
name string
args []string
name string
args []string
wantSynopsis string // first line on stderr
}{
{
name: "zero_args",
args: []string{"ci"},
name: "zero_args",
args: []string{"ci"},
wantSynopsis: "expected 1 image or archive, got 0",
},
{
name: "too_many_args",
args: []string{"ci", "a", "b"},
name: "too_many_args",
args: []string{"ci", "a", "b"},
wantSynopsis: "expected 1 image or archive, got 2",
},
}
Expand Down
72 changes: 61 additions & 11 deletions cmd/compare.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"errors"
"fmt"
"io"
"slices"
"sort"
"strings"
"sync"
Expand All @@ -13,6 +14,8 @@ import (

"github.com/deveshctl/layerx/config"
"github.com/deveshctl/layerx/image"
"github.com/deveshctl/layerx/internal/sizebudget"
"github.com/deveshctl/layerx/tui"
"github.com/spf13/cobra"
)

Expand Down Expand Up @@ -75,7 +78,26 @@ Reads size-budget and theme from .layerx.yaml; --config selects another file.
Flags override size budgets. CI efficiency thresholds and path rules apply
only to ci; compare retains its efficiency/waste regression checks.
Size budgets measure uncompressed layer tar bytes. File differences compare
size and metadata, not file contents. Use --format json or markdown for reports.`,
size and metadata, not file contents. Use --format json or markdown for reports.

Use -i to browse paired layers and file changes, and inspect bounded text
differences. Interactive mode does not emit a report or a machine-parseable
final verdict line. Requires terminal input and output; cannot be combined
with --mode, --top, or non-text --format.

Interactive keys:
1/2/3, Tab layers, files, overview; cycle views
arrows, j/k move; PgUp/PgDn page; Ctrl+u/d half page; g/G ends
Enter open file or build step details, or investigate a directory
d, v compare selected file text
p compare text at an exact path in Files
c, w inspect checks or waste changes in Overview
1/2/3/4 inside file: Diff, Before, After, Details
/, s, m filter paths, change file ranking, toggle metadata
h/l, left/right scroll text; l opens the origin layer in metadata details
? open/close the comparison guide
Esc go back or clear file scope/filter
q, Ctrl+C go back or exit; Ctrl+C always exits (both cancel loading)`,
Example: ` layerx compare app:1.4.0 app:1.5.0
layerx compare ./build/previous.tar ./build/current.tar
layerx compare --mode full app:1.4.0 app:1.5.0
Expand All @@ -89,6 +111,7 @@ size and metadata, not file contents. Use --format json or markdown for reports.
}

func init() {
compareCmd.Flags().BoolP("interactive", "i", false, "browse layer and file differences (requires a terminal)")
compareCmd.Flags().StringVar(&flagCompareMode, "mode", compareModeCompact,
"report detail: compact, full, or summary")
compareCmd.Flags().IntVar(&flagCompareTop, "top", compareTopDefault,
Expand Down Expand Up @@ -138,6 +161,10 @@ func runCompareCmd(cmd *cobra.Command, args []string) error {

func runCompareCmdInner(cmd *cobra.Command, args []string) error {
oldRef, newRef := args[0], args[1]
if err := validateInteractiveCompare(cmd); err != nil {
return err
}
interactive, _ := cmd.Flags().GetBool("interactive")

if err := validateCompareFlags(flagCompareMode, flagCompareTop); err != nil {
return err
Expand Down Expand Up @@ -172,11 +199,39 @@ func runCompareCmdInner(cmd *cobra.Command, args []string) error {
return fmt.Errorf("preparing new image %q: %w", newRef, err)
}

oldDigest, oldAnalysis, err := analyzeForCompare(ctx, oldResolver, oldRef, noCache, "old", stderr)
var oldDigest, newDigest string
var oldAnalysis, newAnalysis *image.Analysis
if interactive {
outcome, runErr := tui.RunCompareAnalysis(ctx, tui.CompareConfig{
Inputs: [2]image.CompareInput{{Ref: oldRef, Resolver: oldResolver}, {Ref: newRef, Resolver: newResolver}},
Options: image.CompareRunOptions{NoCache: noCache, Platform: activePlatformDisplay()},
Theme: themeName, Input: cmd.InOrStdin(), Output: out,
TransparentBg: cfg.TransparentBackground,
CheckSize: func(before, after *image.Analysis) ([]sizebudget.Result, error) {
if limits.Growth != nil {
if err := matchingPlatforms(before, after); err != nil {
return nil, err
}
}
return limits.Evaluate(budgetConfig, after.UncompressedSize, &before.UncompressedSize)
},
})
if runErr != nil {
return runErr
}
if outcome.CheckError != nil {
return outcome.CheckError
}
if outcome.Result.IsRegression() || slices.ContainsFunc(outcome.Checks, func(check sizebudget.Result) bool { return !check.Passed }) {
return &ErrCompareRegression{}
}
return nil
}
oldDigest, oldAnalysis, err = analyzeForCompare(ctx, oldResolver, oldRef, noCache, "old", stderr)
if err != nil {
return fmt.Errorf("analyzing old image %q: %w", oldRef, err)
}
newDigest, newAnalysis, err := analyzeForCompare(ctx, newResolver, newRef, noCache, "new", stderr)
newDigest, newAnalysis, err = analyzeForCompare(ctx, newResolver, newRef, noCache, "new", stderr)
if err != nil {
return fmt.Errorf("analyzing new image %q: %w", newRef, err)
}
Expand Down Expand Up @@ -232,10 +287,8 @@ func validateCompareFlags(mode string, top int) error {

// analyzeForCompare runs the analyze pipeline for ref with progress events
// drained to stderr (prefixed with side="old"/"new" so the user can tell which
// image is currently resolving). Returns the post-resolve image digest used
// for no-op detection. Post-analyze ImageID errors are surfaced as warnings
// on stderr (the analysis succeeded; the digest is only used for the no-op
// shortcut, so a missing digest is not fatal).
// image is currently resolving). Returns the analyzed snapshot's digest for
// no-op detection. Digest lookup warnings are delivered through progress.
func analyzeForCompare(ctx context.Context, resolver image.Resolver, ref string, noCache bool, side string, stderr io.Writer) (string, *image.Analysis, error) {
progress := make(chan image.ProgressEvent, 32)
var wg sync.WaitGroup
Expand All @@ -255,10 +308,7 @@ func analyzeForCompare(ctx context.Context, resolver image.Resolver, ref string,
if err != nil {
return "", nil, err
}
digest, idErr := resolver.ImageID(ctx, ref)
if idErr != nil {
fmt.Fprintf(stderr, "warning: could not resolve digest for %q after analyze: %v\n", ref, idErr)
}
digest := analysis.Digest
if digest != "" {
fmt.Fprintf(stderr, "[%s] resolved %s\n", side, shortDigest(digest))
}
Expand Down
30 changes: 30 additions & 0 deletions cmd/compare_interactive.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package cmd

import (
"fmt"
"os"

"github.com/spf13/cobra"
"golang.org/x/term"
)

func validateInteractiveCompare(cmd *cobra.Command) error {
interactive, _ := cmd.Flags().GetBool("interactive")
if !interactive {
return nil
}
for _, name := range []string{"mode", "top"} {
if cmd.Flags().Changed(name) {
return fmt.Errorf("--interactive cannot be combined with --%s", name)
}
}
format, _ := cmd.Flags().GetString("format")
if format != "text" {
return fmt.Errorf("--interactive requires --format text")
}
out, ok := cmd.OutOrStdout().(*os.File)
if !isTerminal(cmd.InOrStdin()) || !ok || !term.IsTerminal(int(out.Fd())) {
return fmt.Errorf("--interactive requires terminal input and output; omit -i for redirected reports")
}
return nil
}
70 changes: 70 additions & 0 deletions cmd/compare_interactive_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
package cmd

import (
"bytes"
"strings"
"testing"

"github.com/deveshctl/layerx/image"
"github.com/spf13/cobra"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func interactiveCompareCommand(t *testing.T, args ...string) *cobra.Command {
t.Helper()
cmd := &cobra.Command{}
cmd.Flags().BoolP("interactive", "i", false, "")
cmd.Flags().String("mode", compareModeCompact, "")
cmd.Flags().Int("top", compareTopDefault, "")
cmd.Flags().String("format", "text", "")
cmd.SetIn(strings.NewReader(""))
cmd.SetOut(&bytes.Buffer{})
require.NoError(t, cmd.ParseFlags(args))
return cmd
}

func TestInteractiveCompareFlagGuards(t *testing.T) {
for _, tc := range []struct {
name string
args []string
want string
}{
{"noninteractive pipes", nil, ""},
{"explicit false", []string{"--interactive=false", "--format=json"}, ""},
{"short flag pipes", []string{"-i"}, "terminal input and output"},
{"long flag pipes", []string{"--interactive"}, "terminal input and output"},
{"text allowed", []string{"-i", "--format=text"}, "terminal input and output"},
{"json", []string{"-i", "--format=json"}, "--format text"},
{"markdown", []string{"-i", "--format=markdown"}, "--format text"},
{"mode even default", []string{"-i", "--mode=compact"}, "--mode"},
{"top even default", []string{"-i", "--top=10"}, "--top"},
} {
t.Run(tc.name, func(t *testing.T) {
err := validateInteractiveCompare(interactiveCompareCommand(t, tc.args...))
if tc.want == "" {
require.NoError(t, err)
} else {
require.ErrorContains(t, err, tc.want)
}
})
}
}

func TestInteractiveCompareValidationBeforeResolver(t *testing.T) {
previous := selectResolver
t.Cleanup(func() { selectResolver = previous })
selectResolver = func(string) (image.Resolver, error) {
t.Fatal("invalid interactive invocation reached resolver setup")
return nil, nil
}
cmd := interactiveCompareCommand(t, "-i")
require.ErrorContains(t, runCompareCmdInner(cmd, []string{"old", "new"}), "terminal input and output")
}

func TestCompareRegistersInteractiveShorthand(t *testing.T) {
flag := compareCmd.Flags().ShorthandLookup("i")
require.NotNil(t, flag)
assert.Equal(t, "interactive", flag.Name)
assert.Equal(t, "false", flag.DefValue)
}
6 changes: 4 additions & 2 deletions cmd/json.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"syscall"

"github.com/deveshctl/layerx/image"
"github.com/deveshctl/layerx/internal/atomicfile"
)

// jsonExport is the on-disk shape of `layerx --json`. SchemaVersion is the
Expand Down Expand Up @@ -37,7 +38,8 @@ type jsonExport struct {
//
// 1.0.2 — adds uncompressedLayerBytes and the observed measuredPlatform.
// 1.0.1 — added optional "platform" field (omitempty); existing consumers
// that don't read it are unaffected, so this is a patch bump.
//
// that don't read it are unaffected, so this is a patch bump.
const jsonSchemaVersion = "1.0.2"

type jsonEfficiency struct {
Expand Down Expand Up @@ -204,7 +206,7 @@ func writeJSONAtomic(targetPath string, data []byte) error {
os.Remove(tmp)
return cleanDiskWriteErr(targetPath, err)
}
if err := os.Rename(tmp, targetPath); err != nil {
if err := atomicfile.Rename(tmp, targetPath); err != nil {
os.Remove(tmp)
return cleanDiskWriteErr(targetPath, err)
}
Expand Down
2 changes: 1 addition & 1 deletion cmd/progress_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ func TestStderrProgress_FlushesOnPhaseChange(t *testing.T) {
lines := strings.Split(strings.TrimSpace(out), "\n")
require.Len(t, lines, 3, "got: %q", out)
assert.Contains(t, lines[0], "pulling")
assert.Contains(t, lines[1], "pulled") // flushed before phase change
assert.Contains(t, lines[1], "pulled") // flushed before phase change
assert.Contains(t, lines[2], "exporting")
}

Expand Down
Loading
Loading