generated from filamentphp/plugin-skeleton
-
Notifications
You must be signed in to change notification settings - Fork 14
/
generate-toc.php
122 lines (97 loc) · 2.74 KB
/
generate-toc.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
<?php
namespace Pboivin\FilamentPeek;
use Illuminate\Support\Str;
require_once './vendor/autoload.php';
define('BASE_URL', 'https://github.com/pboivin/filament-peek/blob/2.x/');
define('DOC_FILES', [
'docs/configuration.md',
'docs/page-previews.md',
'docs/builder-previews.md',
'docs/javascript-hooks.md',
'docs/upgrade-guide.md',
]);
function generateToc(string $prefix): string
{
$toc = [];
foreach (DOC_FILES as $file) {
foreach (file($file) as $line) {
if (preg_match('/^# /', $line)) {
$title = preg_replace('/^# /', '', trim($line));
$slug = Str::slug($title);
$toc[] = "- [$title]({$prefix}{$file})";
} elseif (preg_match('/^## /', $line)) {
$title = preg_replace('/^## /', '', trim($line));
$slug = Str::slug($title);
$toc[] = " - [$title]({$prefix}{$file}#{$slug})";
}
}
}
return implode("\n", [
'<!-- BEGIN_TOC -->',
'',
...$toc,
'',
'<!-- END_TOC -->',
]);
}
function generateFooter(string $prefix): string
{
$toc = [];
foreach (DOC_FILES as $file) {
foreach (file($file) as $line) {
$file = basename($file);
if (preg_match('/^# /', $line)) {
$title = preg_replace('/^# /', '', trim($line));
$toc[] = "- [$title]({$prefix}{$file})";
}
}
}
return implode("\n", [
'<!-- BEGIN_TOC -->',
'',
...$toc,
'',
'<!-- END_TOC -->',
]);
}
function updateMarkdown(string $file, string $toc): string
{
$readme = [];
$in_toc = false;
foreach (file($file) as $line) {
if (preg_match('/BEGIN_TOC/', $line)) {
$in_toc = true;
continue;
}
if (preg_match('/END_TOC/', $line)) {
$in_toc = false;
$readme[] = $toc;
continue;
}
if ($in_toc) {
continue;
}
$readme[] = rtrim($line);
}
return implode("\n", [
...$readme,
'',
]);
}
// Main README
file_put_contents('./README.md.new', updateMarkdown('./README.md', generateToc(BASE_URL)));
unlink('./README.md');
rename('./README.md.new', './README.md');
// Docs index
file_put_contents('./docs/README.md.new', updateMarkdown('./docs/README.md', generateToc(BASE_URL)));
unlink('./docs/README.md');
rename('./docs/README.md.new', './docs/README.md');
// Page footers
$footer = generateFooter('./');
foreach (DOC_FILES as $file) {
file_put_contents("./{$file}.new", updateMarkdown("./{$file}", $footer));
unlink("./{$file}");
rename("./{$file}.new", "./{$file}");
}
echo "\nDONE!\n\n";
exit(0);