/
patch-doc.p6
executable file
·133 lines (111 loc) · 2.91 KB
/
patch-doc.p6
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
123
124
125
126
127
128
129
130
131
132
133
#!/usr/bin/env perl6
# use Grammar::Tracer;
use lib 'lib';
use OO::Plugin;
grammar MyPOD {
token TOP {
[
<pod>
|| <dummy>
]+
}
token dummy {
[ <!before <.pod-begin>> . && . ]+
}
token pod-begin {
^^ '=begin' \h
}
token pod-start ( $pod-kw is rw ) {
<pod-begin> \h* $<pod-kw>=\w+ { $pod-kw = ~$/<pod-kw> } \h* $$
}
token pod-end ( $pod-kw ) {
^^ '=end' \h+ $pod-kw \h* $$
}
token pod {
:my $pod-kw;
<pod-start( $pod-kw )>
[
|| <pod-link>
|| <pod-text>
]+
<pod-end( $pod-kw )>
}
token pod-text {
.+? <?before 'L<' || [^^ '=end']>
}
proto token pod-link {*}
multi token pod-link:sym<mod-url> {
'L' '<' <link-text> '|' <link-url> '>'
}
multi token pod-link:sym<mod-only> {
'L' '<' <link-module> '>'
}
token link-text {
<-[\|\>]>+
}
token link-module {
[ <.alnum>+ ] ** 1..* % '::'
}
token link-url {
$<link-prefix>=[ 'https://github.com/' .+? '/blob/v' ] <version> $<link-suffix>=[ '/' [<!before '>'> . && .]+ ]
}
token version {
[\d+] ** 3 % '.'
}
}
class MyPOD-Actions {
has Bool $.replaced is rw = False;
has $!ver = OO::Plugin.^ver;
has $!ver-str = ~OO::Plugin.^ver;
method version ($m) {
$.replaced ||= Version.new( $m ) ≠ $!ver;
$m.make( $!ver-str );
}
method pod-link:sym<mod-only> ( $m ) {
my $link-mod = $m<link-module>.made;
my $link-path = $link-mod.subst('::', '/', :g);
$m.make(
'L<' ~ $m<link-module>.made
~ '|https://github.com/vrurg/Perl6-OO-Plugin/blob/v'
~ $!ver-str ~ '/docs/md/'
~ $link-path ~ '.md'
~ '>'
);
$.replaced = True;
}
# method link-url ($m) {
# $m.make( $m<link-prefix> ~ $m<version> ~ $m<link-suffix> )
# }
method FALLBACK ($name, $m) {
$m.make(
$m.chunks.map( { given .value { .?made // ~$_ } } ).join
);
}
}
sub MAIN ( Str:D $pod-file, Str :o($output)? is copy, Bool :r($replace)=False ) {
my Bool $backup = False;
my $src = $pod-file.IO.slurp;
my $actions = MyPOD-Actions.new;
my $res = MyPOD.parse( $src, :$actions );
die "Failed to parse the source" unless $res;
if $actions.replaced {
if !$output and $replace {
$backup = True;
$output = $pod-file;
}
if $backup {
my $idx = 0;
my $bak-file = $pod-file ~ ".bk";
while $bak-file.IO.e {
$bak-file = $pod-file ~ (++$idx).fmt(".%02d.bk");
}
$pod-file.IO.rename( $bak-file );
}
if $output {
$output.IO.spurt( $res.made );
}
else {
say $res.made;
}
}
}