Skip to content

Instantly share code, notes, and snippets.

@stuartwdouglas
Created February 15, 2020 07:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stuartwdouglas/585b941c0c78daa50f9e2b0480da7e40 to your computer and use it in GitHub Desktop.
Save stuartwdouglas/585b941c0c78daa50f9e2b0480da7e40 to your computer and use it in GitHub Desktop.
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class JpaTocFixer {
public static void main(String[] args) throws Exception {
String toc = new String(Files.readAllBytes(Paths.get("/Users/stuart/jpatoc.txt")), StandardCharsets.UTF_8);
Pattern tocPatters = Pattern.compile("((\\d+\\.?)+) ([^\\.\\d]+)");
Matcher m = tocPatters.matcher(toc);
Map<String, Deque<Integer>> found = new HashMap<>();
while (m.find()) {
String group = m.group(3).replace("\n", " ").trim();
Deque<Integer> list = found.computeIfAbsent(group, s -> new ArrayDeque<>());
int count = 0;
for (char i : m.group(1).toCharArray()) {
if (i == '.') {
count++;
}
}
list.add(count);
}
String file = "/Users/stuart/workspace/jpa-api/spec/src/main/asciidoc/spec.adoc";
Path path = Paths.get(file);
String document = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
StringBuilder sb = new StringBuilder();
Pattern p = Pattern.compile("=== (\\[\\[\\w+]])?(.*)");
m = p.matcher(document);
int last = 0;
while (m.find()) {
sb.append(document, last, m.start());
last = m.end();
Deque<Integer> list = found.get(m.group(2));
System.out.println(list + m.group());
if (list == null) {
sb.append("[discrete]\n");
sb.append(m.group());
} else {
sb.append("==");
int val = list.pop();
if(list.isEmpty()){
found.remove(m.group(2));
}
for (int i = 0;i < val; ++i){
sb.append("=");
}
sb.append(" ");
if (m.group(1) != null){
sb.append(m.group(1));
}
sb.append(m.group(2));
}
}
sb.append(document, last, document.length());
Files.write(path, sb.toString().getBytes(StandardCharsets.UTF_8));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment