utf8-forge

utf8-forge — Full Usage Guide

Complete CLI reference, recipes, and operational notes. For architecture and invariants see DESIGN.md. For the D:\server rollout see EXECUTION.md.


1. Synopsis

utf8-forge <COMMAND> [OPTIONS]

Commands: scan, convert, verify, fix, diff.


2. Commands

2.1 scan

Detect encodings only. Writes nothing. Emits a summary + optional JSON report. Every unknown file also prints a stderr problem line (unknown <path>), consistent with the other modes (exit stays 1).

utf8-forge scan --root D:\server --report scan.json

Exit codes:

2.2 convert

Detect + transcode + atomic write.

# Default: → UTF-8 without BOM
utf8-forge convert --root D:\server

# Dry-run
utf8-forge convert --root D:\server --dry-run --report dry.json

# With backup
utf8-forge convert --root D:\server --backup-dir D:\backup\utf8-forge

# Custom target
utf8-forge convert --root D:\server --target gb18030

# Remote file
utf8-forge convert --url https://example.com/a.cpp --output ./a.cpp

Remote fetch notes (--url): an unrecognizable payload (no detection match) is classified exactly like tree mode — action skipped_unknown, counted in summary.unknown, listed in unknown_files (not error_files), with one stderr problem line. A write-protected destination file is refused exactly like tree mode: exit 1, an error record with io_error: file is write-protected (read-only); chmod +w to convert; the destination is left untouched.

Exit codes:

2.3 verify

Assert every whitelisted file is UTF-8 without BOM.

utf8-forge verify --root D:\server --report verify.json

Exit codes:

2.4 fix

Convert + verify in ONE pass over one traversal: every candidate runs the convert pipeline, then the verify gate over the same file list — no re-walk.

utf8-forge fix --root D:\server --report fix.json

# Preview: the convert pass writes nothing, but the verify pass still runs
# read-only — a dirty tree previews as exit 3 (the current end state).
utf8-forge fix --root D:\server --dry-run

Flags: the full tree flag set plus --target / --dry-run / --backup-dir. No --url / --output (remote fetch stays convert-only). --target accepts only the default utf-8: any other value (CLI or config) is a fatal exit 2 before anything is touched, because the verify gate asserts UTF-8 without BOM.

Exit codes:

2.5 diff

Compare two utf8-forge JSON reports per path. Inputs must be utf8-forge reports containing a files[] array — anything else (wrong schema, a bare array, malformed JSON) is a fatal exit 2 (fix reports expose their convert records; verify outcomes are not compared).

utf8-forge diff --before apply.json --after apply2.json

# CI gate: non-empty diff → exit 1
utf8-forge diff --before a.json --after b.json --fail-on-change

# Write the diff JSON to a file (the summary line always goes to stderr)
utf8-forge diff --before a.json --after b.json --report diff.json

# Without --report, stdout carries only the JSON document: `diff … | jq .` works
utf8-forge diff --before a.json --after b.json | jq .

Record paths are compared relative to each report’s root: the root prefix is stripped (separators normalized to /) before comparing, so identical trees scanned under different root directories no longer diff as full churn. Differing root fields still print a warning; the diff document carries optional before_root / after_root fields (omitted when the source report has no root).

Exit codes:


3. Options

Flag Default Notes
-r, --root <PATH> . Recursive root
-e, --ext <LIST> see DESIGN §5.1 Replaces default whitelist; leading dots stripped (.cpp == cpp); an empty normalized list (--ext ""), a value still starting with a dot (..h), containing /, or containing an inner dot (tar.gz — matching uses the text after the last dot) is fatal (exit 2); a whitelist emptied by --exclude-ext is fatal too
-x, --exclude <LIST> see DESIGN §5.2 Appended to default excludes
-X, --exclude-ext <LIST> empty Appended
--exclude-glob <GLOB> empty Repeatable. Case-insensitive (ASCII folding — non-ASCII byte pairs compare literally) glob over root-relative path components; /-separated, \ accepted; ** spans components, */? match within one; empty pattern → exit 2
--include-rc false Adds .rc/.rc2/.dlg
--include-msbuild false Adds .sln/.vcxproj/...
--include-hidden false Processes dot-prefixed files and directories
--config <PATH> none TOML config supplying defaults; CLI flags override config values; missing/malformed file or unknown keys → exit 2; fatal (exit 2) combined with --url (fetch reads no config)
--ignore-file <PATH> auto Gitignore-style exclusions; fatal (exit 2) when the explicit file is missing; replaces auto-discovery of <root>/.utf8forgeignore
--no-ignore-file false Disables ignore-file handling entirely, including auto-discovery
-t, --target <ENC> utf-8 utf-8-bom, gb18030, utf-16le, utf-16be (convert; fix accepts only the default utf-8)
--dry-run false No writes (convert, fix)
--backup-dir <PATH> none Backup before overwrite (convert, fix)
--max-file-size <BYTES> 200 MiB Skip oversized
--threads <N> CPU count Rayon pool; values below 1 clamp to 1; values above 1024 are rejected as a fatal input error (exit 2)
--report <PATH> none JSON report; parent dirs are created, the report path is excluded from scanning; an unwritable report directory, a report path that is an existing directory, an existing write-protected report file, or a report path equal to the active ignore file (--ignore-file / auto-discovered <root>/.utf8forgeignore) is fatal (exit 2) before any processing
--url <URL> none Remote fetch (convert only); ignores --root
--output <PATH> derived Destination for --url (requires --url)
-q, --quiet false Errors only; in verify / fix, a walk warning about an uninspectable subtree still prints to stderr
-v, --verbose false Per-file detail

