|
| 1 | +package org.hacksource.core; |
| 2 | + |
| 3 | +import com.github.javaparser.JavaParser; |
| 4 | +import com.github.javaparser.ParseResult; |
| 5 | + |
| 6 | +import com.github.javaparser.ast.CompilationUnit; |
| 7 | +import com.github.javaparser.ast.Node; |
| 8 | +import com.github.javaparser.ast.NodeList; |
| 9 | +import com.github.javaparser.ast.stmt.*; |
| 10 | + |
| 11 | + |
| 12 | +import java.io.BufferedReader; |
| 13 | +import java.io.IOException; |
| 14 | +import java.nio.file.Files; |
| 15 | +import java.nio.file.Paths; |
| 16 | +import java.util.Arrays; |
| 17 | +import java.util.List; |
| 18 | + |
| 19 | +import static com.github.javaparser.ParseStart.*; |
| 20 | +import static com.github.javaparser.Providers.provider; |
| 21 | + |
| 22 | +public class SourceFormat { |
| 23 | + |
| 24 | + public static String format(String source) throws SourceException { |
| 25 | + JavaParser javaParser = new JavaParser(); |
| 26 | + ParseResult<CompilationUnit> result = javaParser.parse(COMPILATION_UNIT, provider(source)); |
| 27 | + |
| 28 | + CompilationUnit cu = result.getResult().orElseThrow(() -> new SourceException(result.getProblems())); |
| 29 | + |
| 30 | + Arrays.stream(new Class[]{ |
| 31 | + IfStmt.class, ForStmt.class, ForEachStmt.class, WhileStmt.class |
| 32 | + }).forEach(c -> addBracket(cu, c)); |
| 33 | + |
| 34 | + return cu.toString(); |
| 35 | + } |
| 36 | + |
| 37 | + private static <T extends Statement> void addBracket(CompilationUnit cu, Class<T> c) { |
| 38 | + cu.findAll(c).forEach(stmt -> { |
| 39 | + List<Node> children = stmt.getChildNodes(); |
| 40 | + if(children.size() != 0) { |
| 41 | + Statement block = (Statement)children.get(children.size() - 1); |
| 42 | + if(!block.isBlockStmt()) { |
| 43 | + stmt.replace(block, new BlockStmt(new NodeList<Statement>(block))); |
| 44 | + } |
| 45 | + } |
| 46 | + }); |
| 47 | + } |
| 48 | + |
| 49 | + public static void main(String[] args) throws IOException { |
| 50 | + |
| 51 | + StringBuilder sb = new StringBuilder(); |
| 52 | + |
| 53 | + String path = SourceFormat.class.getResource("/example.java").getPath(); |
| 54 | + path = path.substring(1); |
| 55 | + |
| 56 | + try (BufferedReader br = Files.newBufferedReader(Paths.get(path))) { |
| 57 | + String line; |
| 58 | + while ((line = br.readLine()) != null) { |
| 59 | + sb.append(line).append("\n"); |
| 60 | + } |
| 61 | + |
| 62 | + } catch (IOException e) { |
| 63 | + e.printStackTrace(); |
| 64 | + } |
| 65 | + |
| 66 | + try { |
| 67 | + System.out.println(format(sb.toString())); |
| 68 | + } catch (SourceException e) { |
| 69 | + e.printStackTrace(); |
| 70 | + } |
| 71 | + } |
| 72 | +} |
0 commit comments