-
Notifications
You must be signed in to change notification settings - Fork 238
Expand file tree
/
Copy pathJavaDocDescriptionRenderer.java
More file actions
566 lines (508 loc) · 19.3 KB
/
JavaDocDescriptionRenderer.java
File metadata and controls
566 lines (508 loc) · 19.3 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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
/*
* Copyright 2016-2026 Qameta Software Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.qameta.allure.description;
import java.util.Locale;
/**
* Renders raw JavaDoc comment text into a safe, markdown-friendly description for Allure.
*
* <p>This renderer intentionally implements a small, conservative subset of the JavaDoc comment
* specification instead of attempting to preserve the full doclet output. The goal is to keep
* JavaDoc-backed descriptions readable in reports while ensuring that untrusted comment content is
* never treated as executable HTML.</p>
*
* <p>The rendering algorithm is intentionally simple:</p>
* <ol>
* <li>Take only the main description, stopping at the first block tag such as {@code @param}
* or {@code @throws}.</li>
* <li>Render the remaining content with a small parser that recognizes a limited set of inline
* JavaDoc tags and structural HTML tags.</li>
* <li>Escape or drop everything else so the output remains plain text or safe markdown.</li>
* </ol>
*
* <p>Currently supported JavaDoc constructs include inline tags such as {@code {@code ...}},
* {@code {@literal ...}}, {@code {@link ...}}, and {@code {@linkplain ...}}.</p>
*
* <p>The renderer also understands a small set of structural HTML tags: {@code p}, {@code br},
* {@code ul}, {@code ol}, {@code li}, and {@code code}. Common entity references such as
* {@code &lt;}, {@code &gt;}, {@code &amp;}, {@code &#064;},
* {@code &lbrace;}, and numeric entities are decoded before the output is escaped again.</p>
*
* <p>Unsupported tags are degraded to escaped text instead of being interpreted. Unknown HTML tags
* are ignored as markup while their text content remains visible. This keeps the JavaDoc
* description path suitable for open source projects where comments may evolve over time and where
* security is more important than pixel-perfect parity with the standard doclet.</p>
*/
final class JavaDocDescriptionRenderer {
private static final String PARAGRAPH_BREAK = "\n\n";
private static final String HTML_LT = "<";
private static final String HTML_GT = ">";
private static final String HTML_AMP = "&";
private static final String INLINE_CODE_MARKER = "`";
private static final String ESCAPED_INLINE_CODE_MARKER = "``";
private static final String CODE_TAG = "code";
private static final String HTML_TAG_END = ">";
private static final String CLOSING_TAG_PREFIX = "</";
/**
* Converts raw JavaDoc comment text into the description format stored by the annotation
* processor.
*
* <p>The method extracts the JavaDoc main description, renders the supported inline and HTML
* constructs into plain text or markdown, normalizes whitespace, and escapes unsafe content.
* The returned value is intended for Allure's plain {@code description} field, not for
* {@code descriptionHtml}.</p>
*
* @param rawDocComment the comment text returned by {@link javax.lang.model.util.Elements#getDocComment}
* @return a safe markdown/plain-text description, or an empty string if the comment has no main
* description
*/
String render(final String rawDocComment) {
final String descriptionBody = extractDescriptionBody(rawDocComment);
if (descriptionBody.isEmpty()) {
return "";
}
final StringBuilder rendered = new StringBuilder();
renderFragment(descriptionBody, rendered);
return cleanup(rendered.toString());
}
private String extractDescriptionBody(final String rawDocComment) {
final String[] lines = normalize(rawDocComment).split("\n", -1);
final StringBuilder body = new StringBuilder();
boolean blockTagStarted = false;
int inlineTagDepth = 0;
for (String line : lines) {
if (inlineTagDepth == 0 && startsBlockTag(line)) {
blockTagStarted = true;
}
if (blockTagStarted) {
continue;
}
if (body.length() > 0) {
body.append('\n');
}
body.append(trimTrailingWhitespace(line));
inlineTagDepth = updateInlineTagDepth(line, inlineTagDepth);
}
return trimBlankLines(body.toString());
}
private boolean startsBlockTag(final String line) {
final String trimmed = line.trim();
return trimmed.length() > 1 && trimmed.charAt(0) == '@' && Character.isJavaIdentifierStart(trimmed.charAt(1));
}
@SuppressWarnings("checkstyle:CyclomaticComplexity")
private void renderFragment(final String fragment, final StringBuilder rendered) {
int index = 0;
while (index < fragment.length()) {
final char current = fragment.charAt(index);
if (current == '{' && index + 1 < fragment.length() && fragment.charAt(index + 1) == '@') {
final int nextIndex = renderInlineTag(fragment, index, rendered);
if (nextIndex > index) {
index = nextIndex;
continue;
}
}
if (current == '<') {
final int nextIndex = renderHtmlTag(fragment, index, rendered);
if (nextIndex > index) {
index = nextIndex;
continue;
}
rendered.append(HTML_LT);
index++;
continue;
}
if (current == '&') {
final int nextIndex = renderEntityReference(fragment, index, rendered);
if (nextIndex > index) {
index = nextIndex;
continue;
}
rendered.append(HTML_AMP);
index++;
continue;
}
if (current == '>') {
rendered.append(HTML_GT);
index++;
continue;
}
rendered.append(current);
index++;
}
}
@SuppressWarnings("checkstyle:ReturnCount")
private int renderInlineTag(final String fragment, final int start, final StringBuilder rendered) {
final int end = findInlineTagEnd(fragment, start);
if (end < 0) {
return start;
}
final String content = fragment.substring(start + 2, end).trim();
if (content.isEmpty()) {
return end + 1;
}
final int separator = findWhitespace(content);
final String tag = separator < 0 ? content : content.substring(0, separator);
final String payload = separator < 0 ? "" : content.substring(separator + 1).trim();
if (CODE_TAG.equals(tag)) {
appendCode(rendered, payload);
return end + 1;
}
if ("literal".equals(tag)) {
rendered.append(escapeText(payload));
return end + 1;
}
if ("link".equals(tag) || "linkplain".equals(tag)) {
appendLink(rendered, payload);
return end + 1;
}
rendered.append(escapeText(content));
return end + 1;
}
@SuppressWarnings({
"checkstyle:CyclomaticComplexity",
"checkstyle:NPathComplexity",
"checkstyle:ReturnCount"})
private int renderHtmlTag(final String fragment, final int start, final StringBuilder rendered) {
final int end = fragment.indexOf('>', start + 1);
if (end < 0) {
return start;
}
final String rawTag = fragment.substring(start + 1, end).trim();
if (rawTag.isEmpty()) {
return start;
}
boolean closing = false;
String tag = rawTag;
if (tag.charAt(0) == '/') {
closing = true;
tag = tag.substring(1).trim();
}
if (tag.endsWith("/")) {
tag = tag.substring(0, tag.length() - 1).trim();
}
final int separator = findTagNameEnd(tag);
if (separator <= 0) {
return end + 1;
}
final String name = tag.substring(0, separator).toLowerCase(Locale.ROOT);
if ("br".equals(name)) {
appendLineBreak(rendered);
return end + 1;
}
if ("p".equals(name) || "ul".equals(name) || "ol".equals(name)) {
appendParagraphBreak(rendered);
return end + 1;
}
if ("li".equals(name)) {
if (!closing) {
startListItem(rendered);
}
return end + 1;
}
if (CODE_TAG.equals(name)) {
if (!closing) {
final int closingStart = findClosingTag(fragment, end + 1, CODE_TAG);
if (closingStart > end) {
appendCode(rendered, fragment.substring(end + 1, closingStart));
return closingStart + (CLOSING_TAG_PREFIX + CODE_TAG + HTML_TAG_END).length();
}
return end + 1;
}
return end + 1;
}
return end + 1;
}
private void appendLink(final StringBuilder rendered, final String payload) {
if (payload.isEmpty()) {
return;
}
final int separator = findWhitespace(payload);
if (separator < 0) {
rendered.append(escapeText(shortenReference(payload)));
return;
}
final String label = payload.substring(separator + 1).trim();
if (label.isEmpty()) {
rendered.append(escapeText(shortenReference(payload.substring(0, separator))));
return;
}
renderFragment(label, rendered);
}
private String shortenReference(final String reference) {
final String trimmed = reference.trim();
final int hashIndex = trimmed.lastIndexOf('#');
if (hashIndex >= 0 && hashIndex + 1 < trimmed.length()) {
return trimmed.substring(hashIndex + 1);
}
final int dotIndex = trimmed.lastIndexOf('.');
if (dotIndex >= 0 && dotIndex + 1 < trimmed.length()) {
return trimmed.substring(dotIndex + 1);
}
return trimmed;
}
private void appendCode(final StringBuilder rendered, final String payload) {
final String escaped = escapeText(payload);
final String marker = escaped.contains(INLINE_CODE_MARKER)
? ESCAPED_INLINE_CODE_MARKER
: INLINE_CODE_MARKER;
rendered.append(marker)
.append(escaped)
.append(marker);
}
private void startListItem(final StringBuilder rendered) {
trimTrailingSpaces(rendered);
if (rendered.length() > 0 && rendered.charAt(rendered.length() - 1) != '\n') {
rendered.append('\n');
}
rendered.append("- ");
}
private void appendParagraphBreak(final StringBuilder rendered) {
trimTrailingSpaces(rendered);
if (rendered.length() == 0 || endsWith(rendered, PARAGRAPH_BREAK)) {
return;
}
if (rendered.charAt(rendered.length() - 1) == '\n') {
rendered.append('\n');
return;
}
rendered.append(PARAGRAPH_BREAK);
}
private void appendLineBreak(final StringBuilder rendered) {
trimTrailingSpaces(rendered);
if (rendered.length() == 0 || rendered.charAt(rendered.length() - 1) == '\n') {
return;
}
rendered.append('\n');
}
private String cleanup(final String rendered) {
final String[] lines = normalize(rendered).split("\n", -1);
final StringBuilder cleaned = new StringBuilder();
boolean blankLinePending = false;
for (String line : lines) {
final String trimmed = line.trim();
if (trimmed.isEmpty()) {
if (cleaned.length() > 0) {
blankLinePending = true;
}
continue;
}
if (cleaned.length() > 0) {
cleaned.append(blankLinePending ? PARAGRAPH_BREAK : "\n");
}
cleaned.append(trimmed);
blankLinePending = false;
}
return cleaned.toString();
}
private String trimBlankLines(final String value) {
final String[] lines = normalize(value).split("\n", -1);
int start = 0;
int end = lines.length;
while (start < end && isBlank(lines[start])) {
start++;
}
while (end > start && isBlank(lines[end - 1])) {
end--;
}
final StringBuilder result = new StringBuilder();
for (int index = start; index < end; index++) {
if (result.length() > 0) {
result.append('\n');
}
result.append(lines[index]);
}
return result.toString();
}
private int updateInlineTagDepth(final String line, final int initialDepth) {
int depth = initialDepth;
int index = 0;
while (index < line.length()) {
final char current = line.charAt(index);
if (depth == 0) {
if (current == '{' && index + 1 < line.length() && line.charAt(index + 1) == '@') {
depth = 1;
index += 2;
continue;
}
} else if (current == '{') {
depth++;
} else if (current == '}') {
depth--;
}
index++;
}
return depth;
}
private void trimTrailingSpaces(final StringBuilder builder) {
while (builder.length() > 0) {
final char current = builder.charAt(builder.length() - 1);
if (current != ' ' && current != '\t') {
break;
}
builder.deleteCharAt(builder.length() - 1);
}
}
private boolean endsWith(final StringBuilder builder, final String suffix) {
return builder.length() >= suffix.length()
&& builder.substring(builder.length() - suffix.length()).equals(suffix);
}
private int findWhitespace(final String value) {
for (int index = 0; index < value.length(); index++) {
if (Character.isWhitespace(value.charAt(index))) {
return index;
}
}
return -1;
}
private int findTagNameEnd(final String tag) {
for (int index = 0; index < tag.length(); index++) {
final char current = tag.charAt(index);
if (!(Character.isLetterOrDigit(current) || current == '-' || current == '_')) {
return index;
}
}
return tag.length();
}
private int findClosingTag(final String fragment, final int fromIndex, final String tagName) {
return fragment.toLowerCase(Locale.ROOT).indexOf(CLOSING_TAG_PREFIX + tagName + HTML_TAG_END, fromIndex);
}
private int findInlineTagEnd(final String fragment, final int start) {
int depth = 1;
for (int index = start + 2; index < fragment.length(); index++) {
final char current = fragment.charAt(index);
if (current == '{') {
depth++;
continue;
}
if (current == '}') {
depth--;
if (depth == 0) {
return index;
}
}
}
return -1;
}
private String trimTrailingWhitespace(final String line) {
int end = line.length();
while (end > 0) {
final char current = line.charAt(end - 1);
if (current != ' ' && current != '\t') {
break;
}
end--;
}
return line.substring(0, end);
}
private String normalize(final String value) {
return value.replace("\r\n", "\n").replace('\r', '\n');
}
private boolean isBlank(final String value) {
for (int index = 0; index < value.length(); index++) {
if (!Character.isWhitespace(value.charAt(index))) {
return false;
}
}
return true;
}
private int renderEntityReference(final String fragment, final int start, final StringBuilder rendered) {
final int end = fragment.indexOf(';', start + 1);
if (end < 0) {
return start;
}
final String decoded = decodeEntity(fragment.substring(start + 1, end));
if (decoded == null) {
return start;
}
rendered.append(escapeText(decoded));
return end + 1;
}
@SuppressWarnings({
"checkstyle:CyclomaticComplexity",
"checkstyle:NPathComplexity",
"checkstyle:ReturnCount"})
private String decodeEntity(final String entity) {
if (entity.isEmpty()) {
return null;
}
if (entity.charAt(0) == '#') {
return decodeNumericEntity(entity);
}
if ("amp".equals(entity)) {
return Character.toString('&');
}
if ("lt".equals(entity)) {
return Character.toString('<');
}
if ("gt".equals(entity)) {
return Character.toString('>');
}
if ("quot".equals(entity)) {
return "\"";
}
if ("apos".equals(entity)) {
return "'";
}
if ("nbsp".equals(entity)) {
return " ";
}
if ("lbrace".equals(entity)) {
return "{";
}
if ("rbrace".equals(entity)) {
return "}";
}
if ("commat".equals(entity)) {
return Character.toString('@');
}
return null;
}
private String decodeNumericEntity(final String entity) {
try {
final int codePoint;
if (entity.startsWith("#x") || entity.startsWith("#X")) {
codePoint = Integer.parseInt(entity.substring(2), 16);
} else {
codePoint = Integer.parseInt(entity.substring(1), 10);
}
return new String(Character.toChars(codePoint));
} catch (IllegalArgumentException e) {
return null;
}
}
private String escapeText(final String value) {
final StringBuilder escaped = new StringBuilder();
int index = 0;
while (index < value.length()) {
final char current = value.charAt(index);
if (current == '&') {
final int nextIndex = renderEntityReference(value, index, escaped);
if (nextIndex > index) {
index = nextIndex;
continue;
}
escaped.append(HTML_AMP);
} else if (current == '<') {
escaped.append(HTML_LT);
} else if (current == '>') {
escaped.append(HTML_GT);
} else {
escaped.append(current);
}
index++;
}
return escaped.toString();
}
}