-
Notifications
You must be signed in to change notification settings - Fork 672
/
Copy pathTableOfContentsGenerator.java
97 lines (78 loc) · 2.62 KB
/
TableOfContentsGenerator.java
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
package com.gitblit.markdown;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class TableOfContentsGenerator {
public static final String DEFAULT_HEADER = "#";
public static final char DEFAULT_HEADER_CHAR = '#';
public static final String ALT_1_HEADER = "=";
public static final String ALT_2_HEADER = "-";
public static final String TOC_HEADER = "## Table of contents";
private String markdown;
private List<ModifyModel> rootModels = new ArrayList<ModifyModel>();
public TableOfContentsGenerator(String markdown) {
this.markdown = markdown;
}
public String start() {
if (!this.markdown.contains("__TOC__")) {
return this.markdown;
}
int patternLineNumber = -1;
int currentLine = 0;
String[] items = markdown.split("\n");
List<String> fileContent = new ArrayList<String>(Arrays.asList(items));
String previousLine = null;
for (String line : fileContent) {
++currentLine;
if (line.startsWith(DEFAULT_HEADER)) {
String trim = line.trim();
int count = getCount(trim);
if (count < 1 || count > 6) {
previousLine = line;
continue;
}
String headerName = line.substring(count);
rootModels.add(new ModifyModel(count, headerName, Utils.normalize(headerName)));
} else if (line.startsWith(ALT_1_HEADER) && !Utils.isEmpty(previousLine)) {
if (line.replaceAll(ALT_1_HEADER, "").isEmpty()) {
rootModels.add(new ModifyModel(1, previousLine, Utils.normalize(previousLine)));
}
} else if (line.startsWith(ALT_2_HEADER) && !Utils.isEmpty(previousLine)) {
if (line.replaceAll(ALT_2_HEADER, "").isEmpty()) {
rootModels.add(new ModifyModel(2, previousLine, Utils.normalize(previousLine)));
}
} else if (line.trim().equals("__TOC__")) {
patternLineNumber = currentLine;
}
previousLine = line;
}
return getMarkdown(fileContent, patternLineNumber).replaceAll("__TOC__", "");
}
private String getMarkdown(List<String> fileContent, int patternLineNumber) {
StringBuilder writer = new StringBuilder();
if (patternLineNumber == -1) {
System.out.println("Pattern for replace not found!");
return "";
}
fileContent.add(patternLineNumber - 1, TOC_HEADER);
for (ModifyModel modifyModel : rootModels) {
fileContent.add(patternLineNumber, modifyModel.create());
patternLineNumber++;
}
for (String line : fileContent) {
writer.append(line).append("\n");
}
return writer.toString();
}
private int getCount(String string) {
int count = 0;
for (int i = 0; i < string.length(); i++) {
if (string.charAt(i) == DEFAULT_HEADER_CHAR) {
++count;
} else {
break;
}
}
return count;
}
}