2009-05-20 13 views
3

我有一個大的(閱讀:夢魘)方法已經經過多年的成長,支持我的項目的不斷增長的命令行參數列表。我的意思是幾頁自述文檔,用於每個參數的簡要說明。掰開長的命令行測試方法

正如我添加的每個功能,我只需「註冊」的通過添加幾行,以這種方法處理這一論點的方式。

然而,該方法是目前不雅觀,容易出現錯誤,而且很難理解。下面是目前處理這兩種方法中較短的一個的例子:

//All double dash arguments modify global options of the program, 
//such as --all --debug --timeout etc. 
void consoleParser::wordArgParse(std::vector<criterion *> *results) 
{ 
    TCHAR const *compareCurWordArg = curToken.c_str()+2; 
    if (!_tcsicmp(compareCurWordArg,_T("all"))) 
    { 
     globalOptions::showall = TRUE; 
    } else if (!_tcsnicmp(compareCurWordArg,_T("custom"),6)) 
    { 
     if (curToken[9] == L':') 
     { 
      globalOptions::display = curToken.substr(10,curToken.length()-11); 
     } else 
     { 
      globalOptions::display = curToken.substr(9,curToken.length()-10); 
     } 
    } else if (*compareCurWordArg == L'c' || *compareCurWordArg == L'C') 
    { 
     if (curToken[3] == L':') 
     { 
      globalOptions::display = curToken.substr(5,curToken.length()-6); 
     } else 
     { 
      globalOptions::display = curToken.substr(4,curToken.length()-5); 
     } 
    } else if (!_tcsicmp(compareCurWordArg,_T("debug"))) 
    { 
     globalOptions::debug = TRUE; 
    } else if (!_tcsicmp(compareCurWordArg,L"expand")) 
    { 
     globalOptions::expandRegex = false; 
    } else if (!_tcsicmp(compareCurWordArg,L"fileLook")) 
    { 
     globalOptions::display = L"---- #f ----#nCompany: #d#nFile Description: #e#nFile Version: #g" 
     L"#nProduct Name: #i#nCopyright: #j#nOriginal file name: #k#nFile Size: #u#nCreated Time: #c" 
     L"#nModified Time: #m#nAccessed Time: #a#nMD5: #5#nSHA1: #1"; 
    } else if (!_tcsicmp(compareCurWordArg,_T("peinfo"))) 
    { 
     globalOptions::display = _T("[#p] #f"); 
    } else if (!_tcsicmp(compareCurWordArg,L"enable-filesystem-redirector-64")) 
    { 
     globalOptions::disable64Redirector = false; 
    } else if (!_tcsnicmp(compareCurWordArg,_T("encoding"),8)) 
    { 
     //Performance enhancement -- encoding compare only done once. 
     compareCurWordArg += 8; 
     if (!_tcsicmp(compareCurWordArg,_T("acp"))) 
     { 
      globalOptions::encoding = globalOptions::ENCODING_TYPE_ACP; 
     } else if (!_tcsicmp(compareCurWordArg,_T("oem"))) 
     { 
      globalOptions::encoding = globalOptions::ENCODING_TYPE_OEM; 
     } else if (!_tcsicmp(compareCurWordArg,_T("utf8"))) 
     { 
      globalOptions::encoding = globalOptions::ENCODING_TYPE_UTF8; 
     } else if (!_tcsicmp(compareCurWordArg,_T("utf16"))) 
     { 
      globalOptions::encoding = globalOptions::ENCODING_TYPE_UTF16; 
     } else 
     { 
      throw eMsg(L"Unrecognised encoding word argument!\r\nValid choices are --encodingACP --encodingOEM --encodingUTF8 and --encodingUTF16. Terminate."); 
     } 
    } else if (!_tcsnicmp(compareCurWordArg,L"files",5)) 
    { 
     compareCurWordArg += 5; 
     if (*compareCurWordArg == L':') compareCurWordArg++; 
     std::wstring filePath(compareCurWordArg); 
     globalOptions::regexes.insert(globalOptions::regexes.end(), new filesRegexPlaceHolder); 
     results->insert(results->end(),new filesRegexPlaceHolder); 
     boost::algorithm::trim_if(filePath,std::bind2nd(std::equal_to<wchar_t>(),L'"')); 
     loadFiles(filePath); 
    } else if (!_tcsicmp(compareCurWordArg,_T("full"))) 
    { 
     globalOptions::fullPath = TRUE; 
    } else if (!_tcsicmp(compareCurWordArg,_T("fs32"))) 
    { 
     globalOptions::disable64Redirector = false; 
    } else if (!_tcsicmp(compareCurWordArg,_T("long"))) 
    { 
     globalOptions::display = _T("#t #s #m #f"); 
     globalOptions::summary = TRUE; 
    } else if (!_tcsnicmp(compareCurWordArg,_T("limit"),5)) 
    { 
     compareCurWordArg += 5; 
     if (*compareCurWordArg == _T(':')) 
      compareCurWordArg++; 
     globalOptions::lineLimit = _tcstoui64(compareCurWordArg,NULL,10); 
     if (!globalOptions::lineLimit) 
     { 
      std::wcerr << eMsg(L"Warning: You are limiting to infinity lines. Check one of your --limit options!\r\n"); 
     } 
    } else if (!_tcsicmp(compareCurWordArg,_T("short"))) 
    { 
     globalOptions::display = _T("#8"); 
    } else if (!_tcsicmp(compareCurWordArg,_T("summary"))) 
    { 
     globalOptions::summary = TRUE; 
    } else if (!_tcsicmp(compareCurWordArg,_T("norecursion"))) 
    { 
     globalOptions::noSubDirs = TRUE; 
    } else if (!_tcsnicmp(compareCurWordArg,_T("timeout"),7)) 
    { 
     compareCurWordArg += 7; 
     if (*compareCurWordArg == _T(':')) 
      compareCurWordArg++; 
     globalOptions::timeout = _tcstoul(compareCurWordArg,NULL,10); 
     if (!globalOptions::timeout) 
     { 
      std::wcerr << eMsg(L"Warning: You are limiting to infinite time. Check one of your --timeout options!\r\n"); 
     } 
    } else if (!_tcsnicmp(compareCurWordArg,_T("tx"),2)) 
    { 
     compareCurWordArg += 2; 
     if (*compareCurWordArg == _T(':')) 
      compareCurWordArg++; 
     globalOptions::timeout = _tcstoul(compareCurWordArg,NULL,10); 
     if (!globalOptions::timeout) 
     { 
      std::wcerr << eMsg(L"Warning: You are limiting to infinite time. Check one of your --timeout options!\r\n"); 
     } 
    } else 
    { 
     throw eMsg(L"Could not understand word argument! Ensure all of your directives are spelled correctly. Terminate."); 
    } 
} 