--exclude-glob semantics: a pattern must match an entry’s full root-relative component list (a trailing ** absorbs the rest, including zero components) — --exclude-glob src, src/ and src/** all exclude the whole src/ subtree (matching directories are pruned with their contents); **/name/** excludes name/ at any depth. The same grammar restriction applies to ignore-file patterns: in an explicitly given --ignore-file such a line is fatal (exit 2); in the auto-discovered .utf8forgeignore the line is skipped with a warning and the remaining rules stay active.

The grammar supports only *, ? and **; [ and { are rejected as a fatal input error rather than silently matching literally.

Per-command flag surface: --target, --dry-run and --backup-dir exist on convert and fix (fix accepts only --target utf-8). scan and verify reject them (clap error, exit 2). --url / --output are convert-only; --output requires --url (clap error, exit 2). diff accepts only --before, --after, --report and --fail-on-change.

Value placeholders in --help are the option’s field name (e.g. <ROOT>, <EXCLUDE_EXT>); this document uses descriptive names for the same values.

Conflicts (fatal, exit 2):

Notes:


4. Encoding Semantics

4.1 Detection order

UTF-8 BOM → UTF-32 BE BOM (00 00 FE FF) → UTF-32 LE / UTF-16 LE (shared FF FE prefix; the next two bytes 00 00 decide UTF-32 LE) → UTF-16 BE → strict UTF-8 → strict GB18030 → Unknown.

00 00 FE FF (UTF-32 BE) is checked before FF FE — WHATWG-style longest-prefix precedence. Consequence: a file starting FF FE 00 00 is always decoded as UTF-32LE — a UTF-16LE encoding whose first character is U+0000 is genuinely indistinguishable there. If the payload is not also valid UTF-32, the strict UTF-32 decode fails loudly (decode_error, never silent mojibake); if it is, the file simply reads as UTF-32. That ambiguity is why convert --target utf-16le refuses content whose first character is U+0000: the output would begin FF FE 00 00, byte-identical to the UTF-32LE BOM, so a second run would mis-read the file as UTF-32LE and corrupt it. Such a file is recorded as an error row with an encode_error reason (exit 1; original bytes untouched), counted under the summary’s encode_errors. --target utf-16be is safe (FE FF 00 00 re-reads as UTF-16BE).

UTF-32 is read-only: strict decode rejects surrogates, scalar values above 0x10FFFF, and misaligned tails (payload length not a multiple of 4 after the BOM). There is no UTF-32 write target (--target utf-32le → exit 2), and verify fails UTF-32 files (they are not UTF-8).

4.2 BOM policy

4.3 Line endings

Never normalized. CRLF stays CRLF; LF stays LF.

4.4 GB18030 target

--target gb18030 uses WHATWG’s gb18030 encoder, which cannot map exactly one Unicode scalar: U+E5E5 (a Private Use Area character that legacy files sometimes contain). Content containing U+E5E5 is refused: the file is recorded as an error row with an encode_error reason (exit 1, original bytes untouched) — the same refusal pattern as the UTF-16LE NUL guard (§4.1).

Besides U+E5E5, --target gb18030 refuses one more content class: text whose gb18030 encoding is itself valid UTF-8 that reads back as different characters. 1920 scalars encode this way — every gb18030 two-byte cell with lead byte C2–DF and trail byte 80–BF, exactly the byte pairs that also decode as two-byte UTF-8 (e.g. 一 → D2 BB, which the detector reads back as һ; all 1920 re-encode differently after the read-back). Writing such output would make the next run re-detect the file as UTF-8 and silently rewrite it, so the transcode fails with encode_error (exit 1) and the file keeps its original bytes. ASCII content and content whose gb18030 output is not valid UTF-8 convert freely.

The WHATWG mappings are also canonical: a --target gb18030 pass over already-GB18030 files rewrites legacy byte spellings into their canonical WHATWG forms — byte 0x80 → A2 E3 for the euro sign, A3 A0 → A1 A1 for the ideographic space, and 18 further scalars — the CJK ideographs U+9FB4–U+9FBB and the vertical forms U+FE10–U+FE19, whose legacy byte spellings formerly encoded Private Use Area characters — consolidate onto their assigned equivalents. Such files are byte-different but content-equivalent: the first pass reports them converted, and the result is idempotent from the second pass on.


5. Recipes

5.1 C/C++ only

utf8-forge convert --root D:\server --ext h,hpp,c,cpp,cc,inl

5.2 Include MSBuild

utf8-forge convert --root D:\server --include-msbuild

5.3 Exclude a module

utf8-forge scan --root D:\server --exclude "GameServer201,Test_Client"

5.4 Glob exclusion

utf8-forge convert --root D:\server --exclude-glob "**/Generated/**"

5.5 Remote GBK → UTF-8

utf8-forge convert \
  --url https://example.com/legacy_server.cpp \
  --output D:\server\external\legacy_server.cpp \
  --target utf-8 \
  --report fetch-report.json

5.6 Reverse (legacy only)

utf8-forge convert --root D:\server\legacy\scripts --target gb18030 --ext bat,cmd

Content containing U+E5E5 is refused (error row, exit 1); already-GB18030 files are rewritten to their canonical WHATWG byte forms on the first pass (see §4.4).

5.7 Ignore file

# One-off: gitignore-style exclusions from an explicit file (missing → exit 2)
utf8-forge convert --root D:\server --ignore-file D:\server\my.ignore

# Standing setup: commit .utf8forgeignore at the tree root; it is picked up
# automatically (missing → silent, unreadable → warning + continue)
utf8-forge convert --root D:\server

# Turn every ignore source off
utf8-forge convert --root D:\server --no-ignore-file

Example .utf8forgeignore (one pattern per line; # only starts a full-line comment):

# comments and blank lines are skipped
Generated/
legacy.cpp
/tools/tmp*
build/**/auto*.h
!keep.gen

