Skip to content
This repository was archived by the owner on Nov 23, 2026. It is now read-only.

Commit 7bc0765

Browse files
committed
Color and tabulate converter and verify output
1 parent 1badd25 commit 7bc0765

3 files changed

Lines changed: 95 additions & 24 deletions

File tree

‎admin/convert.php‎

Lines changed: 37 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -38,14 +38,27 @@ function loadEnvConfig(): array {
3838
return $config;
3939
}
4040

41+
/**
42+
* Writes `$message` and a newline, in the ANSI SGR `$style` when `$stream` is a terminal and `NO_COLOR` is unset.
43+
*
44+
* @param resource $stream
45+
*/
46+
function writeLine(string $message, string $style = '', $stream = STDOUT): void {
47+
if ($style !== '' && (string) getenv('NO_COLOR') === '' && stream_isatty($stream)) {
48+
$message = sprintf("\033[%sm%s\033[0m", $style, $message);
49+
}
50+
51+
fwrite($stream, $message . "\n");
52+
}
53+
4154
function getSourceDirectory(): string {
4255
$config = loadEnvConfig();
4356

4457
if ($config['DOCS_SOURCE_TYPE'] === 'project' && !empty($config['DOCS_PROJECT_PATH'])) {
4558
$projectPath = rtrim($config['DOCS_PROJECT_PATH'], '/') . '/';
4659
if (!is_dir($projectPath)) {
47-
echo "Error: Project path does not exist: $projectPath\n";
48-
echo "Please check your .env file configuration.\n";
60+
writeLine(sprintf('Error: Project path does not exist: %s', $projectPath), STYLE_ERROR, STDERR);
61+
writeLine('Please check your .env file configuration.', '', STDERR);
4962
exit(1);
5063
}
5164
return $projectPath;
@@ -58,17 +71,22 @@ function checkPandocVersion(): void {
5871
exec('pandoc --version', $output, $exitCode);
5972

6073
if ($exitCode !== 0) {
61-
fwrite(STDERR, "Error: pandoc is not installed. Install pandoc " . PANDOC_VERSION . ".\n");
74+
writeLine(sprintf('Error: pandoc is not installed. Install pandoc %s.', PANDOC_VERSION), STYLE_ERROR, STDERR);
6275
exit(1);
6376
}
6477

6578
$installed = trim(str_replace('pandoc', '', $output[0]));
6679

6780
if ($installed !== PANDOC_VERSION) {
68-
fwrite(STDERR, "Warning: pandoc $installed is installed, but the conversion is verified against pandoc " . PANDOC_VERSION . ".\n");
81+
writeLine(sprintf('Warning: pandoc %s is installed, but the conversion is verified against pandoc %s.', $installed, PANDOC_VERSION), STYLE_WARNING, STDERR);
6982
}
7083
}
7184

85+
const STYLE_ERROR = '31';
86+
const STYLE_WARNING = '33';
87+
const STYLE_SUCCESS = '32';
88+
const STYLE_STEP = '1';
89+
7290
define('PANDOC_VERSION', '3.12.1');
7391
define('PANDOC_WORKERS', 8);
7492
define('SOURCE_DIR', getSourceDirectory());
@@ -150,7 +168,7 @@ function updateFile(array $file, string $function): void {
150168
$result = $function($data, $file['folder']);
151169

152170
if ($result === null) {
153-
fwrite(STDERR, "Error: $function failed on {$file['path']} (" . preg_last_error_msg() . "), leaving the file unfiltered\n");
171+
writeLine(sprintf('Error: %s failed on %s (%s), leaving the file unfiltered', $function, $file['path'], preg_last_error_msg()), STYLE_ERROR, STDERR);
154172
return;
155173
}
156174

@@ -241,7 +259,7 @@ function createMkDocsAssets(): void {
241259
$assetsDir = TARGET_DIR . 'assets/';
242260

243261
if (!is_dir($staticDir)) {
244-
echo "Warning: _static directory not found, skipping MkDocs assets creation\n";
262+
writeLine('Warning: _static directory not found, skipping MkDocs assets creation', STYLE_WARNING);
245263
return;
246264
}
247265

@@ -297,7 +315,7 @@ function createMkDocsThemeCSS(): void {
297315
echo "Copying MkDocs theme CSS: $sourcePath to $targetPath\n";
298316
copy($sourcePath, $targetPath);
299317
} else {
300-
echo "Warning: CSS file not found: $sourcePath\n";
318+
writeLine(sprintf('Warning: CSS file not found: %s', $sourcePath), STYLE_WARNING);
301319
}
302320
}
303321

@@ -313,7 +331,7 @@ function createMkDocsThemeCSS(): void {
313331
echo "Copying MkDocs theme JS: $sourcePath to $targetPath\n";
314332
copy($sourcePath, $targetPath);
315333
} else {
316-
echo "Warning: JS file not found: $sourcePath\n";
334+
writeLine(sprintf('Warning: JS file not found: %s', $sourcePath), STYLE_WARNING);
317335
}
318336
}
319337
}
@@ -340,7 +358,7 @@ function convertRstToMd(array $jobs): int {
340358
applyAfterFilters($job['target'], $copies[$i]);
341359

342360
if ($exitCodes[$i] !== 0) {
343-
fwrite(STDERR, "Error: pandoc failed with exit code {$exitCodes[$i]} on {$job['source']}\n");
361+
writeLine(sprintf('Error: pandoc failed with exit code %d on %s', $exitCodes[$i], $job['source']), STYLE_ERROR, STDERR);
344362
$failures++;
345363
}
346364
}
@@ -430,7 +448,7 @@ function convertSingleFile(string $filename): bool {
430448
$targetFile = TARGET_DIR . $filename . '.md';
431449

432450
if ($sourceFile === false) {
433-
echo "Error: File '$filename.rst' not found in " . SOURCE_DIR . "\n";
451+
writeLine(sprintf("Error: File '%s.rst' not found in %s", $filename, SOURCE_DIR), STYLE_ERROR, STDERR);
434452
return false;
435453
}
436454

@@ -443,7 +461,7 @@ function convertSingleFile(string $filename): bool {
443461
return false;
444462
}
445463

446-
echo "Conversion completed successfully!\n";
464+
writeLine('Conversion completed successfully!', STYLE_SUCCESS);
447465
return true;
448466
}
449467

@@ -453,31 +471,31 @@ function convertSingleFile(string $filename): bool {
453471
$filename = $argv[1];
454472
exit(convertSingleFile($filename) ? 0 : 1);
455473
} else {
456-
echo "Starting full conversion...\n";
474+
writeLine('Starting full conversion...', STYLE_STEP);
457475

458476
if (!is_dir(TARGET_DIR)) {
459-
echo "Creating target directory...\n";
477+
writeLine('Creating target directory...', STYLE_STEP);
460478
mkdir(TARGET_DIR, 0755, true);
461479
}
462480

463-
echo "Cleaning target directory...\n";
481+
writeLine('Cleaning target directory...', STYLE_STEP);
464482
clean(TARGET_DIR);
465483

466-
echo "Copying essential assets...\n";
484+
writeLine('Copying essential assets...', STYLE_STEP);
467485
copyAssets();
468486

469-
echo "Loading filters...\n";
487+
writeLine('Loading filters...', STYLE_STEP);
470488
loadFilters();
471489

472-
echo "Converting RST files to Markdown...\n";
490+
writeLine('Converting RST files to Markdown...', STYLE_STEP);
473491
$jobs = [];
474492
convert(SOURCE_DIR, TARGET_DIR, $jobs);
475493
$failures = convertRstToMd($jobs);
476494

477495
if ($failures > 0) {
478-
fwrite(STDERR, "Conversion failed for $failures file(s).\n");
496+
writeLine(sprintf('Conversion failed for %d file(s).', $failures), STYLE_ERROR, STDERR);
479497
exit(1);
480498
}
481499

482-
echo "Conversion completed successfully!\n";
500+
writeLine('Conversion completed successfully!', STYLE_SUCCESS);
483501
}

‎admin/filters/includes.php‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ function before_filter_includes(string $data, string $folder): ?string {
5353
$file = str_starts_with($matches[3], '/') ? rtrim(SOURCE_DIR, '/') . $matches[3] : $folder . '/' . $matches[3];
5454

5555
if (! is_file($file)) {
56-
fwrite(STDERR, sprintf("Warning: sample %s not found for literalinclude in %s\n", $matches[3], $folder));
56+
writeLine(sprintf('Warning: sample %s not found for literalinclude in %s', $matches[3], $folder), STYLE_WARNING, STDERR);
5757
array_push($result, ...$directive);
5858

5959
continue;

‎admin/verify.php‎

Lines changed: 57 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,58 @@
1111
define('ALIGNMENT_WINDOW', 3);
1212
define('MAX_LISTED_FAILURES', 20);
1313

14+
const STYLE_HEADING = '1';
15+
const STYLE_PASS = '32';
16+
const STYLE_FAIL = '1;31';
17+
18+
/**
19+
* `$text` in the ANSI SGR `$style` when standard output is a terminal and `NO_COLOR` is unset.
20+
*/
21+
function styled(string $text, string $style): string {
22+
if ((string) getenv('NO_COLOR') !== '' || ! stream_isatty(STDOUT)) {
23+
return $text;
24+
}
25+
26+
return sprintf("\033[%sm%s\033[0m", $style, $text);
27+
}
28+
29+
/**
30+
* ASCII table with a bold header row, padding each cell before styling it.
31+
*
32+
* @param list<string> $headers
33+
* @param list<list<array{string, string}>> $rows Cells as `[text, style]` pairs
34+
* @param list<int> $rightAligned Column indexes
35+
*/
36+
function renderTable(array $headers, array $rows, array $rightAligned): string {
37+
$widths = array_map('strlen', $headers);
38+
39+
foreach ($rows as $row) {
40+
foreach ($row as $column => [$text]) {
41+
$widths[$column] = max($widths[$column], strlen($text));
42+
}
43+
}
44+
45+
$border = '+' . implode('+', array_map(fn (int $width): string => str_repeat('-', $width + 2), $widths)) . "+\n";
46+
$line = function (array $cells) use ($widths, $rightAligned): string {
47+
$padded = [];
48+
49+
foreach ($cells as $column => [$text, $style]) {
50+
$text = str_pad($text, $widths[$column], ' ', in_array($column, $rightAligned, true) ? STR_PAD_LEFT : STR_PAD_RIGHT);
51+
$padded[] = $style === '' ? $text : styled($text, $style);
52+
}
53+
54+
return sprintf("| %s |\n", implode(' | ', $padded));
55+
};
56+
57+
$table = $border . $line(array_map(fn (string $header): array => [$header, STYLE_HEADING], $headers)) . $border;
58+
59+
foreach ($rows as $row) {
60+
$table .= $line($row);
61+
}
62+
63+
return $table . $border;
64+
}
65+
1466
function usage(): never {
1567
fwrite(STDERR, "Usage: php admin/verify.php --source <rst dir> --output <docs dir> [--summary <file>]\n");
1668
exit(2);
@@ -429,15 +481,14 @@ function checkLeftovers(array &$checks, array $markdown, string $outputFile): vo
429481
* @param array<string, array{expected: int, actual: int, failures: list<string>}> $checks
430482
*/
431483
function report(array $checks, ?string $summaryFile): void {
432-
printf("%-20s %10s %10s %s\n", 'Check', 'Expected', 'Actual', 'Result');
433-
484+
$rows = [];
434485
$markdown = "## Conversion checks\n\n| Check | Expected | Actual | Result |\n| --- | ---: | ---: | --- |\n";
435486
$details = '';
436487

437488
foreach ($checks as $name => $check) {
438489
$passed = $check['failures'] === [];
439490

440-
printf("%-20s %10d %10d %s\n", $name, $check['expected'], $check['actual'], $passed ? 'pass' : 'FAIL');
491+
$rows[] = [[$name, ''], [(string) $check['expected'], ''], [(string) $check['actual'], ''], $passed ? ['pass', STYLE_PASS] : ['FAIL', STYLE_FAIL]];
441492
$markdown .= sprintf("| `%s` | %d | %d | %s |\n", $name, $check['expected'], $check['actual'], $passed ? '✅' : '❌');
442493

443494
if (! $passed) {
@@ -448,9 +499,11 @@ function report(array $checks, ?string $summaryFile): void {
448499
}
449500
}
450501

502+
echo renderTable(['Check', 'Expected', 'Actual', 'Result'], $rows, [1, 2]);
503+
451504
foreach ($checks as $name => $check) {
452505
if ($check['failures'] !== []) {
453-
printf("\n%s (%d):\n", $name, count($check['failures']));
506+
printf("\n%s\n", styled(sprintf('%s (%d):', $name, count($check['failures'])), STYLE_HEADING));
454507

455508
foreach (array_slice($check['failures'], 0, MAX_LISTED_FAILURES) as $failure) {
456509
echo ' ', $failure, "\n";

0 commit comments

Comments
 (0)