我會張貼長一個,但它超過500行。

是處理這方面的問題有更好的方法,或者我應該只是把它作爲一個長期的方法?

編輯:我不是在尋找一個符號化庫 - 我已經做了的骯髒的工作。我很好奇,如果用更大的骯髒方法制作存根方法是有意義的。

Billy3

回答

5

我敢肯定,還有的getopt(3)函數用於Windows的等效。 這是Google的第一個熱門遊戲 - Pete Wilson。 或者你可以看看Boost Program Options一個體面的C++庫。

+0

增強庫(我已經使用boost)支持讀取以下作爲一個單一論據? [-files「C:\ Documents and Settings \ User \ Desktop \ InFile.txt」]請注意令牌如何不被引用,並且確實包含空格。引號在標記本身內部開始。 – 2009-05-20 02:35:04

+0

嘗試一下,它的使用非常簡單。 – 2009-05-20 03:19:31

2

什麼你需要是command line option parser library採取的處理命令行參數的繁瑣的細節關懷。

我不確定哪一個對C++來說是最好的,因爲我是一個C#開發人員,他使用CSharpOptParse ...但這個概念應該是相同的,所以希望知道要查找什麼會指向正確的方向。

0

HI所有,我寫這個小幫手與命令行工作。我還更新了它與時髦: - 文件'東西'並按提問者需求分開。 爲了讓它使用另一種字符類型,只需使用正在使用的字符替換字符類型即可。這是一個完整的工作示例,您可以將其粘貼到main.cpp中並運行。 代碼做了適當的轉義,引用,和:and ='「作爲名稱/值分隔符的args,所以你可以做--flag:1或者-file」c:\ test「。注意空間用作選項分隔符。它看起來像這樣使用它的代碼:

