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 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. /*
  2. * Copyright 2011 gitblit.com.
  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.gitblit.build;
  17. import java.io.BufferedReader;
  18. import java.io.File;
  19. import java.io.FileOutputStream;
  20. import java.io.FileReader;
  21. import java.io.FilenameFilter;
  22. import java.io.OutputStreamWriter;
  23. import java.nio.charset.Charset;
  24. import java.text.MessageFormat;
  25. import java.text.ParseException;
  26. import java.text.SimpleDateFormat;
  27. import java.util.ArrayList;
  28. import java.util.Arrays;
  29. import java.util.Date;
  30. import java.util.HashMap;
  31. import java.util.List;
  32. import java.util.Map;
  33. import java.util.Vector;
  34. import com.beust.jcommander.JCommander;
  35. import com.beust.jcommander.Parameter;
  36. import com.beust.jcommander.ParameterException;
  37. import com.beust.jcommander.Parameters;
  38. import com.gitblit.Constants;
  39. import com.gitblit.utils.FileUtils;
  40. import com.gitblit.utils.MarkdownUtils;
  41. import com.gitblit.utils.StringUtils;
  42. /**
  43. * Builds the web site or deployment documentation from Markdown source files.
  44. *
  45. * All Markdown source files must have the .mkd extension.
  46. *
  47. * Natural string sort order of the Markdown source filenames is the order of
  48. * page links. "##_" prefixes are used to control the sort order.
  49. *
  50. * @author James Moger
  51. *
  52. */
  53. public class BuildSite {
  54. private final static String CASE_SENSITIVE = "CASE-SENSITIVE";
  55. private final static String RESTART_REQUIRED = "RESTART REQUIRED";
  56. private final static String SINCE = "SINCE";
  57. public static void main(String... args) {
  58. Params params = new Params();
  59. JCommander jc = new JCommander(params);
  60. try {
  61. jc.parse(args);
  62. } catch (ParameterException t) {
  63. usage(jc, t);
  64. }
  65. File sourceFolder = new File(params.sourceFolder);
  66. File destinationFolder = new File(params.outputFolder);
  67. File[] markdownFiles = sourceFolder.listFiles(new FilenameFilter() {
  68. @Override
  69. public boolean accept(File dir, String name) {
  70. return name.toLowerCase().endsWith(".mkd");
  71. }
  72. });
  73. Arrays.sort(markdownFiles);
  74. Map<String, String> aliasMap = new HashMap<String, String>();
  75. for (String alias : params.aliases) {
  76. String[] values = alias.split("=");
  77. aliasMap.put(values[0], values[1]);
  78. }
  79. System.out.println(MessageFormat.format("Generating site from {0} Markdown Docs in {1} ",
  80. markdownFiles.length, sourceFolder.getAbsolutePath()));
  81. String linkPattern = "<a href=''{0}''>{1}</a>";
  82. StringBuilder sb = new StringBuilder();
  83. for (File file : markdownFiles) {
  84. String documentName = getDocumentName(file);
  85. if (!params.skips.contains(documentName)) {
  86. String displayName = documentName;
  87. if (aliasMap.containsKey(documentName)) {
  88. displayName = aliasMap.get(documentName);
  89. } else {
  90. displayName = displayName.replace('_', ' ');
  91. }
  92. String fileName = documentName + ".html";
  93. sb.append(MessageFormat.format(linkPattern, fileName, displayName));
  94. sb.append(" | ");
  95. }
  96. }
  97. sb.setLength(sb.length() - 3);
  98. sb.trimToSize();
  99. String htmlHeader = FileUtils.readContent(new File(params.pageHeader), "\n");
  100. String htmlAdSnippet = null;
  101. if (!StringUtils.isEmpty(params.adSnippet)) {
  102. File snippet = new File(params.adSnippet);
  103. if (snippet.exists()) {
  104. htmlAdSnippet = FileUtils.readContent(snippet, "\n");
  105. }
  106. }
  107. String htmlFooter = FileUtils.readContent(new File(params.pageFooter), "\n");
  108. String links = sb.toString();
  109. String header = MessageFormat.format(htmlHeader, Constants.FULL_NAME, links);
  110. if (!StringUtils.isEmpty(params.analyticsSnippet)) {
  111. File snippet = new File(params.analyticsSnippet);
  112. if (snippet.exists()) {
  113. String htmlSnippet = FileUtils.readContent(snippet, "\n");
  114. header = header.replace("<!-- ANALYTICS -->", htmlSnippet);
  115. }
  116. }
  117. final String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
  118. final String footer = MessageFormat.format(htmlFooter, "generated " + date);
  119. for (File file : markdownFiles) {
  120. try {
  121. String documentName = getDocumentName(file);
  122. if (!params.skips.contains(documentName)) {
  123. String fileName = documentName + ".html";
  124. System.out.println(MessageFormat.format(" {0} => {1}", file.getName(),
  125. fileName));
  126. String rawContent = FileUtils.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(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. for (String token : params.substitutions) {
  168. String[] kv = token.split("=", 2);
  169. content = content.replace(kv[0], kv[1]);
  170. }
  171. for (String token:params.regex) {
  172. String[] kv = token.split("!!!", 2);
  173. content = content.replaceAll(kv[0], kv[1]);
  174. }
  175. for (String alias : params.properties) {
  176. String[] kv = alias.split("=", 2);
  177. String loadedContent = generatePropertiesContent(new File(kv[1]));
  178. content = content.replace(kv[0], loadedContent);
  179. }
  180. for (String alias : params.loads) {
  181. String[] kv = alias.split("=" ,2);
  182. String loadedContent = FileUtils.readContent(new File(kv[1]), "\n");
  183. loadedContent = StringUtils.escapeForHtml(loadedContent, false);
  184. loadedContent = StringUtils.breakLinesForHtml(loadedContent);
  185. content = content.replace(kv[0], loadedContent);
  186. }
  187. OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(
  188. new File(destinationFolder, fileName)), Charset.forName("UTF-8"));
  189. writer.write(header);
  190. if (!StringUtils.isEmpty(htmlAdSnippet)) {
  191. writer.write(htmlAdSnippet);
  192. }
  193. writer.write(content);
  194. writer.write(footer);
  195. writer.close();
  196. }
  197. } catch (Throwable t) {
  198. System.err.println("Failed to transform " + file.getName());
  199. t.printStackTrace();
  200. }
  201. }
  202. }
  203. private static String getDocumentName(File file) {
  204. String displayName = file.getName().substring(0, file.getName().lastIndexOf('.'))
  205. .toLowerCase();
  206. int underscore = displayName.indexOf('_') + 1;
  207. if (underscore > -1) {
  208. // trim leading ##_ which is to control display order
  209. return displayName.substring(underscore);
  210. }
  211. return displayName;
  212. }
  213. private static String generatePropertiesContent(File propertiesFile) throws Exception {
  214. // Read the current Gitblit properties
  215. BufferedReader propertiesReader = new BufferedReader(new FileReader(propertiesFile));
  216. Vector<Setting> settings = new Vector<Setting>();
  217. List<String> comments = new ArrayList<String>();
  218. String line = null;
  219. while ((line = propertiesReader.readLine()) != null) {
  220. if (line.length() == 0) {
  221. Setting s = new Setting("", "", comments);
  222. settings.add(s);
  223. comments.clear();
  224. } else {
  225. if (line.charAt(0) == '#') {
  226. comments.add(line.substring(1).trim());
  227. } else {
  228. String[] kvp = line.split("=", 2);
  229. String key = kvp[0].trim();
  230. Setting s = new Setting(key, kvp[1].trim(), comments);
  231. settings.add(s);
  232. comments.clear();
  233. }
  234. }
  235. }
  236. propertiesReader.close();
  237. StringBuilder sb = new StringBuilder();
  238. for (Setting setting : settings) {
  239. for (String comment : setting.comments) {
  240. if (comment.contains(SINCE) || comment.contains(RESTART_REQUIRED)
  241. || comment.contains(CASE_SENSITIVE)) {
  242. sb.append(MessageFormat.format("<span style=\"color:#004000;\"># <i>{0}</i></span>", transformMarkdown(comment)));
  243. } else {
  244. sb.append(MessageFormat.format("<span style=\"color:#004000;\"># {0}</span>", transformMarkdown(comment)));
  245. }
  246. sb.append("<br/>\n");
  247. }
  248. if (!StringUtils.isEmpty(setting.name)) {
  249. sb.append(MessageFormat.format("<span style=\"color:#000080;\">{0}</span> = <span style=\"color:#800000;\">{1}</span>", setting.name, StringUtils.escapeForHtml(setting.value, false)));
  250. }
  251. sb.append("<br/>\n");
  252. }
  253. return sb.toString();
  254. }
  255. private static String transformMarkdown(String comment) throws ParseException {
  256. String md = MarkdownUtils.transformMarkdown(comment);
  257. if (md.startsWith("<p>")) {
  258. md = md.substring(3);
  259. }
  260. if (md.endsWith("</p>")) {
  261. md = md.substring(0, md.length() - 4);
  262. }
  263. return md;
  264. }
  265. private static void usage(JCommander jc, ParameterException t) {
  266. System.out.println(Constants.getGitBlitVersion());
  267. System.out.println();
  268. if (t != null) {
  269. System.out.println(t.getMessage());
  270. System.out.println();
  271. }
  272. if (jc != null) {
  273. jc.usage();
  274. }
  275. System.exit(0);
  276. }
  277. private static class Setting {
  278. final String name;
  279. final String value;
  280. final List<String> comments;
  281. Setting(String name, String value, List<String> comments) {
  282. this.name = name;
  283. this.value = value;
  284. this.comments = new ArrayList<String>(comments);
  285. }
  286. }
  287. @Parameters(separators = " ")
  288. private static class Params {
  289. @Parameter(names = { "--sourceFolder" }, description = "Markdown Source Folder", required = true)
  290. public String sourceFolder;
  291. @Parameter(names = { "--outputFolder" }, description = "HTML Ouptut Folder", required = true)
  292. public String outputFolder;
  293. @Parameter(names = { "--pageHeader" }, description = "Page Header HTML Snippet", required = true)
  294. public String pageHeader;
  295. @Parameter(names = { "--pageFooter" }, description = "Page Footer HTML Snippet", required = true)
  296. public String pageFooter;
  297. @Parameter(names = { "--adSnippet" }, description = "Ad HTML Snippet", required = false)
  298. public String adSnippet;
  299. @Parameter(names = { "--analyticsSnippet" }, description = "Analytics HTML Snippet", required = false)
  300. public String analyticsSnippet;
  301. @Parameter(names = { "--skip" }, description = "Filename to skip", required = false)
  302. public List<String> skips = new ArrayList<String>();
  303. @Parameter(names = { "--alias" }, description = "Filename=Linkname aliases", required = false)
  304. public List<String> aliases = new ArrayList<String>();
  305. @Parameter(names = { "--substitute" }, description = "%TOKEN%=value", required = false)
  306. public List<String> substitutions = new ArrayList<String>();
  307. @Parameter(names = { "--load" }, description = "%TOKEN%=filename", required = false)
  308. public List<String> loads = new ArrayList<String>();
  309. @Parameter(names = { "--properties" }, description = "%TOKEN%=filename", required = false)
  310. public List<String> properties = new ArrayList<String>();
  311. @Parameter(names = { "--nomarkdown" }, description = "%STARTTOKEN%:%ENDTOKEN%", required = false)
  312. public List<String> nomarkdown = new ArrayList<String>();
  313. @Parameter(names = { "--regex" }, description = "searchPattern!!!replacePattern", required = false)
  314. public List<String> regex = new ArrayList<String>();
  315. }
  316. }