You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

BuildSite.java 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. /*
  2. * Copyright 2011 James Moger.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package com.iciql.build;
  17. import java.io.BufferedReader;
  18. import java.io.File;
  19. import java.io.FileInputStream;
  20. import java.io.FileOutputStream;
  21. import java.io.FilenameFilter;
  22. import java.io.IOException;
  23. import java.io.InputStreamReader;
  24. import java.io.OutputStreamWriter;
  25. import java.io.Reader;
  26. import java.io.StringReader;
  27. import java.io.StringWriter;
  28. import java.nio.charset.Charset;
  29. import java.text.MessageFormat;
  30. import java.text.ParseException;
  31. import java.text.SimpleDateFormat;
  32. import java.util.ArrayList;
  33. import java.util.Arrays;
  34. import java.util.Date;
  35. import java.util.HashMap;
  36. import java.util.List;
  37. import java.util.Map;
  38. import java.util.Vector;
  39. import org.tautua.markdownpapers.Markdown;
  40. import com.beust.jcommander.JCommander;
  41. import com.beust.jcommander.Parameter;
  42. import com.beust.jcommander.ParameterException;
  43. import com.beust.jcommander.Parameters;
  44. import com.iciql.Constants;
  45. import com.iciql.util.StringUtils;
  46. /**
  47. * Builds the web site or deployment documentation from Markdown source files.
  48. *
  49. * All Markdown source files must have the .mkd extension.
  50. *
  51. * Natural string sort order of the Markdown source filenames is the order of
  52. * page links. "##_" prefixes are used to control the sort order.
  53. *
  54. * @author James Moger
  55. *
  56. */
  57. public class BuildSite {
  58. public static void main(String... args) {
  59. Params params = new Params();
  60. JCommander jc = new JCommander(params);
  61. try {
  62. jc.parse(args);
  63. } catch (ParameterException t) {
  64. usage(jc, t);
  65. }
  66. File sourceFolder = new File(params.sourceFolder);
  67. File destinationFolder = new File(params.outputFolder);
  68. File[] markdownFiles = sourceFolder.listFiles(new FilenameFilter() {
  69. @Override
  70. public boolean accept(File dir, String name) {
  71. return name.toLowerCase().endsWith(".mkd");
  72. }
  73. });
  74. Arrays.sort(markdownFiles);
  75. Map<String, String> aliasMap = new HashMap<String, String>();
  76. for (String alias : params.aliases) {
  77. String[] values = alias.split("=");
  78. aliasMap.put(values[0], values[1]);
  79. }
  80. System.out.println(MessageFormat.format("Generating site from {0} Markdown Docs in {1} ", markdownFiles.length,
  81. sourceFolder.getAbsolutePath()));
  82. String linkPattern = "<a href=''{0}''>{1}</a>";
  83. StringBuilder sb = new StringBuilder();
  84. for (File file : markdownFiles) {
  85. String documentName = getDocumentName(file);
  86. if (!params.skips.contains(documentName)) {
  87. String displayName = documentName;
  88. if (aliasMap.containsKey(documentName)) {
  89. displayName = aliasMap.get(documentName);
  90. } else {
  91. displayName = displayName.replace('_', ' ');
  92. }
  93. String fileName = documentName + ".html";
  94. sb.append(MessageFormat.format(linkPattern, fileName, displayName));
  95. sb.append(" | ");
  96. }
  97. }
  98. sb.setLength(sb.length() - 3);
  99. sb.trimToSize();
  100. String htmlHeader = readContent(new File(params.pageHeader), "\n");
  101. String htmlAdSnippet = null;
  102. if (!StringUtils.isNullOrEmpty(params.adSnippet)) {
  103. File snippet = new File(params.adSnippet);
  104. if (snippet.exists()) {
  105. htmlAdSnippet = readContent(snippet, "\n");
  106. }
  107. }
  108. String htmlFooter = readContent(new File(params.pageFooter), "\n");
  109. String links = sb.toString();
  110. String header = MessageFormat.format(htmlHeader, Constants.NAME, links);
  111. if (!StringUtils.isNullOrEmpty(params.analyticsSnippet)) {
  112. File snippet = new File(params.analyticsSnippet);
  113. if (snippet.exists()) {
  114. String htmlSnippet = readContent(snippet, "\n");
  115. header = header.replace("<!-- ANALYTICS -->", htmlSnippet);
  116. }
  117. }
  118. final String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
  119. final String footer = MessageFormat.format(htmlFooter, "generated " + date);
  120. for (File file : markdownFiles) {
  121. try {
  122. String documentName = getDocumentName(file);
  123. if (!params.skips.contains(documentName)) {
  124. String fileName = documentName + ".html";
  125. System.out.println(MessageFormat.format(" {0} => {1}", file.getName(), fileName));
  126. String rawContent = readContent(file, "\n");
  127. String markdownContent = rawContent;
  128. Map<String, List<String>> nomarkdownMap = new HashMap<String, List<String>>();
  129. // extract sections marked as no-markdown
  130. int nmd = 0;
  131. for (String token : params.nomarkdown) {
  132. StringBuilder strippedContent = new StringBuilder();
  133. String nomarkdownKey = "%NOMARKDOWN" + nmd + "%";
  134. String[] kv = token.split(":", 2);
  135. String beginToken = kv[0];
  136. String endToken = kv[1];
  137. // strip nomarkdown chunks from markdown and cache them
  138. List<String> chunks = new Vector<String>();
  139. int beginCode = 0;
  140. int endCode = 0;
  141. while ((beginCode = markdownContent.indexOf(beginToken, endCode)) > -1) {
  142. if (endCode == 0) {
  143. strippedContent.append(markdownContent.substring(0, beginCode));
  144. } else {
  145. strippedContent.append(markdownContent.substring(endCode, beginCode));
  146. }
  147. strippedContent.append(nomarkdownKey);
  148. endCode = markdownContent.indexOf(endToken, beginCode);
  149. chunks.add(markdownContent.substring(beginCode, endCode));
  150. nomarkdownMap.put(nomarkdownKey, chunks);
  151. }
  152. // get remainder of text
  153. if (endCode < markdownContent.length()) {
  154. strippedContent.append(markdownContent.substring(endCode, markdownContent.length()));
  155. }
  156. markdownContent = strippedContent.toString();
  157. nmd++;
  158. }
  159. // transform markdown to html
  160. String content = transformMarkdown(new StringReader(markdownContent.toString()));
  161. // reinsert nomarkdown chunks
  162. for (Map.Entry<String, List<String>> nomarkdown : nomarkdownMap.entrySet()) {
  163. for (String chunk : nomarkdown.getValue()) {
  164. content = content.replaceFirst(nomarkdown.getKey(), chunk);
  165. }
  166. }
  167. // perform specified substitutions
  168. for (String token : params.substitutions) {
  169. String[] kv = token.split("=", 2);
  170. content = content.replace(kv[0], kv[1]);
  171. }
  172. OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(new File(destinationFolder,
  173. fileName)), Charset.forName("UTF-8"));
  174. writer.write(header);
  175. if (!StringUtils.isNullOrEmpty(htmlAdSnippet)) {
  176. writer.write(htmlAdSnippet);
  177. }
  178. writer.write(content);
  179. writer.write(footer);
  180. writer.close();
  181. }
  182. } catch (Throwable t) {
  183. System.err.println("Failed to transform " + file.getName());
  184. t.printStackTrace();
  185. }
  186. }
  187. }
  188. private static String getDocumentName(File file) {
  189. String displayName = file.getName().substring(0, file.getName().lastIndexOf('.')).toLowerCase();
  190. int underscore = displayName.indexOf('_') + 1;
  191. if (underscore > -1) {
  192. // trim leading ##_ which is to control display order
  193. return displayName.substring(underscore);
  194. }
  195. return displayName;
  196. }
  197. /**
  198. * Returns the string content of the specified file.
  199. *
  200. * @param file
  201. * @param lineEnding
  202. * @return the string content of the file
  203. */
  204. private static String readContent(File file, String lineEnding) {
  205. StringBuilder sb = new StringBuilder();
  206. try {
  207. InputStreamReader is = new InputStreamReader(new FileInputStream(file), Charset.forName("UTF-8"));
  208. BufferedReader reader = new BufferedReader(is);
  209. String line = null;
  210. while ((line = reader.readLine()) != null) {
  211. sb.append(line);
  212. if (lineEnding != null) {
  213. sb.append(lineEnding);
  214. }
  215. }
  216. reader.close();
  217. } catch (Throwable t) {
  218. System.err.println("Failed to read content of " + file.getAbsolutePath());
  219. t.printStackTrace();
  220. }
  221. return sb.toString();
  222. }
  223. private static String transformMarkdown(Reader markdownReader) throws ParseException {
  224. // Read raw markdown content and transform it to html
  225. StringWriter writer = new StringWriter();
  226. try {
  227. Markdown md = new Markdown();
  228. md.transform(markdownReader, writer);
  229. return writer.toString().trim();
  230. } catch (org.tautua.markdownpapers.parser.ParseException p) {
  231. throw new java.text.ParseException(p.getMessage(), 0);
  232. } finally {
  233. try {
  234. markdownReader.close();
  235. } catch (IOException e) {
  236. // IGNORE
  237. }
  238. try {
  239. writer.close();
  240. } catch (IOException e) {
  241. // IGNORE
  242. }
  243. }
  244. }
  245. private static void usage(JCommander jc, ParameterException t) {
  246. System.out.println(Constants.NAME + " v" + Constants.VERSION);
  247. System.out.println();
  248. if (t != null) {
  249. System.out.println(t.getMessage());
  250. System.out.println();
  251. }
  252. if (jc != null) {
  253. jc.usage();
  254. }
  255. System.exit(0);
  256. }
  257. /**
  258. * Command-line parameters for BuildSite utility.
  259. */
  260. @Parameters(separators = " ")
  261. private static class Params {
  262. @Parameter(names = { "--sourceFolder" }, description = "Markdown Source Folder", required = true)
  263. public String sourceFolder;
  264. @Parameter(names = { "--outputFolder" }, description = "HTML Ouptut Folder", required = true)
  265. public String outputFolder;
  266. @Parameter(names = { "--pageHeader" }, description = "Page Header HTML Snippet", required = true)
  267. public String pageHeader;
  268. @Parameter(names = { "--pageFooter" }, description = "Page Footer HTML Snippet", required = true)
  269. public String pageFooter;
  270. @Parameter(names = { "--adSnippet" }, description = "Ad HTML Snippet", required = false)
  271. public String adSnippet;
  272. @Parameter(names = { "--analyticsSnippet" }, description = "Analytics HTML Snippet", required = false)
  273. public String analyticsSnippet;
  274. @Parameter(names = { "--skip" }, description = "Filename to skip", required = false)
  275. public List<String> skips = new ArrayList<String>();
  276. @Parameter(names = { "--alias" }, description = "Filename=Linkname aliases", required = false)
  277. public List<String> aliases = new ArrayList<String>();
  278. @Parameter(names = { "--substitute" }, description = "%TOKEN%=value", required = false)
  279. public List<String> substitutions = new ArrayList<String>();
  280. @Parameter(names = { "--nomarkdown" }, description = "%STARTTOKEN%:%ENDTOKEN%", required = false)
  281. public List<String> nomarkdown = new ArrayList<String>();
  282. }
  283. }