Syntax is a gitignore subset: case-insensitive (ASCII folding — non-ASCII byte pairs compare literally), no escapes (a backslash is a literal character), no character classes or brace expansion ([ and { are not part of the grammar), and — git parity — a file cannot be re-included when its parent directory is excluded. An invalid line in an explicit --ignore-file is fatal (exit 2, line number named); in the auto-discovered file each invalid line is skipped with a warning while the remaining rules stay active. Folding is pinned by tests to ASCII letters: a non-ASCII pattern character matches only its literal counterpart. Negation lifts only the ignore layer; the whitelist / --exclude / --exclude-glob layers still apply.

5.8 Config file

# Defaults from TOML; CLI flags override config values when passed
utf8-forge convert --root D:\server --config D:\server\forge.toml

Example forge.toml:

[filter]
extensions = ["h", "hpp", "c", "cpp", "cc"]
exclude_dirs = ["legacy"]
exclude_ext = ["png"]
exclude_globs = ["**/Generated/**"]
include_rc = false
include_msbuild = false
include_hidden = false

[convert]
target = "utf-8"
backup_dir = "D:\\backup\\utf8-forge\\orig"

[options]
max_file_size = 209715200
threads = 8

Precedence is CLI > config > defaults. List values REPLACE across layers (never concatenate). Missing, malformed, or unknown-key files are fatal (exit 2) — messages carry the TOML line/column. Value validation mirrors the CLI: [filter].extensions = [] (present but empty) is fatal (exit 2) exactly like --ext "" — an absent key keeps the default whitelist — and [convert].backup_dir = "" is fatal, naming the key. root, report, dry-run, url, output, ignore_file, and quiet/verbose are deliberately absent from the schema (ignore_file in TOML is a fatal unknown key); --config combined with --url is fatal too — fetch mode reads no config.

5.9 Operator notes


6. Reports

JSON report schema is documented in EXECUTION.md §12.

Key fields:

The summary block is mode-specific:

already_utf8 counts files already byte-identical at the target encoding: with --target gb18030, untouched ASCII files count too. GB18030 files that carry legacy byte spellings are not byte-identical: the first --target gb18030 pass canonicalizes them (§4.4) and reports converted; they count as unchanged only from the second pass on.


7. Exit Codes

Code Meaning
0 Success (diff: comparison finished — differences do not change the exit code unless --fail-on-change)
1 Non-fatal per-file issues (unknown, decode_error, encode_error, io_error; convert: also fetch_error, oversized --url payload); diff --fail-on-change: the reports differ
2 Fatal in every command (bad args, missing root, flag conflicts, I/O setup failure); also emitted by clap; diff: missing/malformed input report
3 verify found non-UTF-8 whitelisted files (or could not inspect part of the tree); fix: any file fails the verify gate (oversized/unreadable count as failed — fail-closed; the gate wins over convert-side issues)

8. CI Integration

- name: Verify encoding
  run: utf8-forge verify --root . --report encoding-report.json

verify exit 3 fails the job — this is the intended gate.


9. Troubleshooting

See AGENT.md §9 and EXECUTION.md §11.