1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.commons.cli;
19
20 import java.io.BufferedReader;
21 import java.io.IOException;
22 import java.io.PrintWriter;
23 import java.io.Serializable;
24 import java.io.StringReader;
25 import java.io.UncheckedIOException;
26 import java.util.ArrayList;
27 import java.util.Arrays;
28 import java.util.Collection;
29 import java.util.Collections;
30 import java.util.Comparator;
31 import java.util.Iterator;
32 import java.util.List;
33 import java.util.Objects;
34 import java.util.function.Function;
35 import java.util.function.Supplier;
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 public class HelpFormatter {
69
70
71
72
73
74
75 public static class Builder implements Supplier<HelpFormatter> {
76
77
78
79
80
81
82 private static final Function<Option, String> DEFAULT_DEPRECATED_FORMAT = o -> "[Deprecated] " + getDescription(o);
83
84
85
86
87 private Function<Option, String> deprecatedFormatFunction = DEFAULT_DEPRECATED_FORMAT;
88
89
90
91
92 private PrintWriter printStream = createDefaultPrintWriter();
93
94
95 private boolean showSince;
96
97 @Override
98 public HelpFormatter get() {
99 return new HelpFormatter(deprecatedFormatFunction, printStream, showSince);
100 }
101
102
103
104
105
106
107
108 public Builder setPrintWriter(final PrintWriter printWriter) {
109 this.printStream = Objects.requireNonNull(printWriter, "printWriter");
110 return this;
111 }
112
113
114
115
116
117
118
119 public Builder setShowDeprecated(final boolean useDefaultFormat) {
120 return setShowDeprecated(useDefaultFormat ? DEFAULT_DEPRECATED_FORMAT : null);
121 }
122
123
124
125
126
127
128
129
130 public Builder setShowDeprecated(final Function<Option, String> deprecatedFormatFunction) {
131 this.deprecatedFormatFunction = deprecatedFormatFunction;
132 return this;
133 }
134
135
136
137
138
139
140
141 public Builder setShowSince(final boolean showSince) {
142 this.showSince = showSince;
143 return this;
144 }
145 }
146
147
148
149
150 private static final class OptionComparator implements Comparator<Option>, Serializable {
151
152
153 private static final long serialVersionUID = 5305467873966684014L;
154
155
156
157
158
159
160
161
162
163
164 @Override
165 public int compare(final Option opt1, final Option opt2) {
166 return opt1.getKey().compareToIgnoreCase(opt2.getKey());
167 }
168 }
169
170 private static final String HEADER_OPTIONS = "Options";
171
172
173 private static final String HEADER_SINCE = "Since";
174
175
176 private static final String HEADER_DESCRIPTION = "Description";
177
178
179 public static final int DEFAULT_WIDTH = 74;
180
181
182 public static final int DEFAULT_LEFT_PAD = 1;
183
184
185 public static final int DEFAULT_DESC_PAD = 3;
186
187
188 public static final String DEFAULT_SYNTAX_PREFIX = "usage: ";
189
190
191 public static final String DEFAULT_OPT_PREFIX = "-";
192
193
194 public static final String DEFAULT_LONG_OPT_PREFIX = "--";
195
196
197
198
199
200
201 public static final String DEFAULT_LONG_OPT_SEPARATOR = " ";
202
203
204 public static final String DEFAULT_ARG_NAME = "arg";
205
206
207
208
209
210
211
212 public static Builder builder() {
213 return new Builder();
214 }
215
216 private static PrintWriter createDefaultPrintWriter() {
217 return new PrintWriter(System.out);
218 }
219
220
221
222
223
224
225
226 public static String getDescription(final Option option) {
227 final String desc = option.getDescription();
228 return desc == null ? "" : desc;
229 }
230
231
232
233
234
235
236 @Deprecated
237 public int defaultWidth = DEFAULT_WIDTH;
238
239
240
241
242
243
244 @Deprecated
245 public int defaultLeftPad = DEFAULT_LEFT_PAD;
246
247
248
249
250
251
252 @Deprecated
253 public int defaultDescPad = DEFAULT_DESC_PAD;
254
255
256
257
258
259
260 @Deprecated
261 public String defaultSyntaxPrefix = DEFAULT_SYNTAX_PREFIX;
262
263
264
265
266
267
268 @Deprecated
269 public String defaultNewLine = System.lineSeparator();
270
271
272
273
274
275
276 @Deprecated
277 public String defaultOptPrefix = DEFAULT_OPT_PREFIX;
278
279
280
281
282
283
284 @Deprecated
285 public String defaultLongOptPrefix = DEFAULT_LONG_OPT_PREFIX;
286
287
288
289
290
291
292 @Deprecated
293 public String defaultArgName = DEFAULT_ARG_NAME;
294
295
296
297
298
299
300 protected Comparator<Option> optionComparator = new OptionComparator();
301
302
303
304
305 private final Function<Option, String> deprecatedFormatFunction;
306
307
308
309
310 private final PrintWriter printWriter;
311
312
313 private final boolean showSince;
314
315
316
317
318 private String longOptSeparator = DEFAULT_LONG_OPT_SEPARATOR;
319
320
321
322
323 public HelpFormatter() {
324 this(null, createDefaultPrintWriter(), false);
325 }
326
327
328
329
330
331 private HelpFormatter(final Function<Option, String> deprecatedFormatFunction, final PrintWriter printWriter, final boolean showSince) {
332
333
334 this.deprecatedFormatFunction = deprecatedFormatFunction;
335 this.printWriter = printWriter;
336 this.showSince = showSince;
337 }
338
339
340
341
342
343
344
345
346 private void appendOption(final StringBuilder buff, final Option option, final boolean required) {
347 if (!required) {
348 buff.append("[");
349 }
350 if (option.getOpt() != null) {
351 buff.append("-").append(option.getOpt());
352 } else {
353 buff.append("--").append(option.getLongOpt());
354 }
355
356 if (option.hasArg() && (option.getArgName() == null || !option.getArgName().isEmpty())) {
357 buff.append(option.getOpt() == null ? longOptSeparator : " ");
358 buff.append("<").append(option.getArgName() != null ? option.getArgName() : getArgName()).append(">");
359 }
360
361 if (!required) {
362 buff.append("]");
363 }
364 }
365
366
367
368
369
370
371
372
373
374 private void appendOptionGroup(final StringBuilder buff, final OptionGroup group) {
375 if (!group.isRequired()) {
376 buff.append("[");
377 }
378 final List<Option> optList = new ArrayList<>(group.getOptions());
379 if (getOptionComparator() != null) {
380 Collections.sort(optList, getOptionComparator());
381 }
382
383 for (final Iterator<Option> it = optList.iterator(); it.hasNext();) {
384
385 appendOption(buff, it.next(), true);
386
387 if (it.hasNext()) {
388 buff.append(" | ");
389 }
390 }
391 if (!group.isRequired()) {
392 buff.append("]");
393 }
394 }
395
396
397
398
399
400
401
402
403
404
405
406
407 <A extends Appendable> A appendOptions(final A sb, final int width, final Options options, final int leftPad, final int descPad) throws IOException {
408 final String lpad = createPadding(leftPad);
409 final String dpad = createPadding(descPad);
410
411
412
413
414 int max = 0;
415 final int maxSince = showSince ? determineMaxSinceLength(options) + leftPad : 0;
416 final List<StringBuilder> prefixList = new ArrayList<>();
417 final List<Option> optList = options.helpOptions();
418 if (getOptionComparator() != null) {
419 Collections.sort(optList, getOptionComparator());
420 }
421 for (final Option option : optList) {
422 final StringBuilder optBuf = new StringBuilder();
423 if (option.getOpt() == null) {
424 optBuf.append(lpad).append(" ").append(getLongOptPrefix()).append(option.getLongOpt());
425 } else {
426 optBuf.append(lpad).append(getOptPrefix()).append(option.getOpt());
427 if (option.hasLongOpt()) {
428 optBuf.append(',').append(getLongOptPrefix()).append(option.getLongOpt());
429 }
430 }
431 if (option.hasArg()) {
432 final String argName = option.getArgName();
433 if (argName != null && argName.isEmpty()) {
434
435 optBuf.append(' ');
436 } else {
437 optBuf.append(option.hasLongOpt() ? longOptSeparator : " ");
438 optBuf.append("<").append(argName != null ? option.getArgName() : getArgName()).append(">");
439 }
440 }
441
442 prefixList.add(optBuf);
443 max = Math.max(optBuf.length() + maxSince, max);
444 }
445 final int nextLineTabStop = max + descPad;
446 if (showSince) {
447 final StringBuilder optHeader = new StringBuilder(HEADER_OPTIONS).append(createPadding(max - maxSince - HEADER_OPTIONS.length() + leftPad))
448 .append(HEADER_SINCE);
449 optHeader.append(createPadding(max - optHeader.length())).append(lpad).append(HEADER_DESCRIPTION);
450 appendWrappedText(sb, width, nextLineTabStop, optHeader.toString());
451 sb.append(getNewLine());
452 }
453
454 int x = 0;
455 for (final Iterator<Option> it = optList.iterator(); it.hasNext();) {
456 final Option option = it.next();
457 final StringBuilder optBuf = new StringBuilder(prefixList.get(x++).toString());
458 if (optBuf.length() < max) {
459 optBuf.append(createPadding(max - maxSince - optBuf.length()));
460 if (showSince) {
461 optBuf.append(lpad).append(option.getSince() == null ? "-" : option.getSince());
462 }
463 optBuf.append(createPadding(max - optBuf.length()));
464 }
465 optBuf.append(dpad);
466
467 if (deprecatedFormatFunction != null && option.isDeprecated()) {
468 optBuf.append(deprecatedFormatFunction.apply(option).trim());
469 } else if (option.getDescription() != null) {
470 optBuf.append(option.getDescription());
471 }
472 appendWrappedText(sb, width, nextLineTabStop, optBuf.toString());
473 if (it.hasNext()) {
474 sb.append(getNewLine());
475 }
476 }
477 return sb;
478 }
479
480
481
482
483
484
485
486
487
488
489
490
491 <A extends Appendable> A appendWrappedText(final A appendable, final int width, final int nextLineTabStop, final String text) throws IOException {
492 String render = text;
493 int nextLineTabStopPos = nextLineTabStop;
494 int pos = findWrapPos(render, width, 0);
495 if (pos == -1) {
496 appendable.append(rtrim(render));
497 return appendable;
498 }
499 appendable.append(rtrim(render.substring(0, pos))).append(getNewLine());
500 if (nextLineTabStopPos >= width) {
501
502 nextLineTabStopPos = 1;
503 }
504
505 final String padding = createPadding(nextLineTabStopPos);
506 while (true) {
507 render = padding + render.substring(pos).trim();
508 pos = findWrapPos(render, width, 0);
509 if (pos == -1) {
510 appendable.append(render);
511 return appendable;
512 }
513 if (render.length() > width && pos == nextLineTabStopPos - 1) {
514 pos = width;
515 }
516 appendable.append(rtrim(render.substring(0, pos))).append(getNewLine());
517 }
518 }
519
520
521
522
523
524
525
526
527 protected String createPadding(final int len) {
528 final char[] padding = new char[len];
529 Arrays.fill(padding, ' ');
530 return new String(padding);
531 }
532
533 private int determineMaxSinceLength(final Options options) {
534 final int minLen = HEADER_SINCE.length();
535 final int len = options.getOptions().stream().map(o -> o.getSince() == null ? minLen : o.getSince().length()).max(Integer::compareTo).orElse(minLen);
536 return len < minLen ? minLen : len;
537 }
538
539
540
541
542
543
544
545
546
547
548
549 protected int findWrapPos(final String text, final int width, final int startPos) {
550
551 int pos = text.indexOf(Char.LF, startPos);
552 if (pos != -1 && pos <= width) {
553 return pos + 1;
554 }
555 pos = text.indexOf(Char.TAB, startPos);
556 if (pos != -1 && pos <= width) {
557 return pos + 1;
558 }
559 if (startPos + width >= text.length()) {
560 return -1;
561 }
562
563 for (pos = startPos + width; pos >= startPos; --pos) {
564 final char c = text.charAt(pos);
565 if (c == Char.SP || c == Char.LF || c == Char.CR) {
566 break;
567 }
568 }
569
570 if (pos > startPos) {
571 return pos;
572 }
573
574 pos = startPos + width;
575 return pos == text.length() ? -1 : pos;
576 }
577
578
579
580
581
582
583 public String getArgName() {
584 return defaultArgName;
585 }
586
587
588
589
590
591
592 public int getDescPadding() {
593 return defaultDescPad;
594 }
595
596
597
598
599
600
601 public int getLeftPadding() {
602 return defaultLeftPad;
603 }
604
605
606
607
608
609
610 public String getLongOptPrefix() {
611 return defaultLongOptPrefix;
612 }
613
614
615
616
617
618
619
620 public String getLongOptSeparator() {
621 return longOptSeparator;
622 }
623
624
625
626
627
628
629 public String getNewLine() {
630 return defaultNewLine;
631 }
632
633
634
635
636
637
638
639
640 public Comparator<Option> getOptionComparator() {
641 return optionComparator;
642 }
643
644
645
646
647
648
649 public String getOptPrefix() {
650 return defaultOptPrefix;
651 }
652
653
654
655
656
657
658 public String getSyntaxPrefix() {
659 return defaultSyntaxPrefix;
660 }
661
662
663
664
665
666
667 public int getWidth() {
668 return defaultWidth;
669 }
670
671
672
673
674
675
676
677
678
679
680
681 public void printHelp(final int width, final String cmdLineSyntax, final String header, final Options options, final String footer) {
682 printHelp(width, cmdLineSyntax, header, options, footer, false);
683 }
684
685
686
687
688
689
690
691
692
693
694
695
696 public void printHelp(final int width, final String cmdLineSyntax, final String header, final Options options, final String footer,
697 final boolean autoUsage) {
698 final PrintWriter pw = new PrintWriter(printWriter);
699 printHelp(pw, width, cmdLineSyntax, header, options, getLeftPadding(), getDescPadding(), footer, autoUsage);
700 pw.flush();
701 }
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717 public void printHelp(final PrintWriter pw, final int width, final String cmdLineSyntax, final String header, final Options options, final int leftPad,
718 final int descPad, final String footer) {
719 printHelp(pw, width, cmdLineSyntax, header, options, leftPad, descPad, footer, false);
720 }
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736 public void printHelp(final PrintWriter pw, final int width, final String cmdLineSyntax, final String header, final Options options, final int leftPad,
737 final int descPad, final String footer, final boolean autoUsage) {
738 if (Util.isEmpty(cmdLineSyntax)) {
739 throw new IllegalArgumentException("cmdLineSyntax not provided");
740 }
741 if (autoUsage) {
742 printUsage(pw, width, cmdLineSyntax, options);
743 } else {
744 printUsage(pw, width, cmdLineSyntax);
745 }
746 if (header != null && !header.isEmpty()) {
747 printWrapped(pw, width, header);
748 }
749 printOptions(pw, width, options, leftPad, descPad);
750 if (footer != null && !footer.isEmpty()) {
751 printWrapped(pw, width, footer);
752 }
753 }
754
755
756
757
758
759
760
761
762 public void printHelp(final String cmdLineSyntax, final Options options) {
763 printHelp(getWidth(), cmdLineSyntax, null, options, null, false);
764 }
765
766
767
768
769
770
771
772
773
774 public void printHelp(final String cmdLineSyntax, final Options options, final boolean autoUsage) {
775 printHelp(getWidth(), cmdLineSyntax, null, options, null, autoUsage);
776 }
777
778
779
780
781
782
783
784
785
786
787 public void printHelp(final String cmdLineSyntax, final String header, final Options options, final String footer) {
788 printHelp(cmdLineSyntax, header, options, footer, false);
789 }
790
791
792
793
794
795
796
797
798
799
800
801 public void printHelp(final String cmdLineSyntax, final String header, final Options options, final String footer, final boolean autoUsage) {
802 printHelp(getWidth(), cmdLineSyntax, header, options, footer, autoUsage);
803 }
804
805
806
807
808
809
810
811
812
813
814
815 public void printOptions(final PrintWriter pw, final int width, final Options options, final int leftPad, final int descPad) {
816 try {
817 pw.println(appendOptions(new StringBuilder(), width, options, leftPad, descPad));
818 } catch (final IOException e) {
819
820 throw new UncheckedIOException(e);
821 }
822 }
823
824
825
826
827
828
829
830
831 public void printUsage(final PrintWriter pw, final int width, final String cmdLineSyntax) {
832 final int argPos = cmdLineSyntax.indexOf(' ') + 1;
833 printWrapped(pw, width, getSyntaxPrefix().length() + argPos, getSyntaxPrefix() + cmdLineSyntax);
834 }
835
836
837
838
839
840
841
842
843
844 public void printUsage(final PrintWriter pw, final int width, final String app, final Options options) {
845
846 final StringBuilder buff = new StringBuilder(getSyntaxPrefix()).append(app).append(Char.SP);
847
848 final Collection<OptionGroup> processedGroups = new ArrayList<>();
849 final List<Option> optList = new ArrayList<>(options.getOptions());
850 if (getOptionComparator() != null) {
851 Collections.sort(optList, getOptionComparator());
852 }
853
854 for (final Iterator<Option> it = optList.iterator(); it.hasNext();) {
855
856 final Option option = it.next();
857
858 final OptionGroup group = options.getOptionGroup(option);
859
860 if (group != null) {
861
862 if (!processedGroups.contains(group)) {
863
864 processedGroups.add(group);
865
866 appendOptionGroup(buff, group);
867 }
868
869
870 }
871
872 else {
873 appendOption(buff, option, option.isRequired());
874 }
875 if (it.hasNext()) {
876 buff.append(Char.SP);
877 }
878 }
879
880
881 printWrapped(pw, width, buff.toString().indexOf(' ') + 1, buff.toString());
882 }
883
884
885
886
887
888
889
890
891
892 public void printWrapped(final PrintWriter pw, final int width, final int nextLineTabStop, final String text) {
893 pw.println(renderWrappedTextBlock(new StringBuilder(text.length()), width, nextLineTabStop, text));
894 }
895
896
897
898
899
900
901
902
903 public void printWrapped(final PrintWriter pw, final int width, final String text) {
904 printWrapped(pw, width, 0, text);
905 }
906
907
908
909
910
911
912
913
914
915
916
917
918 protected StringBuffer renderOptions(final StringBuffer sb, final int width, final Options options, final int leftPad, final int descPad) {
919 try {
920 return appendOptions(sb, width, options, leftPad, descPad);
921 } catch (final IOException e) {
922
923 throw new UncheckedIOException(e);
924 }
925 }
926
927
928
929
930
931
932
933
934
935
936
937 protected StringBuffer renderWrappedText(final StringBuffer sb, final int width, final int nextLineTabStop, final String text) {
938 try {
939 return appendWrappedText(sb, width, nextLineTabStop, text);
940 } catch (final IOException e) {
941
942 throw new UncheckedIOException(e);
943 }
944 }
945
946
947
948
949
950
951
952
953
954
955 private <A extends Appendable> A renderWrappedTextBlock(final A appendable, final int width, final int nextLineTabStop, final String text) {
956 try {
957 final BufferedReader in = new BufferedReader(new StringReader(text));
958 String line;
959 boolean firstLine = true;
960 while ((line = in.readLine()) != null) {
961 if (!firstLine) {
962 appendable.append(getNewLine());
963 } else {
964 firstLine = false;
965 }
966 appendWrappedText(appendable, width, nextLineTabStop, line);
967 }
968 } catch (final IOException e) {
969
970 }
971 return appendable;
972 }
973
974
975
976
977
978
979
980 protected String rtrim(final String s) {
981 if (Util.isEmpty(s)) {
982 return s;
983 }
984 int pos = s.length();
985 while (pos > 0 && Character.isWhitespace(s.charAt(pos - 1))) {
986 --pos;
987 }
988 return s.substring(0, pos);
989 }
990
991
992
993
994
995
996 public void setArgName(final String name) {
997 this.defaultArgName = name;
998 }
999
1000
1001
1002
1003
1004
1005 public void setDescPadding(final int padding) {
1006 this.defaultDescPad = padding;
1007 }
1008
1009
1010
1011
1012
1013
1014 public void setLeftPadding(final int padding) {
1015 this.defaultLeftPad = padding;
1016 }
1017
1018
1019
1020
1021
1022
1023 public void setLongOptPrefix(final String prefix) {
1024 this.defaultLongOptPrefix = prefix;
1025 }
1026
1027
1028
1029
1030
1031
1032
1033
1034 public void setLongOptSeparator(final String longOptSeparator) {
1035 this.longOptSeparator = longOptSeparator;
1036 }
1037
1038
1039
1040
1041
1042
1043 public void setNewLine(final String newline) {
1044 this.defaultNewLine = newline;
1045 }
1046
1047
1048
1049
1050
1051
1052
1053
1054 public void setOptionComparator(final Comparator<Option> comparator) {
1055 this.optionComparator = comparator;
1056 }
1057
1058
1059
1060
1061
1062
1063 public void setOptPrefix(final String prefix) {
1064 this.defaultOptPrefix = prefix;
1065 }
1066
1067
1068
1069
1070
1071
1072 public void setSyntaxPrefix(final String prefix) {
1073 this.defaultSyntaxPrefix = prefix;
1074 }
1075
1076
1077
1078
1079
1080
1081 public void setWidth(final int width) {
1082 this.defaultWidth = width;
1083 }
1084
1085 }