2015-06-03 43 views
0

我有點與Apache的commons-CLI V1.3掙扎選項,我還沒有發現以下問題的切實辦法尚未:的Java:Apache的公地CLI如何處理彼此依賴

我有一個命令行工具 - 根據指定的參數 - 創建一個字符串(或從本地文件中讀取它),可能對其進行內聯編輯,並可選擇顯示,將所述字符串寫入本地文件或通過HTTP發送請求到服務器。所以我有選項「c」爲「創建」,「r」爲「讀」,「e」爲「編輯」(通過cli),「d」爲顯示,「w」爲「寫」 「和」p「表示」推送到服務器「

顯然有些組合是可能的。例如。應該可以創建該字符串並將其推送出去,而無需從文件讀取或寫入文件。此外,它應該能夠創建並沒有推寫,等等...

所以參數的語義是:

("c" OR ("r" ["e"])) ["d" "w" "p"] 

很明顯,當字符串是「c」 reated,它一定不能是「r」ead。當「c」reating時,我會使用cli解析器的交互式輸入。當「r」eading時,我想讓用戶通過來自cli的交互式輸入「e」dit。其餘的參數是可選的。

Next:當「r」eading時,需要指定文件名/路徑。另外,當「w」定位時,這是必要的。無論如何,應該可以指定要從中讀取的文件以及要寫入的第二個文件。所以文件名有兩個參數,都是可選的。

產生的語法是這樣的:

tool -cp 
tool -rp "filenametoread" 
tool -rdwp "filenametoread" "filenametowrite" 
tool -cw "filenametowrite" 

等。

我在這裏有點迷路。如何將commons-cli配置爲具有兩個文件名參數,這些參數是根據指定的參數(選項)而需要的?這甚至有可能嗎?

回答

2

不幸的是,Commons CLI沒有辦法指定這樣的相互依賴的選項。爲了解決這個問題,你需要做你自己的if檢查。例如,像這樣

CommandLineParser parser = new PosixParser(); 
Options options = new Options(); 
options.addOption(new Option("h", "help", false, "display this message")); 
options.addOption(new Option("c", "create", true, "Create a file")); 
options.addOption(new Option("r", "read", truee, "Read a file")); 
options.addOption(new Option("e", "edit", false, "Edit a file")); 
options.addOption(new Option("d", "display", false, "Display a file")); 
options.addOption(new Option("w", "write", false, "Write a file")); 
options.addOption(new Option("p", "push", false, "Push a file")); 

try { 
    CommandLine commandLine = parser.parse(options, args); 
    if (commandLine.hasOption("h")) { 
     showHelp(options); 
     System.exit(0); 
    } 
    // validate the commandline 
    // obviously, these can be split up to give more helpful error messages 
    if ((!(commandLine.hasOption("c")^(commandLine.hasOption("r") || commandLine.hasOption("e")))) 
     || !(commandLine.hasOption("d")^commandLine.hasOption("w")^commandLine.hasOption("p"))) { 
     throw new ParseException("Invalid combination"); 
    } 
    if ((!commandLine.hasOption("c") && !commandLine.hasOption("r")) { 
     throw new ParseException("Missing required arg"); 
    } 

    // rest of the logic 
} catch (ParseException pe) { 
    throw new ParseException("Bad arguments\n" + pe.getMessage()); 
}