commons-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From jstrac...@apache.org
Subject cvs commit: jakarta-commons-sandbox/cli/src/test/org/apache/commons/cli HelpFormatterExamples.java TestHelpFormatter.java AllTest.java
Date Fri, 01 Feb 2002 16:28:35 GMT
jstrachan    02/02/01 08:28:35

  Modified:    cli      STATUS.html TODO.txt build.xml
               cli/src/test/org/apache/commons/cli AllTest.java
  Added:       cli/src/java/org/apache/commons/cli HelpFormatter.java
               cli/src/test/org/apache/commons/cli
                        HelpFormatterExamples.java TestHelpFormatter.java
  Log:
  Added Slavek's patch which adds support for pretty printing of the command line options. Also added a much tidier Ant build file from digester.
  
  Revision  Changes    Path
  1.2       +5 -2      jakarta-commons-sandbox/cli/STATUS.html
  
  Index: STATUS.html
  ===================================================================
  RCS file: /home/cvs/jakarta-commons-sandbox/cli/STATUS.html,v
  retrieving revision 1.1
  retrieving revision 1.2
  diff -u -r1.1 -r1.2
  --- STATUS.html	19 Dec 2001 18:16:25 -0000	1.1
  +++ STATUS.html	1 Feb 2002 16:28:34 -0000	1.2
  @@ -7,7 +7,7 @@
   
   <div align="center">
   <h1>The Jakarta Commons <em>CLI</em> Package</h1>
  -$Id: STATUS.html,v 1.1 2001/12/19 18:16:25 jstrachan Exp $<br>
  +$Id: STATUS.html,v 1.2 2002/02/01 16:28:34 jstrachan Exp $<br>
   <a href="#Introduction">[Introduction]</a>
   <a href="#Dependencies">[Dependencies]</a>
   <a href="#Release Info">[Release Info]</a>
  @@ -28,7 +28,10 @@
   The following classes are included:</p>
   <ul>
   <li><strong>Options</strong> - provide a simple mechanism to setup a programs options with a parse() method to parse the command line arguments.</li>
  +<li><b>Option</b> - represents a single option, its abbreviation, name and 
  +description</li>
   <li><strong>CommandLine</strong> - the command line arguments after parsing.</li>
  +<li><b>HelpFormatter</b> - formats the usage to display help to the user</li>
   </ul>
   
   <a name="Dependencies"></a>
  @@ -92,4 +95,4 @@
   </table>
   
   </body>
  -</html>
  +</html>
  \ No newline at end of file
  
  
  
  1.2       +7 -4      jakarta-commons-sandbox/cli/TODO.txt
  
  Index: TODO.txt
  ===================================================================
  RCS file: /home/cvs/jakarta-commons-sandbox/cli/TODO.txt,v
  retrieving revision 1.1
  retrieving revision 1.2
  diff -u -r1.1 -r1.2
  --- TODO.txt	19 Dec 2001 18:16:25 -0000	1.1
  +++ TODO.txt	1 Feb 2002 16:28:34 -0000	1.2
  @@ -1,8 +1,11 @@
   Project To Do List
   ==================
   
  -* provide a helper method to output the usage of a program
  -  displaying all the options, whether they take a value etc.
  -
   * provide simple mechanism for mandatory options?
  -  
  +
  +* provide groups of options which are allowable?
  +
  +* generate the usage summary, such as...
  +
  +	man [-c|-f|-k|-w|-tZT device] [-adlhu7V] [-Mpath] [-Ppager] [-Slist] 
  +          [-msystem] [-pstring] [-Llocale] [-eextension] [section] page ...
  
  
  
  1.2       +195 -240  jakarta-commons-sandbox/cli/build.xml
  
  Index: build.xml
  ===================================================================
  RCS file: /home/cvs/jakarta-commons-sandbox/cli/build.xml,v
  retrieving revision 1.1
  retrieving revision 1.2
  diff -u -r1.1 -r1.2
  --- build.xml	19 Dec 2001 18:16:25 -0000	1.1
  +++ build.xml	1 Feb 2002 16:28:34 -0000	1.2
  @@ -1,273 +1,228 @@
  -<!-- $Id: build.xml,v 1.1 2001/12/19 18:16:25 jstrachan Exp $ -->
  -<project name="messenger" default="test" basedir=".">
  +<project name="Digester" default="compile" basedir=".">
   
  -   <!-- patternset describing files to be copied from the doc directory -->
  -   <patternset id="patternset-doc"/>
  +<!--
  +        $Id: build.xml,v 1.2 2002/02/01 16:28:34 jstrachan Exp $
  +-->
   
  -   <!-- patternset describing test classes -->
  -   <patternset id="patternset-test-classes">
  -      <include name="**/Test*.class"/>
  -   </patternset>
  -
  -   <!-- patternset describing non test classes -->
  -   <patternset id="patternset-non-test-classes">
  -      <include name="**/*.class"/>
  -      <exclude name="**/Test*.class"/>
  -   </patternset>
  -
  -   <!-- patternset describing non test source files (*.java, *html, etc.) -->
  -   <patternset id="patternset-javadocable-sources">
  -      <include name="**/*"/>
  -      <exclude name="**/Test*.java"/>
  -   </patternset>
  -
  -   <!-- patternset describing config files -->
  -   <patternset id="patternset-config-files">
  -      <include name="**/*.xml"/>
  -   </patternset>
  -
  -   <!-- ######################################################### -->
  -
  -   <target name="init">
  -      <tstamp/>
  -
  -      <!-- read properties from the build.properties, if any -->
  -      <property name="component-propfile" value="${basedir}/build.properties"/>
  -      <property file="${component-propfile}"/>
  -
  -      <!-- read properties from the commons build.properties, if any -->
  -      <property name="commons-propfile" value="${basedir}/../build.properties"/>
  -      <property file="${commons-propfile}"/>
  -
  -      <!-- read properties from the ${user.home}/propfile, if any -->
  -      <property name="user-propfile" value="${user.home}/build.properties"/>
  -      <property file="${user-propfile}"/>
  -
  -
  -      <!-- command line classpath, if any -->
  -      <property name="cp" value=""/>
  -
  -      <property name="name" value="cli"/>
  -      <property name="Name" value="Commons CLI"/>
  -      <property name="Name-Long" value="Jakarta Commons CLI Package"/>
  -      <property name="version" value="1.0"/>
  -      <property name="quality" value="beta"/>
  -
  -      <!-- The current version number of this component -->
  -      <property name="component.version"       value="${version}-${quality}"/>
  -
  -      <property name="test.entry" value="org.apache.commons.cli.AllTest"/>
  -      <property name="test.failonerror" value="true" />
  -      <property name="test.runner" value="junit.textui.TestRunner" />
  -
  -      <property name="workdir" value="${java.io.tmpdir}/buildtemp_${DSTAMP}${TSTAMP}"/>
  -
  -      <property name="source" value="${basedir}"/>
  -      <property name="source.src" value="${basedir}/src"/>
  -      <property name="source.src.conf" value="${source.src}/conf"/>
  -      <property name="source.src.java" value="${source.src}/java"/>
  -      <property name="source.src.test" value="${source.src}/test"/>
  -      <property name="source.doc" value="${basedir}/doc"/>
  -      <property name="dest" value="${basedir}/dist"/>
  -      <property name="dest.classes" value="${dest}/classes"/>
  -      <property name="dest.doc" value="${dest}/doc"/>
  -      <property name="dest.doc.api" value="${dest.doc}/api"/>
  -      <property name="dest.jardir" value="${dest}"/>
  -      <property name="dest.jardir.jar" value="${dest.jardir}/commons-${name}.jar"/>
  -      <property name="javadoc-website-dir" value="../../jakarta-commons/docs/${name}/api"/>
  -      <property name="build.webapp" value="${webapp.dir}/web/WEB-INF"/>
  -
  -      <available property="available-doc" file="${source.doc}"/> <!-- does this module have docs? -->
  -      <available property="available-src-java" file="${source.src.java}"/> <!-- does this module have java src? -->
  -      <available property="available-src-test" file="${source.src.test}"/> <!-- does this module have test src? -->
   
  +<!-- ========== Initialize Properties ===================================== -->
   
  -      <!-- now combine the classpaths -->
  -      <property name="classpath" value="${cp}"/>
   
  -      <!-- classpath for unit tests -->
  -      <property name="test.classpath" value="${cp}:${junit.jar}"/>
  +  <property file="build.properties"/>                <!-- Component local   -->
  +  <property file="../build.properties"/>             <!-- Commons local     -->
  +  <property file="${user.home}/build.properties"/>   <!-- User local        -->
   
  -   </target>
   
  -   <!-- ######################################################### -->
  +<!-- ========== External Dependencies ===================================== -->
   
  -   <target name="clean" depends="clean-dist,clean-build,clean-doc" description="removes generated files">
  -      <delete dir="${dest}"/>
  -   </target>
   
  -   <target name="clean-doc" depends="init,clean-javadoc">
  -      <delete dir="${dest.doc}"/>
  -   </target>
  +  <!-- The directories corresponding to your necessary dependencies -->
  +  <property name="junit.home"              value="/usr/local/junit3.7"/>
  +  <property name="commons.home"            value="../../jakarta-commons"/>
  +  <property name="beanutils.home"          value="${commons.home}/beanutils"/>
  +  <property name="collections.home"        value="${commons.home}/collections"/>
  +  <property name="logging.home"            value="${commons.home}/logging"/>
  +  <property name="digester.home"           value="${commons.home}/digester"/>
   
  -   <target name="clean-javadoc" depends="init">
  -      <delete dir="${dest.doc.api}"/>
  -   </target>
   
  -   <target name="clean-build" depends="init">
  -      <delete dir="${dest.classes}"/>
  -      <delete dir="${build.webapp}"/>
  -   </target>
  +<!-- ========== Derived Values ============================================ -->
   
  -   <target name="clean-dist" depends="init">
  -      <delete file="${dest.jardir.jar}"/>
  -   </target>
   
  -   <!-- ######################################################### -->
  +  <!-- The locations of necessary jar files -->
  +  <property name="jdk.api"                 value="${jdk.home}/docs/api"/>
  +  <property name="junit.jar"               value="${junit.home}/junit.jar"/>
  +  
   
  -   <target name="doc" depends="init,doc-top,doc-copy,doc-javadoc" description="generates javadocs and other documentation">
  -   </target>
  +<!-- ========== Component Declarations ==================================== -->
   
  -   <target name="doc-top" depends="init">
  -      <mkdir  dir="${dest}"/>
  -      <copy todir="${dest}" file="../LICENSE"/>
  -   </target>
   
  -   <target name="doc-copy" depends="init" if="available-doc">
  -<!--
  -      <mkdir dir="${dest.xdocs}"/>
  -      <copy todir="${dest.xdocs}">
  -        <fileset dir="${source.xdocs}">
  -          <patternset refid="patternset-doc"/>
  -        </fileset>
  -      </copy>
  --->
  -      <copy todir="${dest.doc}">
  -        <fileset dir="${source.doc}">
  -          <patternset refid="patternset-doc"/>
  -        </fileset>
  -      </copy>
  -   </target>
  +  <!-- The name of this component -->
  +  <property name="component.name"          value="cli"/>
   
  -<!--
  -   <target name="doc-html" depends="init" if="available-doc">
  -    <style    
  -      basedir="${source.xdocs}" 
  -      destdir="${source.doc}" 
  -      style="site.xsl"
  -      includes="**/*.xml"
  -      excludes="project.xml"/>
  -   </target>
  --->
  +  <!-- The primary package name of this component -->
  +  <property name="component.package"       value="org.apache.commons.cli"/>
   
  -   <target name="doc-javadoc" depends="init" if="available-src-java">
  -      <!-- copy all the non-test sources out to the work directory and javadoc that -->
  -      <mkdir dir="${workdir}"/>
  -      <copy todir="${workdir}">
  -        <fileset dir="${source.src.java}">
  -          <patternset refid="patternset-javadocable-sources"/>
  -        </fileset>
  -      </copy>
  -      <replace dir="${workdir}" includes="**"
  -               token="##VERSION##" value="${version}"/>
  -      <replace dir="${workdir}" includes="**"
  -               token="##QUALITY##" value="${quality}"/>
  -      <mkdir dir="${dest.doc.api}"/>
  -      <javadoc packagenames="org.*"
  -               sourcepath="${workdir}"
  -               destdir="${dest.doc.api}"
  -               windowtitle="${Name-Long}"
  -               doctitle="${Name-Long}"
  -               bottom="&lt;small&gt;Copyright &amp;copy; 2001 Apache Software Foundation. Documenation generated ${TODAY}&lt;/small&gt;."
  -               protected="true"
  -               version="true"
  -               author="true"
  -               splitindex="false"
  -               nodeprecated="true"
  -               nodeprecatedlist="true"
  -               notree="true"
  -               noindex="false"
  -               nohelp="true"
  -               nonavbar="false"
  -               serialwarn="false">
  -          <link href="http://java.sun.com/j2se/1.3/docs/api"/>
  -      </javadoc>
  -      <delete dir="${workdir}"/>
  -   </target>
  +  <!-- The title of this component -->
  +  <property name="component.title"         value="CLI - Command Line Interface toolkit"/>
   
  -   <!-- Updates the JavaDoc in the jakarta-commons/docs area -->
  -   <target name="website" depends="doc-javadoc" if="available-src-java">
  -      <copy todir="${javadoc-website-dir}" filtering="no">
  -         <fileset dir="${dest.doc.api}"/>
  -      </copy>
  -   </target>
  +  <!-- The current version number of this component -->
  +  <property name="component.version"       value="1.0-dev"/>
   
  -   <!-- ######################################################### -->
  +  <!-- The base directory for compilation targets -->
  +  <property name="build.home"              value="target"/>
   
  -   <target name="build" depends="init,build-java" description="compiles source files"/>
  +  <!-- The base directory for component configuration files -->
  +  <property name="conf.home"               value="src/conf"/>
   
  -   <target name="build-java" depends="init" if="available-src-java">
  -      <mkdir dir="${dest.classes}"/>
  -      <javac destdir="${dest.classes}"
  -             srcdir="${source.src.java}"
  -             classpath="${classpath}"
  -             debug="false"
  -             deprecation="false"
  -             optimize="true"/>
  -   </target>
  +  <!-- The base directory for distribution targets -->
  +  <property name="dist.home"               value="dist"/>
   
  -   <target name="build-test" depends="init,build-java" if="available-src-test">
  -      <mkdir dir="${dest.classes}"/>
  -      <javac destdir="${dest.classes}"
  -             srcdir="${source.src.test}"
  -             classpath="${test.classpath}"
  -             debug="false"
  -             deprecation="true"
  -             optimize="true"/>
  -
  -      <copy todir="${dest.classes}" filtering="no">
  -         <fileset dir="${source.src.conf}">
  -            <patternset refid="patternset-config-files"/>
  -         </fileset>
  -      </copy>
  -   </target>
  +  <!-- The base directory for component sources -->
  +  <property name="source.home"             value="src/java"/>
   
  -   <!-- ######################################################### -->
  +  <!-- The base directory for unit test sources -->
  +  <property name="test.home"               value="src/test"/>
   
  -   <!-- ######################################################### -->
   
  -   <target name="test" depends="build-test" if="test.entry" description="runs (junit) unit tests">
  -      <!--
  -      <junit printsummary="yes" fork="on" haltonfailure="yes">
  -      	<formatter type="plain" usefile="false"/>
  -      	<test name="${test.entry}"/>
  -      	<classpath>
  -          <pathelement location="${dest.classes}" />
  -          <pathelement path="${classpath}" />
  -          <pathelement path="${java.class.path}" />
  -      	</classpath>
  -      </junit>
  -      -->
  -
  -      <java classname="${test.runner}" fork="yes" failonerror="${test.failonerror}">
  -        <classpath>
  -          <pathelement location="${dest.classes}" />
  -          <pathelement path="${test.classpath}"/>
  -          <pathelement path="${java.class.path}" />
  -        </classpath>
  +<!-- ========== Compiler Defaults ========================================= -->
   
  -        <arg value="${test.entry}"/>
  -      </java>
  -   </target>
   
  -   <!-- ######################################################### -->
  +  <!-- Should Java compilations set the 'debug' compiler option? -->
  +  <property name="compile.debug"           value="true"/>
  +
  +  <!-- Should Java compilations set the 'deprecation' compiler option? -->
  +  <property name="compile.deprecation"     value="false"/>
  +
  +  <!-- Should Java compilations set the 'optimize' compiler option? -->
  +  <property name="compile.optimize"        value="true"/>
  +
  +  <!-- Construct compile classpath -->
  +  <path id="compile.classpath">
  +    <pathelement location="${build.home}/classes"/>
  +  </path>
  +
  +
  +<!-- ========== Test Execution Defaults =================================== -->
  +
  +
  +  <!-- Construct unit test classpath -->
  +  <path id="test.classpath">
  +    <pathelement location="${build.home}/classes"/>
  +    <pathelement location="${build.home}/tests"/>
  +    <pathelement location="${junit.jar}"/>
  +  </path>
  +
  +  <!-- Should all tests fail if one does? -->
  +  <property name="test.failonerror"        value="true"/>
  +
  +  <!-- The test runner to execute -->
  +  <property name="test.runner"             value="junit.textui.TestRunner"/>
  +
  +
  +<!-- ========== Executable Targets ======================================== -->
  +
  +
  +  <target name="init"
  +   description="Initialize and evaluate conditionals">
  +    <echo message="-------- ${component.name} ${component.version} --------"/>
  +    <filter  token="name"                  value="${component.package}"/>
  +    <filter  token="version"               value="${component.version}"/>
  +  </target>
  +
  +
  +  <target name="prepare" depends="init"
  +   description="Prepare build directory">
  +    <mkdir dir="${build.home}"/>
  +    <mkdir dir="${build.home}/classes"/>
  +    <mkdir dir="${build.home}/conf"/>
  +    <mkdir dir="${build.home}/tests"/>
  +  </target>
  +
  +
  +  <target name="static" depends="prepare"
  +   description="Copy static files to build directory">
  +    <tstamp/>
  +    <copy  todir="${build.home}/conf" filtering="on">
  +      <fileset dir="${conf.home}" includes="*.MF"/>
  +    </copy>
  +  </target>
  +
  +
  +  <target name="compile" depends="static"
  +   description="Compile shareable components">
  +    <javac  srcdir="${source.home}"
  +           destdir="${build.home}/classes"
  +             debug="${compile.debug}"
  +       deprecation="${compile.deprecation}"
  +          optimize="${compile.optimize}">
  +      <classpath refid="compile.classpath"/>
  +    </javac>
  +    <copy    todir="${build.home}/classes" filtering="on">
  +      <fileset dir="${source.home}" excludes="**/*.java"/>
  +    </copy>
  +  </target>
  +
  +
  +  <target name="compile.tests" depends="compile"
  +   description="Compile unit test cases">
  +    <javac  srcdir="${test.home}"
  +           destdir="${build.home}/tests"
  +             debug="${compile.debug}"
  +       deprecation="${compile.deprecation}"
  +          optimize="${compile.optimize}">
  +      <classpath refid="test.classpath"/>
  +    </javac>
  +    <copy    todir="${build.home}/tests" filtering="on">
  +      <fileset dir="${test.home}" excludes="**/*.java"/>
  +    </copy>
  +  </target>
  +
  +
  +  <target name="clean"
  +   description="Clean build and distribution directories">
  +    <delete    dir="${build.home}"/>
  +    <delete    dir="${dist.home}"/>
  +  </target>
  +
  +
  +  <target name="all" depends="clean,compile"
  +   description="Clean and compile all components"/>
  +
  +
  +  <target name="javadoc" depends="compile"
  +   description="Create component Javadoc documentation">
  +    <mkdir      dir="${dist.home}"/>
  +    <mkdir      dir="${dist.home}/docs"/>
  +    <mkdir      dir="${dist.home}/docs/api"/>
  +    <javadoc sourcepath="${source.home}"
  +                destdir="${dist.home}/docs/api"
  +           packagenames="org.apache.commons.*"
  +                 author="true"
  +                private="true"
  +                version="true"
  +               doctitle="&lt;h1&gt;${component.title}&lt;/h1&gt;"
  +            windowtitle="${component.title} (Version ${component.version})"
  +                 bottom="Copyright (c) 2002 - Apache Software Foundation">
  +      <link     offline="true"  packagelistLoc="${jdk.api}"
  +                   href="http://java.sun.com/products/jdk/1.3/docs/api"/>
  +      <classpath  refid="compile.classpath"/>
  +    </javadoc>
  +  </target>
  +
  +
  +  <target name="dist" depends="compile,javadoc"
  +   description="Create binary distribution">
  +    <mkdir      dir="${dist.home}"/>
  +    <copy      file="../LICENSE"
  +              todir="${dist.home}"/>
  +    <mkdir      dir="${build.home}/classes/META-INF"/>
  +    <copy      file="../LICENSE"
  +             tofile="${build.home}/classes/META-INF/LICENSE.txt"/>
  +    <jar    jarfile="${dist.home}/commons-${component.name}.jar"
  +            basedir="${build.home}/classes"
  +           manifest="${build.home}/conf/MANIFEST.MF"/>
  +  </target>
  +
  +
  +<!-- ========== Unit Test Targets ========================================= -->
  +
  +
  +  <target name="test" depends="compile.tests"
  +   description="Run all unit test cases">
  +    <java classname="${component.package}.AllTest" fork="yes" failonerror="${test.failonerror}">
  +      <classpath refid="test.classpath"/>
  +    </java>
  +  </target>
  +
   
  -   <target name="dist" depends="dist-jar,doc" description="builds binary distribution"/>
  +<!-- ========== Sample Program Targets ==================================== -->
   
  -   <target name="dist-jar" depends="build">
  -      <mkdir dir="${dest.jardir}"/>
  -      <mkdir dir="${workdir}"/>
  -      <copy todir="${workdir}">
  -         <fileset dir="${dest.classes}">
  -            <patternset refid="patternset-non-test-classes"/>
  -         </fileset>
  -      </copy>
  -      <jar jarfile="${dest.jardir.jar}" manifest="${source.src}/conf/MANIFEST.MF">
  -         <fileset dir="${workdir}"/>
  -      </jar>
  -      <delete dir="${workdir}"/>
  -      <delete dir="${dest.classes}"/>
  +   <target name="demo.help" depends="compile.tests" 
  +      description="Runs the help format sample">
  +    <echo message="Running the help format sample..."/>
  +    <java classname="org.apache.commons.cli.HelpFormatterExamples" fork="yes">
  +      <classpath refid="test.classpath"/>
  +    </java>
      </target>
   
  -   <!-- ######################################################### -->
   </project>
  
  
  
  1.1                  jakarta-commons-sandbox/cli/src/java/org/apache/commons/cli/HelpFormatter.java
  
  Index: HelpFormatter.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE file.
   * 
   * $Id: HelpFormatter.java,v 1.1 2002/02/01 16:28:34 jstrachan Exp $
   */
  package org.apache.commons.cli;
  
  import java.io.PrintWriter;
  import java.util.Iterator;
  import java.util.List;
  import java.util.ArrayList;
  import java.util.Collections;
  import java.util.Comparator;
  
  /** 
   * A formatter of help messages for the current command line options
   *
   * @author Slawek Zachcial
   **/
  public class HelpFormatter
  {
     // --------------------------------------------------------------- Constants
  
     public static final int DEFAULT_WIDTH              = 80;
     public static final int DEFAULT_LEFT_PAD           = 1;
     public static final int DEFAULT_DESC_PAD           = 3;
     public static final String DEFAULT_SYNTAX_PREFIX   = "usage: ";
     public static final String DEFAULT_OPT_PREFIX      = "-";
     public static final String DEFAULT_LONG_OPT_PREFIX = "--";
     public static final String DEFAULT_ARG_NAME        = "arg";
  
     // ------------------------------------------------------------------ Static
  
     // -------------------------------------------------------------- Attributes
  
     public int defaultWidth;
     public int defaultLeftPad;
     public int defaultDescPad;
     public String defaultSyntaxPrefix;
     public String defaultNewLine;
     public String defaultOptPrefix;
     public String defaultLongOptPrefix;
     public String defaultArgName;
  
     // ------------------------------------------------------------ Constructors
     public HelpFormatter()
     {
        defaultWidth = DEFAULT_WIDTH;
        defaultLeftPad = DEFAULT_LEFT_PAD;
        defaultDescPad = DEFAULT_DESC_PAD;
        defaultSyntaxPrefix = DEFAULT_SYNTAX_PREFIX;
        defaultNewLine = System.getProperty("line.separator");
        defaultOptPrefix = DEFAULT_OPT_PREFIX;
        defaultLongOptPrefix = DEFAULT_LONG_OPT_PREFIX;
        defaultArgName = DEFAULT_ARG_NAME;
     }
  
     // ------------------------------------------------------------------ Public
  
     public void printHelp( String cmdLineSyntax,
                            Options options )
     {
        printHelp( defaultWidth, cmdLineSyntax, null, options, null );
     }
  
     public void printHelp( String cmdLineSyntax,
                            String header,
                            Options options,
                            String footer )
     {
        printHelp(defaultWidth, cmdLineSyntax, header, options, footer);
     }
  
     public void printHelp( int width,
                            String cmdLineSyntax,
                            String header,
                            Options options,
                            String footer )
     {
        PrintWriter pw = new PrintWriter(System.out);
        printHelp( pw, width, cmdLineSyntax, header,
                   options, defaultLeftPad, defaultDescPad, footer );
        pw.flush();
     }
  
     public void printHelp( PrintWriter pw,
                            int width,
                            String cmdLineSyntax,
                            String header,
                            Options options,
                            int leftPad,
                            int descPad,
                            String footer )
        throws IllegalArgumentException
     {
        if ( cmdLineSyntax == null || cmdLineSyntax.length() == 0 )
        {
           throw new IllegalArgumentException("cmdLineSyntax not provided");
        }
  
        printUsage( pw, width, cmdLineSyntax );
        if ( header != null && header.trim().length() > 0 )
        {
           printWrapped( pw, width, header );
        }
        printOptions( pw, width, options, leftPad, descPad );
        if ( footer != null && footer.trim().length() > 0 )
        {
           printWrapped( pw, width, footer );
        }
     }
  
     public void printUsage( PrintWriter pw, int width, String cmdLineSyntax )
     {
        int argPos = cmdLineSyntax.indexOf(' ') + 1;
        printWrapped(pw, width, defaultSyntaxPrefix.length() + argPos,
                     defaultSyntaxPrefix + cmdLineSyntax);
     }
  
     public void printOptions( PrintWriter pw, int width, Options options, int leftPad, int descPad )
     {
        StringBuffer sb = new StringBuffer();
        renderOptions(sb, width, options, leftPad, descPad);
        pw.println(sb.toString());
     }
  
     public void printWrapped( PrintWriter pw, int width, String text )
     {
        printWrapped(pw, width, 0, text);
     }
  
     public void printWrapped( PrintWriter pw, int width, int nextLineTabStop, String text )
     {
        StringBuffer sb = new StringBuffer(text.length());
        renderWrappedText(sb, width, nextLineTabStop, text);
        pw.println(sb.toString());
     }
  
     // --------------------------------------------------------------- Protected
  
     protected StringBuffer renderOptions( StringBuffer sb,
                                           int width,
                                           Options options,
                                           int leftPad,
                                           int descPad )
     {
        final String lpad = createPadding(leftPad);
        final String dpad = createPadding(descPad);
  
        //first create list containing only <lpad>-a,--aaa where -a is opt and --aaa is
        //long opt; in parallel look for the longest opt string
        //this list will be then used to sort options ascending
        int max = 0;
        StringBuffer optBuf;
        List prefixList = new ArrayList();
        Option option;
        for ( Iterator i = options.getOptions().iterator(); i.hasNext(); )
        {
           option = (Option) i.next();
           optBuf = new StringBuffer(8);
           optBuf.append(lpad).append(defaultOptPrefix).append(option.getOpt());
           if ( option.hasLongOpt() )
           {
              optBuf.append(',').append(defaultLongOptPrefix).append(option.getLongOpt());
           }
           if ( option.hasArg() )
           {
              //FIXME - should have a way to specify arg name per option
              optBuf.append(' ').append(defaultArgName);
           }
           prefixList.add(optBuf);
           max = optBuf.length() > max ? optBuf.length() : max;
        }
  
        //right pad the prefixes
        for ( Iterator i = prefixList.iterator(); i.hasNext(); )
        {
           optBuf = (StringBuffer) i.next();
           if ( optBuf.length() < max )
           {
              optBuf.append(createPadding(max-optBuf.length()));
           }
           optBuf.append(dpad);
        }
  
        //sort this list ascending
        Collections.sort(prefixList, new StringBufferComparator());
  
        //finally render options
        int nextLineTabStop = max + descPad;
        char opt;
        int optOffset = leftPad + defaultOptPrefix.length();
  
        for ( Iterator i = prefixList.iterator(); i.hasNext(); )
        {
           optBuf = (StringBuffer) i.next();
           opt = optBuf.charAt(optOffset);
           option = options.getOption(opt);
           renderWrappedText(sb, width, nextLineTabStop,
                             optBuf.append(option.getDescription()).toString());
           if ( i.hasNext() )
           {
              sb.append(defaultNewLine);
           }
        }
  
        return sb;
     }
  
     protected StringBuffer renderWrappedText( StringBuffer sb,
                                               int width,
                                               int nextLineTabStop,
                                               String text )
     {
        int pos = findWrapPos( text, width, 0);
        if ( pos == -1 )
        {
           sb.append(rtrim(text));
           return sb;
        }
        else
        {
           sb.append(rtrim(text.substring(0, pos))).append(defaultNewLine);
        }
  
        //all following lines must be padded with nextLineTabStop space characters
        final String padding = createPadding(nextLineTabStop);
  
        while ( true )
        {
           text = padding + text.substring(pos).trim();
           pos = findWrapPos( text, width, nextLineTabStop );
           if ( pos == -1 )
           {
              sb.append(text);
              return sb;
           }
  
           sb.append(rtrim(text.substring(0, pos))).append(defaultNewLine);
        }
  
     }
  
     /**
      * Finds the next text wrap position after <code>startPos</code> for the text
      * in <code>sb</code> with the column width <code>width</code>.
      * The wrap point is the last postion before startPos+width having a whitespace
      * character (space, \n, \r).
      *
      * @param sb text to be analyzed
      * @param width width of the wrapped text
      * @param startPos position from which to start the lookup whitespace character
      * @return postion on which the text must be wrapped or -1 if the wrap position is at the end
      *         of the text
      */
     protected int findWrapPos( String text, int width, int startPos )
     {
        int pos = -1;
        // the line ends before the max wrap pos or a new line char found
        if ( ((pos = text.indexOf('\n', startPos)) != -1 && pos <= width)  ||
             ((pos = text.indexOf('\t', startPos)) != -1 && pos <= width) )
        {
           return pos;
        }
        else if ( (startPos + width) >= text.length() )
        {
           return -1;
        }
  
        //look for the last whitespace character before startPos+width
        pos = startPos + width;
        char c;
        while ( pos >= startPos && (c = text.charAt(pos)) != ' ' && c != '\n' && c != '\r' )
        {
           --pos;
        }
        //if we found it - just return
        if ( pos > startPos )
        {
           return pos;
        }
        else
        {
           //must look for the first whitespace chearacter after startPos + width
           pos = startPos + width;
           while ( pos <= text.length() && (c = text.charAt(pos)) != ' ' && c != '\n' && c != '\r' )
           {
              ++pos;
           }
           return pos == text.length() ? -1 : pos;
        }
     }
  
     protected String createPadding(int len)
     {
        StringBuffer sb = new StringBuffer(len);
        for ( int i = 0; i < len; ++i )
        {
           sb.append(' ');
        }
        return sb.toString();
     }
  
     protected String rtrim( String s )
     {
        if ( s == null || s.length() == 0 )
        {
           return s;
        }
  
        int pos = s.length();
        while ( pos >= 0 && Character.isWhitespace(s.charAt(pos-1)) )
        {
           --pos;
        }
        return s.substring(0, pos);
     }
  
     // ------------------------------------------------------- Package protected
     
     // ----------------------------------------------------------------- Private
     
     // ----------------------------------------------------------- Inner classes
  
     private static class StringBufferComparator
     implements Comparator
     {
        public int compare( Object o1, Object o2 )
        {
           return ((StringBuffer) o1).toString().compareTo(((StringBuffer) o2).toString());
        }
     }
  }
  
  
  
  1.2       +10 -3     jakarta-commons-sandbox/cli/src/test/org/apache/commons/cli/AllTest.java
  
  Index: AllTest.java
  ===================================================================
  RCS file: /home/cvs/jakarta-commons-sandbox/cli/src/test/org/apache/commons/cli/AllTest.java,v
  retrieving revision 1.1
  retrieving revision 1.2
  diff -u -r1.1 -r1.2
  --- AllTest.java	19 Dec 2001 18:16:25 -0000	1.1
  +++ AllTest.java	1 Feb 2002 16:28:34 -0000	1.2
  @@ -5,16 +5,21 @@
    * version 1.1, a copy of which has been included with this distribution in
    * the LICENSE file.
    * 
  - * $Id: AllTest.java,v 1.1 2001/12/19 18:16:25 jstrachan Exp $
  + * $Id: AllTest.java,v 1.2 2002/02/01 16:28:34 jstrachan Exp $
    */
   
   package org.apache.commons.cli;
   
   import junit.framework.Test;
   import junit.framework.TestSuite;
  +import junit.textui.TestRunner;
   
  -public class AllTest 
  -{
  +public class AllTest {
  +    
  +    public static void main( String[] args ) {
  +        TestRunner.run( suite() );
  +    }
  +    
       public static Test suite() { 
   
           TestSuite suite= new TestSuite(); 
  @@ -22,8 +27,10 @@
           suite.addTest(BuildTest.suite()); 
           suite.addTest(ValueTest.suite()); 
           suite.addTest(ParseTest.suite()); 
  +        suite.addTest(TestHelpFormatter.suite()); 
   
           return suite; 
       }
  +    
       
   }
  
  
  
  1.1                  jakarta-commons-sandbox/cli/src/test/org/apache/commons/cli/HelpFormatterExamples.java
  
  Index: HelpFormatterExamples.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE file.
   * 
   * $Id: HelpFormatterExamples.java,v 1.1 2002/02/01 16:28:34 jstrachan Exp $
   */
  package org.apache.commons.cli;
  
  /** 
   * A sample program shpwing the use of Options and the HelpFormatter class 
   *
   * @author Slawek Zachcial
   **/
  public class HelpFormatterExamples
  {
     // --------------------------------------------------------------- Constants
  
     // ------------------------------------------------------------------ Static
  
     public static void main( String[] args )
     {
        System.out.println("\n#\n# 'man' example\n#");
        manExample();
  /*
        System.out.println("\n#\n# 'bzip2' example\n#");
        bzip2Example();
        System.out.println("\n#\n# 'ls' example\n#");
        lsExample();
  */
     }
  
     static void manExample()
     {
        String cmdLine =
           "man [-c|-f|-k|-w|-tZT device] [-adlhu7V] [-Mpath] [-Ppager] [-Slist] " +
           "[-msystem] [-pstring] [-Llocale] [-eextension] [section] page ...";
        Options opts =
           new Options().
           addOption('a', "all",            false, "find all matching manual pages.").
           addOption('d', "debug",          false, "emit debugging messages.").
           addOption('e', "extension",      false, "limit search to extension type 'extension'.").
           addOption('f', "whatis",         false, "equivalent to whatis.").
           addOption('k', "apropos",        false, "equivalent to apropos.").
           addOption('w', "location",       false, "print physical location of man page(s).").
           addOption('l', "local-file",     false, "interpret 'page' argument(s) as local filename(s)").
           addOption('u', "update",         false, "force a cache consistency check.").
           //FIXME - should generate -r,--prompt string
           addOption('r', "prompt",         true,  "provide 'less' pager with prompt.").
           addOption('c', "catman",         false, "used by catman to reformat out of date cat pages.").
           addOption('7', "ascii",          false, "display ASCII translation or certain latin1 chars.").
           addOption('t', "troff",          false, "use troff format pages.").
           //FIXME - should generate -T,--troff-device device
           addOption('T', "troff-device",   true,  "use groff with selected device.").
           addOption('Z', "ditroff",        false, "use groff with selected device.").
           addOption('D', "default",        false, "reset all options to their default values.").
           //FIXME - should generate -M,--manpath path
           addOption('M', "manpath",        true,  "set search path for manual pages to 'path'.").
           //FIXME - should generate -P,--pager pager
           addOption('P', "pager",          true,  "use program 'pager' to display output.").
           //FIXME - should generate -S,--sections list
           addOption('S', "sections",       true,  "use colon separated section list.").
           //FIXME - should generate -m,--systems system
           addOption('m', "systems",        true,  "search for man pages from other unix system(s).").
           //FIXME - should generate -L,--locale locale
           addOption('L', "locale",         true,  "defaine the locale for this particular man search.").
           //FIXME - should generate -p,--preprocessor string
           addOption('p', "preprocessor",   true,  "string indicates which preprocessor to run.\n" +
                                                   " e - [n]eqn  p - pic     t - tbl\n" +
                                                   " g - grap    r - refer   v - vgrind").
           addOption('V', "version",        false, "show version.").
           addOption('h', "help",           false, "show this usage message.");
  
        HelpFormatter hf = new HelpFormatter();
        //hf.printHelp(cmdLine, opts);
        hf.printHelp(60, cmdLine, null, opts, null);
     }
  
     static void bzip2Example()
     {
        System.out.println( "Coming soon" );
     }
  
     static void lsExample()
     {
        System.out.println( "Coming soon" );
     }
  
  
     // -------------------------------------------------------------- Attributes
  
     // ------------------------------------------------------------ Constructors
     
     // ------------------------------------------------------------------ Public
  
     // --------------------------------------------------------------- Protected
  
     // ------------------------------------------------------- Package protected   
     
     // ----------------------------------------------------------------- Private
     
     // ----------------------------------------------------------- Inner classes
  
  }
  
  
  
  1.1                  jakarta-commons-sandbox/cli/src/test/org/apache/commons/cli/TestHelpFormatter.java
  
  Index: TestHelpFormatter.java
  ===================================================================
  /*
   * Copyright (C) The Apache Software Foundation. All rights reserved.
   *
   * This software is published under the terms of the Apache Software License
   * version 1.1, a copy of which has been included with this distribution in
   * the LICENSE file.
   * 
   * $Id: TestHelpFormatter.java,v 1.1 2002/02/01 16:28:34 jstrachan Exp $
   */
  package org.apache.commons.cli;
  
  import junit.framework.TestCase;
  import junit.framework.TestSuite;
  
  import java.io.StringWriter;
  import java.io.PrintWriter;
  
  /** 
   * Test case for the HelpFormatter class 
   *
   * @author Slawek Zachcial
   **/
  public class TestHelpFormatter
  extends TestCase
  {
     // --------------------------------------------------------------- Constants
  
     // ------------------------------------------------------------------ Static
  
     public static void main( String[] args )
     {
        String[] testName = { TestHelpFormatter.class.getName() };
        junit.textui.TestRunner.main(testName);
     }
  
     public static TestSuite suite()
     {
        return new TestSuite(TestHelpFormatter.class);
     }
  
     // -------------------------------------------------------------- Attributes
  
     // ------------------------------------------------------------ Constructors
     public TestHelpFormatter( String s )
     {
        super( s );
     }
     // ------------------------------------------------------------------ Public
  
     public void testFindWrapPos()
        throws Exception
     {
        HelpFormatter hf = new HelpFormatter();
  
        String text = "This is a test.";
        //text width should be max 8; the wrap postition is 7
        assertEquals("wrap position", 7, hf.findWrapPos(text, 8, 0));
        //starting from 8 must give -1 - the wrap pos is after end
        assertEquals("wrap position 2", -1, hf.findWrapPos(text, 8, 8));
        //if there is no a good position before width to make a wrapping look for the next one
        text = "aaaa aa";
        assertEquals("wrap position 3", 4, hf.findWrapPos(text, 3, 0));
     }
  
     public void testPrintWrapped()
        throws Exception
     {
        StringBuffer sb = new StringBuffer();
        HelpFormatter hf = new HelpFormatter();
  
        String text = "This is a test.";
        String expected;
  
        expected = "This is a" + hf.defaultNewLine + "test.";
        hf.renderWrappedText(sb, 12, 0, text);
        assertEquals("single line text", expected, sb.toString());
  
        sb.setLength(0);
        expected = "This is a" + hf.defaultNewLine + "    test.";
        hf.renderWrappedText(sb, 12, 4, text);
        assertEquals("single line padded text", expected, sb.toString());
  
        text =
           "aaaa aaaa aaaa" + hf.defaultNewLine +
           "aaaaaa" + hf.defaultNewLine +
           "aaaaa";
  
        expected = text;
        sb.setLength(0);
        hf.renderWrappedText(sb, 16, 0, text);
        assertEquals("multi line text", expected, sb.toString());
  
        expected =
           "aaaa aaaa aaaa" + hf.defaultNewLine +
           "    aaaaaa" + hf.defaultNewLine +
           "    aaaaa";
        sb.setLength(0);
        hf.renderWrappedText(sb, 16, 4, text);
        assertEquals("multi-line padded text", expected, sb.toString());
     }
  
     public void testPrintOptions()
        throws Exception
     {
        StringBuffer sb = new StringBuffer();
        HelpFormatter hf = new HelpFormatter();
        final int leftPad = 1;
        final int descPad = 3;
        final String lpad = hf.createPadding(leftPad);
        final String dpad = hf.createPadding(descPad);
        Options options = null;
        String expected = null;
  
        options = new Options().addOption('a', false, "aaaa aaaa aaaa aaaa aaaa");
        expected = lpad + "-a" + dpad + "aaaa aaaa aaaa aaaa aaaa";
        hf.renderOptions(sb, 60, options, leftPad, descPad);
        assertEquals("simple non-wrapped option", expected, sb.toString());
  
        int nextLineTabStop = leftPad+descPad+"-a".length();
        expected =
           lpad + "-a" + dpad + "aaaa aaaa aaaa" + hf.defaultNewLine +
           hf.createPadding(nextLineTabStop) + "aaaa aaaa";
        sb.setLength(0);
        hf.renderOptions(sb, nextLineTabStop+17, options, leftPad, descPad);
        assertEquals("simple wrapped option", expected, sb.toString());
  
  
        options = new Options().addOption('a', "aaa", false, "dddd dddd dddd dddd");
        expected = lpad + "-a,--aaa" + dpad + "dddd dddd dddd dddd";
        sb.setLength(0);
        hf.renderOptions(sb, 60, options, leftPad, descPad);
        assertEquals("long non-wrapped option", expected, sb.toString());
  
        nextLineTabStop = leftPad+descPad+"-a,--aaa".length();
        expected =
           lpad + "-a,--aaa" + dpad + "dddd dddd" + hf.defaultNewLine +
           hf.createPadding(nextLineTabStop) + "dddd dddd";
        sb.setLength(0);
        hf.renderOptions(sb, 25, options, leftPad, descPad);
        assertEquals("long wrapped option", expected, sb.toString());
  
        options = new Options().
           addOption('a', "aaa", false, "dddd dddd dddd dddd").
           addOption('b', false, "feeee eeee eeee eeee");
        expected =
           lpad + "-a,--aaa" + dpad + "dddd dddd" + hf.defaultNewLine +
           hf.createPadding(nextLineTabStop) + "dddd dddd" + hf.defaultNewLine +
           lpad + "-b      " + dpad + "feeee eeee" + hf.defaultNewLine +
           hf.createPadding(nextLineTabStop) + "eeee eeee";
        sb.setLength(0);
        hf.renderOptions(sb, 25, options, leftPad, descPad);
        assertEquals("multiple wrapped options", expected, sb.toString());
     }
  
     // --------------------------------------------------------------- Protected
  
     // ------------------------------------------------------- Package protected   
     
     // ----------------------------------------------------------------- Private
     
     // ----------------------------------------------------------- Inner classes
  
  }
  
  
  

--
To unsubscribe, e-mail:   <mailto:commons-dev-unsubscribe@jakarta.apache.org>
For additional commands, e-mail: <mailto:commons-dev-help@jakarta.apache.org>


Mime
View raw message