Records the reasoning: the flaws of the old Oh My Zsh extract, the move from Bash to Go, backend choices, staging and placement, --force semantics, profiles, exclusion, the progress display and the testing approach.
15 KiB
Design notes
This file records why x and c behave the way they do. The README describes
what they do.
1. History
Oh My Zsh's extract. Before this project, x was Oh My Zsh's extract
plugin (alias x=extract). Its flaws set the requirements:
Problem in extract |
Here |
|---|---|
mkdir + cd per archive before validating anything |
everything is validated first |
status taken from $? after || and pipe fallbacks, so failures could pass as success |
every backend status is checked; pipelines fail if any stage fails |
| extracts straight into the target, so a corrupt archive leaves partial output | staging directory, then an atomic rename |
random suffix (dir-x7k2q) on a name collision |
deterministic name; a collision is an error unless --force |
cpio/rpm via GNU cpio -id without --no-absolute-filenames |
bsdtar with its secure defaults |
.deb: rm *.tar.* in the current directory |
the payload member is streamed; nothing to clean up |
-r deletes the source archive |
no delete option at all |
pigz/pbzip2/pixz fallback chains |
one backend per format |
The Bash version. The first implementation was two Bash scripts. It
worked and passed 83 tests, but Bash limited its quality. Each script had to
duplicate the shared helpers to stay independently executable. Testing needed
a homemade harness plus Python to generate fixtures. Several guarantees were
weaker than they should be: a non-atomic check-then-mv, a --force merge
done with cp -a, and an interrupted backend that ran to completion before
the trap fired.
2. Why Go
- Shared code without coupling. Both commands compile the same
internal/packages into separate static binaries. Each binary is still independently executable and installable, with no library path to manage. - Types and tooling. Typed code,
gofmt,go vet, staticcheck, and the standardtestingpackage replace convention-based shell code. - Correctness primitives. The tools use
renameat2(RENAME_NOREPLACE), context-cancelled child processes, and exact argument vectors with no shell quoting layer. - No runtime. The binaries are static (
CGO_ENABLED=0), with no interpreter version to depend on.
The only dependency is golang.org/x/sys, which is maintained by the Go
team. The standard syscall package has no renameat2 on amd64, and
x/sys also provides a proper isatty check. The CLI parser is about 80
lines of tested code, which beats adding a CLI framework.
Archive formats are still handled by system tools, as specified. Go's
archive/* packages are used only in tests, to generate archives.
3. Architecture
cmd/x, cmd/c cli.Main("x", extract.Run): nothing else
internal/cli Parse (GNU-style options), Logger, exit codes, Problems
(collects every validation error), Main (signals -> context)
internal/proc Pipeline: runs argv commands connected by pipes, with
pipefail semantics; on cancel, SIGTERM then kill after 5 s
internal/fsx RenameNoReplace, Move, Merge, RemoveAll
internal/extract format table, UDF probe, backend argv builders, staging,
placement
internal/create type table, profile table, argv builders, validation,
output handling
Every backend command line is built by a pure function, so the unit tests pin
the exact arguments of every backend and every profile. Side effects live in
thin run/build functions that the end-to-end tests exercise.
4. Backend choice
x uses bsdtar (libarchive) wherever it reads a format well. On Arch it
is always present (pacman depends on libarchive). It detects compression
automatically, and its default secure-extraction flags were verified with
crafted archives: it refuses .., refuses to extract through symlinks, and
strips absolute paths. Using one backend gives tar, zip, cab, ISO 9660, cpio,
deb and rpm one shared security model. It also makes unzip, cabextract,
cpio and rpm2cpio unnecessary (rpm2cpio isn't even installed here).
7-Zip handles 7z and RAR. libarchive's 7z reader lacks some filters, and
its RAR5 support is partial. Arch's 7zip includes the RAR codec, so unrar
isn't needed. 7-Zip rewrites .. instead of refusing it, but entries still
stay inside the output directory, and versions 25 and later refuse dangerous
links (verified).
ISO: bsdtar normally, 7-Zip for UDF. This is a deterministic choice, not
a fallback. bsdtar keeps Rock Ridge names, symlinks and modes, while 7-Zip
truncates names to Joliet's 64 characters and loses symlinks. But bsdtar
cannot read UDF, and UDF-only images such as Windows media carry an ISO 9660
"bridge" that contains only a README. bsdtar would successfully extract the
wrong thing. x therefore checks the volume recognition sequence for an
NSR02/NSR03 descriptor (identifier at byte 1 of each 2048-byte sector from
byte 32768). Passing -tudf to 7-Zip broke hybrid images; its own detection
picks UDF correctly.
Standalone compressors run with -dc, so the source is never touched.
.Z goes through gzip.
c uses GNU tar. It needs a separate directory per input (-C) and must
accept names that start with -. GNU tar's --add-file=NAME handles both.
The compressor runs as a separate pipeline stage with an exact argument list.
c uses Info-ZIP zip. It has no -C, so c runs it once per input,
with the input's parent as the working directory (exec.Cmd.Dir, not
cd), appending to the same archive each time. Exclude patterns go through a
file (-x@file), because zip would parse a pattern that starts with - as an
option.
c uses 7-Zip for 7z. Given an absolute path, 7-Zip stores the last
component, which matches the naming rule. -snl stores symlinks as links.
7-Zip writes an archive even when an input is missing (exit 1), which is one
more reason c validates inputs first and treats any non-zero exit as a
failure.
5. Staging and placement (x)
Each archive is extracted into DEST/.x-NNNN (os.MkdirTemp, mode 0700, on
the destination filesystem). After the backend succeeds:
- one top-level entry:
Moveit toDEST/<entry>; - several entries: set the stage to the umask default mode and
Movethe stage itself toDEST/<stem>; - none: warn.
Move is renameat2(RENAME_NOREPLACE). That makes the existence check and
the rename a single atomic step, so a path that appears concurrently is never
replaced. (On a filesystem without the flag, it falls back to
check-then-rename.) An EEXIST from the rename is the conflict signal; x
doesn't check beforehand.
The single-root rule is the one automatic naming rule. It is justified because both alternatives are worse:
- always extracting into
stem/createsproj-1.0/proj-1.0/for nearly every source tarball; - never wrapping scatters tarbombs across the directory.
It applies identically to every format.
Lessons from testing that the code handles:
- Read-only directories. Renaming a read-only directory to a new parent
fails, because its
..entry must change, and ISO images routinely contain such directories.Moveaddsu+wfor the rename and restores the full mode bits (setgid and sticky included). - Cleanup. A failed stage may contain read-only directories.
RemoveAllmakes directories accessible before removing them. It decides what is a directory with lstat (fs.DirEntry), so it never follows symlinks; a unit test proves a symlink's target keeps its mode. - Umask. The umask is read once, with a pair of
umask(2)calls before any files are created, to compute the mode of the wrapper directory.
6. --force semantics
"Overwrite where supported" could mean replacing whole directories, but that
would delete user files that aren't in the archive. --force therefore
merges, and fsx.Merge does it by renaming entries, not copying them:
- each file or symlink is renamed over its counterpart, an atomic step that needs no copy (stage and destination share a filesystem);
- directories are merged recursively;
- a file never replaces a directory, and a directory never replaces a file;
- the destination is inspected with
lstat, so a symlink in the destination is treated as a file and never followed (unit-tested); - the archive being extracted is never overwritten, even when it lies inside the target.
The merge as a whole is not atomic. A transactional merge would need a copy of the whole destination.
7. Keeping sources
The specification asked whether keeping sources should be the default. x
never deletes its input and has no option to do so. -k is accepted as a
no-op so that gzip/zstd habits don't cause errors.
8. Output handling (c)
- Temporary file. The archive is built at
OUTDIR/.c-NNNN/archive.<type>. A directory is needed because zip and 7z append an extension to a name without one, and zip rejects an existing empty file. - Existing output.
cfails before doing any work. With--force, the old file is replaced only by a finished archive (rename(2)). Without--force, the final rename is no-replace, so a file that appears during archiving is not destroyed. - Output inside an input. This is refused rather than auto-excluded. Auto-exclusion would mean translating a path into each backend's pattern language, which is fragile. Refusal is one rule with an obvious fix.
- Naming. Inputs are resolved like
realpathand stored asbasename(resolved). That way.,.., trailing slashes and absolute paths all behave sensibly, with one rule for all backends. A symlink given as an input is stored under its target's name. Symlinks inside trees stay links. - Type resolution.
--typewins if given; otherwise the extension decides. A contradiction between the two is an error.
9. Profiles
Flags are set per tool and never shared between tools. "Best" is the highest
standard level: xz -9, zstd -19, 7z -mx=9. zstd --ultra -22 and
xz -9e are excluded: they cost far more memory for marginal gains, and
--ultra output needs large windows to decompress. xz and zstd run with
-T0. xz's multithreaded block splitting costs very little ratio, and xz
reduces the thread count to fit its memory limit. bzip2's default is already
-9, so --best equals the default there, and this is documented.
10. Exclusion semantics
The three backends match exclusion patterns differently: tar against path
components, zip against full stored paths, and 7z against names via -xr!.
c defines one meaning, "a shell glob matched against a file or directory
name, at any depth", and translates it for each backend:
- tar:
--exclude=P(unanchored by default); - zip:
P,*/P,P/*,*/P/*; - 7z:
-xr!P.
Patterns with / are rejected, because they couldn't mean the same thing for
all three. An end-to-end test checks the same exclusions against every type.
11. CLI conventions
- Option parsing. GNU-style permutation,
--to end options, bundled short flags, and attached or=values. Long options can't be abbreviated, which keeps parsing predictable. - Repeated flags. The last of
-q/-vwins, and likewise the last of-f/-binc. - Output. Messages are
x: …/c: error: …on stderr. Stdout is used only for--helpand--version. - Signals. SIGINT, SIGTERM and SIGHUP cancel a context.
procsends SIGTERM to the backend, its deferred cleanup removes the temporary directory, and the tool exits with 128 + n. The first signal unregisters the handler, so a second Ctrl-C kills immediately. - The
-fconflict. The specification gives-fto--forceinxand to--fastinc.cexposes force only as--force, so a stray-fcan at worst make an archive larger.
12. Progress display
The display copies zap's look (Catppuccin colors, gradient bar, braille
spinner, a data · speed · eta line), but not its implementation. zap uses
Charm's bubbletea, which takes over the terminal for its own renderer. Here,
external backends write warnings and errors to the same terminal, so a
full-screen framework would fight them. internal/progress instead draws
three lines with plain ANSI codes and erases them in place. It adds no
dependencies.
- Measurement. The tools don't parse backend output. Every 80 ms, the
monitor reads
rchar(bytes read) from/proc/PID/iofor one process of the pipeline. That works the same for bsdtar, 7-Zip, GNU tar, zip and the compressors, without changing how any of them is run.proc.PipelineIOreports the process IDs through a callback.xwatches the process that reads the archive (the first stage).cwith tar formats watches the compressor (the last stage). The compressor is the slow stage, andtarcan finish in a fraction of a second when xz buffers its whole input. A process that has exited can't be read, so watchingtarshowed 0 bytes for the whole run.- Reads by successive processes add up, because zip runs once per input.
- Honest limits. Once everything has been read, the info line says "finishing…" instead of an ETA of 0. Re-reads (zip rereads its archive when appending) are clamped at the total. Speed is an exponential moving average with weight 0.15, as in zap.
- Never in the way.
- The display draws only on a terminal of at least 40 columns, only at normal verbosity, and only after 250 ms.
- Each line is truncated to the terminal width, so nothing wraps and the display can be erased line by line.
- Backend output goes through
progress.Writer, which erases the display, prints complete lines and redraws. - Two signs of a password prompt stop the display: an unterminated line that
stays put for 150 ms (7-Zip's prompt), or a backend that opens
/dev/tty(bsdtar's prompt). The display then never draws again. In the/dev/ttycase it is left on screen rather than erased, because the cursor will have moved. - Interrupts erase the display through the same deferred
Stopthat removes the staging directory.
- Testability. Rendering is a pure function of a
frame. The monitor's clock, terminal,/procreaders and delay are all injectable.
13. Testing
| Layer | What it covers |
|---|---|
internal/* unit tests |
parser table; format and type tables; UDF probe on synthetic images; exact argv of every backend and profile; pipeline pipefail, missing programs, cancellation; fsx no-replace, read-only moves, merge rules, symlink-safe removal |
internal/progress |
rendering (layout, gradient endpoints, widths, truncation, no-color), smoothing, accumulation across processes, show delay, erase sequences, messages above the display, both kinds of prompt; /proc readers against the test process itself |
tests/ end-to-end |
builds both binaries; every format round trip; every type × profile checked by the format's own tool; malicious archives; conflicts and --force; missing dependencies (a PATH built from symlinks that leaves the tool out); zsh invocation; the progress display on a real pseudo-terminal (script(1)), including -q and NO_COLOR |
Test fixtures are generated in Go: tar and zip with archive/*, and RPM,
CAB, RAR 4 and .Z written byte by byte. No binary blobs are checked in, and
Python is not required. A test skips, rather than fails, when an external
tool is missing.