1
2
3
4
5
6 package mockit.coverage.reporting;
7
8 import edu.umd.cs.findbugs.annotations.NonNull;
9
10 import java.io.File;
11 import java.io.IOException;
12 import java.io.PrintWriter;
13 import java.nio.charset.StandardCharsets;
14 import java.nio.file.Path;
15 import java.util.regex.Pattern;
16
17 public final class OutputFile extends PrintWriter {
18 private static final Pattern PATH_SEPARATOR = Pattern.compile("/");
19
20 @NonNull
21 private final String relPathToOutDir;
22 private final boolean sourceFile;
23
24 public OutputFile(@NonNull File file) throws IOException {
25 super(file, StandardCharsets.UTF_8);
26 relPathToOutDir = "";
27 sourceFile = false;
28 }
29
30 public OutputFile(@NonNull String outputDir, @NonNull String sourceFilePath) throws IOException {
31 super(getOutputFileCreatingDirIfNeeded(outputDir, sourceFilePath));
32 relPathToOutDir = getRelativeSubPathToOutputDir(sourceFilePath);
33 sourceFile = true;
34 }
35
36 @NonNull
37 private static File getOutputFileCreatingDirIfNeeded(@NonNull String outputDir, @NonNull String sourceFilePath) {
38 File outputFile = getOutputFile(outputDir, sourceFilePath);
39 File parentDir = outputFile.getParentFile();
40
41 if (!parentDir.exists()) {
42 boolean outputDirCreated = parentDir.mkdirs();
43 assert outputDirCreated : "Failed to create output dir: " + outputDir;
44 }
45
46 return outputFile;
47 }
48
49 @NonNull
50 static File getOutputFile(@NonNull String outputDir, @NonNull String sourceFilePath) {
51 int p = sourceFilePath.lastIndexOf('.');
52 String outputFileName = sourceFilePath.substring(0, p) + ".html";
53 return Path.of(outputDir, outputFileName).toFile();
54 }
55
56 @NonNull
57 private static String getRelativeSubPathToOutputDir(@NonNull String filePath) {
58 StringBuilder cssRelPath = new StringBuilder();
59 int n = PATH_SEPARATOR.split(filePath).length;
60
61 for (int i = 1; i < n; i++) {
62 cssRelPath.append("../");
63 }
64
65 return cssRelPath.toString();
66 }
67
68 public void writeCommonHeader(@NonNull String pageTitle) {
69 println("<!DOCTYPE html>");
70 println("<html>");
71 println("<head>");
72 println(" <title>" + pageTitle + "</title>");
73 println(" <meta charset='UTF-8'>");
74 println(" <link rel='stylesheet' type='text/css' href='" + relPathToOutDir + (sourceFile ? "source" : "index")
75 + ".css'>");
76 println(" <link rel='shortcut icon' type='image/png' href='" + relPathToOutDir + "logo.png'>");
77 println(" <script src='" + relPathToOutDir + "coverage.js'></script>");
78 println(" <base target='_blank'>");
79
80 if (sourceFile) {
81 println(" <script src='" + relPathToOutDir + "prettify.js'></script>");
82 }
83
84 println("</head>");
85 println(sourceFile ? "<body onload='prettyPrint()'>" : "<body>");
86 }
87
88 public void writeCommonFooter() {
89 println("</body>");
90 println("</html>");
91 }
92 }