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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  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 static final String SPACE_DELIMITED = "SPACE-DELIMITED";
  55. private static final String CASE_SENSITIVE = "CASE-SENSITIVE";
  56. private static final String RESTART_REQUIRED = "RESTART REQUIRED";
  57. private static final String SINCE = "SINCE";
  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 = "<li><a href=''{0}''>{1}</a></li>";
  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 = FileUtils.readContent(new File(params.pageHeader), "\n");
  101. String htmlAdSnippet = null;
  102. if (!StringUtils.isEmpty(params.adSnippet)) {
  103. File snippet = new File(params.adSnippet);
  104. if (snippet.exists()) {
  105. htmlAdSnippet = FileUtils.readContent(snippet, "\n");
  106. }
  107. }
  108. String htmlFooter = FileUtils.readContent(new File(params.pageFooter), "\n");
  109. String links = sb.toString();
  110. String header = MessageFormat.format(htmlHeader, Constants.FULL_NAME, links);
  111. if (!StringUtils.isEmpty(params.analyticsSnippet)) {
  112. File snippet = new File(params.analyticsSnippet);
  113. if (snippet.exists()) {
  114. String htmlSnippet = FileUtils.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(),
  126. fileName));
  127. String rawContent = FileUtils.readContent(file, "\n");
  128. String markdownContent = rawContent;
  129. Map<String, List<String>> nomarkdownMap = new HashMap<String, List<String>>();
  130. // extract sections marked as no-markdown
  131. int nmd = 0;
  132. for (String token : params.nomarkdown) {
  133. StringBuilder strippedContent = new StringBuilder();
  134. String nomarkdownKey = "%NOMARKDOWN" + nmd + "%";
  135. String[] kv = token.split(":", 2);
  136. String beginToken = kv[0];
  137. String endToken = kv[1];
  138. // strip nomarkdown chunks from markdown and cache them
  139. List<String> chunks = new Vector<String>();
  140. int beginCode = 0;
  141. int endCode = 0;
  142. while ((beginCode = markdownContent.indexOf(beginToken, endCode)) > -1) {
  143. if (endCode == 0) {
  144. strippedContent.append(markdownContent.substring(0, beginCode));
  145. } else {
  146. strippedContent.append(markdownContent
  147. .substring(endCode, beginCode));
  148. }
  149. strippedContent.append(nomarkdownKey);
  150. endCode = markdownContent.indexOf(endToken, beginCode);
  151. chunks.add(markdownContent.substring(beginCode, endCode));
  152. nomarkdownMap.put(nomarkdownKey, chunks);
  153. }
  154. // get remainder of text
  155. if (endCode < markdownContent.length()) {
  156. strippedContent.append(markdownContent.substring(endCode,
  157. markdownContent.length()));
  158. }
  159. markdownContent = strippedContent.toString();
  160. nmd++;
  161. }
  162. // transform markdown to html
  163. String content = transformMarkdown(markdownContent.toString());
  164. // reinsert nomarkdown chunks
  165. for (Map.Entry<String, List<String>> nomarkdown : nomarkdownMap.entrySet()) {
  166. for (String chunk : nomarkdown.getValue()) {
  167. content = content.replaceFirst(nomarkdown.getKey(), chunk);
  168. }
  169. }
  170. for (String token : params.substitutions) {
  171. String[] kv = token.split("=", 2);
  172. content = content.replace(kv[0], kv[1]);
  173. }
  174. for (String token : params.regex) {
  175. String[] kv = token.split("!!!", 2);
  176. content = content.replaceAll(kv[0], kv[1]);
  177. }
  178. for (String alias : params.properties) {
  179. String[] kv = alias.split("=", 2);
  180. String loadedContent = generatePropertiesContent(new File(kv[1]));
  181. content = content.replace(kv[0], loadedContent);
  182. }
  183. for (String alias : params.loads) {
  184. String[] kv = alias.split("=", 2);
  185. String loadedContent = FileUtils.readContent(new File(kv[1]), "\n");
  186. loadedContent = StringUtils.escapeForHtml(loadedContent, false);
  187. loadedContent = StringUtils.breakLinesForHtml(loadedContent);
  188. content = content.replace(kv[0], loadedContent);
  189. }
  190. OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(
  191. new File(destinationFolder, fileName)), Charset.forName("UTF-8"));
  192. writer.write(header);
  193. if (!StringUtils.isEmpty(htmlAdSnippet)) {
  194. writer.write(htmlAdSnippet);
  195. }
  196. writer.write(content);
  197. writer.write(footer);
  198. writer.close();
  199. }
  200. } catch (Throwable t) {
  201. System.err.println("Failed to transform " + file.getName());
  202. t.printStackTrace();
  203. }
  204. }
  205. }
  206. private static String getDocumentName(File file) {
  207. String displayName = file.getName().substring(0, file.getName().lastIndexOf('.'))
  208. .toLowerCase();
  209. int underscore = displayName.indexOf('_') + 1;
  210. if (underscore > -1) {
  211. // trim leading ##_ which is to control display order
  212. return displayName.substring(underscore);
  213. }
  214. return displayName;
  215. }
  216. private static String generatePropertiesContent(File propertiesFile) throws Exception {
  217. // Read the current Gitblit properties
  218. BufferedReader propertiesReader = new BufferedReader(new FileReader(propertiesFile));
  219. Vector<Setting> settings = new Vector<Setting>();
  220. List<String> comments = new ArrayList<String>();
  221. String line = null;
  222. while ((line = propertiesReader.readLine()) != null) {
  223. if (line.length() == 0) {
  224. Setting s = new Setting("", "", comments);
  225. settings.add(s);
  226. comments.clear();
  227. } else {
  228. if (line.charAt(0) == '#') {
  229. comments.add(line.substring(1).trim());
  230. } else {
  231. String[] kvp = line.split("=", 2);
  232. String key = kvp[0].trim();
  233. Setting s = new Setting(key, kvp[1].trim(), comments);
  234. settings.add(s);
  235. comments.clear();
  236. }
  237. }
  238. }
  239. propertiesReader.close();
  240. StringBuilder sb = new StringBuilder();
  241. for (Setting setting : settings) {
  242. for (String comment : setting.comments) {
  243. if (comment.contains(SINCE) || comment.contains(RESTART_REQUIRED)
  244. || comment.contains(CASE_SENSITIVE) || comment.contains(SPACE_DELIMITED)) {
  245. sb.append(MessageFormat.format(
  246. "<span style=\"color:#004000;\"># <i>{0}</i></span>",
  247. transformMarkdown(comment)));
  248. } else {
  249. sb.append(MessageFormat.format("<span style=\"color:#004000;\"># {0}</span>",
  250. transformMarkdown(comment)));
  251. }
  252. sb.append("<br/>\n");
  253. }
  254. if (!StringUtils.isEmpty(setting.name)) {
  255. sb.append(MessageFormat
  256. .format("<span style=\"color:#000080;\">{0}</span> = <span style=\"color:#800000;\">{1}</span>",
  257. setting.name, StringUtils.escapeForHtml(setting.value, false)));
  258. }
  259. sb.append("<br/>\n");
  260. }
  261. return sb.toString();
  262. }
  263. private static String transformMarkdown(String comment) throws ParseException {
  264. String md = MarkdownUtils.transformMarkdown(comment);
  265. if (md.startsWith("<p>")) {
  266. md = md.substring(3);
  267. }
  268. if (md.endsWith("</p>")) {
  269. md = md.substring(0, md.length() - 4);
  270. }
  271. return md;
  272. }
  273. private static void usage(JCommander jc, ParameterException t) {
  274. System.out.println(Constants.getGitBlitVersion());
  275. System.out.println();
  276. if (t != null) {
  277. System.out.println(t.getMessage());
  278. System.out.println();
  279. }
  280. if (jc != null) {
  281. jc.usage();
  282. }
  283. System.exit(0);
  284. }
  285. /**
  286. * Setting represents a setting with its comments from the properties file.
  287. */
  288. private static class Setting {
  289. final String name;
  290. final String value;
  291. final List<String> comments;
  292. Setting(String name, String value, List<String> comments) {
  293. this.name = name;
  294. this.value = value;
  295. this.comments = new ArrayList<String>(comments);
  296. }
  297. }
  298. /**
  299. * JCommander Parameters class for BuildSite.
  300. */
  301. @Parameters(separators = " ")
  302. private static class Params {
  303. @Parameter(names = { "--sourceFolder" }, description = "Markdown Source Folder", required = true)
  304. public String sourceFolder;
  305. @Parameter(names = { "--outputFolder" }, description = "HTML Ouptut Folder", required = true)
  306. public String outputFolder;
  307. @Parameter(names = { "--pageHeader" }, description = "Page Header HTML Snippet", required = true)
  308. public String pageHeader;
  309. @Parameter(names = { "--pageFooter" }, description = "Page Footer HTML Snippet", required = true)
  310. public String pageFooter;
  311. @Parameter(names = { "--adSnippet" }, description = "Ad HTML Snippet", required = false)
  312. public String adSnippet;
  313. @Parameter(names = { "--analyticsSnippet" }, description = "Analytics HTML Snippet", required = false)
  314. public String analyticsSnippet;
  315. @Parameter(names = { "--skip" }, description = "Filename to skip", required = false)
  316. public List<String> skips = new ArrayList<String>();
  317. @Parameter(names = { "--alias" }, description = "Filename=Linkname aliases", required = false)
  318. public List<String> aliases = new ArrayList<String>();
  319. @Parameter(names = { "--substitute" }, description = "%TOKEN%=value", required = false)
  320. public List<String> substitutions = new ArrayList<String>();
  321. @Parameter(names = { "--load" }, description = "%TOKEN%=filename", required = false)
  322. public List<String> loads = new ArrayList<String>();
  323. @Parameter(names = { "--properties" }, description = "%TOKEN%=filename", required = false)
  324. public List<String> properties = new ArrayList<String>();
  325. @Parameter(names = { "--nomarkdown" }, description = "%STARTTOKEN%:%ENDTOKEN%", required = false)
  326. public List<String> nomarkdown = new ArrayList<String>();
  327. @Parameter(names = { "--regex" }, description = "searchPattern!!!replacePattern", required = false)
  328. public List<String> regex = new ArrayList<String>();
  329. }
  330. }