Commit graph

4 commits

Author SHA1 Message Date
Alex Goodman
75dea9077a
fix a batch of TUI, efficiency, CI and build bugs (#741)
* guard nil parent when moving the tree cursor left

- the left arrow evaluator read `curNode.Parent` without a nil check, and the tree walk evaluates the root (which has no parent since the stereoscope port), so pressing left anywhere in the file tree crashed
- left and current node lookup now share one visible row evaluator, which already had the guard

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* keep the tree cursor working while a filter is active

- cursor lookups required every node on the walk to match the filter regex, root included. Root's path is `/`, so most filters pruned the whole walk and nothing was ever selected: space, left and right did nothing and ctrl+e crashed on the nil node
- even when root matched, unmatched ancestor dirs were skipped while the render kept them, so the selected node drifted from the highlighted row
- navigation now only looks at the `Hidden` flag, which `Update` already derives from the filter (ancestors of matches included), so `CurrentNode`, `CursorLeft`, `CursorRight` and `ToggleCollapse` no longer take the regex
- extract is a no-op when nothing is selected (e.g. a filter with no matches)

Co-authored-by: John Claus <johnclaus@gmail.com>
Co-authored-by: bejaratommy <tommy@bejara.net>
Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* stop the tree cursor at the last visible row

- `VisibleSize` counted every collapsed dir before checking `Hidden`, so with collapsed dirs hidden (e.g. collapse all, then hide unmodified) the cursor could keep moving down into blank rows with nothing selected
- hidden collapsed dirs are no longer counted

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* clamp the tree cursor when the visible rows or pane height change

- nothing adjusted the cursor when a filter, hidden diff type or resize shrank the tree or the pane, so the cursor could sit past the last row (pane renders empty, many Ups to recover) or below the bottom of the pane while actions applied to a row that wasn't highlighted
- `Update` now clamps the cursor to the last visible row, keeps the highlighted row inside the pane, and scrolls back up when the pane would otherwise show blank rows below the end of the tree

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* keep the file tree sort order across layer changes

- the sort order lived on the model tree, and selecting another layer swaps in a cached tree that has its own sort order, so ctrl+o was lost on every layer change (and revisiting a layer could flip it back)
- the view model now owns the sort order and applies it to whichever tree is swapped in

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* fold CR line breaks in the layer command preview

- the layer row only replaced `\n` in the command, so a CRLF heredoc `RUN` left a `\r` in the row, which sends the terminal cursor back to column 0 and the command text overwrote the Cmp and Size columns
- `\r\n` and a bare `\r` now become the same `↵` marker as `\n`

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* fail the linux acceptance run on any dive invocation failure

- the nested loop in ci-test-linux-run had no set -e, so the step only reported the exit code of the very last dive call; earlier engine and oci-archive runs could fail without failing CI
- add set -e and drop the && after the inner loop (set -e is ignored on the left side of &&, which would have hidden inner loop failures)

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* bump golang.org/x/net to v0.60.0

- v0.59.0 has several reachable http2 vulns per govulncheck (GO-2026-6617, GO-2026-6612, GO-2026-6611, GO-2026-6610, GO-2026-6603), including the transport accepting malformed framing headers on the registry pull path

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* bump github.com/klauspost/compress to v1.20.2

- v1.20.0 can panic on two-block frames (GO-2026-6865), flagged as reachable by govulncheck

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* bump release image to alpine 3.24 and docker cli 29.10.0

- alpine 3.21 went EOL on 2026-11-01 and docker cli 28.0.0 is long out of support, so image scanners keep flagging the published image
- the docker cli is only needed for `dive build` now, nothing depends on the 28.x line

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* update readme and help text to match current behavior

- CI rule comments now say highestWastedBytes and highestUserWastedPercent fail on more than the threshold (both compare with a strict >)
- log config sample uses the real keys (`quiet`, `level`, `file`) instead of `enabled`/`path`, which were silently ignored
- config search paths list what is actually read: `./.dive.yaml`, `./.dive/config.yaml`, `~/.dive.yaml`, then `config.yaml` in the XDG dirs (other file names there are never loaded)
- keybinding docs drop `Q` for exit (only ctrl+c is bound) and add ctrl+o, ctrl+p and ctrl+e
- `toggle-wrap-tree` gets a field description in `dive config` output
- `--ci-config` help mentions it applies with `--ci` too, not only `CI=true`

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* stop tree copies from rewiring the source tree's parents

- `FileNode.Copy` set each source child's `Parent` to the new copy, so after `ModelTree.Copy()` every model node pointed up into the view tree
- removing a node from the source tree then removed it from the copy instead, and walking up from a model node read the copy's state
- the copy already gets the right parent from `NewNode`, so the extra assignment is dropped

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* show the file type in the tree's permission column

- the leading column only knew about dirs, so symlinks, devices and fifos all rendered as `-`
- it now shows `l`, `c`, `b` and `p` from the tar type flag, like `ls -l`

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* escape control characters in tree file names

- a file name (or symlink target) with a newline rendered across two rows, so the tree's row count and the cursor drifted apart, and escape bytes went straight to the terminal
- control characters are now shown as their Go escape (`\n`, `\x1b`) when the node is rendered

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* skip content hashing when a file is compared with itself

- the startup view compares layer 0 against itself, which read and hashed every regular file in the base layer before the TUI showed up
- `FileInfo.Compare` now returns Unmodified right away when both sides point at the same catalog entry

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* reset memoized dir sizes when a node is removed

- dir sizes are memoized on first use; sorting by size computed them while the view tree still had the filtered or hidden nodes, sorting by name computed them after those were removed
- with a filter or hidden diff types active, the same dir showed different sizes depending on the sort order
- removing a node now clears the memoized size of every ancestor so it is recomputed from what is left

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* keep lower dir metadata when a layer only implies the dir

- layers without parent dir entries (common with ko, jib, bazel and crane) gave those dirs an empty `FileInfo`, so they rendered as `----------  0:0` and collapse skipped them since they weren't dirs
- comparing such a layer against a real dir below it marked the dir Modified and copied the empty info over it
- implicit dirs now get a 0755 root owned dir `FileInfo` flagged as implicit, compare as Unmodified against a dir below (children still bubble up changes), and don't overwrite the lower dir's metadata

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* drop the old dir contents when a layer replaces a dir with a file or link

- when a layer replaced a dir with a symlink (e.g. usrmerge's `/bin -> /usr/bin`), the node took the symlink's metadata but kept the old dir's children, so the link rendered with the old files nested under it and couldn't be collapsed
- the lower dir's children are now removed from the tree before the upper payload is persisted

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* re-derive removed nodes when a later layer re-creates them

- in the aggregated view, once a node was marked Removed by one top layer, later top layers only re-derived diff types for Unmodified nodes
- a dir whited out by one layer and re-created by the next stayed red/Removed even though it exists in the final image
- Removed nodes the current top layer contains are now re-derived the same way as untouched ones, so the dir shows as Modified (its old children stay Removed, the new ones Added)

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* compare extended attributes when diffing tree nodes

- `FileInfo.Compare` only looked at type, mode, owner, size, link name and content, so a layer that only changed xattrs (e.g. `setcap` writing `security.capability`) showed the file as Unmodified
- the `SCHILY.xattr.*` PAX records are now carried on `FileInfo` and a difference marks the node Modified

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* lay out the TUI at a minimum width instead of panicking on narrow terminals

- on a terminal narrower than 12 columns the filter footer's input view (placed after the "Path Filter: " label) and
  narrow tree columns got a left edge at or past their right edge, gocui refused to create them, and the view setup
  was then called with a nil view and panicked (at startup or on resize)
- the layout manager now lays out as if the screen were at least 12 columns wide and lets gocui clip the rest
- column and footer layout errors are returned instead of being swallowed

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* report an image with no layers instead of an invalid layer range

- an image without layers analyzes fine, but the TUI flashed and exited with `invalid layer range: Index(0:0)` since the views need a selected layer
- the TUI now refuses up front with "image has no layers" before taking over the terminal

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* move the toggle modified files default off of ctrl+m

- terminals send the same byte for ctrl+m and enter, so hitting enter on a directory in the file tree hid every modified file
- the default is now ctrl+n (a configured ctrl+m still works as before)

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* show the filter key help and restore focus when the filter closes

- opening the filter focused it but left the status bar showing the previous pane's key help
- closing it always moved focus to the layer view, regardless of where the filter was opened from
- the focused view and its key help are now remembered when the filter opens and restored when it closes

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* show extract results in the status bar and keep file modes

- extracting with ctrl+e gave no feedback: success was silent, the destination was never shown, and errors only showed up after quitting
- the status bar now says where the files went ("extracted <path> to <abs dir>") or why it failed, until the next status redraw; the full error report is still printed on exit
- extracted files were created 0666 (less the umask), so executables lost their exec bits; they now get the permission bits from the image (setuid/setgid/sticky dropped, umask still applies)
- ctrl+e is listed in the README key table

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* draw box characters one cell wide under CJK locales

- go-runewidth counts east asian ambiguous width runes as two cells when the locale is ko/ja/zh, but terminals draw the tree and border box characters (`│ ├ └ ─`) one cell wide, so the panes rendered misaligned
- the TUI now turns that off before starting unless `RUNEWIDTH_EASTASIAN` is set explicitly
- `go-runewidth` becomes a direct dependency (same version)

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* fail fast on a terminal without a size instead of hanging

- on a 0x0 pty (some CI runners, `docker exec` without a size) gocui puts the terminal in raw mode and then waits for a resize forever; ctrl-c arrives as a key rather than SIGINT, so it can't be interrupted
- the TUI now checks the terminal size first and errors out with a hint to set one
- `golang.org/x/term` becomes a direct dependency (same version)

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* stop listing 0 byte paths as inefficient files

- a path that repeats across layers but never has any bytes (an empty dir like `/etc`, an empty file) was listed as an inefficiency with 0 B wasted, padding the CI table and the TUI list
- paths whose copies add up to 0 bytes are no longer listed

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* count files under removed directories as waste

- a dir whiteout was recorded as a single new occurrence of the dir path, sized as everything under it, so it was never listed and actually raised the efficiency score. Opaque dirs were skipped on purpose and a dir replaced by a file or symlink wasn't noticed at all, so `RUN rm -rf /tmp/build` style cleanup scored 100%
- removals are now found by comparing squashed trees: any path seen in a lower layer that is gone from the layer's squashed tree under a whiteout target, an opaque dir, or a non-dir put in place of a dir counts as removed, the same way a single file whiteout always has
- files the layer adds back (opaque dir recreated with some of the same names) are treated as overwrites, not removals

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* count only unreachable bytes as wasted

- `WastedBytes` and each inefficiency's size were the cumulative size of every copy of a path, including the one the final image still needs, while the efficiency score kept the smallest copy. Bytes and score disagreed, a `chmod` of a base file reported 2x its size as waste (over 100% user wasted), and a file that was removed then added back counted twice because the removal pulled the "needed" copy down to 0
- waste per path is now `cumulative - final`: every byte layers added for the path minus what the final image holds there (0 when removed). Rows, `WastedBytes`, user wasted percent and the score all come from that one number, and the score is `1 - wasted/added`
- a path whose earlier copies were empty (a symlink or empty file replaced by real content) is no longer listed
- the TUI column is now "Wasted Space" since rows are no longer totals

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* use the analysis user wasted percent in CI

- the CI stats recomputed wasted / user bytes on their own instead of reading `WastedUserPercent` from the analysis, so an image whose user layers add 0 bytes (e.g. only `rm` a base file) printed `+Inf %` (or `NaN` with no waste) and disagreed with the analysis, which reports 0 there
- CI now reads the analysis value, so the percent rule sees 0 when there are no user bytes and `highestWastedBytes` is the rule that catches waste in that case

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* reject NaN CI thresholds

- `lowestEfficiency` and `highestUserWastedPercent` accepted `NaN` since it slips past the 0-1 range check, and any comparison against NaN is false, so the rule always passed
- NaN is now rejected as out of range, the same as any other value outside 0-1

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* pass dive build args through to the engine untouched

- the build args were run through a cleanup that dropped empty strings and trimmed spaces, so `--label "" -t x .` turned `-t` into the label value and `--build-arg "PAD= "` lost its trailing space
- args now go to `docker build` / `podman build` exactly as given

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* find the dive build Dockerfile from the build context only

- `--file=X` and `-fX` weren't recognized as a given Dockerfile, so dive searched for a default one and failed when the context had none
- every arg was checked for a directory holding a Dockerfile, flag values included: `dive build -t app .` with `./app/Dockerfile` present built `app/Dockerfile` against `.`
- stdin (`-`) and URL contexts always failed without `-f`
- the args are now walked as docker flags to find the actual context (the last positional arg), and only that directory is searched for a Containerfile/Dockerfile. When nothing is found, no `-f` is added and docker decides

Co-authored-by: tgolob <34978067+tgolob@users.noreply.github.com>
Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* take dive flags before a "--" in dive build and show its help

- `dive build` has flag parsing turned off so the build args pass through, which meant every arg went to `docker build`: there was no way to give dive flags like `--ci`, `--json` or `--source`, and `dive build --help` started a build
- args before a `--` are now parsed as dive flags (ahead of the config load, so they override the config like on other commands) and the rest go to the build: `dive build --ci -- -t app .`. Without a `--` everything still goes to the build
- `-h` / `--help` anywhere shows the dive build help

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* build with podman or docker whatever the configured source is

- `dive build` passed the configured source straight through as the engine to build with, so `containers-storage` (a natural choice for podman on linux) or an archive/registry source failed with "cannot build with source"
- `containers-storage` now builds with podman, and every source other than podman builds with docker

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* report a dive build image missing from the docker daemon

- with a buildx builder that doesn't use the docker driver (e.g. docker-container) and no `--load`, the built image stays in the builder's cache, and loading its ID from the daemon fell through to a pull of `sha256:<id>` from Docker Hub with a confusing "pull access denied"
- after a docker build the ID is now checked with `docker image inspect`, and a missing image fails with a hint to add `--load`

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* pick the podman socket from containers.conf deterministically

- with several unix `service_destinations` and none active, the socket came from ranging over a map, so it could change from run to run. Destinations are now tried in name order
- the user config was always read from `~/.config`, ignoring `$XDG_CONFIG_HOME`, and `containers.conf.d` drop-ins were never read. Both are now picked up, in podman's order

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* fall back to the default docker host when the docker config can't be read

- an unreadable or malformed `~/.docker/config.json` (e.g. root owned 0600 after `sudo docker login`) made dive refuse to talk to docker at all, while the docker cli only warns and uses the default host
- dive now does the same: it logs a warning and uses the default docker host. `DOCKER_HOST` and `DOCKER_CONTEXT` never needed the file and work as before

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* clamp the layer cursor so page down can't run past the last layer

- page down only shortened its step when the target was beyond the layer count, so landing exactly one past the last layer set an out of range index and the next `CurrentLayer()` panicked
- `SetCursor` now clamps to the valid layer range, which covers paging and every other caller

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* draw panes directly instead of queueing render closures

- every pane's `Render` wrapped its drawing in `gui.Update`, which hands the closure to a new goroutine, so two renders queued back to back (a fast tab between panes) could be applied in either order and leave a stale header highlight or contents
- all callers are already on the UI goroutine (key handlers, layout, or setup before the main loop starts), so `Render` now draws straight into the views
- renders requested before the layout has created a pane's views are a no-op; the first layout renders every pane anyway

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* keep the layer pane scroll position while the selection stays visible

- each render cleared the pane (which resets the origin) and then set the origin to `selected - height` when the selection was past the first page, so after scrolling down the selection stayed pinned to the bottom row on the way back up
- the previous origin is now kept and only moved when the selected layer would leave the pane, like a normal list

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* scroll the image and layer details panes with the cursor

- `CursorStep` only moved the origin when `SetCursor` failed, but gocui clamps instead of failing, so the highlight walked off the bottom of the pane and the rest of the content was unreachable
- it also mixed the view relative cursor row with buffer line indexes, and paging refused to move when less than a page was left
- the step now works on absolute (wrapped) line positions, clamps to the last non blank line, and moves the origin whenever the cursor would leave the view

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* build the image details report once

- the inefficiency report was rebuilt with `+=` string concatenation (quadratic) and the whole pane rewritten on every render, and every layer move re-renders every pane, so images with many duplicated paths took seconds per arrow press
- the report is built with a `strings.Builder` and the body is only written the first time, since it only depends on the image (gocui wraps it at draw time); later renders just redraw the header
- this also keeps the pane's scroll position when other panes trigger a render

Co-authored-by: Harold Hunt <harold@pwrdrvr.com>
Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* honor filetree.pane-width

- the option was validated and documented, but the tree pane's `RequestedSize` returned nil (the real code was commented out), so the layout always split the screen evenly
- the tree pane now requests its configured share of the width, the layer column gets the rest

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* clear the filter label before redrawing it

- the filter label `Render` appended the label without clearing the view first, so its buffer grew by a line on every layout change

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* measure pane headers in display cells, not bytes

- the header fill was sized with `len()` of the title, and the focused title's `●` marker is 3 bytes but 1 cell, so the focused pane's header line ended 2 cells short
- the title is now measured with `runewidth.StringWidth` (go-runewidth was already an indirect dependency via gocui)

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* evaluate ci rules when also exporting json

- `run` returned right after writing `--json`, so with CI mode on the rules never ran and dive exited 0. CI mode turns on from `CI=true`, which most runners set, so any pipeline exporting json silently lost the gate.
- now export happens first, then evaluation, and the TUI only starts when neither is requested.

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* pass the diff.hide config through to the TUI

- `TUIPreferences` hardcoded `FiletreeDiffHide: nil`, so `diff.hide` (and `DIVE_DIFF_HIDE`) was parsed and validated, then dropped.
- the TUI errors out on unknown hide values while config loading only warned, so passing the list through as-is would let a typo stop the TUI from starting. Invalid values are now dropped (with the existing warning) when the config loads, and matched case-insensitively like the TUI does.

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* error on an invalid image source instead of falling back to docker

- an unknown `--source` / `container-engine` value only logged a warning and switched to docker, so the run then failed with an unrelated docker load error (or analyzed the wrong image).
- config loading now fails with the list of valid sources, the same way an invalid `--platform` already does.

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* honor the legacy source config key

- configs written for older releases set the image source with `source:`, but only `container-engine` has been read since the clio port, so `source: podman` silently loaded from docker.
- `source` is read again and promoted to `container-engine` with a deprecation warning when `container-engine` is still at its default; an explicit `container-engine` wins.

Co-authored-by: Tommy <tommy@bejarano.io>
Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* detect the CI env var case-insensitively

- CI mode only turned on for lowercase `CI=true/1/yes`. AppVeyor exports `CI=True`, so dive tried to start the TUI there and failed opening `/dev/tty`.
- the value is now trimmed and lowercased before matching.

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* let --ci=false override CI=true

- the `CI` env var was OR-ed into the loaded value after flags, env and config were applied, so `--ci=false`, `DIVE_CI=false` or `ci: false` could never turn CI mode off on a runner that sets `CI=true`.
- `CI` now only seeds the default for `ci`, so the usual precedence applies on top of it: flag > `DIVE_CI` > config file > `CI` env.

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* only read the ci rules file in ci mode

- the `.dive-ci` file was read and its values parsed on every run, so a bad value in it made the interactive TUI and `--json` exports fail in that directory even though no rules were evaluated.
- the file is now only loaded when CI mode is on. Rule values from the app config, env and flags are still validated as before.

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* error when an explicit --ci-config file is missing

- a `--ci-config` (or `ci-config:`) path that didn't exist was skipped silently and the run used the default rules, so a typo in a pipeline quietly changed the gate.
- a missing file is now an error in CI mode unless it's the default `.dive-ci`, which stays optional.

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* accept snake-case keys in the ci rules file

- the `.dive-ci` file only understood the camelCase rule keys and ignored anything else, while the app config warns that camelCase is deprecated in favor of snake-case. Following that advice in `.dive-ci` silently ran the default rules.
- both spellings are read now (snake-case wins if both are given), and unknown keys under `rules` log a warning.

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* let rule flags and env vars win over the ci rules file

- when a `.dive-ci` file existed it replaced every rule after flags and env were applied, so `--lowestEfficiency 0.99` or `DIVE_RULES_LOWEST_EFFICIENCY` were silently dropped. Before the clio port flags won over the file.
- precedence is now the same as fangs uses for everything else: flag > `DIVE_RULES_*` env > `.dive-ci` > app config > defaults. A rule only takes its value from the file when its flag wasn't given and its env var isn't set.
- the deprecated camelCase rule keys in the app config also no longer override a rule flag or env var.
- `spf13/pflag` moves to a direct dependency, it's used to see which rule flags were given.

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* skip rules that a ci rules file leaves out

- the `.dive-ci` file was layered over the default rules, so commenting out or omitting `highestUserWastedPercent` still ran it at 0.1 and could fail the build. `highestWastedBytes` only seemed to work because its default is already `disabled`.
- a `.dive-ci` that has a `rules` section is now treated as the complete rule set: rules it leaves out are skipped (they show as SKIP in the report) instead of running at their default.
- this only applies when such a file is present. Runs without a `.dive-ci` (e.g. just `CI=true`) keep the default 0.9 / 0.1 gate, and a file with no `rules` section falls through to the app config and defaults instead of resetting them. Flipping the global default instead would have silently dropped the user wasted percent check for everyone running in CI without a file.
- rule flags and `DIVE_RULES_*` env vars still win over the file, so a rule the file skips can still be turned on for a single run.

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* exit non-zero when dive is interrupted

- clio cancels the run on SIGINT (and on ctrl-c in the progress UI, which arrives as a key press) but adds no error, so dive exited 0 even with `--ci`. `dive --ci img && deploy` would deploy after a ctrl-c.
- main now keeps the first signal and exits 128+n after cleaning up temp dirs (130 for SIGINT). ctrl-c in the progress UI is recorded by `bus.ExitWithInterrupt` and exits 130 as well.

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* clean up temp dirs when dive gets SIGTERM

- clio only traps SIGINT, so SIGTERM (`docker stop`, CI job cancel, systemd, k8s eviction) took the default handler and killed dive before `source.Cleanup` ran, leaving the full image copy in `$TMPDIR`.
- main now turns SIGTERM into an interrupt so it goes through clio's cancel path and the same cleanup, then exits 143.

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* keep writing log.file while a UI mutes the console

- clio tees the console and `log.file` through one writer, and muting the console while the progress UI, the line UI or the TUI draws swapped that whole writer for `io.Discard`. The log file missed every line logged in between (all of a TUI session, warnings during a `--ci` run).
- dive now builds the logger itself (clio's default, with the file opened by dive) and records the file with `log.SetFile`. Muting the console points the logger at the file instead of discarding.

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* print the CI report under --quiet

- the line UI returned early on the report event when quiet, so `-q --ci` printed nothing and exited 1, with no way to see which rule failed.
- quiet only silences status lines on stderr now, the report still goes to stdout.

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* report a progress UI that fails to start

- when bubbletea failed to start, the error was logged while console logs were muted (so it went nowhere) and the run was stopped through the interrupt path, exiting 0 with no output.
- the error is now kept and returned from `Teardown`, so clio prints it as the command's error and exits 1.

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* skip unknown layer sizes in the pull summary

- containerd's pull status reports a layer it has no progress for yet as size -1, and the pull row summed `uint64(prog.Size())`, so the total wrapped and showed `[... / 18 EB]`.
- the docker and containerd pull summaries now only add positive sizes and counts.

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* fail the pull row when its image source gives up

- stereoscope marks a docker (or containerd) pull status complete in a defer, failures included, so a pull that failed rendered as "✔ Pulled image". With `--source auto` that showed up for every daemon the fallback skipped past.
- `source.Load` now publishes `ImageSourceFailed` for each provider that fails. The progress handler wraps the pull rows of the current attempt and fails them (✘) on that event.

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* finish the fetch and read rows of a failed image source

- stereoscope only completes a layer's read monitor (and a daemon fetch's progress) on success, so after a failed provider attempt (e.g. a bad archive before the `--source auto` fallback found the image) its rows kept spinning. They also held the progress UI's wait group, so the TUI only started after `stop()` gave up waiting a second later.
- fetch, read image and read layer rows are now failed on `ImageSourceFailed` like the pull rows, which completes them and releases the wait group. Failed layer rows drop out like finished ones.

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* guard the line UI against task events it can't use

- on an unparsable `TaskStarted` event the line UI logged the parse error and then used the nil task anyway, and an event without a progress value (which the parser allows) panicked on `prog.Stage()`.
- it now skips unparsable events and only reads the stage when there is a progress value.

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* pick line UI status colors from stderr

- the line UI's status line and notification styles were made from lipgloss' default renderer, which detects colors on stdout, but they are written to stderr. `dive --ci img 2>ci.log` from a terminal put ANSI codes in the log.
- those styles now come from a renderer on stderr. The default renderer stays on stdout since the CI report written there uses it.

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* only color the final error on a color terminal

- clio renders the command's final error red with gookit color, which only `NO_COLOR` turns off, so pipes, files, `TERM=dumb` and `log.file` all got ANSI codes.
- dive now turns gookit color off unless stderr is a color terminal (termenv's detection, so `TERM=dumb`, `NO_COLOR` and `CLICOLOR_FORCE` work) and no log file is set, since the file gets the same logged line.
- `github.com/gookit/color` becomes a direct dependency (same version).

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

---------

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>
Co-authored-by: John Claus <johnclaus@gmail.com>
Co-authored-by: bejaratommy <tommy@bejara.net>
Co-authored-by: tgolob <34978067+tgolob@users.noreply.github.com>
Co-authored-by: Harold Hunt <harold@pwrdrvr.com>
Co-authored-by: Tommy <tommy@bejarano.io>
2026-11-17 00:03:11 -05:00
Alex Goodman
e97febbeb6
port image loading and analysis to stereoscope (#727)
* [wip] port to stereoscope

* revert wip stereoscope port

- the v1/v2 split behind `dev.use-stereoscope` is being replaced by an in-place port onto stereoscope
- reusable pieces (progress handlers, bubbletea setup) get pulled back from f14b994 as needed

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* add docker-free image fixture builder

- `internal/imagefixture` writes deterministic image tarballs from handwritten layer specs: legacy `docker save`, docker 25+ OCI `docker save` (uncompressed, gzip or zstd layers) and plain oci-archive
- named fixture set covering whiteouts (file, dir, opaque, missing target), links, history edge cases, mode/uid only changes and duplicated files, plus the checked in `.data` save tarballs

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* record export and CI parity goldens from the current parser

- `internal/imagefixture/testdata/golden/<fixture>.export.json` and `<fixture>.ci.json` capture what the pre-stereoscope code produces for every fixture, so the stereoscope port can be checked against them without the old code
- regenerate with `UPDATE_GOLDEN=true go test ./cmd/dive/cli/internal/command/...`

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* add stereoscope v0.3.4 and wire its bus and logger

- stereoscope publishes on dive's partybus and logs through dive's logger (nested under `from-lib=stereoscope`)
- `go` directive moves to 1.26.8 (stereoscope's minimum), CI bootstraps go 1.26.x to match
- `docker/cli` moves to v29.8.2 (via stereoscope), `docker/docker` to v28.5.2 so the existing resolver still builds against the newer `go-connections`
- `scylladb/go-set` stays on the pseudo version stereoscope pins (386 fix, never tagged); a `replace` back to v1.0.2 would break `go install ...@latest`

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* build linux releases with containers-storage support

- linux builds get `-tags containers_image_openpgp,exclude_graphdriver_btrfs` (same as syft), which compiles in stereoscope's containers-storage provider for podman/buildah stores
- still `CGO_ENABLED=0` and static; darwin/windows are unchanged since there's no local store there
- linux/amd64 binary grows about 7MB (21MB to 28MB)

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* add stereoscope based image analysis

- `dive.Analyze(ctx, ref, img)` derives layer info (diff ID, history command, size) and efficiency stats from a
  stereoscope image, exposing the image itself on `Analysis`
- efficiency walks each layer's own tree and sizes whiteouts from the squashed tree of the layers below, no
  restacking
- a whiteout of a path no lower layer has is skipped instead of cutting the layer's walk short
- inefficiencies come sorted largest first with ties ordered by path
- `imagefixture.Load` reads a fixture through stereoscope

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* cover stereoscope efficiency on fixture images

duplicates, removed files and dirs, opaque dirs, whiteouts of missing paths and hardlinks

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* add JSON export from the stereoscope analysis

`export.NewExportFromAnalysis` sits alongside `NewExport` with the same JSON shape:
- `layer[].id` and `layer[].digestId` are both the diff ID
- file lists walk each layer's own tree using the tar header as written, so hardlinks stay links
- implicit parent dirs (no tar header) are left out instead of showing up as empty entries
- `FileInfo` is now export's own type rather than `dive/filetree`'s

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* evaluate CI rules from a stats value

rules and the report read `ci.Stats` (efficiency, wasted bytes, user wasted percent, inefficient files) instead of
`*image.Analysis`, so both analyses can feed the evaluator. `ci.NewStats` reads the stereoscope analysis,
`ci.NewStatsFromImageAnalysis` the old one. Rules and report text are unchanged

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* check export and CI goldens against the stereoscope path

the golden tests now load every fixture through stereoscope and run `dive.Analyze`, `NewExportFromAnalysis` and
the CI evaluator. The old parser versions of these tests are gone (git history has their goldens).

every difference from the old goldens is intentional:
- all 17 `*.export.json`: `layer[].id` is now the diff ID (was the legacy layer dir hash, or `"blobs"` for OCI saves)
- `history-fewer-than-layers.export.json`, `no-history.export.json`: `digestId` is the diff ID even without a
  history entry (was `""`)
- `implicit-parent-dirs.export.json`: implicit parent dirs no longer show up as empty `path: ""` entries
- `duplicate-files-across-layers.{export,ci}.json`, `test-docker-image.{export,ci}.json`,
  `test-oci-docker-image.{export,ci}.json`: equal size inefficient files are ordered by path (was `sort.Sort` order)
- `whiteout-missing-target.{export,ci}.json`: a whiteout of a path no lower layer has no longer aborts the layer's
  efficiency walk, so `/opt/a` counts as 250 wasted bytes, efficiency goes 0.99 -> 0.5 and both rule sets now fail
  `lowestEfficiency` and `highestUserWastedPercent`
- `oci-archive-gzip`: layer order comes from the index now, but the fixture has one layer so only `id` changes

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* add stereoscope based image source loading

- `source.Load` resolves a reference to a stereoscope image, caller owns `img.Cleanup()`
- accepts dive's `docker://` style and stereoscope's `docker:` style schemes
- new sources: oci-archive, oci-dir, registry (`oci-registry`), containerd, containers-storage, auto
- docker client keeps dive's host resolution (`DOCKER_HOST`, `DOCKER_CONTEXT`, config context, ssh hosts)
- podman reads containers-storage first on linux, then the podman socket
- `source.Build` wraps `docker build` / `podman build` and returns a loadable reference

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* accept the new image sources and add --platform

- `--source` / `container-engine` accept every `source.Sources` value plus the `docker-tar` and `oci-registry` aliases
- new `--platform` / `platform` option
- `Analysis.Reference` keeps the image argument as given (scheme included) for `source.Load`
- the old resolver path keeps working off `Analysis.Source` and `Analysis.Image`

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* add bubbletea progress handlers copied from syft

- depend on `github.com/anchore/bubbly` v0.2.2 (brings in bubbletea v1.3.10)
- handlers for stereoscope's pull docker, pull containerd, fetch image and read image events, copied from syft v1.55.0 without the cataloger/SBOM parts
- per layer rows from the new `ReadLayer` event, nested under the read image row and dropped once each layer is indexed
- dive's `TaskStarted` events render as one task tree; tasks that reuse an ID (dive passes the image name for several tasks) still get their own row

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* add a bubbletea progress UI that hands off to the TUI

- `ui.New` picks the bubbletea progress UI on an interactive terminal and the existing line based UI otherwise (no TTY, piped stdin, `--quiet`, `-v`, `NO_TTY`, or `CI` set)
- on `ExploreAnalysis` the progress program quits and restores the terminal before the gocui TUI starts; both UIs share one handoff function
- reports and notifications are held until the progress UI exits, the report text on stdout matches the line based UI
- ctrl-c / esc while the progress UI owns the terminal publishes an interrupt exit event
- console log output (dive's and stereoscope's, which share a logger) is muted while a UI draws, file logging is left alone

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* add a UI-only file tree built from stereoscope trees

- ported the view parts of `dive/filetree` (nodes, view info, render, sort, diff marks) into `ui/v1/filetree`
- the bottom of a layer range is the layer's precomputed `SquashedTree`, each top layer's own tree is compared in turn, same marks as before
- compare trees are built on demand per range and cached, instead of eagerly for every range
- "modified" content checks hash lazily through the image file catalog, only for files present on both sides with equal metadata, cached per file reference
- file metadata comes from the original tar header so hardlinks, sizes and modes look the same as before

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* run the TUI and extract on the stereoscope analysis

- `ExploreAnalysis` now carries a `*dive.Analysis` and blocks the publisher until the TUI is done with it, so the caller can clean up the image afterwards (the payload type sits in the `event` package for now, `payload` importing `dive` is an import cycle until the old resolvers go)
- layer views derive the id, short id and "FROM <id>" from the layer diff ID; image details list inefficiencies in their new (largest first) order
- extract reads the selected layer's files under the selected path from the loaded image instead of re-saving it, and writes them relative to the cwd as before, refusing absolute or `..` tar names, paths through symlinks that leave the cwd, and existing symlinks at a file's own path. It now matches the selected path exactly instead of as a string prefix
- temporary bridge: the old command path loads the image again through `dive/source` for the TUI

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* run dive and dive build on the stereoscope path

- both commands now go options -> `source.Load` -> `dive.Analyze` -> `--json` export, `--ci` evaluation or the TUI, the temporary bridge and the old resolver/adapter calls are gone
- `dive build` runs `source.Build` and loads the built image by its ID; `auto` builds with docker. It keeps the line UI since the build subprocess writes to the terminal
- `dive` uses `ui.New` (bubbletea progress UI where the terminal allows it)
- same task rows as before (Loading, Analyzing, Exporting, Evaluating, Building), and a failed task now stops its spinner
- every `source.Load` temp dir hangs off one generator and `source.Cleanup()` runs after `app.Run()`, so an interrupt (which skips the command's own cleanup) no longer leaves the image copy behind
- the "this can take a while" notification is dropped
- `--json` truncates an existing file instead of writing over its start
- `options.Analysis` keeps only `Image` (the raw reference), `V1UI` is now `LineUI`

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* delete the old image parser and file tree

- `dive/filetree`, `dive/image` (docker and podman resolvers included), `dive.GetImageResolver` and `command/adapter` are gone, stereoscope is the only image model now
- `export.NewExportFromAnalysis` is now `export.NewExport`, `ci.NewStatsFromImageAnalysis` is gone
- the `ExploreAnalysis` payload moves back to `internal/bus/event/payload`
- `docker/docker` is no longer a dependency

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* move the TUI from ui/v1 to ui/tui

- package `v1` is now `tui`, the line UI lives in `ui/line_ui.go`, no behavior change

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* deprecate --ignore-errors

- path errors no longer block the TUI, so the flag gates nothing. It is still accepted (flag and `ignore-errors` config) and warns when set

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* make the CLI tests run without docker

- tests that need docker or podman skip with the reason when the engine (or dive's docker config) isn't reachable
- new docker-free tests run the real command against docker-archive and oci-archive fixtures for `--json` (checked against the export goldens) and `--ci` pass/fail
- the default CI config test now runs `--ci` on the archive instead of relying on a load failure
- snapshots no longer embed the repo path; layer `id` in the JSON snapshot is now the diff ID, and inefficient file ties are ordered by path

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* move to golangci-lint v2

- v1.64.8 is built with go1.24 and refuses the go 1.26 module, binny now pins v2.14.0
- `.golangci.yaml` migrated with `golangci-lint migrate` (same funlen limits, default linters)
- fixes the staticcheck findings v2 reports

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* document the new image sources

- sources table with the new values, both scheme forms, `auto` and `--platform`
- podman reads containers-storage on linux (build tag, on in linux release builds) and the socket elsewhere
- pulls go through the docker API, layer `id` in the JSON is the diff ID, `ignore-errors` is deprecated

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* address review feedback on the stereoscope port

- `dive/source` moves to `internal/source`, and `dive.WalkTree` / `dive.TarHeader` are replaced by an internal `layertree` walker, so the only public surface left is `dive.Analyze` (which now honors ctx)
- docker client is built from the context endpoint (context TLS and ssh kept), `DOCKER_TLS` / `DOCKER_TLS_VERIFY` honored for env hosts
- podman client is built in dive and refuses ssh destinations, since stereoscope's fallback skipped host key checks
- registry http fallback limited to `localhost` and loopback literals, User-Agent no longer carries the binary path
- ctx reaches the TUI, cleanup waits for in-flight loads, and a second ctrl-c during cleanup no longer kills dive
- notifications always print (quiet aside), are escaped, show above the progress frame, and are drained on teardown
- extract writes with `O_EXCL` inside an `os.Root` and reports problems after the TUI exits instead of ending it
- TUI marks opaque whiteouts and their ancestors, implicit dirs no longer render Modified, failed hash reads aren't cached

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* keep go.uber.org/atomic v1.11.0 from main

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* allow CC0-1.0 licensed dependencies

`github.com/therootcompany/xz` (pulled in through stereoscope) is CC0-1.0, a public domain dedication like the already allowed `Unlicense`.

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* escape untrusted text in the final command error

Load errors carry text a registry or daemon controls (response bodies, pull messages), and clio prints the command's error raw, so a registry could drive the terminal (e.g. OSC 52 to set the clipboard).

- root and `build` errors now go through the same escaping as notifications, wrapped so `errors.Is` / `errors.As` still work
- the shared filter also escapes Unicode format characters (bidi overrides, zero width), so a path can't display as something else

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* find the podman machine socket on macOS

Since the ssh fallback was dropped, `--source podman` (and `dive build` with podman) on macOS found nothing unless `CONTAINER_HOST` was set, because podman machine only records ssh destinations in its config.

When no other socket is found, dive now asks `podman machine inspect` for the default machine's API socket and uses it if it exists.

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* check the snapshot cleanup error in the CLI tests

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* point the acceptance tests at the renamed snapshot build dirs

Splitting the goreleaser builds into `linux-build` and `build` changed the snapshot output dirs (`linux-build_linux_amd64_v1`, `build_darwin_amd64_v1`, `build_windows_amd64_v1`), so the acceptance jobs couldn't find the binaries.

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* read OCI archives through docker-archive too

main's parser accepted an OCI archive under `--source docker-archive`, stereoscope's docker-archive provider needs a `manifest.json`. `docker-archive` now falls back to the oci-archive provider, so existing invocations keep working.

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

---------

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>
2026-10-30 10:37:51 -04:00
Alex Goodman
788fcd3834
chore: refactor command structure (#587)
* refactor cli harness

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* use single configuration for ui

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* remove remaining viper rules

* add basic CLI tests

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>

* separate cmd and api concerns for keybindings

* plumb through context for future logging

* port to using internal logger

* internalize non-analysis path

* encapsulate ui with clio

* merge runtime into cmd + add adapter package

* support legacy config shapes

* improve testing around formatting

* fix log-ui interactions

* fix linting and update test snapshots

* fix initialization of tree viewmodel

* indent files in report

* fix build

* setup qemu and buildx in release workflow

* show formatted output in CI

* add cli tests for source flag

* add default ci config cli test

---------

Signed-off-by: Alex Goodman <wagoodman@users.noreply.github.com>
2025-04-08 12:19:18 -04:00
Alex Goodman
dd450a7474
port makefile to taskfile (#584) 2025-03-28 15:16:13 -04:00