-
Notifications
You must be signed in to change notification settings - Fork 587
Expand file tree
/
Copy pathmain.rs
More file actions
315 lines (293 loc) · 7.59 KB
/
main.rs
File metadata and controls
315 lines (293 loc) · 7.59 KB
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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
use std::path::PathBuf;
use std::sync::LazyLock;
use std::{fs, process};
use anyhow::Result;
use clap::Parser;
use ignore::Walk;
use regex::Regex;
#[derive(Parser)]
struct Cli {
/// File or directory to check
path: PathBuf,
#[arg(long)]
/// Modify files that do not comply
overwrite: bool,
/// Applies to lines that are to be split
#[arg(long, default_value_t = 80)]
line_length_limit: usize,
}
static REGEX_IGNORE_END: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"(\.|\?|;|!|,|\-)$").unwrap());
static REGEX_IGNORE_LINK_TARGETS: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"^\[.+\]: ").unwrap());
static REGEX_SPLIT: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"([^\.\d\-\*]\.|[^r\~]\?|!)\s").unwrap());
// list elements, numbered (1.) or not (- and *)
static REGEX_LIST_ENTRY: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"^\s*(\d\.|\-|\*|\d\))\s+").unwrap());
fn main() -> Result<()> {
let cli = Cli::parse();
let mut compliant = Vec::new();
let mut not_compliant = Vec::new();
let mut made_compliant = Vec::new();
for result in Walk::new(cli.path) {
let entry = result?;
if entry.file_type().expect("no stdin").is_dir() {
continue;
}
let path = entry.into_path();
if let Some(extension) = path.extension() {
if extension != "md" {
continue;
}
let old = fs::read_to_string(&path)?;
let new = lengthen_lines(&comply(&old), cli.line_length_limit);
if new == old {
compliant.push(path.clone());
} else if cli.overwrite {
fs::write(&path, new)?;
made_compliant.push(path.clone());
} else {
not_compliant.push(path.clone());
}
}
}
if !compliant.is_empty() {
display("compliant", &compliant);
}
if !made_compliant.is_empty() {
display("made compliant", &made_compliant);
}
if !not_compliant.is_empty() {
display("not compliant", ¬_compliant);
process::exit(1);
}
Ok(())
}
fn display(header: &str, paths: &[PathBuf]) {
println!("{header}:");
for element in paths {
println!("- {}", element.display());
}
}
fn ignore(line: &str, in_code_block: bool) -> bool {
in_code_block
|| line.to_lowercase().contains("e.g.")
|| line.to_lowercase().contains("n.b.")
|| line.contains(" etc.")
|| line.contains("i.e.")
|| line.contains("et. al")
|| line.contains("<!--")
|| line.contains("-->")
|| line.contains('|')
|| line.trim_start().starts_with('>')
|| line.starts_with('#')
|| line.trim().is_empty()
|| REGEX_IGNORE_LINK_TARGETS.is_match(line)
}
fn comply(content: &str) -> String {
let content: Vec<_> = content.lines().map(std::borrow::ToOwned::to_owned).collect();
let mut new_content = content.clone();
let mut new_n = 0;
let mut in_code_block = false;
for (n, line) in content.into_iter().enumerate() {
if n != 0 {
new_n += 1;
}
if line.trim_start().starts_with("```") {
in_code_block = !in_code_block;
continue;
}
if ignore(&line, in_code_block) {
continue;
}
if REGEX_SPLIT.is_match(&line) {
let indent = if let Some(regex_match) = REGEX_LIST_ENTRY.find(&line) {
regex_match.len()
} else {
line.find(|ch: char| !ch.is_whitespace()).unwrap()
};
let mut newly_split_lines = line.split_inclusive(&*REGEX_SPLIT);
let first = newly_split_lines.next().unwrap().trim_end().to_owned();
let mut remaining: Vec<_> = newly_split_lines
.map(|portion| format!("{:indent$}{}", "", portion.trim_end()))
.collect();
let mut new_lines = Vec::new();
new_lines.push(first);
new_lines.append(&mut remaining);
new_content.splice(new_n..=new_n, new_lines.clone());
new_n += new_lines.len() - 1;
}
}
new_content.join("\n") + "\n"
}
fn lengthen_lines(content: &str, limit: usize) -> String {
let content: Vec<_> = content.lines().map(std::borrow::ToOwned::to_owned).collect();
let mut new_content = content.clone();
let mut new_n = 0;
let mut in_code_block = false;
let mut in_html_div = false;
let mut skip_next = false;
for (n, line) in content.iter().enumerate() {
if skip_next {
skip_next = false;
continue;
}
if n != 0 {
new_n += 1;
}
if line.trim_start().starts_with("```") {
in_code_block = !in_code_block;
continue;
}
if line.trim_start().starts_with("<div") {
in_html_div = true;
continue;
}
if line.trim_start().starts_with("</div") {
in_html_div = false;
continue;
}
if in_html_div {
continue;
}
if line.trim_end().ends_with("<br>") {
continue;
}
if ignore(line, in_code_block) || REGEX_SPLIT.is_match(line) {
continue;
}
let Some(next_line) = content.get(n + 1) else {
continue;
};
if next_line.trim_start().starts_with("```") {
continue;
}
if ignore(next_line, in_code_block)
|| REGEX_LIST_ENTRY.is_match(next_line)
|| REGEX_IGNORE_END.is_match(line)
{
continue;
}
if line.len() + next_line.len() < limit {
new_content[new_n] = format!("{line} {}", next_line.trim_start());
new_content.remove(new_n + 1);
skip_next = true;
}
}
new_content.join("\n") + "\n"
}
#[test]
fn test_sembr() {
let original = "
# some. heading
must! be. split?
1. ignore a dot after number. but no further
ignore | tables
ignore e.g. and
ignore i.e. and
ignore etc. and
ignore E.g. too
- list. entry
* list. entry
1) list. entry
```
some code. block
```
sentence with *italics* should not be ignored. truly.
git log main.. compiler
foo. bar. baz
o? whatever
r? @reviewer
r? @reviewer
~? diagnostic
";
let expected = "
# some. heading
must!
be.
split?
1. ignore a dot after number.
but no further
ignore | tables
ignore e.g. and
ignore i.e. and
ignore etc. and
ignore E.g. too
- list.
entry
* list.
entry
1) list.
entry
```
some code. block
```
sentence with *italics* should not be ignored.
truly.
git log main.. compiler
foo.
bar.
baz
o?
whatever
r? @reviewer
r? @reviewer
~? diagnostic
";
assert_eq!(expected, comply(original));
}
#[test]
fn test_lengthen_lines() {
let original = "\
do not split
short sentences
<div class='warning'>
a bit of text inside
</div>
preserve next line
1. one
preserve next line
- two
preserve next line
* three
do not mess with code block chars
```
leave the
text alone
```
<!-- ignore
html comment opening
--> ignore
html comment closing
handle the
indented well
[a target]: https://example.com
[another target]: https://example.com
";
let expected = "\
do not split short sentences
<div class='warning'>
a bit of text inside
</div>
preserve next line
1. one
preserve next line
- two
preserve next line
* three
do not mess with code block chars
```
leave the
text alone
```
<!-- ignore
html comment opening
--> ignore
html comment closing
handle the indented well
[a target]: https://example.com
[another target]: https://example.com
";
assert_eq!(expected, lengthen_lines(original, 50));
}