001/**
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *     http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.cli2;
018
019import java.io.IOException;
020import java.io.PrintWriter;
021import java.io.StringWriter;
022import java.util.ArrayList;
023import java.util.Iterator;
024import java.util.List;
025
026import junit.framework.TestCase;
027
028import org.apache.commons.cli2.builder.ArgumentBuilder;
029import org.apache.commons.cli2.builder.DefaultOptionBuilder;
030import org.apache.commons.cli2.builder.GroupBuilder;
031import org.apache.commons.cli2.commandline.Parser;
032import org.apache.commons.cli2.commandline.WriteableCommandLineImpl;
033import org.apache.commons.cli2.option.DefaultOption;
034import org.apache.commons.cli2.option.PropertyOption;
035import org.apache.commons.cli2.util.HelpFormatter;
036
037/**
038 * @author Rob
039 */
040public class DocumentationTest extends TestCase {
041
042    public void testBasicUsage() throws IOException, OptionException {
043        HelpFormatter helpFormatter = new HelpFormatter();
044        //ignore all printed
045        helpFormatter.setPrintWriter(new PrintWriter(new StringWriter()));
046
047        /*
048         * --version -? -h --help -log file -s|-q|-v|-d Bursting File/Num/Date
049         * validation Switches Commands Auto help Auto exception help
050         *
051         */
052        DefaultOptionBuilder obuilder = new DefaultOptionBuilder();
053        Option version =
054            obuilder
055                .withLongName("version")
056                .withDescription("Displays version information and then exits")
057                .create();
058
059        Option help =
060            obuilder
061                .withShortName("h")
062                .withShortName("?")
063                .withLongName("help")
064                .withDescription("Displays help on usage and then exits")
065                .create();
066
067        ArgumentBuilder abuilder = new ArgumentBuilder();
068        Argument logFile =
069            abuilder
070                .withDescription("The log file to write to")
071                .withName("file")
072                .withMinimum(1)
073                .withMaximum(1)
074                .create();
075        Option log =
076            obuilder
077                .withArgument(logFile)
078                .withShortName("log")
079                .withDescription("Log progress information to a file")
080                .create();
081
082        GroupBuilder gbuilder = new GroupBuilder();
083        Group outputQuality =
084            gbuilder
085                .withName("quality")
086                .withDescription("Controls the quality of console output")
087                .withMaximum(1)
088                .withOption(
089                    obuilder
090                        .withShortName("s")
091                        .withDescription("Silent")
092                        .create())
093                .withOption(
094                    obuilder
095                        .withShortName("q")
096                        .withDescription("Quiet")
097                        .create())
098                .withOption(
099                    obuilder
100                        .withShortName("n")
101                        .withDescription("Normal")
102                        .create())
103                .withOption(
104                    obuilder
105                        .withShortName("v")
106                        .withDescription("Verbose")
107                        .create())
108                .withOption(
109                    obuilder
110                        .withShortName("d")
111                        .withDescription("Debug")
112                        .create())
113                .create();
114
115        Group options =
116            new GroupBuilder()
117                .withName("options")
118                .withOption(version)
119                .withOption(help)
120                .withOption(log)
121                .withOption(outputQuality)
122                .create();
123
124        final String[] args = new String[] { "--bad-option" };
125
126        Parser parser = new Parser();
127        parser.setHelpFormatter(helpFormatter);
128        parser.setGroup(options);
129        parser.setHelpOption(help);
130        CommandLine commandLine = parser.parseAndHelp(args);
131        if (commandLine != null) {
132            if (commandLine.hasOption(version)) {
133                System.out.println("MyApp ver 1.0");
134                return;
135            }
136            if (commandLine.hasOption("-log")) {
137                String filename = (String)commandLine.getValue("-log");
138                //...
139            }
140        }
141
142        try {
143            commandLine = parser.parse(args);
144            fail("Unexpected Option!");
145        }
146        catch (OptionException uoe) {
147            assertEquals(
148                "Unexpected --bad-option while processing options",
149                uoe.getMessage());
150        }
151    }
152
153    public void testManualIntroduction() {
154
155        DefaultOptionBuilder oBuilder = new DefaultOptionBuilder();
156        ArgumentBuilder aBuilder = new ArgumentBuilder();
157        GroupBuilder gBuilder = new GroupBuilder();
158
159        DefaultOption xmlOption =
160            oBuilder
161                .withLongName("xml")
162                .withDescription("Output using xml format")
163                .create();
164
165        Argument pathArgument =
166            aBuilder
167                .withName("path")
168                .withMinimum(1)
169                .withMaximum(1)
170                .create();
171
172        Group outputChildren =
173            gBuilder
174                .withOption(xmlOption)
175                .create();
176
177        Option outputOption =
178            oBuilder
179                .withLongName("output")
180                .withDescription("Outputs to a file")
181                .withArgument(pathArgument)
182                .withChildren(outputChildren)
183                .create();
184
185        ///////////////////////////////////////////////////
186
187        Group options = outputChildren;
188        HelpFormatter hf = new HelpFormatter();
189
190        Parser p = new Parser();
191        p.setGroup(options);
192        p.setHelpFormatter(hf);
193        p.setHelpTrigger("--help");
194        CommandLine cl = p.parseAndHelp(new String[]{});
195        if(cl==null) {
196            System.exit(-1);
197        }
198
199        //////////////////////////////////////////////////
200
201        cl = new WriteableCommandLineImpl(outputChildren,new ArrayList());
202
203        // if we have --output option
204        if(cl.hasOption("--output")) {
205            // grab the path
206            String path = (String)cl.getValue("--output");
207            // grab the format
208            boolean xml = cl.hasOption("--xml");
209            // configure the application's output
210            configureOutput(path,xml);
211        }
212
213
214
215
216    }
217
218    private void configureOutput(String path, boolean xml) {
219        // TODO Auto-generated method stub
220
221    }
222
223    public void testExampleAnt() throws IOException, OptionException {
224        // Apache Ant version 1.6.1 compiled on February 12 2004
225
226        final DefaultOptionBuilder obuilder = new DefaultOptionBuilder();
227        final ArgumentBuilder abuilder = new ArgumentBuilder();
228        final GroupBuilder gbuilder = new GroupBuilder();
229
230        Option help =
231            obuilder
232                .withShortName("help")
233                .withShortName("h")
234                .withDescription("print this message")
235                .create();
236        Option projecthelp =
237            obuilder
238                .withShortName("projecthelp")
239                .withShortName("p")
240                .withDescription("print project help information")
241                .create();
242        Option version =
243            obuilder
244                .withShortName("version")
245                .withDescription("print the version information and exit")
246                .create();
247        Option diagnostics =
248            obuilder
249                .withShortName("diagnostics")
250                .withDescription("print information that might be helpful to diagnose or report problems.")
251                .create();
252        Option quiet =
253            obuilder
254                .withShortName("quiet")
255                .withShortName("q")
256                .withDescription("be extra quiet")
257                .create();
258        Option verbose =
259            obuilder
260                .withShortName("verbose")
261                .withShortName("v")
262                .withDescription("be extra verbose")
263                .create();
264        Option debug =
265            obuilder
266                .withShortName("debug")
267                .withShortName("d")
268                .withDescription("print debugging information")
269                .create();
270        Option emacs =
271            obuilder
272                .withShortName("emacs")
273                .withShortName("e")
274                .withDescription("produce logging information without adornments")
275                .create();
276        Option lib =
277            obuilder
278                .withShortName("lib")
279                .withDescription("specifies a path to search for jars and classes")
280                .withArgument(
281                    abuilder
282                        .withName("path")
283                        .withMinimum(1)
284                        .withMaximum(1)
285                        .create())
286                .create();
287        Option logfile =
288            obuilder
289                .withShortName("logfile")
290                .withShortName("l")
291                .withDescription("use given file for log")
292                .withArgument(
293                    abuilder
294                        .withName("file")
295                        .withMinimum(1)
296                        .withMaximum(1)
297                        .create())
298                .create();
299        Option logger =
300            obuilder
301                .withShortName("logger")
302                .withDescription("the class which is to perform logging")
303                .withArgument(
304                    abuilder
305                        .withName("classname")
306                        .withMinimum(1)
307                        .withMaximum(1)
308                        .create())
309                .create();
310        Option listener =
311            obuilder
312                .withShortName("listener")
313                .withDescription("add an instance of class as a project listener")
314                .withArgument(
315                    abuilder
316                        .withName("classname")
317                        .withMinimum(1)
318                        .withMaximum(1)
319                        .create())
320                .create();
321        Option noinput =
322            obuilder
323                .withShortName("noinput")
324                .withDescription("do not allow interactive input")
325                .create();
326        Option buildfile =
327            obuilder
328                .withShortName("buildfile")
329                .withShortName("file")
330                .withShortName("f")
331                .withDescription("use given buildfile")
332                .withArgument(
333                    abuilder
334                        .withName("file")
335                        .withMinimum(1)
336                        .withMaximum(1)
337                        .create())
338                .create();
339        Option property = new PropertyOption();
340        Option propertyfile =
341            obuilder
342                .withShortName("propertyfile")
343                .withDescription("load all properties from file with -D properties taking precedence")
344                .withArgument(
345                    abuilder
346                        .withName("name")
347                        .withMinimum(1)
348                        .withMaximum(1)
349                        .create())
350                .create();
351        Option inputhandler =
352            obuilder
353                .withShortName("inputhandler")
354                .withDescription("the class which will handle input requests")
355                .withArgument(
356                    abuilder
357                        .withName("class")
358                        .withMinimum(1)
359                        .withMaximum(1)
360                        .create())
361                .create();
362        Option find =
363            obuilder
364                .withShortName("find")
365                .withShortName("s")
366                .withDescription("search for buildfile towards the root of the filesystem and use it")
367                .withArgument(
368                    abuilder
369                        .withName("file")
370                        .withMinimum(1)
371                        .withMaximum(1)
372                        .create())
373                .create();
374        Option targets = abuilder.withName("target").create();
375
376        Group options =
377            gbuilder
378                .withName("options")
379                .withOption(help)
380                .withOption(projecthelp)
381                .withOption(version)
382                .withOption(diagnostics)
383                .withOption(quiet)
384                .withOption(verbose)
385                .withOption(debug)
386                .withOption(emacs)
387                .withOption(lib)
388                .withOption(logfile)
389                .withOption(logger)
390                .withOption(listener)
391                .withOption(noinput)
392                .withOption(buildfile)
393                .withOption(property)
394                .withOption(propertyfile)
395                .withOption(inputhandler)
396                .withOption(find)
397                .withOption(targets)
398                .create();
399
400        /////////////////////////////////////
401        String[] args = new String[]{};
402
403        Parser parser = new Parser();
404        parser.setGroup(options);
405        CommandLine cl = parser.parse(args);
406
407        if(cl.hasOption(help)) {
408            //displayHelp();
409            return;
410        }
411        if(cl.hasOption("-version")) {
412            //displayVersion();
413            return;
414        }
415        if(cl.hasOption(logfile)) {
416            String file = (String)cl.getValue(logfile);
417            //setLogFile();
418        }
419        List targetList = cl.getValues(targets);
420        for (Iterator i = targetList.iterator(); i.hasNext();) {
421            String target = (String) i.next();
422            //doTarget(target);
423        }
424
425        /////////////////////////////////////
426
427        HelpFormatter hf = new HelpFormatter();
428        hf.setShellCommand("ant");
429        hf.getFullUsageSettings().add(DisplaySetting.DISPLAY_GROUP_NAME);
430        hf.getFullUsageSettings().add(DisplaySetting.DISPLAY_GROUP_ARGUMENT);
431        hf.getFullUsageSettings().remove(DisplaySetting.DISPLAY_GROUP_EXPANDED);
432
433        hf.getLineUsageSettings().add(DisplaySetting.DISPLAY_PROPERTY_OPTION);
434        hf.getLineUsageSettings().add(DisplaySetting.DISPLAY_PARENT_ARGUMENT);
435        hf.getLineUsageSettings().add(DisplaySetting.DISPLAY_ARGUMENT_BRACKETED);
436
437        hf.getDisplaySettings().remove(DisplaySetting.DISPLAY_GROUP_ARGUMENT);
438
439        hf.setGroup(options);
440        // redirect printed stuff to a string
441        hf.setPrintWriter(new PrintWriter(new StringWriter()));
442        hf.print();
443
444    }
445}