|
| 1 | +package org.openapitools.codegen.cmd; |
| 2 | + |
| 3 | +import io.airlift.airline.Command; |
| 4 | +import io.airlift.airline.Option; |
| 5 | +import org.apache.commons.lang3.StringUtils; |
| 6 | +import org.openapitools.codegen.CodegenConfig; |
| 7 | +import org.openapitools.codegen.CodegenConfigLoader; |
| 8 | +import org.openapitools.codegen.CodegenConstants; |
| 9 | +import org.slf4j.Logger; |
| 10 | +import org.slf4j.LoggerFactory; |
| 11 | + |
| 12 | +import java.io.File; |
| 13 | +import java.io.IOException; |
| 14 | +import java.net.URI; |
| 15 | +import java.net.URISyntaxException; |
| 16 | +import java.nio.file.*; |
| 17 | +import java.nio.file.spi.FileSystemProvider; |
| 18 | +import java.util.*; |
| 19 | +import java.util.regex.Pattern; |
| 20 | +import java.util.stream.Stream; |
| 21 | + |
| 22 | +@SuppressWarnings({"FieldMayBeFinal", "FieldCanBeLocal", "unused"}) |
| 23 | +@Command(name = "template", description = "Retrieve templates for local modification") |
| 24 | +public class AuthorTemplate extends OpenApiGeneratorCommand { |
| 25 | + |
| 26 | + private static final Logger LOGGER = LoggerFactory.getLogger(AuthorTemplate.class); |
| 27 | + |
| 28 | + @Option(name = {"-g", "--generator-name"}, title = "generator name", |
| 29 | + description = "generator to use (see list command for list)", |
| 30 | + required = true) |
| 31 | + private String generatorName; |
| 32 | + |
| 33 | + @Option(name = {"--library"}, title = "library", description = CodegenConstants.LIBRARY_DESC) |
| 34 | + private String library; |
| 35 | + |
| 36 | + @Option(name = {"-o", "--output"}, title = "output directory", |
| 37 | + description = "where to write the template files (defaults to 'out')") |
| 38 | + private String output = ""; |
| 39 | + |
| 40 | + @Option(name = {"-v", "--verbose"}, description = "verbose mode") |
| 41 | + private boolean verbose; |
| 42 | + |
| 43 | + private Pattern pattern = null; |
| 44 | + |
| 45 | + @Override |
| 46 | + void execute() { |
| 47 | + CodegenConfig config = CodegenConfigLoader.forName(generatorName); |
| 48 | + String templateDirectory = config.templateDir(); |
| 49 | + |
| 50 | + log("Requesting '{}' from embedded resource directory '{}'", generatorName, templateDirectory); |
| 51 | + |
| 52 | + Path embeddedTemplatePath; |
| 53 | + try { |
| 54 | + URI uri = Objects.requireNonNull(this.getClass().getClassLoader().getResource(templateDirectory)).toURI(); |
| 55 | + |
| 56 | + if ("jar".equals(uri.getScheme())) { |
| 57 | + Optional<FileSystemProvider> provider = FileSystemProvider.installedProviders() |
| 58 | + .stream() |
| 59 | + .filter(p -> p.getScheme().equalsIgnoreCase("jar")) |
| 60 | + .findFirst(); |
| 61 | + |
| 62 | + if (!provider.isPresent()) { |
| 63 | + throw new ProviderNotFoundException("Unable to load jar file system provider"); |
| 64 | + } |
| 65 | + |
| 66 | + try { |
| 67 | + provider.get().getFileSystem(uri); |
| 68 | + } catch (FileSystemNotFoundException ex) { |
| 69 | + // File system wasn't loaded, so create it. |
| 70 | + provider.get().newFileSystem(uri, Collections.emptyMap()); |
| 71 | + } |
| 72 | + } |
| 73 | + |
| 74 | + embeddedTemplatePath = Paths.get(uri); |
| 75 | + |
| 76 | + log("Copying from jar location {}", embeddedTemplatePath.toAbsolutePath().toString()); |
| 77 | + |
| 78 | + File outputDir; |
| 79 | + if (StringUtils.isNotEmpty(output)) { |
| 80 | + outputDir = new File(output); |
| 81 | + } else { |
| 82 | + outputDir = new File("out"); |
| 83 | + } |
| 84 | + |
| 85 | + Path outputDirPath = outputDir.toPath(); |
| 86 | + if (!Files.exists(outputDirPath)) { |
| 87 | + Files.createDirectories(outputDirPath); |
| 88 | + } |
| 89 | + List<Path> generatedFiles = new ArrayList<>(); |
| 90 | + try (final Stream<Path> templates = Files.walk(embeddedTemplatePath)) { |
| 91 | + templates.forEach(template -> { |
| 92 | + log("Found template: {}", template.toAbsolutePath()); |
| 93 | + Path relativePath = embeddedTemplatePath.relativize(template); |
| 94 | + if (shouldCopy(relativePath)) { |
| 95 | + Path target = outputDirPath.resolve(relativePath.toString()); |
| 96 | + generatedFiles.add(target); |
| 97 | + try { |
| 98 | + if (Files.isDirectory(template)) { |
| 99 | + if (Files.notExists(target)) { |
| 100 | + log("Creating directory: {}", target.toAbsolutePath()); |
| 101 | + Files.createDirectories(target); |
| 102 | + } |
| 103 | + } else { |
| 104 | + if (target.getParent() != null && Files.notExists(target.getParent())) { |
| 105 | + log("Creating directory: {}", target.getParent()); |
| 106 | + Files.createDirectories(target.getParent()); |
| 107 | + } |
| 108 | + log("Copying to: {}", target.toAbsolutePath()); |
| 109 | + Files.copy(template, target, StandardCopyOption.REPLACE_EXISTING); |
| 110 | + } |
| 111 | + } catch (IOException e) { |
| 112 | + LOGGER.error("Unable to create target location '{}'.", target); |
| 113 | + } |
| 114 | + } else { |
| 115 | + log("Directory is excluded by library option: {}", relativePath); |
| 116 | + } |
| 117 | + }); |
| 118 | + } |
| 119 | + |
| 120 | + if (StringUtils.isNotEmpty(library) && !generatedFiles.isEmpty()) { |
| 121 | + Path librariesPath = outputDirPath.resolve("libraries"); |
| 122 | + Path targetLibrary = librariesPath.resolve(library); |
| 123 | + String librariesPrefix = librariesPath.toString(); |
| 124 | + if (!Files.isDirectory(targetLibrary)) { |
| 125 | + LOGGER.warn("The library '{}' was not extracted. Please verify the spelling and retry.", targetLibrary); |
| 126 | + } |
| 127 | + generatedFiles.stream() |
| 128 | + .filter(p -> p.startsWith(librariesPrefix)) |
| 129 | + .forEach(p -> { |
| 130 | + if (p.startsWith(targetLibrary)) { |
| 131 | + // We don't care about empty directories, and not need to check directory for files. |
| 132 | + if (!Files.isDirectory(p)) { |
| 133 | + // warn if the file was not written |
| 134 | + if (Files.notExists(p)) { |
| 135 | + LOGGER.warn("An expected library file was not extracted: {}", p.toAbsolutePath()); |
| 136 | + } |
| 137 | + } |
| 138 | + } else { |
| 139 | + LOGGER.warn("The library filter '{}' extracted an unexpected library path: {}", library, p.toAbsolutePath()); |
| 140 | + } |
| 141 | + }); |
| 142 | + } |
| 143 | + |
| 144 | + LOGGER.info("Extracted templates to '{}' directory. Refer to https://openapi-generator.tech/docs/templating for customization details.", outputDirPath); |
| 145 | + } catch (URISyntaxException | IOException e) { |
| 146 | + LOGGER.error("Unable to load embedded template directory.", e); |
| 147 | + } |
| 148 | + } |
| 149 | + |
| 150 | + private void log(String format, Object... arguments) { |
| 151 | + if (verbose) { |
| 152 | + LOGGER.info(format, arguments); |
| 153 | + } |
| 154 | + } |
| 155 | + |
| 156 | + private boolean shouldCopy(Path relativePath) { |
| 157 | + String path = relativePath.toString(); |
| 158 | + if (StringUtils.isNotEmpty(library) && path.contains("libraries")) { |
| 159 | + if (pattern == null) { |
| 160 | + pattern = Pattern.compile(String.format(Locale.ROOT, "libraries[/\\\\]{1}%s[/\\\\]{1}.*", Pattern.quote(library))); |
| 161 | + } |
| 162 | + |
| 163 | + return pattern.matcher(path).matches(); |
| 164 | + } |
| 165 | + |
| 166 | + return true; |
| 167 | + } |
| 168 | +} |
0 commit comments