001/** 002 * Copyright 2013-2015 John Ericksen 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package org.asciidoctor.asciidoclet; 017 018import com.google.common.base.Optional; 019import com.google.common.io.ByteSink; 020import com.google.common.io.Files; 021import com.google.common.io.Resources; 022import com.sun.javadoc.DocErrorReporter; 023 024import java.io.File; 025import java.io.IOException; 026import java.net.URL; 027 028/** 029 * Sets up a temporary directory containing output templates for use by Asciidoctor. 030 */ 031public class OutputTemplates { 032 033 private static final String[] TEMPLATE_NAMES = new String[] { 034 "section.html.haml", 035 "paragraph.html.haml" 036 }; 037 038 private final File templateDir; 039 040 private OutputTemplates(File templateDir) { 041 this.templateDir = templateDir; 042 } 043 044 static Optional<OutputTemplates> create(DocErrorReporter errorReporter) { 045 File dir = prepareTemplateDir(errorReporter); 046 return dir == null ? Optional.<OutputTemplates>absent() : Optional.of(new OutputTemplates(dir)); 047 } 048 049 File templateDir() { 050 return templateDir; 051 } 052 053 void delete() { 054 for (String templateName : TEMPLATE_NAMES) { 055 new File(templateDir, templateName).delete(); 056 } 057 templateDir.delete(); 058 } 059 060 private static File prepareTemplateDir(DocErrorReporter errorReporter) { 061 // copy our template resources to the templateDir so Asciidoctor can use them. 062 File templateDir = Files.createTempDir(); 063 try { 064 for (String templateName : TEMPLATE_NAMES) { 065 prepareTemplate(templateDir, templateName); 066 } 067 return templateDir; 068 } catch (IOException e) { 069 errorReporter.printWarning("Failed to prepare templates: " + e.getLocalizedMessage()); 070 return null; 071 } 072 } 073 074 private static void prepareTemplate(File templateDir, String template) throws IOException { 075 URL src = OutputTemplates.class.getClassLoader().getResource("templates/" + template); 076 if (src == null) { 077 throw new IOException("Could not find template " + template); 078 } 079 ByteSink dest = Files.asByteSink(new File(templateDir, template)); 080 Resources.asByteSource(src).copyTo(dest); 081 } 082 083}