Skip to content
Merged
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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Go patch releases get their own update PRs so security fixes can land between monthly dependency updates.
- 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.
- Reject missing explicit config files and multi-document YAML so image checks cannot silently skip limits.
- Analyze the image produced by the current build and skip inspection for check-only builds.
- Report inspector failures with a nonzero exit, explain when a terminal or archive is missing, and label binary file sizes correctly.
- Find files in the final image with `F` and see more file content in short terminals.

### Changed
- File browsing now offers folder navigation keys, a files-only size list, and a wider names view.
Expand Down
9 changes: 5 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -252,21 +252,22 @@ layerx --json analysis.json nginx:latest
source <(layerx completion bash)
```

`IMAGE_OR_ARCHIVE` is auto-detected: an existing regular file is read directly without contacting any runtime; anything else is resolved through the active container engine. Inspection, `ci`, `compare` and JSON export accept both forms. `layerx build` builds through the engine, then inspects the resulting image.
`IMAGE_OR_ARCHIVE` is auto-detected: an existing regular file is read directly. Explicit paths such as `./build/app.tar` report filesystem errors directly. Image references use the active container engine. Inspection, `ci`, `compare` and JSON export accept both forms. `layerx build` builds through the engine, then inspects the resulting image.

### TUI keybindings

| Key | Action |
|-------------|--------------------------------------------------------------|
| `Tab` | Cycle Layers → Layer files → Cumulative in split view |
| `j` / `k` | Move up / down |
| `j` / `k` | Move down / up |
| `g` / `G` | Jump to top / bottom |
| `Ctrl-d` / `Ctrl-u` | Half page down / up (file tree and layers) |
| `Ctrl-f` / `Ctrl-b` | Page down / up — also `PgDn` / `PgUp` |
| `h` / `l` | Scroll left / right (file viewer, long lines) |
| `Enter` | Confirm a filter; open a file; expand or collapse a folder |
| `Esc` | Close help, clear search/filter, or close the viewer. Quits only on loading and error screens. |
| `/` | Filter file tree (tree) / search in viewer (viewer) |
| `/` | Filter the selected layer or search within an open file |
| `F` | Find a file in the final image |
| `n` / `N` | Next / previous search match (viewer) |
| `y` | Copy file path to clipboard |
| `Y` | Copy file content to clipboard (viewer only) |
Expand Down Expand Up @@ -428,7 +429,7 @@ path-rules:
# theme: dracula
```

CLI flags override config-file values. Setting a threshold to `0` or negative disables that rule.
CLI flags override config-file values. Set a threshold to `0` to disable that rule. Negative thresholds are rejected.

Full field reference, path-rule semantics, theming, and worked examples: [docs/configuration.md](docs/configuration.md). End-to-end CI/CD recipes (GitHub Actions, GitLab CI, threshold recommendations, exit codes): [docs/ci-integration.md](docs/ci-integration.md).

Expand Down
2 changes: 1 addition & 1 deletion ci/path_rules_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -257,7 +257,7 @@ func TestDenyWastePathRule_LayerCountInDetail(t *testing.T) {
assert.Equal(t, "/var/log/big.log", results[0].Actual)
assert.Contains(t, results[0].Detail, "4 layers")
assert.True(t,
strings.Contains(results[0].Detail, "10.0 MB") || strings.Contains(results[0].Detail, "10 MB"),
strings.Contains(results[0].Detail, "10.0 MiB"),
"detail %q should contain the human-readable size", results[0].Detail)
}

Expand Down
62 changes: 30 additions & 32 deletions cmd/build.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,8 @@ Other arguments, including --platform, go to the engine. --no-cache disables
both build and analysis caches. Set theme in .layerx.yaml for build inspection;
--theme is not handled by this command. Arguments after -- go to the engine.

