/
FrontendToolsManager.java
258 lines (240 loc) · 10.8 KB
/
FrontendToolsManager.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
/*
* Copyright 2000-2018 Vaadin Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.vaadin.flow.plugin.common;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import com.github.eirslett.maven.plugins.frontend.lib.TaskRunnerException;
import com.google.common.collect.ImmutableMap;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Entity to operate frontend tools to transpile files.
* <p>
* Transpilation is based on <a href="https://github.com/gulpjs/gulp">gulp</a>
* and <a href="https://github.com/Polymer/polymer-build">polymer-build</a>.
* <p>
* Polymer tools are used since they are the only ones capable of bundling html
* files along with css and js ones and providing helper method for processing
* web components.
* <p>
* Apart from gulp and polymer-build,
* <a href="https://github.com/yarnpkg/yarn">yarn</a> and
* <a href="https://github.com/nodejs/node">node</a> are used to get and launch
* the tools required.
*
* @author Vaadin Ltd
* @since 1.0.
*/
public class FrontendToolsManager {
private static final Logger LOGGER = LoggerFactory
.getLogger(FrontendToolsManager.class);
private final RunnerManager runnerManager;
private final File workingDirectory;
private final String es5OutputDirectoryName;
private final String es6OutputDirectoryName;
private final FrontendDataProvider frontendDataProvider;
/**
* Prepares the manager.
*
* @param workingDirectory
* the directory to install and process files in, not
* {@code null}
* @param es5OutputDirectoryName
* the name for the directory to put transpiled ES5 files into,
* not {@code null}
* @param es6OutputDirectoryName
* the name for the directory to put minified ES6 files into, not
* {@code null}
* @param frontendDataProvider
* the source of the files required by the
* {@link FrontendToolsManager}, not {@code null}
* @param runnerManager
* node, gulp and yarn runner
*/
public FrontendToolsManager(File workingDirectory,
String es5OutputDirectoryName, String es6OutputDirectoryName,
FrontendDataProvider frontendDataProvider,
RunnerManager runnerManager) {
FlowPluginFileUtils
.forceMkdir(Objects.requireNonNull(workingDirectory));
this.runnerManager = Objects.requireNonNull(runnerManager);
this.workingDirectory = workingDirectory;
this.es5OutputDirectoryName = Objects
.requireNonNull(es5OutputDirectoryName);
this.es6OutputDirectoryName = Objects
.requireNonNull(es6OutputDirectoryName);
this.frontendDataProvider = Objects
.requireNonNull(frontendDataProvider);
}
/**
* Installs tools required for transpilation.
*
* Tools installed are specified in the {@literal package.json} file in the
* plugin project's resources directory. Additionally, copies numerous files
* required for transpilation into the working directory.
*
* @param networkConcurrency
* maximum number of concurrent network requests
*
* @throws IllegalStateException
* if dependency installation fails
* @throws UncheckedIOException
* if supplementary file creation fails
*/
public void installFrontendTools(int networkConcurrency) {
LOGGER.info("Installing required frontend tools to '{}'",
workingDirectory);
createFileFromTemplateResource("package.json", Collections.emptyMap());
createFileFromTemplateResource("yarn.lock", Collections.emptyMap());
try {
StringBuilder args = new StringBuilder("install");
if (networkConcurrency >= 0) {
args.append(" --network-concurrency ");
args.append(networkConcurrency);
}
runnerManager.getYarnRunner().execute(args.toString(),
Collections.emptyMap());
} catch (TaskRunnerException e) {
throw new IllegalStateException(
"Failed to install required frontend dependencies", e);
}
}
private void createFileFromTemplateResource(String templateResourceName,
Map<String, String> replacements) {
try (InputStream resource = getClass().getClassLoader()
.getResourceAsStream(templateResourceName)) {
if (resource == null) {
throw new IllegalStateException(String.format(
"File '%s' is not found in application resources",
templateResourceName));
}
String resourceContents = IOUtils.toString(resource,
StandardCharsets.UTF_8);
for (Map.Entry<String, String> replacement : replacements
.entrySet()) {
resourceContents = resourceContents.replaceFirst(
Pattern.quote(replacement.getKey()),
replacement.getValue().replace("\\", "/"));
}
FileUtils.write(new File(workingDirectory, templateResourceName),
resourceContents, StandardCharsets.UTF_8);
} catch (IOException e) {
throw new UncheckedIOException(String.format(
"Failed to create a file in '%s'", workingDirectory), e);
}
}
/**
* Transpiles files in the directory provided, copying them to the working
* directory. Creates a new output directory, in working directory, with two
* separate directories for ES5 (transpiled) and ES6 (optimized) files.
* Additionally, creates supplementary files, used by transpilation process.
*
* @param es6SourceDirectory
* the directory to get ES6 files from, not {@code null}
* @param outputDirectory
* the directory to put transpiled files into, created if absent
* @param skipEs5
* whether to skip the transpilation step or not
* @return generated output directory path
* @throws IllegalStateException
* if transpilation fails
* @throws IllegalArgumentException
* if es6SourceDirectory is not a directory or does not exist
* @throws UncheckedIOException
* if output directory creation fails or other
* {@link IOException} occurs
*/
public Map<String, File> transpileFiles(File es6SourceDirectory,
File outputDirectory, boolean skipEs5) {
LOGGER.info("Processing frontend files from '{}'", es6SourceDirectory);
try {
FileUtils.forceMkdir(Objects.requireNonNull(outputDirectory));
} catch (IOException e) {
throw new UncheckedIOException(
String.format("Failed to create output directory '%s'",
outputDirectory),
e);
}
if (!Objects.requireNonNull(es6SourceDirectory).isDirectory()) {
throw new IllegalArgumentException(String.format(
"es6SourceDirectory '%s' is not a directory or does not exist",
es6SourceDirectory));
}
ImmutableMap.Builder<String, String> gulpFileParameters = new ImmutableMap.Builder<String, String>()
.put("{es6_source_directory}",
es6SourceDirectory.getAbsolutePath())
.put("{target_directory}", outputDirectory.getAbsolutePath())
.put("{es5_configuration_name}", es5OutputDirectoryName)
.put("{es6_configuration_name}", es6OutputDirectoryName)
.put("{bundle}",
Boolean.toString(frontendDataProvider.shouldBundle()))
.put("{minify}",
Boolean.toString(frontendDataProvider.shouldMinify()))
.put("{hash}",
Boolean.toString(frontendDataProvider.shouldHash()))
.put("{shell_file}",
frontendDataProvider.createShellFile(workingDirectory))
.put("{fragment_files}",
combineFilePathsIntoString(frontendDataProvider
.createFragmentFiles(workingDirectory)));
createFileFromTemplateResource("gulpfile.js",
gulpFileParameters.build());
Map<String, File> transpilationResults = new HashMap<>();
try {
runnerManager.getGulpRunner().execute("build_es6",
Collections.emptyMap());
addTranspilationResult(transpilationResults, outputDirectory,
es6OutputDirectoryName);
if (!skipEs5) {
runnerManager.getGulpRunner().execute("build_es5",
Collections.emptyMap());
addTranspilationResult(transpilationResults, outputDirectory,
es5OutputDirectoryName);
}
} catch (TaskRunnerException e) {
throw new IllegalStateException(
"Transpilation with gulp has failed", e);
}
return transpilationResults;
}
private String combineFilePathsIntoString(Set<String> fragmentFiles) {
return fragmentFiles.stream().map(fileName -> "'" + fileName + "'")
.collect(Collectors.joining(", "));
}
private void addTranspilationResult(Map<String, File> transpilationResults,
File outputDirectory, String configurationName) {
File configurationOutput = FileUtils.getFile(outputDirectory,
configurationName);
if (!configurationOutput.isDirectory()) {
throw new IllegalStateException(String.format(
"Unable to find transpilation result directory at '%s'",
configurationOutput));
}
transpilationResults.put(configurationName, configurationOutput);
}
}