-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAction.java
More file actions
615 lines (535 loc) · 20.2 KB
/
Copy pathAction.java
File metadata and controls
615 lines (535 loc) · 20.2 KB
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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.OpenOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Action {
private Action() {}
static void main(String[] args) throws Exception {
try {
Config config = Config.fromEnv();
ResultWriter resultWriter = ResultWriter.ofExternalName(config.resultType());
for (String file : args) {
Properties properties = Util.readProperties(file, config.missingFileHandler());
// If selectedKeys is set, this Map will have exactly those keys and values may be empty (where selected key is
// not found in properties).
// Otherwise, this Map will have the same keys as the properties file, and "not found" is not possible.
Map<String, Optional<String>> selectedProperties = config.selectedKeys()
.map(keys -> Util.selectProperties(properties, keys, file)) //
.orElseGet(() -> Util.stringEntries(properties));
resultWriter.write(selectedProperties, config);
}
} catch (ExitSilentlyException e) {
System.exit(e.status);
} catch (IoRuntimeException e) {
throw e.getCause();
} catch (OutputException e) {
try (GitHubVariableWriter writer = GitHubOutputFile.OUTPUT.open()) {
writer.write(Ids.OutputName.ERROR, e.getMessage());
}
throw e;
}
}
}
/**
* Identifiers which must match those specified in the action YAML.
*/
class Ids {
private Ids() {}
/**
* Configuration environment variable names and their corresponding action input names for error messages.
*/
enum ConfigVariable {
FILE("file"), //
ON_MISSING_FILE("onMissingFile"), //
KEYS("keys"), //
RESULT_TYPE("resultType"), //
KEY_SEPARATOR("keySeparator"), //
RESULT_NAME_SEPARATOR("resultNameSeparator"), //
OUTPUT_PREFIX(null);
public final String externalName;
private ConfigVariable(String externalName) {
this.externalName = externalName;
}
@Override
public String toString() {
return externalName;
}
}
enum MissingFileHandlerName {
DEBUG_MESSAGE("debug-message"), //
NOTICE_MESSAGE("notice-message"), //
WARNING_MESSAGE("warning-message"), //
ERROR("error");
public final String externalName;
private MissingFileHandlerName(String externalName) {
this.externalName = externalName;
}
}
enum ResultWriterName {
OUTPUT("output"), //
OUTPUT_NAMED("output-named"), //
ENV_NAMED("env-named"), //
ENV("env"), //
JSON("json"), //
JSON_FILE("json-file");
public final String externalName;
private ResultWriterName(String externalName) {
this.externalName = externalName;
}
}
enum OutputName {
JSON, //
VALUE, //
ERROR; // This output is not documented.
public final String externalName = name().toLowerCase();
}
}
class IoRuntimeException extends RuntimeException {
public IoRuntimeException(IOException cause) {
super(cause);
}
@Override
public synchronized IOException getCause() {
return (IOException) super.getCause();
}
}
/**
* An exception for which an {@link Ids.OutputName#ERROR} output should be set.
*/
class OutputException extends RuntimeException {
public OutputException(String message, Throwable cause) {
super(message, cause);
}
public static OutputException forIllegalArgument(String message) {
return new OutputException(message, new IllegalArgumentException(message));
}
}
class ExitSilentlyException extends RuntimeException {
public final int status;
public ExitSilentlyException(int status) {
super();
this.status = status;
}
}
record Config(MissingFileHandler missingFileHandler, Optional<List<String>> selectedKeys, String keySeparator,
String resultTypeWithArg, String resultType, String resultTypeArg, String resultNameSeparator, String outputPrefix) {
public static Config fromEnv() {
// In order to keep the defaults DRY (in action.yml), the environment variables are all mandatory.
String keySeparator = Util.getRequiredEnv(Ids.ConfigVariable.KEY_SEPARATOR);
// System.getenv("KEYS") == null if set to empty string?! So this cannot be checked to be set if we want to allow empty
// string:
String keysStr = System.getenv().getOrDefault(Ids.ConfigVariable.KEYS.name(), "");
Optional<String[]> keys = Util.splitArray(keysStr, keySeparator);
String resultNameSeparator = Util.getRequiredEnv(Ids.ConfigVariable.RESULT_NAME_SEPARATOR);
// RESULT_TYPE format: "<mode>[:<arg>]"
String resultTypeWithArg = Util.getRequiredEnv(Ids.ConfigVariable.RESULT_TYPE);
Matcher matcher = Pattern.compile("([^:]+)(?::(.*))?").matcher(resultTypeWithArg);
if (!matcher.matches()) {
throw OutputException.forIllegalArgument("invalid " + Ids.ConfigVariable.RESULT_TYPE + ": " + resultTypeWithArg);
}
String resultType = matcher.group(1);
String resultTypeArg = Optional.ofNullable(matcher.group(2)).orElse("");
String outputPrefix = Util.getRequiredEnv(Ids.ConfigVariable.OUTPUT_PREFIX);
return new Config( //
MissingFileHandler.ofExternalName(Util.getRequiredEnv(Ids.ConfigVariable.ON_MISSING_FILE)), //
keys.map(List::of), keySeparator, //
resultTypeWithArg, //
resultType, //
resultTypeArg, //
resultNameSeparator, //
outputPrefix);
}
public String requiredResultTypeArg() {
String arg = resultTypeArg();
if ("".equals(arg)) {
throw OutputException.forIllegalArgument(
"invalid " + Ids.ConfigVariable.RESULT_TYPE + " " + resultTypeWithArg() + " (missing argument)");
}
return arg;
}
public void requireNoArg() {
if (!"".equals(resultTypeArg())) {
throw OutputException.forIllegalArgument(
"invalid " + Ids.ConfigVariable.RESULT_TYPE + " " + resultTypeWithArg() + " (non-empty argument)");
}
}
}
enum GithubMessageType {
DEBUG("debug"), //
NOTICE("notice"), //
WARNING("warning"), //
ERROR("error");
public final String externalName;
private GithubMessageType(String externalName) {
this.externalName = externalName;
}
public void format(String format, Object... args) {
String formatWithPrefix = String.format("::%s::%s\n", externalName, format);
System.out.format(formatWithPrefix, args);
}
}
enum MissingFileHandler {
DEBUG_MESSAGE(Ids.MissingFileHandlerName.DEBUG_MESSAGE, GithubMessageType.DEBUG), //
NOTICE_MESSAGE(Ids.MissingFileHandlerName.NOTICE_MESSAGE, GithubMessageType.NOTICE), //
WARNING_MESSAGE(Ids.MissingFileHandlerName.WARNING_MESSAGE, GithubMessageType.WARNING), //
ERROR(Ids.MissingFileHandlerName.ERROR, GithubMessageType.ERROR) {
@Override
public void handleMissingFile(String messageFormat, Object... messageArgs) {
super.handleMissingFile(messageFormat, messageArgs);
throw new ExitSilentlyException(2);
}
};
private final String externalName;
private final GithubMessageType githubMessageType;
private MissingFileHandler(Ids.MissingFileHandlerName externalName, GithubMessageType githubMessageType) {
this.externalName = externalName.externalName;
this.githubMessageType = githubMessageType;
}
public static MissingFileHandler ofExternalName(String externalName) {
for (MissingFileHandler o : MissingFileHandler.values()) {
if (o.externalName.equals(externalName)) {
return o;
}
}
throw OutputException.forIllegalArgument("invalid " + Ids.ConfigVariable.ON_MISSING_FILE + ": " + externalName);
}
@SuppressWarnings("java:S3457") // Sonar rule suggests %n instead of \n, but that would not strictly be covered by the docs
// [https://docs.github.com/en/actions/reference/workflows-and-actions/workflow-commands#setting-a-notice-message], so the \r
// might be considered part of the message.
public void handleMissingFile(String messageFormat, Object... messageArgs) {
String messageStr = String.format(messageFormat, messageArgs);
try (GitHubVariableWriter writer = GitHubOutputFile.OUTPUT.open()) {
writer.write(Ids.OutputName.ERROR, messageStr);
} catch (IOException e) {
// This is an optional output. ⇒ don't throw
GithubMessageType.DEBUG.format("failed to set output %s = \"%s\": %s", Ids.OutputName.ERROR, messageStr, e.toString());
}
githubMessageType.format(messageFormat, messageArgs);
}
}
enum ResultWriter {
OUTPUT(Ids.ResultWriterName.OUTPUT) {
@Override
public void write(Map<String, Optional<String>> props, Config config) throws IOException {
config.requireNoArg();
String lastValue = null;
try (GitHubVariableWriter writer = GitHubOutputFile.OUTPUT.open()) {
for (Map.Entry<String, Optional<String>> entry : props.entrySet()) {
String key = encodeKey(config.outputPrefix() + entry.getKey());
lastValue = entry.getValue().orElse("");
writer.write(key, lastValue);
}
if (config.selectedKeys().isPresent()) {
writer.write(Ids.OutputName.VALUE, lastValue != null ? lastValue : "");
}
}
}
private static String encodeKey(String key) {
StringBuilder result = new StringBuilder(key.length() + 4);
Matcher matcher = Pattern.compile("([\\s\\p{Punct}&&[^_]])").matcher(key);
while (matcher.find()) {
matcher.appendReplacement(result, String.format("-%04X", (int) matcher.group(1).charAt(0)));
}
matcher.appendTail(result);
return result.toString();
}
},
OUTPUT_NAMED(Ids.ResultWriterName.OUTPUT_NAMED) {
@Override
public void write(Map<String, Optional<String>> props, Config config) throws IOException {
writeNamedImpl(props, config, true, GitHubOutputFile.OUTPUT);
}
},
ENV_NAMED(Ids.ResultWriterName.ENV_NAMED) {
@Override
public void write(Map<String, Optional<String>> props, Config config) throws IOException {
writeNamedImpl(props, config, false, GitHubOutputFile.ENV);
}
},
ENV(Ids.ResultWriterName.ENV) {
@Override
public void write(Map<String, Optional<String>> props, Config config) throws IOException {
String prefix = config.resultTypeArg();
try (GitHubVariableWriter writer = GitHubOutputFile.ENV.open()) {
for (Map.Entry<String, Optional<String>> entry : props.entrySet()) {
Optional<String> value = entry.getValue();
value.ifPresent(v -> writer.write(prefix + entry.getKey(), v));
}
}
}
},
JSON(Ids.ResultWriterName.JSON) {
@Override
public void write(Map<String, Optional<String>> props, Config config) throws IOException {
config.requireNoArg();
try (GitHubVariableWriter writer = GitHubOutputFile.OUTPUT.open()) {
writer.write(Ids.OutputName.JSON, Util.toJson(props).s());
}
}
},
JSON_FILE(Ids.ResultWriterName.JSON_FILE) {
@Override
public void write(Map<String, Optional<String>> props, Config config) throws IOException {
String outputFile = config.requiredResultTypeArg();
Path parentDir = Paths.get(outputFile).getParent();
if (parentDir != null) {
Files.createDirectories(parentDir);
}
try (Writer writer = Util.openFile(outputFile, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING)) {
StringIntPair jsonResult = Util.toJson(props);
System.err.format("writing JSON for %s properties to %s%n", jsonResult.i(), outputFile);
writer.write(jsonResult.s());
writer.write('\n');
writer.flush();
}
}
};
private final String externalName;
private ResultWriter(Ids.ResultWriterName externalName) {
this.externalName = externalName.externalName;
}
public static ResultWriter ofExternalName(String externalName) {
for (ResultWriter rw : ResultWriter.values()) {
if (rw.externalName.equals(externalName)) {
return rw;
}
}
throw OutputException.forIllegalArgument("invalid " + Ids.ConfigVariable.RESULT_TYPE + ": " + externalName);
}
public abstract void write(Map<String, Optional<String>> props, Config config) throws IOException;
private static void writeNamedImpl(Map<String, Optional<String>> props, Config config, boolean includeMissing,
GitHubOutputFile gitHubOutputFile) throws IOException {
List<String> selectedKeys = config.selectedKeys().orElseThrow(() -> OutputException.forIllegalArgument("invalid use of "
+ Ids.ConfigVariable.RESULT_TYPE + " " + config.resultType() + " (missing " + Ids.ConfigVariable.KEYS + ")"));
@SuppressWarnings("java:S3655") // Sonar rule: "Optional value should only be accessed after calling isPresent()".
// requiredResultTypeArg() is not empty, so splitArray returns non-empty
String[] resultNames = Util.splitArray(config.requiredResultTypeArg(), config.resultNameSeparator()).get();
if (resultNames.length != selectedKeys.size() && resultNames.length != 1) {
throw OutputException.forIllegalArgument(Ids.ConfigVariable.RESULT_TYPE + " " + config.resultTypeWithArg() + " has "
+ resultNames.length + " arguments, but " + selectedKeys.size() + " keys are selected");
}
try (GitHubVariableWriter writer = gitHubOutputFile.open()) {
for (int i = 0; i < selectedKeys.size(); i++) {
String name = resultNames[resultNames.length == 1 ? 0 : i];
Optional<String> value = props.get(selectedKeys.get(i));
value.ifPresentOrElse(v -> writer.write(name, v), () -> {
if (includeMissing) {
writer.write(name, "");
} else {
// Nothing to do. "not found" has already been logged.
}
});
}
}
}
}
enum GitHubOutputFile {
OUTPUT("GITHUB_OUTPUT", "output"), //
ENV("GITHUB_ENV", "environment variable");
private final String fileName;
private final String description;
private GitHubOutputFile(String fileNameEnvVar, String description) {
this.fileName = Util.getRequiredEnv(fileNameEnvVar);
this.description = description;
}
public GitHubVariableWriter open() throws IOException {
return new GitHubVariableWriter(description, fileName);
}
}
class GitHubVariableWriter implements AutoCloseable {
private static final Pattern SIMPLE_VALUE = Pattern.compile("[\\w.-]+");
private final String description;
private final Writer writer;
public GitHubVariableWriter(String description, String fileName) throws IOException {
this.description = description;
this.writer = Util.openFile(fileName, StandardOpenOption.CREATE, StandardOpenOption.APPEND);
}
public void write(String key, String value) {
try {
System.err.format("setting %s %s%n", description, key);
// write (very) simple values in format "<key>=<value>":
if (SIMPLE_VALUE.matcher(value).matches()) {
this.writer.write(key);
this.writer.write('=');
this.writer.write(value);
this.writer.write('\n');
} else {
writeMultiLine(key, value);
}
} catch (IOException e) {
throw new IoRuntimeException(e);
}
}
public void write(Ids.OutputName key, String value) {
write(key.externalName, value);
}
/**
* Writes a key-value pair in
* <a href="https://docs.github.com/en/actions/reference/workflows-and-actions/workflow-commands#multiline-strings">multiline
* format</a>.
*/
private void writeMultiLine(String key, String value) throws IOException {
String separator = computeSeparator(value);
this.writer.write(key);
this.writer.write("<<");
this.writer.write(separator);
this.writer.write('\n');
this.writer.write(value);
this.writer.write('\n');
this.writer.write(separator);
this.writer.write('\n');
}
/**
* Computes a separator line which does not occur in value.
*/
@SuppressWarnings("java:S1643") // Sonar rule: "Strings should not be concatenated using '+' in a loop".
// False positive: We would need that StringBuilder's toString for each iteration for the contains check anyway.
private static String computeSeparator(String value) {
Set<String> valueLines = new HashSet<>(List.of(value.split("(?s)\n")));
String separatorPart = "----";
String separator = separatorPart;
while (valueLines.contains(separator)) {
separator = separator + separatorPart;
}
return separator;
}
@Override
public void close() throws IOException {
this.writer.close();
}
}
class Util {
private Util() {}
public static String getRequiredEnv(String varName) {
String value = System.getenv(varName);
if (value == null || value.isEmpty()) {
throw OutputException.forIllegalArgument("missing or empty environment variable " + varName);
}
return value;
}
public static String getRequiredEnv(Ids.ConfigVariable varName) {
return getRequiredEnv(varName.name());
}
public static Optional<String[]> splitArray(String arrayStr, String separator) {
return arrayStr.isEmpty() ? Optional.empty() : Optional.of(arrayStr.split(Pattern.quote(separator), -1));
}
public static Writer openFile(String name, OpenOption... options) throws IOException {
return new BufferedWriter(new OutputStreamWriter(Files.newOutputStream(Paths.get(name), options), StandardCharsets.UTF_8));
}
public static Properties readProperties(String file, MissingFileHandler missingFileHandler) {
Properties allProps = new Properties();
Path path = Paths.get(file);
if (!Files.exists(path)) {
missingFileHandler.handleMissingFile("file " + path + " does not exist");
} else if (Files.isDirectory(path)) {
MissingFileHandler.ERROR.handleMissingFile(path + " is a directory");
} else {
try (InputStream in = Files.newInputStream(path)) {
allProps.load(in);
return allProps;
} catch (IOException e) {
missingFileHandler.handleMissingFile("error opening file %s: %s", path, e.getMessage());
} catch (Exception e) { // e.g. IllegalArgumentException: "Malformed \\uxxxx encoding." on invalid contents
MissingFileHandler.ERROR.handleMissingFile("error in file %s: %s", path, e.getMessage());
}
}
return new Properties();
}
/**
* Selects the properties with the given keys and returns them as a Map with the corresponding iteration order.
*/
public static Map<String, Optional<String>> selectProperties(Properties allProps, List<String> selectedKeys, String file) {
Set<String> unmatchedKeysSet = new LinkedHashSet<>(selectedKeys);
Map<String, Optional<String>> results = new LinkedHashMap<>();
for (String key : selectedKeys) {
String value = allProps.getProperty(key);
results.put(key, Optional.ofNullable(value));
if (value != null) {
unmatchedKeysSet.remove(key);
}
}
for (String key : unmatchedKeysSet) {
System.err.format("Property %s not found in %s%n", key, file);
}
return results;
}
/**
* @return the Properties as a Map with each value as a non-empty Optional (strange, but useful for our use case)
*/
public static Map<String, Optional<String>> stringEntries(Properties props) {
Map<String, Optional<String>> map = new LinkedHashMap<>();
for (String key : props.stringPropertyNames()) {
map.put(key, Optional.of(props.getProperty(key)));
}
return map;
}
/**
* @return the JSON string and the number of entries with non-empty value
*/
public static StringIntPair toJson(Map<String, Optional<String>> map) {
AtomicInteger size = new AtomicInteger(0);
StringBuilder s = new StringBuilder(50).append('{');
int initialLength = s.length();
for (Map.Entry<String, Optional<String>> entry : map.entrySet()) {
if (s.length() != initialLength) {
s.append(", ");
}
s.append('"');
appendJsonString(s, entry.getKey());
s.append("\": ");
entry.getValue().ifPresentOrElse(value -> {
size.incrementAndGet();
s.append('"');
appendJsonString(s, value);
s.append('"');
}, () -> s.append("null"));
}
s.append('}');
return new StringIntPair(s.toString(), size.get());
}
private static void appendJsonString(StringBuilder buffer, String s) {
for (char c : s.toCharArray()) {
if (c == ' ') {
buffer.append(c);
} else if (c == '\\') {
buffer.append('\\').append('\\');
} else if (c == '"') {
buffer.append('\\').append('"');
} else if (c == '\t') {
buffer.append('\\').append('t');
} else if (c == '\n') {
buffer.append('\\').append('n');
} else if (c == '\r') {
buffer.append('\\').append('r');
} else if (c == '\f') {
buffer.append('\\').append('f');
} else if (c == '\b') {
buffer.append('\\').append('b');
} else if (c < ' ' || Character.isWhitespace(c)) {
buffer.append('\\').append('u').append(String.format("%04X", (int) c));
} else {
buffer.append(c);
}
}
}
}
record StringIntPair(String s, int i) {
}