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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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} ",
  81. markdownFiles.length, 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,
  155. markdownContent.length()));
  156. }
  157. markdownContent = strippedContent.toString();
  158. nmd++;
  159. }
  160. // transform markdown to html
  161. String content = transformMarkdown(new StringReader(markdownContent.toString()));
  162. // reinsert nomarkdown chunks
  163. for (Map.Entry<String, List<String>> nomarkdown : nomarkdownMap.entrySet()) {
  164. for (String chunk : nomarkdown.getValue()) {
  165. content = content.replaceFirst(nomarkdown.getKey(), chunk);
  166. }
  167. }
  168. // perform specified substitutions
  169. for (String token : params.substitutions) {
  170. String[] kv = token.split("=", 2);
  171. content = content.replace(kv[0], kv[1]);
  172. }
  173. for (String token : params.regex) {
  174. String[] kv = token.split("!!!", 2);
  175. content = content.replaceAll(kv[0], kv[1]);
  176. }
  177. for (String alias : params.loads) {
  178. String[] kv = alias.split("=", 2);
  179. String loadedContent = StringUtils.readContent(new File(kv[1]), "\n");
  180. loadedContent = StringUtils.escapeForHtml(loadedContent, false);
  181. loadedContent = StringUtils.breakLinesForHtml(loadedContent);
  182. content = content.replace(kv[0], loadedContent);
  183. }
  184. OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(new File(
  185. destinationFolder, fileName)), Charset.forName("UTF-8"));
  186. writer.write(header);
  187. if (!StringUtils.isNullOrEmpty(htmlAdSnippet)) {
  188. writer.write(htmlAdSnippet);
  189. }
  190. writer.write(content);
  191. writer.write(footer);
  192. writer.close();
  193. }
  194. } catch (Throwable t) {
  195. System.err.println("Failed to transform " + file.getName());
  196. t.printStackTrace();
  197. }
  198. }
  199. }
  200. private static String getDocumentName(File file) {
  201. String displayName = file.getName().substring(0, file.getName().lastIndexOf('.')).toLowerCase();
  202. int underscore = displayName.indexOf('_') + 1;
  203. if (underscore > -1) {
  204. // trim leading ##_ which is to control display order
  205. return displayName.substring(underscore);
  206. }
  207. return displayName;
  208. }
  209. /**
  210. * Returns the string content of the specified file.
  211. *
  212. * @param file
  213. * @param lineEnding
  214. * @return the string content of the file
  215. */
  216. private static String readContent(File file, String lineEnding) {
  217. StringBuilder sb = new StringBuilder();
  218. try {
  219. InputStreamReader is = new InputStreamReader(new FileInputStream(file), Charset.forName("UTF-8"));
  220. BufferedReader reader = new BufferedReader(is);
  221. String line = null;
  222. while ((line = reader.readLine()) != null) {
  223. sb.append(line);
  224. if (lineEnding != null) {
  225. sb.append(lineEnding);
  226. }
  227. }
  228. reader.close();
  229. } catch (Throwable t) {
  230. System.err.println("Failed to read content of " + file.getAbsolutePath());
  231. t.printStackTrace();
  232. }
  233. return sb.toString();
  234. }
  235. private static String transformMarkdown(Reader markdownReader) throws ParseException {
  236. // Read raw markdown content and transform it to html
  237. StringWriter writer = new StringWriter();
  238. try {
  239. Markdown md = new Markdown();
  240. md.transform(markdownReader, writer);
  241. return writer.toString().trim();
  242. } catch (org.tautua.markdownpapers.parser.ParseException p) {
  243. throw new java.text.ParseException(p.getMessage(), 0);
  244. } finally {
  245. try {
  246. markdownReader.close();
  247. } catch (IOException e) {
  248. // IGNORE
  249. }
  250. try {
  251. writer.close();
  252. } catch (IOException e) {
  253. // IGNORE
  254. }
  255. }
  256. }
  257. private static void usage(JCommander jc, ParameterException t) {
  258. System.out.println(Constants.NAME + " v" + Constants.VERSION);
  259. System.out.println();
  260. if (t != null) {
  261. System.out.println(t.getMessage());
  262. System.out.println();
  263. }
  264. if (jc != null) {
  265. jc.usage();
  266. }
  267. System.exit(0);
  268. }
  269. /**
  270. * Command-line parameters for BuildSite utility.
  271. */
  272. @Parameters(separators = " ")
  273. private static class Params {
  274. @Parameter(names = { "--sourceFolder" }, description = "Markdown Source Folder", required = true)
  275. public String sourceFolder;
  276. @Parameter(names = { "--outputFolder" }, description = "HTML Ouptut Folder", required = true)
  277. public String outputFolder;
  278. @Parameter(names = { "--pageHeader" }, description = "Page Header HTML Snippet", required = true)
  279. public String pageHeader;
  280. @Parameter(names = { "--pageFooter" }, description = "Page Footer HTML Snippet", required = true)
  281. public String pageFooter;
  282. @Parameter(names = { "--adSnippet" }, description = "Ad HTML Snippet", required = false)
  283. public String adSnippet;
  284. @Parameter(names = { "--analyticsSnippet" }, description = "Analytics HTML Snippet", required = false)
  285. public String analyticsSnippet;
  286. @Parameter(names = { "--skip" }, description = "Filename to skip", required = false)
  287. public List<String> skips = new ArrayList<String>();
  288. @Parameter(names = { "--alias" }, description = "Filename=Linkname aliases", required = false)
  289. public List<String> aliases = new ArrayList<String>();
  290. @Parameter(names = { "--substitute" }, description = "%TOKEN%=value", required = false)
  291. public List<String> substitutions = new ArrayList<String>();
  292. @Parameter(names = { "--load" }, description = "%TOKEN%=filename", required = false)
  293. public List<String> loads = new ArrayList<String>();
  294. @Parameter(names = { "--nomarkdown" }, description = "%STARTTOKEN%:%ENDTOKEN%", required = false)
  295. public List<String> nomarkdown = new ArrayList<String>();
  296. @Parameter(names = { "--regex" }, description = "searchPattern!!!replacePattern", required = false)
  297. public List<String> regex = new ArrayList<String>();
  298. }
  299. }