/
Macro.java
2327 lines (1962 loc) · 65.7 KB
/
Macro.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
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
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package aQute.bnd.osgi;
import static aQute.bnd.exceptions.FunctionWithException.asFunction;
import static aQute.bnd.osgi.Processor.removeDuplicateMarker;
import static java.lang.invoke.MethodHandles.publicLookup;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.stream.Collectors.toMap;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.WrongMethodTypeException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.util.AbstractMap;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Deque;
import java.util.Formatter;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Optional;
import java.util.Properties;
import java.util.Random;
import java.util.Set;
import java.util.TimeZone;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import aQute.bnd.exceptions.Exceptions;
import aQute.bnd.header.Parameters;
import aQute.bnd.memoize.Memoize;
import aQute.bnd.osgi.Processor.FileLine;
import aQute.bnd.version.MavenVersion;
import aQute.bnd.version.Version;
import aQute.bnd.version.VersionRange;
import aQute.lib.base64.Base64;
import aQute.lib.date.Dates;
import aQute.lib.filter.ExtendedFilter;
import aQute.lib.formatter.Formatters;
import aQute.lib.hex.Hex;
import aQute.lib.io.IO;
import aQute.lib.strings.Strings;
import aQute.lib.utf8properties.UTF8Properties;
import aQute.libg.glob.Glob;
import aQute.service.reporter.Reporter;
import aQute.service.reporter.Reporter.SetLocation;
/**
* Provide a macro processor. This processor can replace variables in strings
* based on a properties and a domain. The domain can implement functions that
* start with a "_" and take args[], the names of these functions are available
* as functions in the macro processor (without the _). Macros can nest to any
* depth but may not contain loops. Add POSIX macros: ${#parameter} String
* length. ${parameter%word} Remove smallest suffix pattern. ${parameter%%word}
* Remove largest suffix pattern. ${parameter#word} Remove smallest prefix
* pattern. ${parameter##word} Remove largest prefix pattern.
*/
public class Macro {
private final static String NULLVALUE = "c29e43048791e250dfd5723e7b8aa048df802c9262cfa8fbc4475b2e392a8ad2";
private final static String LITERALVALUE = "017a3ddbfc0fcd27bcdb2590cdb713a379ae59ef";
private final static Pattern NUMERIC_P = Pattern
.compile("[-+]?(\\d*\\.?\\d+|\\d+\\.)(e[-+]?[0-9]+)?");
Processor domain;
Reporter reporter;
Object targets[];
boolean flattening;
private boolean nosystem;
public boolean inTest;
private final Map<Class<?>, Map<String, BiFunction<Object, String[], Object>>> macrosByClass = new ConcurrentHashMap<>();
public Macro(Processor domain, Object... targets) {
this.domain = domain;
this.reporter = domain;
this.targets = targets;
if (targets != null) {
for (Object o : targets) {
assert o != null;
}
}
}
public String process(String line, Processor source) {
return process(line, new Link(source, null, line));
}
String process(CharSequence line, Link link) {
StringBuilder sb = new StringBuilder();
process(line, 0, '\u0000', '\u0000', sb, link, false);
return sb.toString();
}
int process(CharSequence org, int index, char begin, char end, StringBuilder result, Link link, boolean inMacro) {
if (org == null) { // treat null like empty string
return index;
}
StringBuilder line = new StringBuilder(org);
int nesting = 1;
boolean first;
List<String> args = inMacro ? new ArrayList<>() : Collections.emptyList();
StringBuilder variable = new StringBuilder();
int pStart = 0;
outer: while (index < line.length()) {
char c1 = line.charAt(index++);
if (c1 == end) {
if (--nesting == 0) {
args.add(variable.substring(pStart));
result.append(replace(variable.toString(), args, link, begin, end));
return index;
}
} else if (c1 == begin)
nesting++;
else if (c1 == '\\' && index < line.length() - 1
&& (line.charAt(index) == '$' || line.charAt(index) == ';')) {
// remove the escape backslash and interpret the dollar or ;
// as a literal
variable.append(line.charAt(index));
index++;
continue outer;
} else if (c1 == '$' && index < line.length() - 2 && !inMacro) {
char c2 = line.charAt(index);
char terminator = getTerminator(c2);
if (terminator != 0) {
index = process(line, index + 1, c2, terminator, variable, link, true);
continue outer;
}
} else if (c1 == '.' && index < line.length() && line.charAt(index) == '/') {
// Found the sequence ./
if (index == 1 || Character.isWhitespace(line.charAt(index - 2))) {
// make sure it is preceded by whitespace or starts at begin
index++;
variable.append(IO.absolutePath(domain.getBase()));
variable.append('/');
continue outer;
}
} else if (inMacro && c1 == ';' && nesting == 1) {
args.add(variable.substring(pStart));
pStart = variable.length() + 1;
}
variable.append(c1);
}
result.append(variable);
return index;
}
public static char getTerminator(char c) {
switch (c) {
case '(' :
return ')';
case '[' :
return ']';
case '{' :
return '}';
case '<' :
return '>';
case '\u00ab' : // Guillemet double << >>
return '\u00bb';
case '\u2039' : // Guillemet single
return '\u203a';
}
return 0;
}
protected String getMacro(String key, Link link) {
return getMacro(key, null, link, '{', '}');
}
private String getMacro(String key, List<String> args2, Link link, char begin, char end) {
if (link != null && link.contains(key))
return "${infinite:" + link.toString() + "}";
if (key != null) {
key = key.trim();
String[] args;
if (args2 == null) {
args = SEMICOLON_P.split(key, 0);
} else {
args = args2.toArray(new String[args2.size()]);
for (int i = 0; i < args.length; i++) {
args[i] = process(args[i], link);
}
}
if (!args[0].isEmpty()) {
//
// If the profile is set, we try to get the key first with the
// profile prefix. If this fails we try to get the correct one.
//
//
// Check if we have a wildcard key. In that case
// we go through all the matching keys and append the values
//
if (args.length == 1) {
Instruction ins = new Instruction(args[0]);
if (!ins.isLiteral()) {
String keyname = key;
return domain.stream()
.filter(ins::matches)
.sorted()
.map(k -> replace(k, null, new Link(domain, link, keyname), begin, end))
.filter(Objects::nonNull)
.collect(Strings.joining());
}
//
// NOTE: To access parameters with wildcard in them you need
// to escape them, e.g. foo\[3\]. The following removes the
// escapes
//
args[0] = ins.getLiteral();
}
//
// Check if the macro is defined as a raw property
//
String value = domain.getUnexpandedProperty(args[0]);
if (value != null) {
Link next = new Link(domain, link, key);
if (args.length > 1) {
return processWithArgs(value, args, next);
} else {
return process(value, next);
}
}
//
// Not found, look it up as a command
//
value = doCommands(args, link);
if (value != null) {
if (value == NULLVALUE)
return null;
if (value == LITERALVALUE)
return LITERALVALUE;
return process(value, new Link(domain, link, key));
}
//
// Last resort, try to find it as a system property
// or environment variable
//
if (args.length == 1) {
value = System.getProperty(args[0]);
if (value != null)
return value;
if (key.startsWith("env.")) {
value = System.getenv(args[0].substring(4));
if (value != null)
return value;
}
}
if (!args[0].startsWith("[")) {
String profile = domain.getUnexpandedProperty(Constants.PROFILE);
if (profile != null) {
profile = process(profile, link);
String profiledKey = "[" + profile + "]" + args[0];
value = domain.getUnexpandedProperty(profiledKey);
if (value != null) {
Link next = new Link(domain, link, key);
if (args.length > 1) {
return processWithArgs(value, args, next);
} else {
return process(value, next);
}
}
}
}
} else {
reporter.warning("Found empty macro key '%s'", key);
}
} else {
reporter.warning("Found null macro key");
}
return null;
}
/*
* Process the template but setup local arguments and # for the joined list
*/
private String processWithArgs(String template, String[] args, Link next) {
try (Processor custom = new Processor(domain)) {
for (int i = 0; i < 16; i++) {
custom.setProperty(Integer.toString(i), i < args.length ? args[i] : "null");
}
String joinedArgs = Arrays.stream(args, 1, args.length)
.collect(Strings.joining());
custom.setProperty("#", joinedArgs);
return custom.getReplacer()
.process(template, next);
} catch (IOException e) {
throw Exceptions.duck(e);
}
}
public String replace(String key, Link link) {
return replace(key, null, link, '{', '}');
}
private String replace(String key, List<String> args, Link link, char begin, char end) {
String value = getMacro(key, args, link, begin, end);
if (value != LITERALVALUE) {
if (value != null)
return value;
if (!flattening && !key.startsWith("@"))
reporter.warning("No translation found for macro: %s", key);
}
return "$" + begin + key + end;
}
/**
* Parse the key as a command. A command consist of parameters separated by
* ':'.
*/
// Handle up to 4 sequential backslashes in the negative lookbehind.
private static final String ESCAPING = "(?<!(?<!(?<!(?<!\\\\)\\\\)\\\\)\\\\)";
private static final String SEMICOLON = ";";
private static final String ESCAPED_SEMICOLON = "\\\\" + SEMICOLON;
private static final Pattern SEMICOLON_P = Pattern.compile(ESCAPING + SEMICOLON);
private static final Pattern ESCAPED_SEMICOLON_P = Pattern.compile(ESCAPING + ESCAPED_SEMICOLON);
@SuppressWarnings("resource")
private String doCommands(String[] args, Link source) {
if (args == null || args.length == 0)
return null;
for (int i = 0; i < args.length; i++)
if (args[i].indexOf('\\') >= 0) {
args[i] = ESCAPED_SEMICOLON_P.matcher(args[i])
.replaceAll(SEMICOLON);
}
if (args[0].startsWith("^")) {
String varname = args[0].substring(1)
.trim();
if (source != null) {
Processor parent = source.start.getParent();
if (parent != null)
return parent.getProperty(varname);
}
return null;
}
Processor rover = domain;
while (rover != null) {
String result = doCommand(rover, args[0], args);
if (result != null)
return result;
rover = rover.getParent();
}
for (int i = 0; targets != null && i < targets.length; i++) {
String result = doCommand(targets[i], args[0], args);
if (result != null)
return result;
}
return doCommand(this, args[0], args);
}
private String doCommand(Object target, String method, String[] args) {
if (target == null)
; // System.err.println("Huh? Target should never be null " +
// domain);
else {
for (int i = 0, len = method.length(); i < len; i++) {
char c = method.charAt(i);
if (c == '-') {
// Assume macro names do not start with '-'
if (i == 0) {
return null;
}
} else if (!Character.isJavaIdentifierPart(c)) {
return null;
}
}
Map<String, BiFunction<Object, String[], Object>> macros = macrosByClass.computeIfAbsent(target.getClass(),
c -> Arrays.stream(c.getMethods())
.filter(m -> (m.getName()
.charAt(0) == '_') && (m.getParameterCount() == 1)
&& (m.getParameterTypes()[0] == String[].class))
.collect(toMap(m -> m.getName()
.substring(1), m -> {
Memoize<MethodHandle> mh = Memoize.supplier(() -> {
try {
return publicLookup().unreflect(m);
} catch (Exception e) {
throw Exceptions.duck(e);
}
});
if (Modifier.isStatic(m.getModifiers())) {
return (Object t, String[] a) -> {
try {
return mh.get()
.invoke(a);
} catch (Throwable e) {
throw Exceptions.duck(e);
}
};
} else {
return (Object t, String[] a) -> {
try {
return mh.get()
.invoke(t, a);
} catch (Throwable e) {
throw Exceptions.duck(e);
}
};
}
})));
String macro = method.replace('-', '_');
BiFunction<Object, String[], Object> invoker = macros.get(macro);
if (invoker == null) {
return null;
}
try {
Object result = invoker.apply(target, args);
return result == null ? NULLVALUE : result.toString();
} catch (Error e) {
throw e;
} catch (WrongMethodTypeException e) {
reporter.warning("Exception in replace: method=%s %s ", method, Exceptions.toString(e));
return NULLVALUE;
} catch (Exception e) {
reporter.error("%s, for cmd: %s, arguments; %s", e.getMessage(), method, Arrays.toString(args));
return NULLVALUE;
} catch (Throwable e) {
reporter.warning("Exception in replace: method=%s %s ", method, Exceptions.toString(e));
return NULLVALUE;
}
}
return null;
}
/**
* Return a unique list where the duplicates are removed.
*/
static final String _uniqHelp = "${uniq;<list> ...}";
public String _uniq(String[] args) {
verifyCommand(args, _uniqHelp, null, 1, Integer.MAX_VALUE);
String result = Arrays.stream(args, 1, args.length)
.flatMap(Strings::splitQuotedAsStream)
.distinct()
.collect(Strings.joining());
return result;
}
/**
* Return the first list where items from the second list are removed.
*/
static final String _removeallHelp = "${removeall;<list>;<list>}";
public String _removeall(String[] args) {
verifyCommand(args, _removeallHelp, null, 1, 3);
if (args.length < 2) {
return "";
}
List<String> result = Strings.splitQuoted(args[1]);
if (args.length > 2) {
result.removeAll(Strings.splitQuoted(args[2]));
}
return Strings.join(result);
}
/**
* Return the first list where items not in the second list are removed.
*/
static final String _retainallHelp = "${retainall;<list>;<list>}";
public String _retainall(String[] args) {
verifyCommand(args, _retainallHelp, null, 1, 3);
if (args.length < 3) {
return "";
}
List<String> result = Strings.splitQuoted(args[1]);
result.retainAll(Strings.splitQuoted(args[2]));
return Strings.join(result);
}
public String _pathseparator(String[] args) {
return File.pathSeparator;
}
public String _separator(String[] args) {
return File.separator;
}
public String _filter(String[] args) {
return filter(args, false);
}
public String _select(String[] args) {
return filter(args, false);
}
public String _filterout(String[] args) {
return filter(args, true);
}
public String _reject(String[] args) {
return filter(args, true);
}
static final String _filterHelp = "${%s;<list>;<regex>}";
String filter(String[] args, boolean include) {
verifyCommand(args, String.format(_filterHelp, args[0]), null, 3, 3);
Pattern pattern = Pattern.compile(args[2]);
String result = Strings.splitQuotedAsStream(args[1])
.filter(s -> pattern.matcher(s)
.matches() != include)
.collect(Strings.joining());
return result;
}
static final String _sortHelp = "${sort;<list>...}";
public String _sort(String[] args) {
verifyCommand(args, _sortHelp, null, 1, Integer.MAX_VALUE);
String result = Arrays.stream(args, 1, args.length)
.flatMap(Strings::splitQuotedAsStream)
.sorted()
.collect(Strings.joining());
return result;
}
static final String _nsortHelp = "${nsort;<list>...}";
public String _nsort(String[] args) {
verifyCommand(args, _nsortHelp, null, 1, Integer.MAX_VALUE);
String result = Arrays.stream(args, 1, args.length)
.flatMap(Strings::splitAsStream)
.sorted((a, b) -> {
while (a.startsWith("0")) {
a = a.substring(1);
}
while (b.startsWith("0")) {
b = b.substring(1);
}
if (a.length() == b.length()) {
return a.compareTo(b);
}
return (a.length() > b.length()) ? 1 : -1;
})
.collect(Strings.joining());
return result;
}
static final String _joinHelp = "${join;<list>...}";
public String _join(String[] args) {
verifyCommand(args, _joinHelp, null, 1, Integer.MAX_VALUE);
String result = Arrays.stream(args, 1, args.length)
.flatMap(Strings::splitAsStream)
.collect(Strings.joining());
return result;
}
static final String _sjoinHelp = "${sjoin;<separator>;<list>...}";
public String _sjoin(String[] args) throws Exception {
verifyCommand(args, _sjoinHelp, null, 2, Integer.MAX_VALUE);
String result = Arrays.stream(args, 2, args.length)
.flatMap(Strings::splitQuotedAsStream)
.collect(Collectors.joining(args[1]));
return result;
}
static final String _ifHelp = "${if;<condition>;<iftrue> [;<iffalse>] } condition is either a filter expression or truthy";
public String _if(String[] args) throws Exception {
verifyCommand(args, _ifHelp, null, 2, 4);
String condition = args[1];
if (isTruthy(condition))
return args.length > 2 ? args[2] : "true";
if (args.length > 3)
return args[3];
return "";
}
public boolean isTruthy(String condition) throws Exception {
if (condition == null)
return false;
condition = condition.trim();
if (condition.startsWith("(") && condition.endsWith(")")) {
return doCondition(condition);
}
return !condition.equalsIgnoreCase("false") && !condition.equals("0") && !condition.equals("0.0")
&& condition.length() != 0;
}
private static final DateTimeFormatter DATE_TOSTRING = Dates.DATE_TOSTRING.withZone(Dates.UTC_ZONE_ID);
public final static String _nowHelp = "${now;pattern|'long'}, returns current time";
public Object _now(String[] args) {
verifyCommand(args, _nowHelp, null, 1, 2);
long now = getBuildNow();
if (args.length == 2) {
if ("long".equals(args[1])) {
return Long.toString(now);
}
DateFormat df = new SimpleDateFormat(args[1], Locale.ROOT);
df.setTimeZone(Dates.UTC_TIME_ZONE);
return df.format(new Date(now));
}
return Dates.formatMillis(DATE_TOSTRING, now);
}
public final static String _fmodifiedHelp = "${fmodified;<list of filenames>...}, return latest modification date";
public String _fmodified(String[] args) throws Exception {
verifyCommand(args, _fmodifiedHelp, null, 2, Integer.MAX_VALUE);
long time = Arrays.stream(args, 1, args.length)
.flatMap(Strings::splitQuotedAsStream)
.map(File::new)
.filter(File::exists)
.mapToLong(File::lastModified)
.max()
.orElse(0);
return Long.toString(time);
}
public String _long2date(String[] args) {
try {
return Dates.formatMillis(DATE_TOSTRING, Long.parseLong(args[1]));
} catch (Exception e) {
return "not a valid long";
}
}
public String _literal(String[] args) {
if (args.length != 2)
throw new RuntimeException("Need a value for the ${literal;<value>} macro");
return "${" + args[1] + "}";
}
static final String _defHelp = "${def;<name>[;<value>]}, get the property or a default value if unset";
public String _def(String[] args) {
verifyCommand(args, _defHelp, null, 2, 3);
return domain.getProperty(args[1], args.length == 3 ? args[2] : "");
}
static final String _listHelp = "${list;[<name>...]}, returns a list of the values of the named properties with escaped semicolons";
public String _list(String[] args) {
verifyCommand(args, _listHelp, null, 1, Integer.MAX_VALUE);
String result = Arrays.stream(args, 1, args.length)
.map(domain::getProperty)
.flatMap(Strings::splitQuotedAsStream)
.map(element -> (element.indexOf(';') < 0) ? element
: SEMICOLON_P.matcher(element)
.replaceAll(ESCAPED_SEMICOLON))
.collect(Strings.joining());
return result;
}
static final String _replaceHelp = "${replace;<list>;<regex>;[<replace>[;delimiter]]}";
public String _replace(String[] args) {
return replace0(_replaceHelp, Strings::splitAsStream, args);
}
static final String _replacelistHelp = "${replacelist;<list>;<regex>;[<replace>[;delimiter]]}";
public String _replacelist(String[] args) {
return replace0(_replacelistHelp, Strings::splitQuotedAsStream, args);
}
private String replace0(String help, Function<String, Stream<String>> splitter, String[] args) {
verifyCommand(args, help, null, 3, 5);
Pattern regex = Pattern.compile(args[2]);
String replace = (args.length > 3) ? args[3] : "";
Collector<CharSequence, ?, String> joining = (args.length > 4) ? Collectors.joining(args[4])
: Strings.joining();
String result = splitter.apply(args[1])
.map(element -> regex.matcher(element)
.replaceAll(replace))
.collect(joining);
return result;
}
static final String _replacestringHelp = "${replacesting;<target>;<regex>;[<replace>]}";
public String _replacestring(String[] args) {
verifyCommand(args, _replacestringHelp, null, 3, 4);
Pattern regex = Pattern.compile(args[2]);
String replace = (args.length > 3) ? args[3] : "";
String result = regex.matcher(args[1])
.replaceAll(replace);
return result;
}
private static final Pattern ANY = Pattern.compile(".*");
private static final Pattern ERROR_P = Pattern.compile("\\$\\{error;");
private static final Pattern WARNING_P = Pattern.compile("\\$\\{warning;");
public String _warning(String[] args) throws Exception {
for (int i = 1; i < args.length; i++) {
SetLocation warning = reporter.warning("%s", process(args[i]));
FileLine header = domain.getHeader(ANY, WARNING_P);
if (header != null)
header.set(warning);
}
return "";
}
public String _error(String[] args) throws Exception {
for (int i = 1; i < args.length; i++) {
SetLocation error = reporter.error("%s", process(args[i]));
FileLine header = domain.getHeader(ANY, ERROR_P);
if (header != null)
header.set(error);
}
return "";
}
/**
* toclassname ; <path>.class ( , <path>.class ) *
*/
static final String _toclassnameHelp = "${toclassname;<list of class paths>}, convert class paths to FQN class names ";
public String _toclassname(String[] args) {
verifyCommand(args, _toclassnameHelp, null, 2, 2);
String result = Strings.splitAsStream(args[1])
.map(path -> {
if (path.endsWith(".class")) {
return path.substring(0, path.length() - 6)
.replace('/', '.');
}
if (path.endsWith(".java")) {
return path.substring(0, path.length() - 5)
.replace('/', '.');
}
reporter.warning("in toclassname, %s is not a class path because it does not end in .class", path);
return null;
})
.filter(Objects::nonNull)
.collect(Strings.joining());
return result;
}
/**
* toclassname ; <path>.class ( , <path>.class ) *
*/
static final String _toclasspathHelp = "${toclasspath;<list>[;boolean]}, convert a list of class names to paths";
public String _toclasspath(String[] args) {
verifyCommand(args, _toclasspathHelp, null, 2, 3);
boolean cl = (args.length > 2) ? Boolean.parseBoolean(args[2]) : true;
Function<String, String> mapper = cl ? name -> name.replace('.', '/') + ".class"
: name -> name.replace('.', '/');
String result = Strings.splitAsStream(args[1])
.map(mapper)
.collect(Strings.joining());
return result;
}
public String _dir(String[] args) {
if (args.length < 2) {
reporter.warning("Need at least one file name for ${dir;...}");
return null;
}
String result = Arrays.stream(args, 1, args.length)
.map(domain::getFile)
.filter(File::exists)
.map(File::getParentFile)
.map(IO::absolutePath)
.collect(Strings.joining());
return result;
}
public String _basename(String[] args) {
if (args.length < 2) {
reporter.warning("Need at least one file name for ${basename;...}");
return null;
}
String result = Arrays.stream(args, 1, args.length)
.map(domain::getFile)
.filter(File::exists)
.map(File::getName)
.collect(Strings.joining());
return result;
}
public String _isfile(String[] args) {
if (args.length < 2) {
reporter.warning("Need at least one file name for ${isfile;...}");
return null;
}
boolean isfile = Arrays.stream(args, 1, args.length)
.map(File::new)
.map(File::getAbsoluteFile)
.allMatch(File::isFile);
return Boolean.toString(isfile);
}
public String _isdir(String[] args) {
// if (args.length < 2) {
// reporter.warning("Need at least one file name for ${isdir;...}");
// return null;
// }
// If no dirs provided, return false
boolean isdir = (args.length < 2) ? false
: Arrays.stream(args, 1, args.length)
.map(File::new)
.map(File::getAbsoluteFile)
.allMatch(File::isDirectory);
return Boolean.toString(isdir);
}
public String _tstamp(String[] args) {
String format;
long now;
TimeZone tz;
if (args.length > 1) {
format = args[1];
} else {
format = "yyyyMMddHHmm";
}
if (args.length > 2) {
tz = TimeZone.getTimeZone(args[2]);
} else {
tz = Dates.UTC_TIME_ZONE;
}
if (args.length > 3) {
now = Long.parseLong(args[3]);
} else {
now = getBuildNow();
}
if (args.length > 4) {
reporter.warning("Too many arguments for tstamp: %s", Arrays.toString(args));
}
SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US);
sdf.setTimeZone(tz);
return sdf.format(new Date(now));
}
private long getBuildNow() {
long now;
String tstamp = domain.getProperty(Constants.TSTAMP);
if (tstamp != null) {
try {
now = Long.parseLong(tstamp);
} catch (NumberFormatException e) {
// ignore, just use current time
now = System.currentTimeMillis();
}
} else {
now = System.currentTimeMillis();
}
return now;
}
static final String _lsrHelp = "${lsr;<dir>;[<selector>...]}";
public String _lsr(String[] args) {
return ls(_lsrHelp, args, true);
}
static final String _lsaHelp = "${lsa;<dir>;[<selector>...]}";
public String _lsa(String[] args) {
return ls(_lsaHelp, args, false);
}
private String ls(String help, String[] args, boolean relative) {
verifyCommand(args, help, null, 2, Integer.MAX_VALUE);
File dir = domain.getFile(args[1]);
if (!dir.isAbsolute())
throw new IllegalArgumentException(
String.format("the ${%s} macro directory parameter is not absolute: %s", args[0], dir));
if (!dir.exists())
throw new IllegalArgumentException(
String.format("the ${%s} macro directory parameter does not exist: %s", args[0], dir));
if (!dir.isDirectory())
throw new IllegalArgumentException(String.format(
"the ${%s} macro directory parameter points to a file instead of a directory: %s", args[0], dir));
List<File> files = IO.listFiles(dir);
if (files.isEmpty()) {
return "";
}
Function<File, String> mapper = relative ? File::getName : IO::absolutePath;
if (args.length < 3) {
String result = files.stream()
.map(mapper)
.collect(Strings.joining());
return result;
}
List<String> result = new ArrayList<>(files.size());
Arrays.stream(args, 2, args.length)
.flatMap(Strings::splitQuotedAsStream)
.map(Instruction::new)
.forEachOrdered(ins -> {
for (Iterator<File> iter = files.iterator(); iter.hasNext();) {
File file = iter.next();
if (ins.matches(file.getPath())) {
iter.remove();
if (!ins.isNegated()) {
result.add(mapper.apply(file));
}
}
}
});
return Strings.join(result);
}
public String _currenttime(String[] args) {
return Long.toString(System.currentTimeMillis());
}
/**
* Modify a version to set a version policy. The policy is a mask that is
* mapped to a version.
*
* <pre>
* + increment - decrement = maintain s only
* pos=3 (qualifier). If qualifer == SNAPSHOT, return m.m.m-SNAPSHOT else
* m.m.m.q s only pos=3 (qualifier). If qualifer == SNAPSHOT, return
* m.m.m-SNAPSHOT else m.m.m ˜ discard ==+ = maintain major, minor,
* increment micro, discard qualifier ˜˜˜= = just get the
* qualifier version="[${version;==;${@}},${version;=+;${@}})"
* </pre>