optparse opt(argstring);
g_someint = strtoul(opt.get('--debuglevel','0'),0,0);
g_somebool = opt.get('--flag')!=0;
g_somestring = opt.get('--file','default.txt')

要回答這個問題:你可以看到,這使得你的論點處理代碼那麼簡單,你真的不需要模塊化是它的可讀性和可維護

#include <string.h> 
#include <stdio.h> 

struct optparse{ 
    optparse(const char *args, size_t len = 0) : first(0) { 
     size_t i; 
     if(!args)args = ""; 
     if(!len)for(;args[len];len++); 
     for(buf=new char[len+1],i=0;i<len;i++)buf[i]=args[i];buf[i]=0; 
     opt *last = first; 
     char *c = buf, *b = c, *v = 0, g = 0, e = 0; 
     do{ 
      if(*c=='\\') e = e?0:1; 
      else if(e?--e:1){ 
       if(g){ if(*c == g) g = 0; } 
       else {  
        if(*c=='"' || *c=='\''){ if(b<c && !v) v = c; g = *c; } 
        else if(!v && (*c==':' || *c=='=')) v = c; 
        else if(*c==' '){      
         if(b<c)last = new opt(last,&first,b,c,v); 
         b = c+1, v = 0; 
        } 
       } 
      } 
      if(*c) c++; 
      if(!*c && b<c) last = new opt(last,&first,b,c,v); 
     }while(*c); 
     for(opt *i = first; i; i = i->next) *(i->ne) = 0, *(i->ve) = 0; 
    } 
    ~optparse(){ 
     delete buf; 
     while(first){ 
      opt *t = first->next; 
      delete first; 
      first = t ; 
     } 
    } 

    const char *get(const char *name, const char *def= 0){ 
     size_t l = strlen(name); 
     for(opt *i = first;i;i = i->next) if(_strnicmp(i->name, name, l) == 0) 
      return i->value; 
     return def; 
    } 

    struct opt{ 
     opt(opt *last, opt **first, char *s, char *e, char *v){ 
      if(!*first) *first = this; if(last) last->next = this; 
      if(v && (*v=='\'' || *v=='"') && (*(e-1)=='\'' || *(e-1) == '"'))e--; 
      next = 0, name = s, value = v?v+1:"", ne = v?v:e, ve = e; 
     } 
     char *name, *value, *ne, *ve; 
     opt *next; 
    }; 
    char *buf; 
    opt *first; 
}; 

int main(){ 

    const char *v, *test ="--debug:1 -file'c:\\something' --odd=10"; 
    optparse opts(test); 

    if(v = opts.get("--debug")){ 
     printf("debug flag value is %s\n",v); 
    } 

    for(optparse::opt *i=opts.first;i;i=i->next){ 
     printf("name: %s value: %s\n",i->name,i->value); 
    } 
} 

解析器很容易調整以支持不同類型的參數處理。 例如,如果你有

if(*b=='-' && *(c+1)!='-')v = v?v:c; 
else{ 
    if(b<c)last = new opt(last,&first,b,c,v); 
    b = c+1, v = 0; 
} 

您將增加參加空間分割參數像「價值」的功能替代

if(b<c)last = new opt(last,&first,b,c,v); 
b = c+1, v = 0; 

:-debug 1 或--files A.TXT b.txt c。txt 此外,如果你不喜歡:作爲一個拆分參數(可能是麻煩在Windows應用程序)只是刪除==':'