Batch HTML Conversion: A Safe CLI and Automation Workflow
Design a repeatable HTML batch process with canaries, logs, validation and rollback.
Canary Checks Before Bulk Processing
Run a canary batch on a representative 5% sample before touching the full file set. A misconfigured conversion corrupting thousands of documents is unrecoverable without backups.
Required Canary Checks
| Check | Purpose | Failure Action |
|---|---|---|
| DOCTYPE presence | Confirms file is HTML, not plain text or XML | Abort batch; flag files for manual review |
| Encoding declaration | Prevents mojibake during re-encoding | Reject files without explicit charset |
| Tag balance | Ensures opening/closing tags match | Log and skip; do not convert malformed files |
| File size sanity | Catches zero-byte or truncated files (>0 bytes, <100 MB) | Remove from batch; notify operator |
A minimal canary script:
for each file in sample_set:
if not has_doctype(file):
log("FAIL: missing DOCTYPE in " + filename)
exit(1)
if not has_charset_meta(file):
log("WARN: no charset in " + filename)
Proceed to full batch only when all canary files pass every check. A single DOCTYPE failure aborts the entire run.
Conversion Patterns and Their Failure Modes
Encoding Migration (ISO-8859-1 to UTF-8)
The HTML specification requires UTF-8 as the preferred encoding. Converting legacy encodings is the most common batch task.
Workflow:
- Read the original
<meta charset>orContent-Typeheader. - Decode using the declared encoding; if absent, attempt detection via BOM.
- Re-encode as UTF-8, updating
<meta charset="UTF-8">. - Write to a new file with a
.utf8.htmlextension. Never overwrite originals.
Failure logging:
2025-04-09 10:32:17 | CONVERT | iso-8859-1 → utf-8 | invoices/2024/october.html | PASS
2025-04-09 10:32:19 | CONVERT | iso-8859-1 → utf-8 | invoices/2024/september.html | FAIL: undecodable byte 0x9A at line 47
When a byte cannot be decoded, log the hex value and line number into a separate error report. Do not skip silently.
Document Type Conversion (HTML4 Strict to HTML5)
The HTML specification changed DOCTYPE requirements between versions. This pattern is more invasive than encoding migration.
Required transformations:
- Replace
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">with<!DOCTYPE html> - Remove deprecated presentational attributes (
bgcolor,align,border) and move styling to CSS - Update void element syntax:
<br>not<br />,<hr>not<hr />
Canary for this pattern: Convert three files manually first. Compare rendered output using a DOM diff tool. If any structural element shifts—a table loses a cell, a form input reflows—redesign the conversion script before proceeding.
Fragment to Full Document
Converting HTML fragments from a CMS export into standalone documents requires wrapping with <html>, <head>, and <body> tags.
Critical validation: Check that the fragment does not already contain these tags. A fragment with a stray </html> produces invalid output.
if contains_any(fragment, ["<html", "<head", "<body"]):
log("SKIP: fragment appears to be a full document")
write_to_separate_manual_review_queue()
Structured Logging and Audit Trail
Every conversion event must produce a machine-readable log. Use JSON-lines format for filtering and replay.
Log Entry Schema
| Field | Example | Purpose |
|---|---|---|
| timestamp | 2025-04-09T10:32:17Z | Sorting and replay ordering |
| source_hash | sha256:abc123... | Detect if source changed mid-batch |
| operation | encode_migration | Which conversion pattern ran |
| input_path | /data/raw/001.html | Original file location |
| output_path | /data/utf8/001.html | Converted file location |
| status | PASS / FAIL / SKIP | Outcome code |
| error_detail | undecodable byte at line 47 | Human-readable failure reason |
| checksum_output | sha256:def456... | Integrity check post-conversion |
Logging Without Side Effects
Write logs to a dedicated directory, not stdout alone. If the batch runs overnight and the terminal closes, logs survive. Rotate logs by date to prevent single-file bloat. Hard limit: 10,000 entries per log file before rotation.
Validation After Conversion
Run three layers of validation. A file passing only one layer is not considered converted.
Layer 1: Structural Integrity
Use a parser that follows the HTML parsing algorithm, such as the W3C Nu HTML Checker. Reject any file that produces parse errors, even if it renders in a browser. Zero parse errors is the only acceptable result.
Layer 2: Content Preservation
For each file pair (original and converted):
- Extract all text nodes from both using a DOM parser.
- Compare text content, ignoring whitespace-only differences.
- Flag any file where text differs by more than 0.5%. This threshold accounts for encoding-related character substitutions but catches dropped paragraphs or truncated content.
Layer 3: Link and Resource Integrity
If the conversion modified paths (relative to absolute, or directory restructuring), validate that internal anchors and resource references resolve. Run this check for document collections with cross-references. A single broken internal anchor halts the batch.
Rollback Procedure
Rollback must restore exact original state—file contents, timestamps, and permissions.
Automated Rollback Steps
- Pause the pipeline immediately upon detecting failures exceeding the configured threshold (default: 3 consecutive failures).
- Restore from backup using the pre-conversion file listing. Preserving originals is a non-negotiable prerequisite for rollback.
- Verify restoration by comparing SHA-256 checksums of restored files against the pre-conversion manifest.
- Reject incomplete rollbacks. If any checksum mismatches, log the discrepancy and do not mark the batch as recovered.
When Rollback Is Impossible
- The conversion script overwrote originals without backup.
- The file system was modified by another process during conversion.
- Input files resided on a network drive that disconnected mid-write.
In these cases, recovery requires file-level restoration from version control or backup tape. The batch workflow must detect these conditions before starting and abort with a clear error message.
Reproducible Automation Sequence
A safe batch conversion script follows this fixed order:
1. Generate SHA-256 checksum manifest of all input files
2. Run canary checks on 5% random sample
3. If canary passes:
a. Copy input files to working directory (never mutate originals)
b. For each file:
- Log start time and source hash
- Perform conversion
- Write to output directory
- Validate structural integrity (Layer 1)
- Compute output checksum
- Log result
c. If any validation fails:
- Log failure details
- Pause pipeline
- Await operator decision (do not auto-resume)
4. If all files pass all three validation layers:
- Replace originals with converted files
- Archive originals as compressed backup (retain for 30 days minimum)
- Generate summary report with pass/fail/skip counts
This sequence prevents the most common failure: converting files without knowing whether the output is valid.
Hard Limits and Boundaries
No automated batch process can recover files that are not HTML. If a file lacks a DOCTYPE, contains binary data, or exceeds 100 MB for a single HTML file, the workflow must reject it. The HTML specification defines the boundaries of what constitutes HTML; files outside those boundaries require separate, format-specific tooling.
Semantic correctness—whether converted HTML conveys the same meaning as the original—cannot be guaranteed by structural validation alone. For critical documents, a human review pass after automation remains the only reliable safeguard.