You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@commons.apache.org by gg...@apache.org on 2024/07/26 11:56:20 UTC

(commons-cli) branch master updated: Initial implementation (#292)

This is an automated email from the ASF dual-hosted git repository.

ggregory pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-cli.git


The following commit(s) were added to refs/heads/master by this push:
     new a70f96b  Initial implementation (#292)
a70f96b is described below

commit a70f96b01ef2a8f714a57c188610ea3e965361e9
Author: Claude Warren <cl...@xenei.com>
AuthorDate: Fri Jul 26 12:56:15 2024 +0100

    Initial implementation (#292)
---
 .../java/org/apache/commons/cli/HelpFormatter.java | 58 ++++++++++++++++++++--
 src/main/java/org/apache/commons/cli/Option.java   | 26 ++++++++++
 .../org/apache/commons/cli/HelpFormatterTest.java  | 32 ++++++++++++
 3 files changed, 111 insertions(+), 5 deletions(-)

diff --git a/src/main/java/org/apache/commons/cli/HelpFormatter.java b/src/main/java/org/apache/commons/cli/HelpFormatter.java
index 8081fa9..3dcf2d9 100644
--- a/src/main/java/org/apache/commons/cli/HelpFormatter.java
+++ b/src/main/java/org/apache/commons/cli/HelpFormatter.java
@@ -90,9 +90,12 @@ public class HelpFormatter {
          */
         private PrintWriter printStream = createDefaultPrintWriter();
 
+        /** The flag to determine if the since values should be dispalyed */
+        private boolean showSince;
+
         @Override
         public HelpFormatter get() {
-            return new HelpFormatter(deprecatedFormatFunc, printStream);
+            return new HelpFormatter(deprecatedFormatFunc, printStream, showSince);
         }
 
         /**
@@ -127,6 +130,17 @@ public class HelpFormatter {
             this.deprecatedFormatFunc = showDeprecatedFunc;
             return this;
         }
+
+        /**
+         * Sets whether to show the date the option was first added.
+         * @param showSince if @{code true} the date the options was first added will be shown.
+         * @return this builder.
+         * @since 1.9.0
+         */
+        public Builder setShowSince(final boolean showSince) {
+            this.showSince = showSince;
+            return this;
+        }
     }
 
     /**
@@ -151,6 +165,15 @@ public class HelpFormatter {
             return opt1.getKey().compareToIgnoreCase(opt2.getKey());
         }
     }
+    /** "Options" text for options header */
+    private static final String HEADER_OPTIONS = "Options";
+
+    /** "Since" text for options header */
+    private static final String HEADER_SINCE = "Since";
+
+    /** "Description" test for options header */
+    private static final String HEADER_DESCRIPTION = "Description";
+
     /** Default number of characters per line */
     public static final int DEFAULT_WIDTH = 74;
 
@@ -285,6 +308,9 @@ public class HelpFormatter {
      */
     private final PrintWriter printWriter;
 
+    /** Flag to determine if since field should be displayed */
+    private final boolean showSince;
+
     /**
      * The separator displayed between the long option and its value.
      */
@@ -294,18 +320,19 @@ public class HelpFormatter {
      * Constructs a new instance.
      */
     public HelpFormatter() {
-        this(null, createDefaultPrintWriter());
+        this(null, createDefaultPrintWriter(), false);
     }
 
     /**
      * Constructs a new instance.
      * @param printStream TODO
      */
-    private HelpFormatter(final Function<Option, String> deprecatedFormatFunc, final PrintWriter printStream) {
+    private HelpFormatter(final Function<Option, String> deprecatedFormatFunc, final PrintWriter printStream, final boolean showSince) {
         // TODO All other instance HelpFormatter instance variables.
         // Make HelpFormatter immutable for 2.0
         this.deprecatedFormatFunc = deprecatedFormatFunc;
         this.printWriter = printStream;
+        this.showSince = showSince;
     }
 
     /**
@@ -748,6 +775,12 @@ public class HelpFormatter {
         printWrapped(pw, width, 0, text);
     }
 
+    private int determineMaxSinceLength(final Options options) {
+        int minLen = HEADER_SINCE.length();
+        int len = options.getOptions().stream().map(o -> o.getSince() == null ? minLen : o.getSince().length()).max(Integer::compareTo).orElse(minLen);
+        return len < minLen ? minLen : len;
+    }
+
     /**
      * Renders the specified Options and return the rendered Options in a StringBuffer.
      *
@@ -767,6 +800,7 @@ public class HelpFormatter {
         // the longest opt string this list will be then used to
         // sort options ascending
         int max = 0;
+        int maxSince = showSince ? determineMaxSinceLength(options) + leftPad : 0;
         final List<StringBuffer> prefixList = new ArrayList<>();
         final List<Option> optList = options.helpOptions();
         if (getOptionComparator() != null) {
@@ -792,18 +826,32 @@ public class HelpFormatter {
                     optBuf.append("<").append(argName != null ? option.getArgName() : getArgName()).append(">");
                 }
             }
+
             prefixList.add(optBuf);
-            max = Math.max(optBuf.length(), max);
+            max = Math.max(optBuf.length() + maxSince, max);
         }
+        final int nextLineTabStop = max + descPad;
+        if (showSince) {
+            StringBuilder optHeader = new StringBuilder(HEADER_OPTIONS).append(createPadding(max - maxSince - HEADER_OPTIONS.length() + leftPad))
+                    .append(HEADER_SINCE);
+            optHeader.append(createPadding(max - optHeader.length())).append(lpad).append(HEADER_DESCRIPTION);
+            renderWrappedText(sb, width, nextLineTabStop, optHeader.toString());
+            sb.append(getNewLine());
+        }
+
         int x = 0;
         for (final Iterator<Option> it = optList.iterator(); it.hasNext();) {
             final Option option = it.next();
             final StringBuilder optBuf = new StringBuilder(prefixList.get(x++).toString());
             if (optBuf.length() < max) {
+                optBuf.append(createPadding(max - maxSince - optBuf.length()));
+                if (showSince) {
+                    optBuf.append(lpad).append(option.getSince() == null ? "-" : option.getSince());
+                }
                 optBuf.append(createPadding(max - optBuf.length()));
             }
             optBuf.append(dpad);
-            final int nextLineTabStop = max + descPad;
+
             if (deprecatedFormatFunc != null && option.isDeprecated()) {
                 optBuf.append(deprecatedFormatFunc.apply(option).trim());
             } else if (option.getDescription() != null) {
diff --git a/src/main/java/org/apache/commons/cli/Option.java b/src/main/java/org/apache/commons/cli/Option.java
index e5b9800..f8300f9 100644
--- a/src/main/java/org/apache/commons/cli/Option.java
+++ b/src/main/java/org/apache/commons/cli/Option.java
@@ -93,6 +93,9 @@ public class Option implements Cloneable, Serializable {
         /** Specifies whether this option is required to be present. */
         private boolean required;
 
+        /** Specifies the version when this option was added.  May be null */
+        private String since;
+
         /** The type of this Option. */
         private Class<?> type = DEFAULT_TYPE;
 
@@ -282,6 +285,16 @@ public class Option implements Cloneable, Serializable {
             return this;
         }
 
+        /** Sets the version number when this option was first defined."
+         *
+         * @param since the version number when this option was first defined.
+         * @return this builder.
+         */
+        public Builder since(final String since) {
+            this.since = since;
+            return this;
+        }
+
         /**
          * Sets the type of the Option.
          *
@@ -395,6 +408,9 @@ public class Option implements Cloneable, Serializable {
     /** Specifies whether this option is required to be present. */
     private boolean required;
 
+    /** Specifies the version when this option was added.  May be null */
+    private String since;
+
     /** The type of this Option. */
     private Class<?> type = String.class;
 
@@ -418,6 +434,7 @@ public class Option implements Cloneable, Serializable {
         this.optionalArg = builder.optionalArg;
         this.deprecated = builder.deprecated;
         this.required = builder.required;
+        this.since = builder.since;
         this.type = builder.type;
         this.valuesep = builder.valueSeparator;
         this.converter = builder.converter;
@@ -644,6 +661,15 @@ public class Option implements Cloneable, Serializable {
         return option;
     }
 
+    /**
+     * Gets the version when this option was added.
+     * @return the version when this option was added, or {@code null} if not set.
+     */
+    public String getSince() {
+        return since;
+    }
+
+
     /**
      * Gets the type of this Option.
      *
diff --git a/src/test/java/org/apache/commons/cli/HelpFormatterTest.java b/src/test/java/org/apache/commons/cli/HelpFormatterTest.java
index 1ca7400..09b449f 100644
--- a/src/test/java/org/apache/commons/cli/HelpFormatterTest.java
+++ b/src/test/java/org/apache/commons/cli/HelpFormatterTest.java
@@ -17,11 +17,13 @@
 
 package org.apache.commons.cli;
 
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertNull;
 import static org.junit.jupiter.api.Assertions.assertThrows;
 
 import java.io.ByteArrayOutputStream;
+import java.io.OutputStreamWriter;
 import java.io.PrintWriter;
 import java.io.StringWriter;
 import java.util.ArrayList;
@@ -490,6 +492,22 @@ public class HelpFormatterTest {
         assertThrows(IllegalArgumentException.class, () -> formatter.printHelp("", new Options(), false), "null command line syntax should be rejected");
     }
 
+    @Test
+    public void testPrintHelpWithSince() {
+        final String [] expected = {"usage: Command syntax", "Header", "Options            Since   Description",
+                "  -n,--no-since    -          Description for n", "  -W,--with-since  1.19.0     Descripton for W", "footer"};
+        final Options options = new Options()
+                .addOption(Option.builder("W").longOpt("with-since").since("1.19.0").desc("Descripton for W").build())
+                .addOption(Option.builder("n").longOpt("no-since").desc("Description for n").build());
+
+        final HelpFormatter formatter = HelpFormatter.builder().setShowSince(true).get();
+        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
+        try (PrintWriter pw = new PrintWriter(new OutputStreamWriter(baos))) {
+            formatter.printHelp(pw, 80, "Command syntax", "Header", options, 2, 5, "footer", false);
+        }
+        assertArrayEquals(expected, baos.toString().split(System.lineSeparator()));
+    }
+
     @Test
     public void testPrintOptionGroupUsage() {
         final OptionGroup group = new OptionGroup();
@@ -638,6 +656,20 @@ public class HelpFormatterTest {
         assertEquals("usage: app [-a] [-b] [-c]" + EOL, bytesOut.toString());
     }
 
+    @Test
+    public void testRenderSince() {
+        final String[] expected = {"Options            Since   Description", "  -n,--no-since    -          Description for n",
+            "  -W,--with-since  1.19.0     Descripton for W"};
+        final Options options = new Options()
+                .addOption(Option.builder("W").longOpt("with-since").since("1.19.0").desc("Descripton for W").build())
+                .addOption(Option.builder("n").longOpt("no-since").desc("Description for n").build());
+        final HelpFormatter formatter = HelpFormatter.builder().setShowSince(true).get();
+
+        final StringBuffer sb = new StringBuffer();
+        formatter.renderOptions(sb, 50, options, 2, 5);
+        assertArrayEquals(expected, sb.toString().split(System.lineSeparator()));
+    }
+
     @Test
     public void testRenderWrappedTextMultiLine() {
         // multi line text