With -t or --tag, LayerX inspects the first tag. Without a tag, it uses the
image ID from --iidfile, creating a temporary ID file if none was supplied.
LayerX inspects the image ID produced by the build, creating a temporary
ID file if --iidfile was not supplied. Check-only builds skip inspection.
Use --json to export analysis instead of opening the interactive viewer.`,
Example: ` layerx build -t app:local .
layerx build --json analysis.json -t app:local .
Expand Down Expand Up @@ -77,20 +77,22 @@ func runBuild(cmd *cobra.Command, args []string) error {
return err
}

firstTag := firstTagFromArgs(engineArgs)

checkOnly := buildDoesNotProduceImage(engineArgs)
var (
iidPath string
previousIID os.FileInfo
ownsIIDFile bool
)
if firstTag == "" {
if !checkOnly {
iidPath, ownsIIDFile, err = ensureIIDFile(&engineArgs)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %s\n", err)
return err
}
if ownsIIDFile {
defer os.Remove(iidPath)
} else if previousIID, err = os.Stat(iidPath); err != nil && !os.IsNotExist(err) {
return presentCLIError(cmd.ErrOrStderr(), fmt.Errorf("checking build image ID file: %w", err))
}
}

Expand All @@ -110,14 +112,18 @@ func runBuild(cmd *cobra.Command, args []string) error {
return presentCLIError(cmd.ErrOrStderr(), fmt.Errorf("failed to invoke %s build: %w", binary, err))
}

imageRef := firstTag
if imageRef == "" {
id, readErr := readIIDFile(iidPath)
if readErr != nil {
fmt.Fprintf(os.Stderr, "warning: build succeeded but could not determine image to inspect (%v); pass -t TAG to layerx build to inspect by tag\n", readErr)
return nil
if checkOnly {
return nil
}
if previousIID != nil {
currentIID, statErr := os.Stat(iidPath)
if statErr == nil && os.SameFile(previousIID, currentIID) && previousIID.ModTime().Equal(currentIID.ModTime()) && previousIID.Size() == currentIID.Size() {
return presentCLIError(cmd.ErrOrStderr(), fmt.Errorf("build completed but did not update the image ID file"))
}
imageRef = id
}
imageRef, err := readIIDFile(iidPath)
if err != nil {
return presentCLIError(cmd.ErrOrStderr(), fmt.Errorf("build completed without an image ID: %w", err))
}

if flagJSON != "" {
Expand Down Expand Up @@ -151,31 +157,23 @@ func runBuild(cmd *cobra.Command, args []string) error {
}))
}

