diff options
Diffstat (limited to 'src/org/libreoffice/tools/options/Command.java')
-rw-r--r-- | src/org/libreoffice/tools/options/Command.java | 80 |
1 files changed, 80 insertions, 0 deletions
diff --git a/src/org/libreoffice/tools/options/Command.java b/src/org/libreoffice/tools/options/Command.java new file mode 100644 index 0000000..2dd9095 --- /dev/null +++ b/src/org/libreoffice/tools/options/Command.java @@ -0,0 +1,80 @@ +package org.libreoffice.tools.options; + +import java.util.Collection; +import java.util.HashMap; + +import org.apache.commons.cli.CommandLine; +import org.apache.commons.cli.CommandLineParser; +import org.apache.commons.cli.Option; +import org.apache.commons.cli.OptionGroup; +import org.apache.commons.cli.Options; +import org.apache.commons.cli.ParseException; + +public class Command { + + private HashMap< String, SubCommand > mCommands; + private Options mCommonOptions; + + public Command( ) { + mCommands = new HashMap<String, SubCommand>(); + } + + public void addCommand( SubCommand pCommand ) { + if ( !mCommands.containsKey( pCommand.getName() ) ) { + mCommands.put( pCommand.getName(), pCommand ); + } + } + + public void removeCommand( String pCommandName ) { + mCommands.remove( pCommandName ); + } + + public Collection< SubCommand > getCommands( ) { + return mCommands.values(); + } + + public void setCommonOptions( Options pOptions ) { + mCommonOptions = pOptions; + } + + public Options getCommonOptions( ) { + return mCommonOptions; + } + + public SubcommandLine parse( String[] pArguments, CommandLineParser pParser ) throws ParseException { + if ( pArguments.length < 1 ) { + throw new ParseException( "No sub-command" ); + } + String subcommand = pArguments[0]; + + // Compute the final options list: common + subcommand + Options allOptions = new Options(); + addAllOptions( allOptions, mCommonOptions ); + + SubCommand def = mCommands.get( subcommand ); + if ( def == null ) { + throw new ParseException( "Invalid sub-command: " + subcommand ); + } + + addAllOptions( allOptions, def.getOptions() ); + + // Get only the subcommand arguments + String[] subCommandArguments = new String[ pArguments.length - 1 ]; + System.arraycopy( pArguments, 1, subCommandArguments, 0, subCommandArguments.length ); + + // Parse + CommandLine cmdline = pParser.parse( allOptions, subCommandArguments ); + + return new SubcommandLine( subcommand, cmdline ); + } + + private void addAllOptions(Options pAllOptions, Options pCommonOptions) { + for ( Object opt : pCommonOptions.getOptions() ) { + if ( opt instanceof Option ) { + pAllOptions.addOption( ( Option ) opt ); + } else if ( opt instanceof OptionGroup ) { + pAllOptions.addOptionGroup( (OptionGroup ) opt ); + } + } + } +} |