| /********************************************************************** |
| * Copyright (c) 2002, 2005 IBM Corporation and others. |
| * All rights reserved. This program and the accompanying materials |
| * are made available under the terms of the Common Public License v1.0 |
| * which accompanies this distribution, and is available at |
| * http://www.eclipse.org/legal/cpl-v10.html |
| * |
| * Contributors: |
| * IBM - Initial API and implementation |
| **********************************************************************/ |
| |
| package org.eclipse.wtp.releng.tools.component.util; |
| |
| import java.util.ArrayList; |
| import java.util.HashMap; |
| import java.util.List; |
| import java.util.Map; |
| |
| /** |
| * The command line parser can parse simple command lines into |
| * a list of options and arguments. |
| * |
| * Consider the following arguments as an example: |
| * -myOpt myValue -myOptNoValue -myOpt2 myValue2 myArg1 myArg2 |
| * |
| * Options in the above command line are: |
| * [myOpt, myValue] |
| * [myOptNoValue, null] |
| * [myOpt2, myValue2] |
| * |
| * Arguments are: |
| * myArg1, myArg2 |
| * |
| * The algorithm used supports options without values, but only |
| * before other options. The delimiter for options is hardcoded to |
| * be '-'. |
| */ |
| public class CommandLineParser { |
| private String fDelimiter= "-"; |
| |
| private Map fOptions; |
| private List fArguments; |
| |
| /** |
| * Creates a new command line parser on the given arguments. |
| * @param args the arguments to be parsed, not <code>null</code>. |
| */ |
| public CommandLineParser(String[] args) { |
| parse(args); |
| } |
| |
| /** |
| * Answers the key-value pairs of options. |
| * Note: The delimiter '-' will be removed from the names |
| * of all options. |
| * @return Map the options, or an empty map, not <code>null</code>. |
| */ |
| public Map getOptions() { |
| return fOptions; |
| } |
| |
| /** |
| * Answers the list of arguments. |
| * @return List the list of arguments or an empty list, not <code>null</code>. |
| */ |
| public List getArguments() { |
| return fArguments; |
| } |
| |
| private void parse(String[] args) { |
| fOptions= new HashMap(); |
| fArguments= new ArrayList(); |
| String argument= null; |
| for(int i= 0; i < args.length; i++) { |
| String arg= args[i]; |
| if (arg != null) { |
| if (arg.startsWith(fDelimiter)) { |
| argument= arg.substring(1); |
| fOptions.put(argument, null); |
| } else { |
| if (argument == null) { |
| for(; i < args.length; i++) { |
| fArguments.add(args[i]); |
| } |
| } else { |
| fOptions.put(argument, arg); |
| argument= null; |
| } |
| } |
| } |
| } |
| } |
| } |