// firstTagFromArgs returns the first -t / --tag value in args, or "" if none.
// Both Docker and Podman accept -t and --tag with either a space or = form;
// only the first occurrence is used because all tags resolve to the same
// image and "the first one" matches what the engine itself would surface as
// the canonical reference for output.
func firstTagFromArgs(args []string) string {
for i := range len(args) {
a := args[i]
if a == "--" {
return ""
// Docker buildx can run a frontend subrequest without building an image.
func buildDoesNotProduceImage(args []string) bool {
for i, arg := range args {
if arg == "--" {
break
}
if a == "-t" || a == "--tag" {
if i+1 < len(args) {
return args[i+1]
}
return ""
if arg == "--check" || arg == "--check=true" {
return true
}
if v, ok := strings.CutPrefix(a, "--tag="); ok {
return v
if arg == "--call" && i+1 < len(args) {
return args[i+1] != "build"
}
if v, ok := strings.CutPrefix(a, "-t="); ok {
return v
if call, ok := strings.CutPrefix(arg, "--call="); ok {
return call != "build"
}
}
return ""
return false
}

func extractLayerxFlags(args []string) ([]string, error) {
Expand Down
71 changes: 46 additions & 25 deletions cmd/build_routing_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,19 +51,9 @@ func TestBuild_JSONRouting(t *testing.T) {
t.Setenv("CI", "true")
}
var forwarded []string
var iidPath string
runBuildCommand = func(c *exec.Cmd) error {
forwarded = append([]string(nil), c.Args[1:]...)
if location == "untagged" {
for i, arg := range forwarded {
if arg == "--iidfile" && i+1 < len(forwarded) {
iidPath = forwarded[i+1]
return os.WriteFile(iidPath, []byte("sha256:built-image\n"), 0o600)
}
}
t.Fatal("untagged build must request an image ID")
}
return nil
return writeTestBuildIID(t, c)
}
tuiCalls := 0
runBuildTUI = func(tui.Config) error {
Expand All @@ -83,15 +73,11 @@ func TestBuild_JSONRouting(t *testing.T) {
require.NoError(t, json.Unmarshal(data, &got))
assert.Equal(t, jsonSchemaVersion, got.SchemaVersion)
assert.Equal(t, 1, got.LayerCount)
wantRef := "app:test"
if location == "untagged" {
wantRef = "sha256:built-image"
_, err := os.Stat(iidPath)
assert.True(t, os.IsNotExist(err), "owned image-ID file must be cleaned up")
} else {
assert.Equal(t, []string{"build", "-t", "app:test", "."}, forwarded)
}
assert.Equal(t, wantRef, got.ImageRef)
assert.Equal(t, "sha256:built-image", got.ImageRef)
require.GreaterOrEqual(t, len(forwarded), 3)
assert.Equal(t, "--iidfile", forwarded[len(forwarded)-2])
_, err = os.Stat(forwarded[len(forwarded)-1])
assert.ErrorIs(t, err, os.ErrNotExist, "owned image-ID file must be cleaned up")
})
}
}
Expand All @@ -104,13 +90,13 @@ func TestBuild_DefaultRoutingRemainsInteractive(t *testing.T) {
resolver := okResolver(passingLayers()...)
withFakeResolver(t, resolver)
runBuildCommand = func(c *exec.Cmd) error {
assert.Equal(t, []string{"build", "--no-cache", "-t", "app:test", "--target", "release", "."}, c.Args[1:])
return nil
assert.Equal(t, []string{"build", "--no-cache", "-t", "app:test", "--target", "release", "."}, c.Args[1:len(c.Args)-2])
return writeTestBuildIID(t, c)
}
tuiCalls := 0
runBuildTUI = func(cfg tui.Config) error {
tuiCalls++
assert.Equal(t, "app:test", cfg.ImageRef)
assert.Equal(t, "sha256:built-image", cfg.ImageRef)
assert.Same(t, resolver, cfg.Resolver)
assert.True(t, cfg.NoCache)
return nil
Expand Down Expand Up @@ -153,7 +139,7 @@ func TestBuild_EngineFailureSkipsInspection(t *testing.T) {
func TestBuild_JSONFailureSkipsTUI(t *testing.T) {
prepareBuildRoutingTest(t)
withFakeResolver(t, okResolver(passingLayers()...))
runBuildCommand = func(*exec.Cmd) error { return nil }
runBuildCommand = func(c *exec.Cmd) error { return writeTestBuildIID(t, c) }
runBuildTUI = func(tui.Config) error {
t.Fatal("failed JSON exports must not fall back to the interactive viewer")
return nil
Expand All @@ -171,7 +157,7 @@ func TestBuild_JSONStillValidatesConfig(t *testing.T) {
output := filepath.Join(t.TempDir(), "analysis.json")
configPath := filepath.Join(t.TempDir(), "config.yaml")
require.NoError(t, os.WriteFile(configPath, []byte("path-rules:\n - id: app-policy\n type: block\n"), 0o600))
runBuildCommand = func(*exec.Cmd) error { return nil }
runBuildCommand = func(c *exec.Cmd) error { return writeTestBuildIID(t, c) }
previous := selectResolver
selectResolver = func(string) (image.Resolver, error) {
t.Fatal("invalid configuration must stop JSON analysis")
Expand All @@ -189,6 +175,41 @@ func TestBuild_JSONStillValidatesConfig(t *testing.T) {
assert.True(t, os.IsNotExist(statErr))
}

func writeTestBuildIID(t *testing.T, c *exec.Cmd) error {
t.Helper()
require.GreaterOrEqual(t, len(c.Args), 3)
require.Equal(t, "--iidfile", c.Args[len(c.Args)-2])
return os.WriteFile(c.Args[len(c.Args)-1], []byte("sha256:built-image\n"), 0o600)
}

func TestBuildCheckDoesNotAnalyzeExistingTag(t *testing.T) {
prepareBuildRoutingTest(t)
output := filepath.Join(t.TempDir(), "analysis.json")
runBuildCommand = func(c *exec.Cmd) error {
assert.Equal(t, []string{"build", "--check", "-t", "app:test", "."}, c.Args[1:])
return nil
}
previous := selectResolver
selectResolver = func(string) (image.Resolver, error) {
t.Fatal("check-only builds must not inspect an existing tag")
return nil, nil
}
t.Cleanup(func() { selectResolver = previous })
rootCmd.SetArgs([]string{"build", "--engine", "docker", "--json", output, "--check", "-t", "app:test", "."})
require.NoError(t, rootCmd.Execute())
_, err := os.Stat(output)
assert.ErrorIs(t, err, os.ErrNotExist)
}

func TestBuildRejectsUnchangedUserIIDFile(t *testing.T) {
prepareBuildRoutingTest(t)
iid := filepath.Join(t.TempDir(), "previous.iid")
require.NoError(t, os.WriteFile(iid, []byte("sha256:previous"), 0o600))
runBuildCommand = func(*exec.Cmd) error { return nil }
rootCmd.SetArgs([]string{"build", "--engine", "docker", "--iidfile", iid, "."})
require.ErrorContains(t, rootCmd.Execute(), "did not update the image ID file")
}

func TestBuildEngineExit(t *testing.T) {
if os.Getenv("LAYERX_TEST_ENGINE_EXIT") == "1" {
os.Exit(7)
Expand Down
35 changes: 11 additions & 24 deletions cmd/build_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ func TestEnsureIIDFile_AppendsTempWhenAbsent(t *testing.T) {

func TestEnsureIIDFile_StopsAtDashDash(t *testing.T) {
// --iidfile after -- must be treated as a build-context argument, not a
// layerx flag. ensureIIDFile must stop scanning at -- (same as firstTagFromArgs).
// layerx flag. ensureIIDFile must stop scanning at --.
args := []string{"-t", "x", "--", "--iidfile=/tmp/ignored.iid"}
path, owns, err := ensureIIDFile(&args)
if err != nil {
Expand Down Expand Up @@ -318,28 +318,15 @@ func TestErrBuildFailed_IsTyped(t *testing.T) {
}
}

func TestFirstTagFromArgs(t *testing.T) {
cases := []struct {
name string
args []string
want string
}{
{"short flag space form", []string{"-t", "myimage", "."}, "myimage"},
{"short flag equals form", []string{"-t=myimage:1.0", "."}, "myimage:1.0"},
{"long flag space form", []string{"--tag", "myimage", "."}, "myimage"},
{"long flag equals form", []string{"--tag=myimage:dev", "."}, "myimage:dev"},
{"first of multiple tags wins", []string{"-t", "first:latest", "-t", "second:1.0", "."}, "first:latest"},
{"no tag", []string{"--build-arg", "X=1", "."}, ""},
{"trailing -t with no value", []string{"-t"}, ""},
{"-- stops parsing", []string{"--", "-t", "tricky", "."}, ""},
{"tag-like positional after build-arg is not picked up", []string{"--build-arg", "VERSION=1", "."}, ""},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
got := firstTagFromArgs(tc.args)
if got != tc.want {
t.Fatalf("firstTagFromArgs(%v) = %q, want %q", tc.args, got, tc.want)
}
})
func TestBuildDoesNotProduceImage(t *testing.T) {
for _, args := range [][]string{{"--check", "."}, {"--check=true", "."}, {"--call", "outline", "."}, {"--call=targets", "."}} {
if !buildDoesNotProduceImage(args) {
t.Errorf("expected no build output for %v", args)
}
}
for _, args := range [][]string{{"."}, {"--call=build", "."}, {"--check=false", "."}, {"--", "--check"}} {
if buildDoesNotProduceImage(args) {
t.Errorf("expected an image for %v", args)
}
}
}
2 changes: 1 addition & 1 deletion cmd/compare_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -362,7 +362,7 @@ func TestDrainProgress_RemoteFlow(t *testing.T) {

assert.Contains(t, out, "[old] resolving nginx:latest", "first event announces side+ref")
assert.Contains(t, out, "[old] pulling image", "phase entry line printed once")
assert.Contains(t, out, "[old] pulling: 1/3 layers, 10.0 KB / 30.0 KB")
assert.Contains(t, out, "[old] pulling: 1/3 layers, 10.0 KiB / 30.0 KiB")
assert.Contains(t, out, "[old] exporting image")
assert.Contains(t, out, "[old] parsing layers")
}
Expand Down
6 changes: 6 additions & 0 deletions cmd/config_load_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,12 @@ func TestLoadConfig_ExplicitPathSkipsDiscovery(t *testing.T) {
var stderr bytes.Buffer
cmd.SetErr(&stderr)
got, err := loadConfig(cmd)
if missing {
require.ErrorIs(t, err, os.ErrNotExist)
assert.Nil(t, got)
assert.Contains(t, stderr.String(), flagConfig)
return
}
require.NoError(t, err)
assert.Equal(t, want, got)
assert.Empty(t, stderr.String())
Expand Down
8 changes: 4 additions & 4 deletions cmd/progress.go
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ func writeHeartbeat(w io.Writer, ev image.ProgressEvent) {
}
}

// humanBytes formats a byte count as KB/MB/GB to one decimal place. We
// humanBytes formats a byte count as KiB/MiB/GiB to one decimal place. We
// don't pull in a third-party library for one helper; the rounding is
// deliberately coarse — this output goes into a CI log, not a UI.
func humanBytes(n int64) string {
Expand All @@ -197,11 +197,11 @@ func humanBytes(n int64) string {
)
switch {
case n >= gb:
return fmt.Sprintf("%.1f GB", float64(n)/float64(gb))
return fmt.Sprintf("%.1f GiB", float64(n)/float64(gb))
case n >= mb:
return fmt.Sprintf("%.1f MB", float64(n)/float64(mb))
return fmt.Sprintf("%.1f MiB", float64(n)/float64(mb))
case n >= kb:
return fmt.Sprintf("%.1f KB", float64(n)/float64(kb))
return fmt.Sprintf("%.1f KiB", float64(n)/float64(kb))
default:
return fmt.Sprintf("%d B", n)
}
Expand Down
10 changes: 5 additions & 5 deletions cmd/progress_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -159,9 +159,9 @@ func TestHumanBytes(t *testing.T) {
}{
{0, "0 B"},
{500, "500 B"},
{2048, "2.0 KB"},
{5 * 1024 * 1024, "5.0 MB"},
{3 * 1024 * 1024 * 1024, "3.0 GB"},
{2048, "2.0 KiB"},
{5 * 1024 * 1024, "5.0 MiB"},
{3 * 1024 * 1024 * 1024, "3.0 GiB"},
}
for _, tc := range cases {
assert.Equal(t, tc.want, humanBytes(tc.in))
Expand Down Expand Up @@ -227,8 +227,8 @@ func TestStderrProgress_GrowingTotalAllowsProgress(t *testing.T) {
out := driveProgress(t, context.Background(), events, tick, true)

// Must contain at least one intermediate progress line (not just 100%).
assert.Contains(t, out, "5.0 MB", "layer-1-only progress line must appear")
// Both 5/5 MB (100%) and 13/13 MB (100%) are distinct completion events —
assert.Contains(t, out, "5.0 MiB", "layer-1-only progress line must appear")
// Both 5/5 MiB (100%) and 13/13 MiB (100%) are distinct completion events —
// they have different BytesCurr/BytesTotal keys so both print exactly once.
assert.GreaterOrEqual(t, strings.Count(out, "100%"), 2, "both distinct 100%% events must appear: %q", out)
}
Expand Down
Loading