1 package org.djutils.cli;
2
3 import java.lang.reflect.Field;
4 import java.text.NumberFormat;
5 import java.util.Arrays;
6 import java.util.HashSet;
7 import java.util.LinkedHashMap;
8 import java.util.List;
9 import java.util.Locale;
10 import java.util.Map;
11
12 import org.djutils.reflection.ClassUtil;
13
14 import picocli.CommandLine;
15 import picocli.CommandLine.Command;
16 import picocli.CommandLine.Help;
17 import picocli.CommandLine.IHelpSectionRenderer;
18 import picocli.CommandLine.ITypeConverter;
19 import picocli.CommandLine.IVersionProvider;
20 import picocli.CommandLine.Model.ArgSpec;
21 import picocli.CommandLine.Option;
22 import picocli.CommandLine.ParseResult;
23 import picocli.CommandLine.Unmatched;
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 public final class CliUtil
88 {
89
90 public static class InitLocale
91 {
92
93 @Option(names = {"--locale"}, defaultValue = "en-US", description = "locale for variables with units.")
94 private String locale;
95 }
96
97
98 public static class RetrieveLocale
99 {
100
101 @Option(names = {"--locale"}, defaultValue = "en-US", description = "locale for variables with units.")
102 private String locale;
103
104
105
106
107 String getLocale()
108 {
109 return this.locale;
110 }
111
112
113 @Unmatched
114 private List<String> remainder;
115 }
116
117
118 private CliUtil()
119 {
120
121 }
122
123
124
125
126
127
128
129
130
131
132 @SuppressWarnings("checkstyle:visibilitymodifier")
133 static Map<String, Object> overrideMap = new LinkedHashMap<>();
134
135
136 @SuppressWarnings("checkstyle:visibilitymodifier")
137 private static Locale defaultValueLocale = Locale.US;
138
139
140 @SuppressWarnings("checkstyle:visibilitymodifier")
141 private static Locale localeOption = null;
142
143
144 @SuppressWarnings("checkstyle:visibilitymodifier")
145 private static boolean parseDefaultValue = false;
146
147
148 @SuppressWarnings("checkstyle:visibilitymodifier")
149 static boolean testMode = false;
150
151
152
153
154
155
156
157
158
159
160 public static void execute(final Object program, final String[] args)
161 {
162 execute(new CommandLine(program), args);
163 }
164
165
166
167
168
169
170
171
172
173
174 @SuppressWarnings("checkstyle:methodlength")
175 public static void execute(final CommandLine commandLine, final String[] args)
176 {
177
178 var initLocale = new InitLocale();
179 commandLine.addMixin("locale", initLocale);
180
181
182 CommandLine.IDefaultValueProvider vp = new CommandLine.IDefaultValueProvider()
183 {
184 @Override
185 public String defaultValue(final ArgSpec argSpec) throws Exception
186 {
187 defaultValueLocale = Locale.US;
188 String fieldName = ((Field) argSpec.userObject()).getName();
189 Class<?> fieldClass = null;
190 try
191 {
192 Field field = ClassUtil.resolveField(commandLine.getCommand().getClass(), fieldName);
193 fieldClass = field.getDeclaringClass();
194 if (field.isAnnotationPresent(DefaultValueLocale.class))
195 {
196 var loc = field.getAnnotation(DefaultValueLocale.class).value();
197 parseDefaultValue = true;
198 defaultValueLocale = parseLocale(loc);
199 }
200 }
201 catch (NoSuchFieldException nsfe)
202 {
203 fieldClass = commandLine.getCommand().getClass();
204 }
205 String key = CliUtil.makeOverrideKeyProperty(fieldClass, fieldName, "defaultValue");
206 if (CliUtil.overrideMap.containsKey(key))
207 {
208 return CliUtil.overrideMap.get(key).toString();
209 }
210 else
211 {
212 return argSpec.defaultValue();
213 }
214 }
215 };
216 commandLine.setDefaultValueProvider(vp);
217
218
219 String programKey = makeOverrideKeyCommand(commandLine.getCommand().getClass(), "name");
220 if (overrideMap.containsKey(programKey))
221 {
222 commandLine.setCommandName(overrideMap.get(programKey).toString());
223 }
224
225
226 String versionKey = makeOverrideKeyCommand(commandLine.getCommand().getClass(), "version");
227 if (overrideMap.containsKey(versionKey))
228 {
229 commandLine.getCommandSpec().versionProvider(new IVersionProvider()
230 {
231 @Override
232 public String[] getVersion() throws Exception
233 {
234 if (overrideMap.get(versionKey) instanceof String[])
235 {
236 return (String[]) overrideMap.get(versionKey);
237 }
238 return new String[] {overrideMap.get(versionKey).toString()};
239 }
240 });
241 }
242
243
244 Map<String, IHelpSectionRenderer> helpMap = commandLine.getHelpSectionMap();
245 final IHelpSectionRenderer defaultDescriptionRenderer = helpMap.get("description");
246 helpMap.put("description", new IHelpSectionRenderer()
247 {
248 @Override
249 public String render(final Help help)
250 {
251 String descriptionKey = makeOverrideKeyCommand(commandLine.getCommand().getClass(), "description");
252 if (overrideMap.containsKey(descriptionKey))
253 {
254 if (overrideMap.get(descriptionKey) instanceof String[])
255 {
256 StringBuilder sb = new StringBuilder();
257 for (String line : (String[]) overrideMap.get(descriptionKey))
258 {
259 sb.append(line);
260 sb.append("\n");
261 }
262 return sb.toString();
263 }
264 return overrideMap.get(descriptionKey).toString();
265 }
266 return defaultDescriptionRenderer.render(help);
267 }
268 });
269 commandLine.setHelpSectionMap(helpMap);
270
271
272 CliUnitConverters.registerAll(commandLine);
273 registerLocaleFloatConverters(commandLine);
274
275
276 Locale saveLocale = Locale.getDefault();
277 RetrieveLocale retrieveLocale = new RetrieveLocale();
278 CommandLine cmdLocale = new CommandLine(retrieveLocale);
279 cmdLocale.parseArgs(args);
280 localeOption =
281 new HashSet<String>(Arrays.asList(args)).contains("--locale") ? parseLocale(retrieveLocale.getLocale()) : null;
282
283
284 commandLine.getCommandSpec().parser().collectErrors(true);
285 ParseResult parseResult = commandLine.parseArgs(args);
286 List<Exception> parseErrors = parseResult.errors();
287 if (parseErrors.size() > 0)
288 {
289 for (Exception e : parseErrors)
290 {
291 System.err.println(e.getMessage());
292 }
293 if (testMode)
294 {
295 throw new CliRuntimeException("parse errors");
296 }
297 System.exit(-1);
298 }
299
300
301 if (parseResult.isUsageHelpRequested())
302 {
303 commandLine.usage(System.out);
304 if (testMode)
305 {
306 throw new CliRuntimeException("usage help requested");
307 }
308 System.exit(0);
309 }
310 else if (parseResult.isVersionHelpRequested())
311 {
312 commandLine.printVersionHelp(System.out);
313 if (testMode)
314 {
315 throw new CliRuntimeException("version help requested");
316 }
317 System.exit(0);
318 }
319
320
321 Object program = commandLine.getCommand();
322 if (program instanceof Checkable)
323 {
324 try
325 {
326 ((Checkable) program).check();
327 }
328 catch (Exception exception)
329 {
330 System.err.println(exception.getMessage());
331 if (testMode)
332 {
333 throw new CliRuntimeException("check error");
334 }
335 System.exit(-1);
336 }
337 }
338
339
340 Locale.setDefault(saveLocale);
341 }
342
343
344
345
346
347
348
349
350
351
352 public static void changeOptionProperty(final Class<?> programClass, final String fieldName, final String propertyName,
353 final Object newValue) throws CliException, NoSuchFieldException
354 {
355 Field field = ClassUtil.resolveField(programClass, fieldName);
356 Option optionAnnotation = field.getAnnotation(Option.class);
357 if (optionAnnotation == null)
358 {
359 throw new CliException(
360 String.format("@Option annotation not found for field %s in class %s", fieldName, programClass.getName()));
361 }
362 String key = makeOverrideKeyProperty(field.getDeclaringClass(), fieldName, propertyName);
363 overrideMap.put(key, newValue);
364 }
365
366
367
368
369
370
371
372
373
374
375 public static void changeOptionProperty(final Object program, final String fieldName, final String propertyName,
376 final Object newValue) throws CliException, NoSuchFieldException
377 {
378 changeOptionProperty(program.getClass(), fieldName, propertyName, newValue);
379 }
380
381
382
383
384
385
386
387
388
389
390 public static void changeOptionDefault(final Object program, final String fieldName, final String newDefaultValue)
391 throws CliException, NoSuchFieldException
392 {
393 changeOptionProperty(program, fieldName, "defaultValue", newDefaultValue);
394 }
395
396
397
398
399
400
401
402
403
404
405 public static void changeOptionDefault(final Class<?> programClass, final String fieldName, final String newDefaultValue)
406 throws CliException, NoSuchFieldException
407 {
408 changeOptionProperty(programClass, fieldName, "defaultValue", newDefaultValue);
409 }
410
411
412
413
414
415
416
417
418 private static void changeCommandProperty(final Object program, final String propertyName, final Object newValue)
419 throws CliException
420 {
421 changeCommandProperty(program.getClass(), propertyName, newValue);
422 }
423
424
425
426
427
428
429
430
431 private static void changeCommandProperty(final Class<?> programClass, final String propertyName, final Object newValue)
432 throws CliException
433 {
434 Class<?> declaringClass = getCommandAnnotationClass(programClass);
435 String key = makeOverrideKeyCommand(declaringClass, propertyName);
436 overrideMap.put(key, newValue);
437 }
438
439
440
441
442
443
444
445
446 public static void changeCommandName(final Object program, final String newName) throws CliException
447 {
448 changeCommandProperty(program, "name", newName);
449 }
450
451
452
453
454
455
456
457
458 public static void changeCommandName(final Class<?> programClass, final String newName) throws CliException
459 {
460 changeCommandProperty(programClass, "name", newName);
461 }
462
463
464
465
466
467
468
469
470 public static void changeCommandDescription(final Object program, final String newDescription) throws CliException
471 {
472 changeCommandProperty(program, "description", new String[] {newDescription});
473 }
474
475
476
477
478
479
480
481
482 public static void changeCommandDescription(final Class<?> programClass, final String newDescription) throws CliException
483 {
484 changeCommandProperty(programClass, "description", new String[] {newDescription});
485 }
486
487
488
489
490
491
492
493
494 public static void changeCommandVersion(final Object program, final String newVersion) throws CliException
495 {
496 changeCommandProperty(program, "version", new String[] {newVersion});
497 }
498
499
500
501
502
503
504
505
506 public static void changeCommandVersion(final Class<?> programClass, final String newVersion) throws CliException
507 {
508 changeCommandProperty(programClass, "version", new String[] {newVersion});
509 }
510
511
512
513
514
515
516
517 public static Command getCommandAnnotation(final Class<?> programClass) throws CliException
518 {
519 return getCommandAnnotationClass(programClass).getDeclaredAnnotation(Command.class);
520 }
521
522
523
524
525
526
527
528 public static Class<?> getCommandAnnotationClass(final Class<?> programClass) throws CliException
529 {
530 Class<?> clazz = programClass;
531 while (clazz != null)
532 {
533 Command commandAnnotation = clazz.getDeclaredAnnotation(Command.class);
534 if (commandAnnotation != null)
535 {
536 return clazz;
537 }
538 clazz = clazz.getSuperclass();
539 }
540 throw new CliException(
541 String.format("@Command annotation not found for class %s or one of its superclasses", programClass.getName()));
542 }
543
544
545
546
547
548
549 public static String[] getCommandVersion(final Class<?> programClass) throws CliException
550 {
551 String versionKey = makeOverrideKeyCommand(programClass, "version");
552 if (overrideMap.containsKey(versionKey))
553 {
554 Object version = overrideMap.get(versionKey);
555 if (version instanceof String[])
556 {
557 return (String[]) version;
558 }
559 return new String[] {version.toString()};
560 }
561 return getCommandAnnotation(programClass).version();
562 }
563
564
565
566
567
568
569 public static String[] getCommandVersion(final Object program) throws CliException
570 {
571 return getCommandVersion(program.getClass());
572 }
573
574
575
576
577
578
579 public static String getCommandName(final Class<?> programClass) throws CliException
580 {
581 String nameKey = makeOverrideKeyCommand(programClass, "name");
582 if (overrideMap.containsKey(nameKey))
583 {
584 return overrideMap.get(nameKey).toString();
585 }
586 return getCommandAnnotation(programClass).name();
587 }
588
589
590
591
592
593
594
595 public static String getCommandName(final Object program) throws CliException
596 {
597 return getCommandName(program.getClass());
598 }
599
600
601
602
603
604
605 public static String[] getCommandDescription(final Class<?> programClass) throws CliException
606 {
607 String descriptionKey = makeOverrideKeyCommand(programClass, "description");
608 if (overrideMap.containsKey(descriptionKey))
609 {
610 Object description = overrideMap.get(descriptionKey);
611 if (description instanceof String[])
612 {
613 return (String[]) description;
614 }
615 return new String[] {description.toString()};
616 }
617 return getCommandAnnotation(programClass).description();
618 }
619
620
621
622
623
624
625
626 public static String[] getCommandDescription(final Object program) throws CliException
627 {
628 return getCommandDescription(program.getClass());
629 }
630
631
632
633
634
635
636
637
638 static String makeOverrideKeyProperty(final Class<?> programClass, final String fieldName, final String propertyName)
639 {
640 return programClass.getName() + "%" + fieldName + "%" + propertyName;
641 }
642
643
644
645
646
647
648
649 static String makeOverrideKeyCommand(final Class<?> programClass, final String propertyName)
650 {
651 return programClass.getName() + "%" + propertyName;
652 }
653
654
655
656
657
658 static void registerLocaleFloatConverters(final CommandLine cmd)
659 {
660 cmd.registerConverter(Double.class, new DoubleConverter());
661 cmd.registerConverter(double.class, new DoubleConverter());
662 cmd.registerConverter(Float.class, new FloatConverter());
663 cmd.registerConverter(float.class, new FloatConverter());
664 }
665
666
667
668
669 public static class DoubleConverter implements ITypeConverter<Double>
670 {
671 @Override
672 public Double convert(final String value) throws Exception
673 {
674 prepareLocale();
675 NumberFormat format = NumberFormat.getInstance(Locale.getDefault());
676 Number number;
677 double ret;
678 try
679 {
680 number = format.parse(value);
681 ret = number.doubleValue();
682 }
683 catch (Exception e)
684 {
685 System.err.println("ERROR parsing double value " + value + ": " + e.getMessage());
686 ret = Double.NaN;
687 }
688 restoreLocale();
689 return ret;
690 }
691 }
692
693
694
695
696 public static class FloatConverter implements ITypeConverter<Float>
697 {
698 @Override
699 public Float convert(final String value) throws Exception
700 {
701 prepareLocale();
702 NumberFormat format = NumberFormat.getInstance(Locale.getDefault());
703 Number number;
704 float ret;
705 try
706 {
707 number = format.parse(value);
708 ret = number.floatValue();
709 }
710 catch (Exception e)
711 {
712 System.err.println("ERROR parsing double value " + value + ": " + e.getMessage());
713 ret = Float.NaN;
714 }
715 restoreLocale();
716 return ret;
717 }
718 }
719
720
721 private static Locale saveLocaleForDefault;
722
723
724
725
726 static void prepareLocale()
727 {
728 saveLocaleForDefault = Locale.getDefault();
729 Locale.setDefault(
730 CliUtil.localeOption != null && !CliUtil.parseDefaultValue ? CliUtil.localeOption : CliUtil.defaultValueLocale);
731 }
732
733
734
735
736 static void restoreLocale()
737 {
738 Locale.setDefault(saveLocaleForDefault);
739 CliUtil.defaultValueLocale = Locale.US;
740 CliUtil.parseDefaultValue = false;
741 }
742
743
744
745
746
747
748 private static Locale parseLocale(final String localeStr)
749 {
750 var s = localeStr.replaceAll("_", "-");
751 var sa = s.split("\\-", 3);
752 return sa.length == 3 ? new Locale(sa[0], sa[1], sa[2])
753 : sa.length == 2 ? new Locale(sa[0], sa[1]) : sa.length == 1 ? new Locale(sa[0]) : new Locale(s);
754 }
755
756 }