From f5bdd3f619e24db1f0011d54837e0cb077381cef Mon Sep 17 00:00:00 2001 From: deveshpharswan Date: Fri, 20 Nov 2026 08:53:18 +0530 Subject: [PATCH] Fix audit findings in configuration, build, and inspection --- CHANGELOG.md | 4 +++ README.md | 9 ++--- ci/path_rules_test.go | 2 +- cmd/build.go | 62 +++++++++++++++++----------------- cmd/build_routing_test.go | 71 +++++++++++++++++++++++++-------------- cmd/build_test.go | 35 ++++++------------- cmd/compare_test.go | 2 +- cmd/config_load_test.go | 6 ++++ cmd/progress.go | 8 ++--- cmd/progress_test.go | 10 +++--- cmd/resolver.go | 10 ++++++ cmd/resolver_test.go | 10 ++++++ cmd/usability_test.go | 2 +- config/config.go | 27 +++++---------- config/config_test.go | 21 ++++++++---- docs/configuration.md | 4 +-- docs/tui.md | 5 +-- image/format.go | 8 ++--- image/format_test.go | 25 +++++++------- tui/filetree.go | 10 +++--- tui/help.go | 3 +- tui/keymap.go | 2 ++ tui/layers_test.go | 20 +++++------ tui/layout_test.go | 4 +-- tui/model.go | 57 +++++++++++++++++++++++++------ tui/model_test.go | 35 ++++++++++++------- tui/waste_detail_test.go | 4 +-- 27 files changed, 270 insertions(+), 186 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c8f5066..606dfcc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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. diff --git a/README.md b/README.md index cc190bb..87ef86f 100644 --- a/README.md +++ b/README.md @@ -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) | @@ -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). diff --git a/ci/path_rules_test.go b/ci/path_rules_test.go index 5823d82..32314d1 100644 --- a/ci/path_rules_test.go +++ b/ci/path_rules_test.go @@ -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) } diff --git a/cmd/build.go b/cmd/build.go index 5dbfaf9..82f68c0 100644 --- a/cmd/build.go +++ b/cmd/build.go @@ -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 . @@ -77,13 +77,13 @@ 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) @@ -91,6 +91,8 @@ func runBuild(cmd *cobra.Command, args []string) error { } 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)) } } @@ -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 != "" { @@ -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) { diff --git a/cmd/build_routing_test.go b/cmd/build_routing_test.go index 36eb511..a2e8d6e 100644 --- a/cmd/build_routing_test.go +++ b/cmd/build_routing_test.go @@ -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 { @@ -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") }) } } @@ -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 @@ -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 @@ -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") @@ -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) diff --git a/cmd/build_test.go b/cmd/build_test.go index d79a361..9b8baed 100644 --- a/cmd/build_test.go +++ b/cmd/build_test.go @@ -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 { @@ -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) + } } } diff --git a/cmd/compare_test.go b/cmd/compare_test.go index 51a0379..b65c5fb 100644 --- a/cmd/compare_test.go +++ b/cmd/compare_test.go @@ -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") } diff --git a/cmd/config_load_test.go b/cmd/config_load_test.go index 19df092..0240767 100644 --- a/cmd/config_load_test.go +++ b/cmd/config_load_test.go @@ -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()) diff --git a/cmd/progress.go b/cmd/progress.go index b20b300..f5ada4f 100644 --- a/cmd/progress.go +++ b/cmd/progress.go @@ -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 { @@ -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) } diff --git a/cmd/progress_test.go b/cmd/progress_test.go index b4af419..de79ca6 100644 --- a/cmd/progress_test.go +++ b/cmd/progress_test.go @@ -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)) @@ -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) } diff --git a/cmd/resolver.go b/cmd/resolver.go index fadd03d..041e3c7 100644 --- a/cmd/resolver.go +++ b/cmd/resolver.go @@ -3,8 +3,10 @@ package cmd import ( "fmt" "os" + "path/filepath" "runtime" "strconv" + "strings" "github.com/deveshctl/layerx/image" "github.com/deveshctl/layerx/image/engine" @@ -60,6 +62,14 @@ func selectResolverDefault(imageRef string) (image.Resolver, error) { if isRegularFilePath(imageRef) { return image.NewArchiveResolverWithPlatform(imageRef, plat), nil } + if filepath.IsAbs(imageRef) || + strings.HasPrefix(imageRef, "./") || strings.HasPrefix(imageRef, "../") || + (runtime.GOOS == "windows" && (strings.HasPrefix(imageRef, `.\`) || strings.HasPrefix(imageRef, `..\`))) { + if _, err := os.Lstat(imageRef); err != nil { + return nil, fmt.Errorf("opening image archive %q: %w", imageRef, err) + } + return nil, fmt.Errorf("image archive %q must be a regular file", imageRef) + } return selectDockerLikeResolver(engineFlag, plat) } diff --git a/cmd/resolver_test.go b/cmd/resolver_test.go index 36ebb2c..2ff774f 100644 --- a/cmd/resolver_test.go +++ b/cmd/resolver_test.go @@ -3,7 +3,9 @@ package cmd import ( "errors" "os" + "path/filepath" "runtime" + "strings" "testing" "github.com/deveshctl/layerx/image" @@ -260,6 +262,14 @@ func TestSelectResolverDefault_RegularFileBypassesEngine(t *testing.T) { } } +func TestSelectResolverDefault_MissingExplicitArchive(t *testing.T) { + resetEngineState(t) + _, err := selectResolverDefault(filepath.Join(t.TempDir(), "missing.tar")) + if !errors.Is(err, os.ErrNotExist) || !strings.Contains(err.Error(), "opening image archive") { + t.Fatalf("expected archive path error, got %v", err) + } +} + func TestSelectResolverDefault_InvalidPlatformIsRejectedEarly(t *testing.T) { // A malformed --platform must not reach any image-resolution code path. // selectResolverDefault returns ErrPlatformInvalid synchronously so the diff --git a/cmd/usability_test.go b/cmd/usability_test.go index ebb9375..7296d71 100644 --- a/cmd/usability_test.go +++ b/cmd/usability_test.go @@ -76,7 +76,7 @@ func TestBuildOperationalErrorsPrintOnce(t *testing.T) { prepareBuildRoutingTest(t) withFakeResolver(t, okResolver(passingLayers()...)) failure := errors.New("inspection unavailable") - runBuildCommand = func(*exec.Cmd) error { return nil } + runBuildCommand = func(c *exec.Cmd) error { return writeTestBuildIID(t, c) } runBuildTUI = func(tui.Config) error { return nil } switch stage { case "engine-start": diff --git a/config/config.go b/config/config.go index 8476e35..1cbe971 100644 --- a/config/config.go +++ b/config/config.go @@ -2,9 +2,7 @@ package config import ( "bytes" - "errors" "fmt" - "io/fs" "math" "os" "path/filepath" @@ -115,15 +113,11 @@ func Load() (*Config, error) { } // LoadFrom reads config from the specified path. -// Returns default config if the file does not exist, is empty, or contains -// only whitespace/comments. +// Returns default config if the file is empty or contains only whitespace/comments. func LoadFrom(path string) (*Config, error) { data, err := os.ReadFile(path) if err != nil { - if errors.Is(err, fs.ErrNotExist) { - return Default(), nil - } - return nil, err + return nil, newLoadError(path, "", err) } if !hasYAMLContent(data) { @@ -136,7 +130,7 @@ func LoadFrom(path string) (*Config, error) { // the receiver could detect after the fact. Catching null requires // inspecting the document AST before the strict struct decode runs; // otherwise `rules: null` silently zeros the user's CI thresholds. - if err := rejectNullSections(path, data); err != nil { + if err := validateDocument(path, data); err != nil { return nil, err } @@ -184,7 +178,7 @@ func LoadFrom(path string) (*Config, error) { return cfg, nil } -// rejectNullSections parses the raw bytes once and rejects any top-level key +// validateDocument rejects multiple documents and any top-level key // whose value is an explicit YAML null when the loader's contract requires a // mapping. The strict struct decode that runs afterwards cannot tell `key:` // from absent — both surface as a Go nil ast.Node — so a separate pass is @@ -193,7 +187,7 @@ func LoadFrom(path string) (*Config, error) { // Both `rules:` and `size-budget:` require mappings. `path-rules:` accepts null as // "no path rules" by design (see normalizePathRules), and other top-level // keys are scalars or maps where strict decode catches the malformed shape. -func rejectNullSections(path string, data []byte) error { +func validateDocument(path string, data []byte) error { f, err := parser.ParseBytes(data, 0) if err != nil { // Don't shadow the strict decode pass's richer error; just let it @@ -203,15 +197,10 @@ func rejectNullSections(path string, data []byte) error { if f == nil || len(f.Docs) == 0 { return nil } - for _, doc := range f.Docs { - if doc == nil || doc.Body == nil { - continue - } - if err := checkRulesNotNull(path, doc.Body); err != nil { - return err - } + if len(f.Docs) > 1 { + return newLoadError(path, "", fmt.Errorf("expected one YAML document")) } - return nil + return checkRulesNotNull(path, f.Docs[0].Body) } func checkRulesNotNull(path string, body ast.Node) error { diff --git a/config/config_test.go b/config/config_test.go index 6ec6521..0cae824 100644 --- a/config/config_test.go +++ b/config/config_test.go @@ -17,9 +17,16 @@ func TestDefault(t *testing.T) { } func TestLoadFrom_MissingFile(t *testing.T) { - cfg, err := LoadFrom("/nonexistent/.layerx.yaml") - require.NoError(t, err) - assert.Equal(t, Default(), cfg) + cfg, err := LoadFrom(filepath.Join(t.TempDir(), "missing.yaml")) + require.ErrorIs(t, err, os.ErrNotExist) + assert.Nil(t, cfg) +} + +func TestLoadFrom_RejectsMultipleDocuments(t *testing.T) { + path := filepath.Join(t.TempDir(), ".layerx.yaml") + require.NoError(t, os.WriteFile(path, []byte("version: 1\n---\nsize-budget: {max: 1B}\n"), 0o600)) + _, err := LoadFrom(path) + require.ErrorContains(t, err, "expected one YAML document") } func TestLoadFrom_ValidYAML(t *testing.T) { @@ -182,10 +189,10 @@ func TestLoadFrom_RejectsUnknownTopLevelKey(t *testing.T) { // have surfaced as a misleading "parsing" error. func TestLoadFrom_EmptyFile_UsesDefaults(t *testing.T) { cases := map[string]string{ - "empty": "", - "whitespace_only": " \n\n\t\n", - "comments_only": "# just a comment\n# another\n", - "comments_and_ws": "\n# placeholder\n\n", + "empty": "", + "whitespace_only": " \n\n\t\n", + "comments_only": "# just a comment\n# another\n", + "comments_and_ws": "\n# placeholder\n\n", } for name, content := range cases { t.Run(name, func(t *testing.T) { diff --git a/docs/configuration.md b/docs/configuration.md index ea0a3c3..0e75999 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -22,9 +22,9 @@ parents for `.layerx.yaml`, then the user configuration directory for directory. `--config FILE` overrides this search. The first file found is used; project, parent, and user files are not merged. Missing values in that file use built-in defaults. A missing file chosen with - `--config` also uses built-in defaults rather than searching for another file. + `--config` is an error. - **YAML library.** Decoded with `goccy/go-yaml` in **strict mode**: any - unknown top-level key fails with a parse error. Empty files (or files + unknown top-level key fails with a parse error. Use one YAML document per file. Empty files (or files containing only comments and whitespace) silently fall back to built-in defaults. - **Schema version.** Only schema version `1` is accepted. `version: 0` is diff --git a/docs/tui.md b/docs/tui.md index c33a4d5..ec0d4da 100644 --- a/docs/tui.md +++ b/docs/tui.md @@ -102,14 +102,15 @@ in `.layerx.yaml` to use your terminal background. | Key | Action | |-------------|--------------------------------------------------------------| | `Tab` | Cycle panels (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` | Navigate folders (tree) or scroll left / right (file viewer) | | `Enter` | Confirm a filter, open a file, or expand/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 | | `Backspace` | Clear a confirmed tree filter | | `n` / `N` | Next / previous search match (viewer) | | `y` | Copy file path to clipboard | diff --git a/image/format.go b/image/format.go index 45cbdf9..a1c1b5e 100644 --- a/image/format.go +++ b/image/format.go @@ -13,11 +13,11 @@ func formatUnsignedBytes(b uint64) string { ) switch { case b >= gb: - return fmt.Sprintf("%.1f GB", float64(b)/float64(gb)) + return fmt.Sprintf("%.1f GiB", float64(b)/float64(gb)) case b >= mb: - return fmt.Sprintf("%.1f MB", float64(b)/float64(mb)) + return fmt.Sprintf("%.1f MiB", float64(b)/float64(mb)) case b >= kb: - return fmt.Sprintf("%.1f KB", float64(b)/float64(kb)) + return fmt.Sprintf("%.1f KiB", float64(b)/float64(kb)) default: return fmt.Sprintf("%d B", b) } @@ -31,7 +31,7 @@ func FormatBytes(b int64) string { } // FormatSignedBytes formats b like FormatBytes but with an explicit sign -// for non-zero values: "+12 MB", "-3.0 MB", "0 B". Used for net deltas. +// for non-zero values: "+12 MiB", "-3.0 MiB", "0 B". Used for net deltas. func FormatSignedBytes(b int64) string { if b == 0 { return "0 B" diff --git a/image/format_test.go b/image/format_test.go index af32a12..0983ad0 100644 --- a/image/format_test.go +++ b/image/format_test.go @@ -16,14 +16,14 @@ func TestFormatBytes(t *testing.T) { {1, "1 B"}, {512, "512 B"}, {1023, "1023 B"}, - {1024, "1.0 KB"}, - {1536, "1.5 KB"}, - {1048576, "1.0 MB"}, - {1572864, "1.5 MB"}, - {1073741824, "1.0 GB"}, - {1610612736, "1.5 GB"}, - {5242880, "5.0 MB"}, - {10485760, "10.0 MB"}, + {1024, "1.0 KiB"}, + {1536, "1.5 KiB"}, + {1048576, "1.0 MiB"}, + {1572864, "1.5 MiB"}, + {1073741824, "1.0 GiB"}, + {1610612736, "1.5 GiB"}, + {5242880, "5.0 MiB"}, + {10485760, "10.0 MiB"}, } for _, tt := range tests { @@ -40,11 +40,11 @@ func TestFormatSignedBytes(t *testing.T) { }{ {0, "0 B"}, {1, "+1 B"}, - {1024, "+1.0 KB"}, - {1572864, "+1.5 MB"}, + {1024, "+1.0 KiB"}, + {1572864, "+1.5 MiB"}, {-1, "-1 B"}, - {-1024, "-1.0 KB"}, - {-3145728, "-3.0 MB"}, + {-1024, "-1.0 KiB"}, + {-3145728, "-3.0 MiB"}, } for _, tt := range tests { @@ -94,4 +94,3 @@ func TestFormatMode(t *testing.T) { }) } } - diff --git a/tui/filetree.go b/tui/filetree.go index 8980848..dc23546 100644 --- a/tui/filetree.go +++ b/tui/filetree.go @@ -156,7 +156,7 @@ func renderTreeBody(in treePaneInput) (body string, hasAbove, hasBelow bool) { if in.showFilterBar { sb.WriteString("\n") - sb.WriteString(renderFilterBar(in.styles, in.filterActive, in.filterQuery, len(in.files), in.contentWidth)) + sb.WriteString(renderFilterBar(in.styles, in.filterActive, in.filterQuery, len(in.files), in.contentWidth, in.currentLayer)) } hasAbove = in.offset > 0 @@ -391,13 +391,15 @@ func renderTreeHeader(st themeStyles, maxWidth int, compact ...bool) string { return st.metaDim.Render(header) } -func renderFilterBar(st themeStyles, active bool, query string, matchCount int, maxWidth int) string { +func renderFilterBar(st themeStyles, active bool, query string, matchCount, maxWidth, layer int) string { + scope := fmt.Sprintf("L%d ", layer+1) + maxWidth = max(0, maxWidth-ansi.StringWidth(scope)) if active { - return renderQueryBar(st, query, true, "", "", maxWidth) + return scope + renderQueryBar(st, query, true, "", "", maxWidth) } matches := st.statusDimRaw.Render(fmt.Sprintf(" (%d matches)", matchCount)) hint := st.unchanged.Render(" [⌫ clear]") - return renderQueryBar(st, query, false, matches, hint, maxWidth) + return scope + renderQueryBar(st, query, false, matches, hint, maxWidth) } func formatFileNodeLine(t Theme, st themeStyles, f *image.FileNode, selected bool, maxWidth int, treeMode bool, collapsed map[string]bool, currentLayer int, filterQuery string, compact ...bool) string { diff --git a/tui/help.go b/tui/help.go index f437c1d..e5962a2 100644 --- a/tui/help.go +++ b/tui/help.go @@ -58,7 +58,8 @@ func defaultHelpSections() []helpSection { { title: "File Tree", entries: []helpEntry{ - {"/", "Filter file paths"}, + {"/", "Filter file paths in the selected layer"}, + {"F", "Find a file in the final image"}, {"Enter", "View file / expand or collapse folder"}, {"h / l", "Collapse / expand folder, or move to parent / child"}, {"m", "Toggle file metadata columns"}, diff --git a/tui/keymap.go b/tui/keymap.go index 3fff41d..9774ca4 100644 --- a/tui/keymap.go +++ b/tui/keymap.go @@ -22,6 +22,7 @@ type keyMap struct { CopyContent key.Binding Help key.Binding Filter key.Binding + FindFinal key.Binding DiffOnly key.Binding Sort key.Binding Aggregate key.Binding @@ -104,6 +105,7 @@ func defaultKeys() keyMap { key.WithKeys("/"), key.WithHelp("/", "filter"), ), + FindFinal: key.NewBinding(key.WithKeys("F")), DiffOnly: key.NewBinding( key.WithKeys("d"), key.WithHelp("d", "diff only"), diff --git a/tui/layers_test.go b/tui/layers_test.go index f617223..34a153b 100644 --- a/tui/layers_test.go +++ b/tui/layers_test.go @@ -24,9 +24,9 @@ func TestFormatLayerLine_DeltaMode_HasSignedColumn(t *testing.T) { l := makeLayer(1, 5*mb, 3*mb, "RUN apt-get install foo") out := formatLayerLine(CatppuccinMocha(), themeStyles{}, l, false, 60, sizeColDelta, 30*mb) // Should contain the signed delta string somewhere. - assert.Contains(t, out, "+3.0 MB") + assert.Contains(t, out, "+3.0 MiB") // Should NOT contain the blob value when in delta mode. - assert.NotContains(t, out, "5.0 MB") + assert.NotContains(t, out, "5.0 MiB") } func TestFormatLayerLine_BlobMode_RegressionGuard(t *testing.T) { @@ -34,23 +34,23 @@ func TestFormatLayerLine_BlobMode_RegressionGuard(t *testing.T) { l := makeLayer(1, 5*mb, 3*mb, "RUN apt-get install foo") out := formatLayerLine(CatppuccinMocha(), themeStyles{}, l, false, 60, sizeColBlob, 30*mb) // Blob value should appear; signed delta should NOT. - assert.Contains(t, out, "5.0 MB") - assert.NotContains(t, out, "+3.0 MB") + assert.Contains(t, out, "5.0 MiB") + assert.NotContains(t, out, "+3.0 MiB") } func TestFormatLayerLine_BothMode_HasBothValues(t *testing.T) { const mb = 1024 * 1024 l := makeLayer(1, 5*mb, 3*mb, "RUN apt-get install foo") out := formatLayerLine(CatppuccinMocha(), themeStyles{}, l, false, 80, sizeColBoth, 30*mb) - assert.Contains(t, out, "5.0 MB") - assert.Contains(t, out, "+3.0 MB") + assert.Contains(t, out, "5.0 MiB") + assert.Contains(t, out, "+3.0 MiB") } func TestFormatLayerLine_NegativeDeltaRendersWithMinus(t *testing.T) { const mb = 1024 * 1024 l := makeLayer(2, 1*mb, -2*mb, "RUN apt-get clean") out := formatLayerLine(CatppuccinMocha(), themeStyles{}, l, false, 60, sizeColDelta, 30*mb) - assert.Contains(t, out, "-2.0 MB") + assert.Contains(t, out, "-2.0 MiB") } func TestRenderLayers_BothMode_FallsBackToDelta_OnNarrowPanel(t *testing.T) { @@ -61,10 +61,10 @@ func TestRenderLayers_BothMode_FallsBackToDelta_OnNarrowPanel(t *testing.T) { } // width = 36 → contentWidth = 34, below the < 38 fallback threshold. out := renderLayers(CatppuccinMocha(), themeStyles{}, layers, 0, 0, 36, 10, true, sizeColBoth, 8*mb) - // In delta-only fallback the blob value (5.0 MB) must be hidden; + // In delta-only fallback the blob value (5.0 MiB) must be hidden; // only the signed delta column is rendered. - assert.NotContains(t, out, " 5.0 MB", "blob value (unsigned) must not appear in delta-fallback") - assert.Contains(t, out, "+5.0 MB") + assert.NotContains(t, out, " 5.0 MiB", "blob value (unsigned) must not appear in delta-fallback") + assert.Contains(t, out, "+5.0 MiB") } func TestRenderLayers_FocusedTitle_ReflectsSizeMode(t *testing.T) { diff --git a/tui/layout_test.go b/tui/layout_test.go index 81034e5..9a7e07a 100644 --- a/tui/layout_test.go +++ b/tui/layout_test.go @@ -147,7 +147,7 @@ func TestLongQueryKeepsCaretAndTailVisible(t *testing.T) { if viewer { line = renderViewerSearchBar(viewerParams{styles: m.styles}, query, true, 12, 0, width) } else { - line = renderFilterBar(m.styles, true, query, 0, width) + line = renderFilterBar(m.styles, true, query, 0, width, 0) } assert.LessOrEqual(t, lipgloss.Width(line), width) assert.Contains(t, ansi.Strip(line), "END█") @@ -157,7 +157,7 @@ func TestLongQueryKeepsCaretAndTailVisible(t *testing.T) { m.filterQuery = query m = send(m, keyPress('Z')) assert.Equal(t, query+"Z", m.filterQuery) - assert.Contains(t, ansi.Strip(renderFilterBar(m.styles, true, m.filterQuery, 0, 30)), "ENDZ█") + assert.Contains(t, ansi.Strip(renderFilterBar(m.styles, true, m.filterQuery, 0, 30, 0)), "ENDZ█") } func TestCommandWrappingHonoursDisplayWidth(t *testing.T) { diff --git a/tui/model.go b/tui/model.go index a3e782a..f97df1c 100644 --- a/tui/model.go +++ b/tui/model.go @@ -8,6 +8,7 @@ import ( "os" "path" "path/filepath" + "slices" "strings" "syscall" "time" @@ -16,6 +17,7 @@ import ( tea "charm.land/bubbletea/v2" "charm.land/lipgloss/v2" "github.com/charmbracelet/x/ansi" + "golang.org/x/term" "github.com/deveshctl/layerx/image" "github.com/deveshctl/layerx/internal/sizebudget" @@ -205,6 +207,7 @@ type treeCacheSlot struct { valid bool layerCursor int filterQuery string + liveFilter bool diffOnly bool sortMode sortMode collapsedGen uint64 @@ -231,6 +234,7 @@ type model struct { layerOffset int treeCursor int treeOffset int + analysisErr error errMsg string quitting bool resolver image.Resolver @@ -251,6 +255,7 @@ type model struct { errorOffset int filterActive bool filterQuery string + liveFilter bool diffOnly bool aggregated bool sortMode sortMode @@ -492,6 +497,7 @@ func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { case analysisMsg: if msg.err != nil { m.state = stateError + m.analysisErr = msg.err m.errMsg = friendlyError(msg.err) m.errorOffset = 0 return m, nil @@ -946,9 +952,18 @@ func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) { } return m, nil + case key.Matches(msg, m.keys.FindFinal): + m.layerCursor = max(0, len(m.layers())-1) + m.focus, m.diffOnly = focusTree, false + m.filterQuery, m.filterActive, m.liveFilter = "", true, true + m.treeCursor, m.treeOffset = 0, 0 + m.aggCursor, m.aggOffset = 0, 0 + m.clampCursors() + return m, nil + case key.Matches(msg, m.keys.Filter): if m.isTreeFocused() { - m.filterActive = true + m.filterActive, m.liveFilter = true, false m.clampCursors() return m, nil } @@ -1389,6 +1404,7 @@ func (m model) displayTreeFor(f focus) []*image.FileNode { if slot.valid && slot.layerCursor == m.layerCursor && slot.filterQuery == m.filterQuery && + slot.liveFilter == m.liveFilter && slot.diffOnly == m.diffOnly && slot.sortMode == m.sortMode && slot.collapsedGen == m.collapsedGen && @@ -1400,6 +1416,7 @@ func (m model) displayTreeFor(f focus) []*image.FileNode { valid: true, layerCursor: m.layerCursor, filterQuery: m.filterQuery, + liveFilter: m.liveFilter, diffOnly: m.diffOnly, sortMode: m.sortMode, collapsedGen: m.collapsedGen, @@ -1422,6 +1439,9 @@ func (m model) computeDisplayTreeFor(f focus) []*image.FileNode { } if m.filterQuery != "" { files = applySubstringFilter(files, m.filterQuery) + if m.liveFilter && m.layerCursor == len(m.layers())-1 { + files = slices.DeleteFunc(files, func(f *image.FileNode) bool { return f.DiffType == image.Removed }) + } } if m.sortMode != sortNone { files = regularFiles(files) @@ -2037,7 +2057,7 @@ func (m model) viewReady() tea.View { leftWidth := m.leftPanelWidth() rightWidth := m.width - leftWidth - 1 // header(1) + panel borders(2) + commandBar(3) + separator(1) + statusBar(1) = 8 - panelHeight := m.height - chromeRows + panelHeight := m.height - chromeRows + 3 - m.commandBarRows() header := m.renderHeader() // The status bar only consumes treeFiles in its non-viewer branch; when the // viewer is open renderStatusBar returns early via renderViewerStatusBar and @@ -2081,14 +2101,16 @@ func (m model) viewReady() tea.View { if m.layerCursor < len(layers) { cmd = layers[m.layerCursor].Command } - commandBar := renderCommandBar(m.styles, cmd, m.width) - // Keep the three reserved command rows even when the command is short. - commandBar += strings.Repeat("\n", max(3-lipgloss.Height(commandBar), 0)) + var commandBar string + if rows := m.commandBarRows(); rows > 0 { + commandBar = renderCommandBar(m.styles, cmd, m.width) + commandBar += strings.Repeat("\n", max(rows-lipgloss.Height(commandBar), 0)) + "\n" + } sep := m.styles.separator.Render(strings.Repeat("─", m.width)) status := m.renderStatusBar(treeFiles) - content := lipgloss.JoinVertical(lipgloss.Left, header, panels, commandBar, sep, status) + content := lipgloss.JoinVertical(lipgloss.Left, header, panels, commandBar+sep, status) if m.showHelp { content = m.overlayHelp() @@ -2177,6 +2199,7 @@ func (m model) renderStatusBar(treeFiles []*image.FileNode) string { if m.focus == focusLayers { hints = []statusHint{ {"Tab", "switch"}, + {"F", "find in image"}, {"j/k", "navigate"}, {"g/G", "top/bottom"}, {"S", "size"}, @@ -2206,7 +2229,7 @@ func (m model) renderStatusBar(treeFiles []*image.FileNode) string { {"Tab", "switch"}, {"j/k", "navigate"}, {"/", "filter"}, - {"m", "columns"}, + {"F", "find"}, {"d", "diff"}, {"s", "sort"}, {"w", "waste + cleanup"}, @@ -2570,8 +2593,15 @@ func (m *model) viewMaxCursorCol() int { return maxW } +func (m model) commandBarRows() int { + if m.viewState != viewNone && m.height <= 16 { + return 0 + } + return 3 +} + func (m *model) viewVisibleHeight() int { - h := m.height - 8 + h := m.height - 5 - m.commandBarRows() if m.viewContent != nil && m.viewContent.Truncated { h-- } @@ -2675,9 +2705,14 @@ func friendlySaveError(err error, name string) string { // Run starts the TUI program with the given configuration. func Run(cfg Config) error { + if !term.IsTerminal(int(os.Stdin.Fd())) || !term.IsTerminal(int(os.Stdout.Fd())) { + return fmt.Errorf("image inspection requires terminal input and output; use --json FILE to export analysis") + } m := NewModel(cfg) defer m.fetchCancel() - p := tea.NewProgram(m) - _, err := p.Run() - return err + final, err := tea.NewProgram(m).Run() + if err != nil { + return err + } + return final.(model).analysisErr } diff --git a/tui/model_test.go b/tui/model_test.go index b856b62..01c8b7e 100644 --- a/tui/model_test.go +++ b/tui/model_test.go @@ -413,13 +413,13 @@ func TestViewLoadingPullProgressFitsInBox(t *testing.T) { m.loadPhase = image.PhasePulling m.pullLayers = 1 m.pullTotal = 3 - m.pullBytes = 254 * 1024 * 1024 // "254.0 MB" - m.pullBytesMax = 4 * 1024 * 1024 * 1024 // "4.0 GB" + m.pullBytes = 254 * 1024 * 1024 // "254.0 MiB" + m.pullBytesMax = 4 * 1024 * 1024 * 1024 // "4.0 GiB" content := viewContent(m.View()) - assert.Contains(t, content, "254.0 MB", "current bytes must render in full") - assert.Contains(t, content, "4.0 GB", "total bytes must render in full") + assert.Contains(t, content, "254.0 MiB", "current bytes must render in full") + assert.Contains(t, content, "4.0 GiB", "total bytes must render in full") assert.Contains(t, content, "Layer 1/3", "layer counter must render in full") } @@ -490,7 +490,7 @@ func TestViewLoadingPullProgressNoBytesTotal(t *testing.T) { // TestViewLoadingPullProgressShrinksBarOnNarrowTerminal asserts the progress // bar shrinks (rather than overflowing or being truncated) when the terminal // is too narrow for the default 20-cell bar plus counter and bytes. -// Regression: the bytes-total ("4.7 GB") was being clipped mid-value because +// Regression: the bytes-total ("4.7 GiB") was being clipped mid-value because // the bar was hard-coded to 20 cells regardless of terminal width. func TestViewLoadingPullProgressShrinksBarOnNarrowTerminal(t *testing.T) { m := NewModel(Config{ImageRef: "ai/qwen3"}) @@ -500,11 +500,11 @@ func TestViewLoadingPullProgressShrinksBarOnNarrowTerminal(t *testing.T) { m.pullLayers = 1 m.pullTotal = 3 m.pullBytes = 69 * 1024 * 1024 - m.pullBytesMax = 5046586573 // ~4.7 GB + m.pullBytesMax = 5046586573 // ~4.7 GiB content := viewContent(m.View()) - assert.Contains(t, content, "4.7 GB", "bytes-total must not be truncated on narrow terminal") + assert.Contains(t, content, "4.7 GiB", "bytes-total must not be truncated on narrow terminal") assert.Contains(t, content, "Layer 1/3") require.LessOrEqual(t, maxPanelLineWidth(content), 50, "panel must not exceed terminal width") @@ -521,11 +521,11 @@ func TestViewLoadingPullProgressDropsBarWhenTooNarrow(t *testing.T) { m.pullLayers = 1 m.pullTotal = 3 m.pullBytes = 69 * 1024 * 1024 - m.pullBytesMax = 5046586573 // ~4.7 GB + m.pullBytesMax = 5046586573 // ~4.7 GiB content := viewContent(m.View()) - assert.Contains(t, content, "4.7 GB") + assert.Contains(t, content, "4.7 GiB") assert.Contains(t, content, "Layer 1/3") assert.NotContains(t, content, "━", "bar should be omitted when terminal cannot fit ≥4 cells") require.LessOrEqual(t, maxPanelLineWidth(content), 40) @@ -543,9 +543,9 @@ func TestViewLoadingPullProgressBytesTotalNotClipped(t *testing.T) { bytesMax int64 expectMax string }{ - {"MB-range", 81920000, 361 * 1024 * 1024, "361.0 MB"}, - {"GB-range", 2 * 1024 * 1024 * 1024, 4*1024*1024*1024 + 700*1024*1024, "4.7 GB"}, - {"large-GB", 8 * 1024 * 1024 * 1024, 12 * 1024 * 1024 * 1024, "12.0 GB"}, + {"MB-range", 81920000, 361 * 1024 * 1024, "361.0 MiB"}, + {"GB-range", 2 * 1024 * 1024 * 1024, 4*1024*1024*1024 + 700*1024*1024, "4.7 GiB"}, + {"large-GB", 8 * 1024 * 1024 * 1024, 12 * 1024 * 1024 * 1024, "12.0 GiB"}, } for _, tc := range cases { for w := 40; w <= 120; w++ { @@ -954,6 +954,17 @@ func TestDiffToggleResetsCursor(t *testing.T) { // --- Filter ------------------------------------------------------------------ +func TestFindInFinalImageMovesFromLayersToFilteredTree(t *testing.T) { + m := setupModelWithDiffs() + m.focus, m.diffOnly = focusLayers, true + m = send(m, keyPress('F')) + assert.Equal(t, len(m.layers())-1, m.layerCursor) + assert.Equal(t, focusTree, m.focus) + assert.True(t, m.filterActive) + assert.True(t, m.liveFilter) + assert.False(t, m.diffOnly) +} + func TestFilterActivation(t *testing.T) { m := setupModelWithDiffs() m = send(m, keyPress('/')) diff --git a/tui/waste_detail_test.go b/tui/waste_detail_test.go index 6c6acc3..9114313 100644 --- a/tui/waste_detail_test.go +++ b/tui/waste_detail_test.go @@ -152,7 +152,7 @@ func TestWasteCleanupAccessibleAtFullEfficiency(t *testing.T) { out := ansi.Strip(m.renderWasteOverlay()) assert.Contains(t, out, "Live files may still offer cleanup") assert.Contains(t, out, "Layer waste: 0 B") - assert.Contains(t, out, "Potential cleanup: 1.0 GB") + assert.Contains(t, out, "Potential cleanup: 1.0 GiB") assert.Contains(t, out, "Tab Review cleanup") m = send(m, keyPressSpecial(tea.KeyTab)) assert.True(t, m.wasteShowCleanup) @@ -264,7 +264,7 @@ func TestWasteDeletionExplanationFitsAtMinimumSize(t *testing.T) { cursor: 1, } out := ansi.Strip(m.renderWasteDetail()) - assert.Contains(t, out, "Deleted later; 16.0 MB remains stored.") + assert.Contains(t, out, "Deleted later; 16.0 MiB remains stored.") assert.Contains(t, out, "Layer 2 deleted the file") assert.Contains(t, out, "Deleting later keeps earlier layer bytes.") assert.Contains(t, out, "Enter to view layer")