forked from diffplug/spotless
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
NpmFormatterStepStateBase.java
193 lines (164 loc) · 6.86 KB
/
NpmFormatterStepStateBase.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
/*
* Copyright 2016-2022 DiffPlug
*
* 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.diffplug.spotless.npm;
import static java.util.Objects.requireNonNull;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.time.Duration;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.diffplug.spotless.FileSignature;
import com.diffplug.spotless.FormatterFunc;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
abstract class NpmFormatterStepStateBase implements Serializable {
private static final Logger logger = LoggerFactory.getLogger(NpmFormatterStepStateBase.class.getName());
private static final long serialVersionUID = 1460749955865959948L;
@SuppressWarnings("unused")
private final FileSignature packageJsonSignature;
@SuppressFBWarnings("SE_TRANSIENT_FIELD_NOT_RESTORED")
public final transient File nodeModulesDir;
@SuppressFBWarnings("SE_TRANSIENT_FIELD_NOT_RESTORED")
private final transient File npmExecutable;
private final NpmConfig npmConfig;
private final String stepName;
protected NpmFormatterStepStateBase(String stepName, NpmConfig npmConfig, File buildDir, File npm) throws IOException {
this.stepName = requireNonNull(stepName);
this.npmConfig = requireNonNull(npmConfig);
this.npmExecutable = npm;
NodeServerLayout layout = prepareNodeServer(buildDir);
this.nodeModulesDir = layout.nodeModulesDir();
this.packageJsonSignature = FileSignature.signAsList(layout.packageJsonFile());
}
private NodeServerLayout prepareNodeServer(File buildDir) throws IOException {
NodeServerLayout layout = new NodeServerLayout(buildDir, stepName);
NpmResourceHelper.assertDirectoryExists(layout.nodeModulesDir());
NpmResourceHelper.writeUtf8StringToFile(layout.packageJsonFile(),
this.npmConfig.getPackageJsonContent());
NpmResourceHelper
.writeUtf8StringToFile(layout.serveJsFile(), this.npmConfig.getServeScriptContent());
if (this.npmConfig.getNpmrcContent() != null) {
NpmResourceHelper.writeUtf8StringToFile(layout.npmrcFile(), this.npmConfig.getNpmrcContent());
} else {
NpmResourceHelper.deleteFileIfExists(layout.npmrcFile());
}
FormattedPrinter.SYSOUT.print("running npm install");
runNpmInstall(layout.nodeModulesDir());
FormattedPrinter.SYSOUT.print("npm install finished");
return layout;
}
private void runNpmInstall(File npmProjectDir) throws IOException {
new NpmProcess(npmProjectDir, this.npmExecutable).install();
}
protected ServerProcessInfo npmRunServer() throws ServerStartException, IOException {
if (!this.nodeModulesDir.exists()) {
prepareNodeServer(NodeServerLayout.getBuildDirFromNodeModulesDir(this.nodeModulesDir));
}
try {
// The npm process will output the randomly selected port of the http server process to 'server.port' file
// so in order to be safe, remove such a file if it exists before starting.
final File serverPortFile = new File(this.nodeModulesDir, "server.port");
NpmResourceHelper.deleteFileIfExists(serverPortFile);
// start the http server in node
Process server = new NpmProcess(this.nodeModulesDir, this.npmExecutable).start();
// await the readiness of the http server - wait for at most 60 seconds
try {
NpmResourceHelper.awaitReadableFile(serverPortFile, Duration.ofSeconds(60));
} catch (TimeoutException timeoutException) {
// forcibly end the server process
try {
if (server.isAlive()) {
server.destroyForcibly();
server.waitFor();
}
} catch (Throwable t) {
// ignore
}
throw timeoutException;
}
// read the server.port file for resulting port and remember the port for later formatting calls
String serverPort = NpmResourceHelper.readUtf8StringFromFile(serverPortFile).trim();
return new ServerProcessInfo(server, serverPort, serverPortFile);
} catch (IOException | TimeoutException e) {
throw new ServerStartException(e);
}
}
protected static String replaceDevDependencies(String template, Map<String, String> devDependencies) {
StringBuilder builder = new StringBuilder();
Iterator<Map.Entry<String, String>> entryIter = devDependencies.entrySet().iterator();
while (entryIter.hasNext()) {
Map.Entry<String, String> entry = entryIter.next();
builder.append("\t\t\"");
builder.append(entry.getKey());
builder.append("\": \"");
builder.append(entry.getValue());
builder.append("\"");
if (entryIter.hasNext()) {
builder.append(",\n");
}
}
return replacePlaceholders(template, Collections.singletonMap("devDependencies", builder.toString()));
}
private static String replacePlaceholders(String template, Map<String, String> replacements) {
String result = template;
for (Entry<String, String> entry : replacements.entrySet()) {
result = result.replaceAll("\\Q${" + entry.getKey() + "}\\E", entry.getValue());
}
return result;
}
public abstract FormatterFunc createFormatterFunc();
protected static class ServerProcessInfo implements AutoCloseable {
private final Process server;
private final String serverPort;
private final File serverPortFile;
public ServerProcessInfo(Process server, String serverPort, File serverPortFile) {
this.server = server;
this.serverPort = serverPort;
this.serverPortFile = serverPortFile;
}
public String getBaseUrl() {
return "http://127.0.0.1:" + this.serverPort;
}
@Override
public void close() throws Exception {
try {
logger.trace("Closing npm server in directory <" + serverPortFile.getParent() + "> and port <" + serverPort + ">");
if (server.isAlive()) {
boolean ended = server.waitFor(5, TimeUnit.SECONDS);
if (!ended) {
logger.info("Force-Closing npm server in directory <" + serverPortFile.getParent() + "> and port <" + serverPort + ">");
server.destroyForcibly().waitFor();
logger.trace("Force-Closing npm server in directory <" + serverPortFile.getParent() + "> and port <" + serverPort + "> -- Finished");
}
}
} finally {
NpmResourceHelper.deleteFileIfExists(serverPortFile);
}
}
}
protected static class ServerStartException extends RuntimeException {
private static final long serialVersionUID = -8803977379866483002L;
public ServerStartException(Throwable cause) {
super(cause);
}
}
}