Cleanup & indent .h files

This commit is contained in:
Philippe Vaucher
2014-03-19 11:39:10 +01:00
parent 460205e943
commit 7da25fc0df
43 changed files with 5827 additions and 5733 deletions

View File

@@ -31,45 +31,67 @@ extern "C" {
#include "trex.h" #include "trex.h"
} }
struct TRexParseException{TRexParseException(const TRexChar *c):desc(c){}const TRexChar *desc;}; struct TRexParseException
{
TRexParseException(const TRexChar *c):desc(c) {} const TRexChar *desc;
};
class TRexpp { class TRexpp
public: {
TRexpp() { _exp = (TRex *)0; } public:
~TRexpp() { CleanUp(); } TRexpp()
// compiles a regular expression {
void Compile(const TRexChar *pattern) { _exp = (TRex *)0;
const TRexChar *error; }
CleanUp(); ~TRexpp()
if(!(_exp = trex_compile(pattern,&error))) {
throw TRexParseException(error); CleanUp();
} }
// return true if the given text match the expression // compiles a regular expression
bool Match(const TRexChar* text) { void Compile(const TRexChar *pattern)
return _exp?(trex_match(_exp,text) != 0):false; {
} const TRexChar *error;
// Searches for the first match of the expression in a zero terminated string CleanUp();
bool Search(const TRexChar* text, const TRexChar** out_begin, const TRexChar** out_end) { if(!(_exp = trex_compile(pattern,&error)))
return _exp?(trex_search(_exp,text,out_begin,out_end) != 0):false; throw TRexParseException(error);
} }
// Searches for the first match of the expression in a string sarting at text_begin and ending at text_end // return true if the given text match the expression
bool SearchRange(const TRexChar* text_begin,const TRexChar* text_end,const TRexChar** out_begin, const TRexChar** out_end) { bool Match(const TRexChar* text)
return _exp?(trex_searchrange(_exp,text_begin,text_end,out_begin,out_end) != 0):false; {
} return _exp?(trex_match(_exp,text) != 0):false;
bool GetSubExp(int n, const TRexChar** out_begin, int *out_len) }
{ // Searches for the first match of the expression in a zero terminated string
TRexMatch match; bool Search(const TRexChar* text, const TRexChar** out_begin, const TRexChar** out_end)
TRexBool res = _exp?(trex_getsubexp(_exp,n,&match)):TRex_False; {
if(res) { return _exp?(trex_search(_exp,text,out_begin,out_end) != 0):false;
*out_begin = match.begin; }
*out_len = match.len; // Searches for the first match of the expression in a string sarting at text_begin and ending at text_end
return true; bool SearchRange(const TRexChar* text_begin,const TRexChar* text_end,const TRexChar** out_begin, const TRexChar** out_end)
} {
return false; return _exp?(trex_searchrange(_exp,text_begin,text_end,out_begin,out_end) != 0):false;
} }
int GetSubExpCount() { return _exp?trex_getsubexpcount(_exp):0; } bool GetSubExp(int n, const TRexChar** out_begin, int *out_len)
private: {
void CleanUp() { if(_exp) trex_free(_exp); _exp = (TRex *)0; } TRexMatch match;
TRex *_exp; TRexBool res = _exp?(trex_getsubexp(_exp,n,&match)):TRex_False;
if(res)
{
*out_begin = match.begin;
*out_len = match.len;
return true;
}
return false;
}
int GetSubExpCount()
{
return _exp?trex_getsubexpcount(_exp):0;
}
private:
void CleanUp()
{
if(_exp) trex_free(_exp);
_exp = (TRex *)0;
}
TRex *_exp;
}; };
#endif //_TREXPP_H_ #endif //_TREXPP_H_

View File

@@ -37,8 +37,8 @@ struct AlprPlate
struct AlprCoordinate struct AlprCoordinate
{ {
int x; int x;
int y; int y;
}; };
class AlprResult class AlprResult

View File

@@ -32,9 +32,9 @@ using namespace cv;
enum NiblackVersion enum NiblackVersion
{ {
NIBLACK=0, NIBLACK=0,
SAUVOLA, SAUVOLA,
WOLFJOLION, WOLFJOLION,
}; };
#define BINARIZEWOLF_VERSION "2.3 (February 26th, 2013)" #define BINARIZEWOLF_VERSION "2.3 (February 26th, 2013)"
@@ -49,7 +49,7 @@ enum NiblackVersion
void NiblackSauvolaWolfJolion (Mat im, Mat output, NiblackVersion version, void NiblackSauvolaWolfJolion (Mat im, Mat output, NiblackVersion version,
int winx, int winy, float k); int winx, int winy, float k);

View File

@@ -24,8 +24,7 @@
#define cJSON__h #define cJSON__h
#ifdef __cplusplus #ifdef __cplusplus
extern "C" extern "C" {
{
#endif #endif
/* cJSON Types: */ /* cJSON Types: */
@@ -40,22 +39,24 @@ extern "C"
#define cJSON_IsReference 256 #define cJSON_IsReference 256
/* The cJSON structure: */ /* The cJSON structure: */
typedef struct cJSON { typedef struct cJSON
struct cJSON *next,*prev; /* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */ {
struct cJSON *child; /* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */ struct cJSON *next,*prev; /* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */
struct cJSON *child; /* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */
int type; /* The type of the item, as above. */ int type; /* The type of the item, as above. */
char *valuestring; /* The item's string, if type==cJSON_String */ char *valuestring; /* The item's string, if type==cJSON_String */
int valueint; /* The item's number, if type==cJSON_Number */ int valueint; /* The item's number, if type==cJSON_Number */
double valuedouble; /* The item's number, if type==cJSON_Number */ double valuedouble; /* The item's number, if type==cJSON_Number */
char *string; /* The item's name string, if this item is the child of, or is in the list of subitems of an object. */ char *string; /* The item's name string, if this item is the child of, or is in the list of subitems of an object. */
} cJSON; } cJSON;
typedef struct cJSON_Hooks { typedef struct cJSON_Hooks
void *(*malloc_fn)(size_t sz); {
void (*free_fn)(void *ptr); void *(*malloc_fn)(size_t sz);
void (*free_fn)(void *ptr);
} cJSON_Hooks; } cJSON_Hooks;
/* Supply malloc, realloc and free functions to cJSON */ /* Supply malloc, realloc and free functions to cJSON */

View File

@@ -110,7 +110,7 @@ class Config
string getPostProcessRuntimeDir(); string getPostProcessRuntimeDir();
string getTessdataPrefix(); string getTessdataPrefix();
private: private:
CSimpleIniA* ini; CSimpleIniA* ini;
string runtimeBaseDir; string runtimeBaseDir;

View File

@@ -23,7 +23,7 @@
#define POSTPROCESS_DIR "/postprocess" #define POSTPROCESS_DIR "/postprocess"
#ifndef DEFAULT_RUNTIME_DIR #ifndef DEFAULT_RUNTIME_DIR
#define DEFAULT_RUNTIME_DIR "/default_runtime_data_dir/" #define DEFAULT_RUNTIME_DIR "/default_runtime_data_dir/"
#endif #endif
#define ENV_VARIABLE_RUNTIME_DIR "OPENALPR_RUNTIME_DIR" #define ENV_VARIABLE_RUNTIME_DIR "OPENALPR_RUNTIME_DIR"

View File

@@ -38,7 +38,8 @@ using namespace std;
struct RecognitionResult { struct RecognitionResult
{
bool haswinner; bool haswinner;
string winner; string winner;
int confidence; int confidence;
@@ -54,7 +55,7 @@ class FeatureMatcher
RecognitionResult recognize( const Mat& queryImg, bool drawOnImage, Mat* outputImage, RecognitionResult recognize( const Mat& queryImg, bool drawOnImage, Mat* outputImage,
bool debug_on, vector<int> debug_matches_array ); bool debug_on, vector<int> debug_matches_array );
bool loadRecognitionSet(string country); bool loadRecognitionSet(string country);
@@ -83,7 +84,7 @@ class FeatureMatcher
void surfStyleMatching( const Mat& queryDescriptors, vector<KeyPoint> queryKeypoints, void surfStyleMatching( const Mat& queryDescriptors, vector<KeyPoint> queryKeypoints,
vector<DMatch>& matches12 ); vector<DMatch>& matches12 );
}; };

View File

@@ -23,8 +23,8 @@
#ifndef OCR_H #ifndef OCR_H
#define OCR_H #define OCR_H
#include <iostream> #include <iostream>
#include <stdio.h> #include <stdio.h>
#include "utility.h" #include "utility.h"
#include "postprocess.h" #include "postprocess.h"

View File

@@ -21,13 +21,13 @@
#ifndef POSTPROCESS_H #ifndef POSTPROCESS_H
#define POSTPROCESS_H #define POSTPROCESS_H
#include "TRexpp.h" #include "TRexpp.h"
#include "constants.h" #include "constants.h"
#include "utility.h" #include "utility.h"
#include <fstream> #include <fstream>
#include <iostream> #include <iostream>
#include <stdio.h> #include <stdio.h>
#include <vector> #include <vector>
#include "config.h" #include "config.h"
using namespace std; using namespace std;
@@ -37,17 +37,17 @@ using namespace std;
struct Letter struct Letter
{ {
char letter; char letter;
int charposition; int charposition;
float totalscore; float totalscore;
int occurences; int occurences;
}; };
struct PPResult struct PPResult
{ {
string letters; string letters;
float totalscore; float totalscore;
bool matchesTemplate; bool matchesTemplate;
}; };

View File

@@ -99,16 +99,18 @@ typedef unsigned char Boolean; /* 0 or 1 */
#define UNI_MAX_UTF32 (UTF32)0x7FFFFFFF #define UNI_MAX_UTF32 (UTF32)0x7FFFFFFF
#define UNI_MAX_LEGAL_UTF32 (UTF32)0x0010FFFF #define UNI_MAX_LEGAL_UTF32 (UTF32)0x0010FFFF
typedef enum { typedef enum
conversionOK, /* conversion successful */ {
sourceExhausted, /* partial character in source, but hit end */ conversionOK, /* conversion successful */
targetExhausted, /* insuff. room in target for conversion */ sourceExhausted, /* partial character in source, but hit end */
sourceIllegal /* source sequence is illegal/malformed */ targetExhausted, /* insuff. room in target for conversion */
sourceIllegal /* source sequence is illegal/malformed */
} ConversionResult; } ConversionResult;
typedef enum { typedef enum
strictConversion = 0, {
lenientConversion strictConversion = 0,
lenientConversion
} ConversionFlags; } ConversionFlags;
/* This is for C++ and does no harm in C */ /* This is for C++ and does no harm in C */
@@ -117,28 +119,28 @@ extern "C" {
#endif #endif
ConversionResult ConvertUTF8toUTF16 ( ConversionResult ConvertUTF8toUTF16 (
const UTF8** sourceStart, const UTF8* sourceEnd, const UTF8** sourceStart, const UTF8* sourceEnd,
UTF16** targetStart, UTF16* targetEnd, ConversionFlags flags); UTF16** targetStart, UTF16* targetEnd, ConversionFlags flags);
ConversionResult ConvertUTF16toUTF8 ( ConversionResult ConvertUTF16toUTF8 (
const UTF16** sourceStart, const UTF16* sourceEnd, const UTF16** sourceStart, const UTF16* sourceEnd,
UTF8** targetStart, UTF8* targetEnd, ConversionFlags flags); UTF8** targetStart, UTF8* targetEnd, ConversionFlags flags);
ConversionResult ConvertUTF8toUTF32 ( ConversionResult ConvertUTF8toUTF32 (
const UTF8** sourceStart, const UTF8* sourceEnd, const UTF8** sourceStart, const UTF8* sourceEnd,
UTF32** targetStart, UTF32* targetEnd, ConversionFlags flags); UTF32** targetStart, UTF32* targetEnd, ConversionFlags flags);
ConversionResult ConvertUTF32toUTF8 ( ConversionResult ConvertUTF32toUTF8 (
const UTF32** sourceStart, const UTF32* sourceEnd, const UTF32** sourceStart, const UTF32* sourceEnd,
UTF8** targetStart, UTF8* targetEnd, ConversionFlags flags); UTF8** targetStart, UTF8* targetEnd, ConversionFlags flags);
ConversionResult ConvertUTF16toUTF32 ( ConversionResult ConvertUTF16toUTF32 (
const UTF16** sourceStart, const UTF16* sourceEnd, const UTF16** sourceStart, const UTF16* sourceEnd,
UTF32** targetStart, UTF32* targetEnd, ConversionFlags flags); UTF32** targetStart, UTF32* targetEnd, ConversionFlags flags);
ConversionResult ConvertUTF32toUTF16 ( ConversionResult ConvertUTF32toUTF16 (
const UTF32** sourceStart, const UTF32* sourceEnd, const UTF32** sourceStart, const UTF32* sourceEnd,
UTF16** targetStart, UTF16* targetEnd, ConversionFlags flags); UTF16** targetStart, UTF16* targetEnd, ConversionFlags flags);
Boolean isLegalUTF8Sequence(const UTF8 *source, const UTF8 *sourceEnd); Boolean isLegalUTF8Sequence(const UTF8 *source, const UTF8 *sourceEnd);

File diff suppressed because it is too large Load Diff

View File

@@ -4,12 +4,12 @@
#ifdef WINDOWS #ifdef WINDOWS
#include "windows/dirent.h" #include "windows/dirent.h"
#include "windows/utils.h" #include "windows/utils.h"
#include "windows/unistd_partial.h" #include "windows/unistd_partial.h"
#else #else
#include <dirent.h> #include <dirent.h>
#include <unistd.h> #include <unistd.h>
#endif #endif
#include <fstream> #include <fstream>
@@ -19,12 +19,12 @@
#include <vector> #include <vector>
bool hasEnding (std::string const &fullString, std::string const &ending); bool hasEnding (std::string const &fullString, std::string const &ending);
bool DirectoryExists( const char* pzPath ); bool DirectoryExists( const char* pzPath );
bool fileExists( const char* pzPath ); bool fileExists( const char* pzPath );
std::vector<std::string> getFilesInDir(const char* dirPath); std::vector<std::string> getFilesInDir(const char* dirPath);
bool stringCompare( const std::string &left, const std::string &right ); bool stringCompare( const std::string &left, const std::string &right );
#endif // FILESYSTEM_H #endif // FILESYSTEM_H

View File

@@ -11,13 +11,13 @@
// Support for Windows // Support for Windows
#ifdef WINDOWS #ifdef WINDOWS
#include <windows.h> #include <windows.h>
#define timespec timeval #define timespec timeval
#endif #endif
void getTime(timespec* time); void getTime(timespec* time);
double diffclock(timespec time1,timespec time2); double diffclock(timespec time1,timespec time2);
#endif #endif

View File

@@ -61,30 +61,30 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
typedef struct typedef struct
{ {
char path[_TINYDIR_PATH_MAX]; char path[_TINYDIR_PATH_MAX];
char name[_TINYDIR_FILENAME_MAX]; char name[_TINYDIR_FILENAME_MAX];
int is_dir; int is_dir;
int is_reg; int is_reg;
#ifdef _MSC_VER #ifdef _MSC_VER
#else #else
struct stat _s; struct stat _s;
#endif #endif
} tinydir_file; } tinydir_file;
typedef struct typedef struct
{ {
char path[_TINYDIR_PATH_MAX]; char path[_TINYDIR_PATH_MAX];
int has_next; int has_next;
int n_files; int n_files;
tinydir_file *_files; tinydir_file *_files;
#ifdef _MSC_VER #ifdef _MSC_VER
HANDLE _h; HANDLE _h;
WIN32_FIND_DATA _f; WIN32_FIND_DATA _f;
#else #else
DIR *_d; DIR *_d;
struct dirent *_e; struct dirent *_e;
#endif #endif
} tinydir_dir; } tinydir_dir;
@@ -116,308 +116,288 @@ int _tinydir_file_cmp(const void *a, const void *b);
_TINYDIR_FUNC _TINYDIR_FUNC
int tinydir_open(tinydir_dir *dir, const char *path) int tinydir_open(tinydir_dir *dir, const char *path)
{ {
if (dir == NULL || path == NULL || strlen(path) == 0) if (dir == NULL || path == NULL || strlen(path) == 0)
{ {
errno = EINVAL; errno = EINVAL;
return -1; return -1;
} }
if (strlen(path) + _TINYDIR_PATH_EXTRA >= _TINYDIR_PATH_MAX) if (strlen(path) + _TINYDIR_PATH_EXTRA >= _TINYDIR_PATH_MAX)
{ {
errno = ENAMETOOLONG; errno = ENAMETOOLONG;
return -1; return -1;
} }
/* initialise dir */
/* initialise dir */ dir->_files = NULL;
dir->_files = NULL;
#ifdef _MSC_VER #ifdef _MSC_VER
dir->_h = INVALID_HANDLE_VALUE; dir->_h = INVALID_HANDLE_VALUE;
#else #else
dir->_d = NULL; dir->_d = NULL;
#endif #endif
tinydir_close(dir); tinydir_close(dir);
strcpy(dir->path, path);
strcpy(dir->path, path);
#ifdef _MSC_VER #ifdef _MSC_VER
strcat(dir->path, "\\*"); strcat(dir->path, "\\*");
dir->_h = FindFirstFile(dir->path, &dir->_f); dir->_h = FindFirstFile(dir->path, &dir->_f);
dir->path[strlen(dir->path) - 2] = '\0'; dir->path[strlen(dir->path) - 2] = '\0';
if (dir->_h == INVALID_HANDLE_VALUE) if (dir->_h == INVALID_HANDLE_VALUE)
#else #else
dir->_d = opendir(path); dir->_d = opendir(path);
if (dir->_d == NULL) if (dir->_d == NULL)
#endif #endif
{ {
errno = ENOENT; errno = ENOENT;
goto bail; goto bail;
} }
/* read first file */
/* read first file */ dir->has_next = 1;
dir->has_next = 1;
#ifndef _MSC_VER #ifndef _MSC_VER
dir->_e = readdir(dir->_d); dir->_e = readdir(dir->_d);
if (dir->_e == NULL) if (dir->_e == NULL)
{ {
dir->has_next = 0; dir->has_next = 0;
} }
#endif #endif
return 0;
return 0;
bail: bail:
tinydir_close(dir); tinydir_close(dir);
return -1; return -1;
} }
_TINYDIR_FUNC _TINYDIR_FUNC
int tinydir_open_sorted(tinydir_dir *dir, const char *path) int tinydir_open_sorted(tinydir_dir *dir, const char *path)
{ {
if (tinydir_open(dir, path) == -1) if (tinydir_open(dir, path) == -1)
{ {
return -1; return -1;
} }
dir->n_files = 0;
dir->n_files = 0; while (dir->has_next)
while (dir->has_next) {
{ tinydir_file *p_file;
tinydir_file *p_file; dir->n_files++;
dir->n_files++; dir->_files = (tinydir_file *)realloc(dir->_files, sizeof(tinydir_file)*dir->n_files);
dir->_files = (tinydir_file *)realloc(dir->_files, sizeof(tinydir_file)*dir->n_files); if (dir->_files == NULL)
if (dir->_files == NULL) {
{ errno = ENOMEM;
errno = ENOMEM; goto bail;
goto bail; }
} p_file = &dir->_files[dir->n_files - 1];
if (tinydir_readfile(dir, p_file) == -1)
p_file = &dir->_files[dir->n_files - 1]; {
if (tinydir_readfile(dir, p_file) == -1) goto bail;
{ }
goto bail; if (tinydir_next(dir) == -1)
} {
goto bail;
if (tinydir_next(dir) == -1) }
{ }
goto bail; qsort(dir->_files, dir->n_files, sizeof(tinydir_file), _tinydir_file_cmp);
} return 0;
}
qsort(dir->_files, dir->n_files, sizeof(tinydir_file), _tinydir_file_cmp);
return 0;
bail: bail:
tinydir_close(dir); tinydir_close(dir);
return -1; return -1;
} }
_TINYDIR_FUNC _TINYDIR_FUNC
void tinydir_close(tinydir_dir *dir) void tinydir_close(tinydir_dir *dir)
{ {
if (dir == NULL) if (dir == NULL)
{ {
return; return;
} }
memset(dir->path, 0, sizeof(dir->path));
memset(dir->path, 0, sizeof(dir->path)); dir->has_next = 0;
dir->has_next = 0; dir->n_files = -1;
dir->n_files = -1; if (dir->_files != NULL)
if (dir->_files != NULL) {
{ free(dir->_files);
free(dir->_files); }
} dir->_files = NULL;
dir->_files = NULL;
#ifdef _MSC_VER #ifdef _MSC_VER
if (dir->_h != INVALID_HANDLE_VALUE) if (dir->_h != INVALID_HANDLE_VALUE)
{ {
FindClose(dir->_h); FindClose(dir->_h);
} }
dir->_h = INVALID_HANDLE_VALUE; dir->_h = INVALID_HANDLE_VALUE;
#else #else
if (dir->_d) if (dir->_d)
{ {
closedir(dir->_d); closedir(dir->_d);
} }
dir->_d = NULL; dir->_d = NULL;
dir->_e = NULL; dir->_e = NULL;
#endif #endif
} }
_TINYDIR_FUNC _TINYDIR_FUNC
int tinydir_next(tinydir_dir *dir) int tinydir_next(tinydir_dir *dir)
{ {
if (dir == NULL) if (dir == NULL)
{ {
errno = EINVAL; errno = EINVAL;
return -1; return -1;
} }
if (!dir->has_next) if (!dir->has_next)
{ {
errno = ENOENT; errno = ENOENT;
return -1; return -1;
} }
#ifdef _MSC_VER #ifdef _MSC_VER
if (FindNextFile(dir->_h, &dir->_f) == 0) if (FindNextFile(dir->_h, &dir->_f) == 0)
#else #else
dir->_e = readdir(dir->_d); dir->_e = readdir(dir->_d);
if (dir->_e == NULL) if (dir->_e == NULL)
#endif #endif
{ {
dir->has_next = 0; dir->has_next = 0;
#ifdef _MSC_VER #ifdef _MSC_VER
if (GetLastError() != ERROR_SUCCESS && if (GetLastError() != ERROR_SUCCESS &&
GetLastError() != ERROR_NO_MORE_FILES) GetLastError() != ERROR_NO_MORE_FILES)
{ {
tinydir_close(dir); tinydir_close(dir);
errno = EIO; errno = EIO;
return -1; return -1;
} }
#endif #endif
} }
return 0;
return 0;
} }
_TINYDIR_FUNC _TINYDIR_FUNC
int tinydir_readfile(const tinydir_dir *dir, tinydir_file *file) int tinydir_readfile(const tinydir_dir *dir, tinydir_file *file)
{ {
if (dir == NULL || file == NULL) if (dir == NULL || file == NULL)
{ {
errno = EINVAL; errno = EINVAL;
return -1; return -1;
} }
#ifdef _MSC_VER #ifdef _MSC_VER
if (dir->_h == INVALID_HANDLE_VALUE) if (dir->_h == INVALID_HANDLE_VALUE)
#else #else
if (dir->_e == NULL) if (dir->_e == NULL)
#endif #endif
{ {
errno = ENOENT; errno = ENOENT;
return -1; return -1;
} }
if (strlen(dir->path) + if (strlen(dir->path) +
strlen( strlen(
#ifdef _MSC_VER #ifdef _MSC_VER
dir->_f.cFileName dir->_f.cFileName
#else #else
dir->_e->d_name dir->_e->d_name
#endif #endif
) + 1 + _TINYDIR_PATH_EXTRA >= ) + 1 + _TINYDIR_PATH_EXTRA >=
_TINYDIR_PATH_MAX) _TINYDIR_PATH_MAX)
{ {
/* the path for the file will be too long */ /* the path for the file will be too long */
errno = ENAMETOOLONG; errno = ENAMETOOLONG;
return -1; return -1;
} }
if (strlen( if (strlen(
#ifdef _MSC_VER #ifdef _MSC_VER
dir->_f.cFileName dir->_f.cFileName
#else #else
dir->_e->d_name dir->_e->d_name
#endif #endif
) >= _TINYDIR_FILENAME_MAX) ) >= _TINYDIR_FILENAME_MAX)
{ {
errno = ENAMETOOLONG; errno = ENAMETOOLONG;
return -1; return -1;
} }
strcpy(file->path, dir->path);
strcpy(file->path, dir->path); strcat(file->path, "/");
strcat(file->path, "/"); strcpy(file->name,
strcpy(file->name,
#ifdef _MSC_VER #ifdef _MSC_VER
dir->_f.cFileName dir->_f.cFileName
#else #else
dir->_e->d_name dir->_e->d_name
#endif #endif
); );
strcat(file->path, file->name); strcat(file->path, file->name);
#ifndef _MSC_VER #ifndef _MSC_VER
if (stat(file->path, &file->_s) == -1) if (stat(file->path, &file->_s) == -1)
{ {
return -1; return -1;
} }
#endif #endif
file->is_dir = file->is_dir =
#ifdef _MSC_VER #ifdef _MSC_VER
!!(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY); !!(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
#else #else
S_ISDIR(file->_s.st_mode); S_ISDIR(file->_s.st_mode);
#endif #endif
file->is_reg = file->is_reg =
#ifdef _MSC_VER #ifdef _MSC_VER
!!(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_NORMAL) || !!(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_NORMAL) ||
( (
!(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_DEVICE) && !(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_DEVICE) &&
!(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && !(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
!(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_ENCRYPTED) && !(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_ENCRYPTED) &&
#ifdef FILE_ATTRIBUTE_INTEGRITY_STREAM #ifdef FILE_ATTRIBUTE_INTEGRITY_STREAM
!(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_INTEGRITY_STREAM) && !(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_INTEGRITY_STREAM) &&
#endif #endif
#ifdef FILE_ATTRIBUTE_NO_SCRUB_DATA #ifdef FILE_ATTRIBUTE_NO_SCRUB_DATA
!(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_NO_SCRUB_DATA) && !(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_NO_SCRUB_DATA) &&
#endif #endif
!(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_OFFLINE) && !(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_OFFLINE) &&
!(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_TEMPORARY)); !(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_TEMPORARY));
#else #else
S_ISREG(file->_s.st_mode); S_ISREG(file->_s.st_mode);
#endif #endif
return 0;
return 0;
} }
_TINYDIR_FUNC _TINYDIR_FUNC
int tinydir_readfile_n(const tinydir_dir *dir, tinydir_file *file, int i) int tinydir_readfile_n(const tinydir_dir *dir, tinydir_file *file, int i)
{ {
if (dir == NULL || file == NULL || i < 0) if (dir == NULL || file == NULL || i < 0)
{ {
errno = EINVAL; errno = EINVAL;
return -1; return -1;
} }
if (i >= dir->n_files) if (i >= dir->n_files)
{ {
errno = ENOENT; errno = ENOENT;
return -1; return -1;
} }
memcpy(file, &dir->_files[i], sizeof(tinydir_file));
memcpy(file, &dir->_files[i], sizeof(tinydir_file)); return 0;
return 0;
} }
_TINYDIR_FUNC _TINYDIR_FUNC
int tinydir_open_subdir_n(tinydir_dir *dir, int i) int tinydir_open_subdir_n(tinydir_dir *dir, int i)
{ {
char path[_TINYDIR_PATH_MAX]; char path[_TINYDIR_PATH_MAX];
if (dir == NULL || i < 0) if (dir == NULL || i < 0)
{ {
errno = EINVAL; errno = EINVAL;
return -1; return -1;
} }
if (i >= dir->n_files || !dir->_files[i].is_dir) if (i >= dir->n_files || !dir->_files[i].is_dir)
{ {
errno = ENOENT; errno = ENOENT;
return -1; return -1;
} }
strcpy(path, dir->_files[i].path);
strcpy(path, dir->_files[i].path); tinydir_close(dir);
tinydir_close(dir); if (tinydir_open_sorted(dir, path) == -1)
if (tinydir_open_sorted(dir, path) == -1) {
{ return -1;
return -1; }
} return 0;
return 0;
} }
_TINYDIR_FUNC _TINYDIR_FUNC
int _tinydir_file_cmp(const void *a, const void *b) int _tinydir_file_cmp(const void *a, const void *b)
{ {
const tinydir_file *fa = (const tinydir_file *)a; const tinydir_file *fa = (const tinydir_file *)a;
const tinydir_file *fb = (const tinydir_file *)b; const tinydir_file *fb = (const tinydir_file *)b;
if (fa->is_dir != fb->is_dir) if (fa->is_dir != fb->is_dir)
{ {
return -(fa->is_dir - fb->is_dir); return -(fa->is_dir - fb->is_dir);
} }
return strncasecmp(fa->name, fb->name, _TINYDIR_FILENAME_MAX); return strncasecmp(fa->name, fb->name, _TINYDIR_FILENAME_MAX);
} }
#endif #endif

File diff suppressed because it is too large Load Diff

View File

@@ -3,5 +3,5 @@
static inline double round(double val) static inline double round(double val)
{ {
return floor(val + 0.5); return floor(val + 0.5);
} }

View File

@@ -51,9 +51,10 @@
typedef unsigned int TRexBool; typedef unsigned int TRexBool;
typedef struct TRex TRex; typedef struct TRex TRex;
typedef struct { typedef struct
const TRexChar *begin; {
int len; const TRexChar *begin;
int len;
} TRexMatch; } TRexMatch;
TREX_API TRex *trex_compile(const TRexChar *pattern,const TRexChar **error); TREX_API TRex *trex_compile(const TRexChar *pattern,const TRexChar **error);

View File

@@ -32,8 +32,8 @@
#include "constants.h" #include "constants.h"
#include "support/timing.h" #include "support/timing.h"
#include "opencv2/highgui/highgui.hpp" #include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp" #include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/core/core.hpp" #include "opencv2/core/core.hpp"
#include "binarize_wolf.h" #include "binarize_wolf.h"
#include <vector> #include <vector>
@@ -41,13 +41,13 @@
/* /*
struct LineSegment struct LineSegment
{ {
float x1; float x1;
float y1; float y1;
float x2; float x2;
float y2; float y2;
}; };
*/ */
@@ -61,7 +61,7 @@ class LineSegment
float length; float length;
float angle; float angle;
// LineSegment(Point point1, Point point2); // LineSegment(Point point1, Point point2);
LineSegment(); LineSegment();
LineSegment(int x1, int y1, int x2, int y2); LineSegment(int x1, int y1, int x2, int y2);
LineSegment(Point p1, Point p2); LineSegment(Point p1, Point p2);
@@ -90,30 +90,30 @@ class LineSegment
}; };
double median(int array[], int arraySize); double median(int array[], int arraySize);
vector<Mat> produceThresholds(const Mat img_gray, Config* config); vector<Mat> produceThresholds(const Mat img_gray, Config* config);
Mat drawImageDashboard(vector<Mat> images, int imageType, int numColumns); Mat drawImageDashboard(vector<Mat> images, int imageType, int numColumns);
void displayImage(Config* config, string windowName, cv::Mat frame); void displayImage(Config* config, string windowName, cv::Mat frame);
void drawAndWait(cv::Mat* frame); void drawAndWait(cv::Mat* frame);
double distanceBetweenPoints(Point p1, Point p2); double distanceBetweenPoints(Point p1, Point p2);
void drawRotatedRect(Mat* img, RotatedRect rect, Scalar color, int thickness); void drawRotatedRect(Mat* img, RotatedRect rect, Scalar color, int thickness);
void drawX(Mat img, Rect rect, Scalar color, int thickness); void drawX(Mat img, Rect rect, Scalar color, int thickness);
void fillMask(Mat img, const Mat mask, Scalar color); void fillMask(Mat img, const Mat mask, Scalar color);
float angleBetweenPoints(Point p1, Point p2); float angleBetweenPoints(Point p1, Point p2);
Size getSizeMaintainingAspect(Mat inputImg, int maxWidth, int maxHeight); Size getSizeMaintainingAspect(Mat inputImg, int maxWidth, int maxHeight);
Mat equalizeBrightness(Mat img); Mat equalizeBrightness(Mat img);
Rect expandRect(Rect original, int expandXPixels, int expandYPixels, int maxX, int maxY); Rect expandRect(Rect original, int expandXPixels, int expandYPixels, int maxX, int maxY);
Mat addLabel(Mat input, string label); Mat addLabel(Mat input, string label);
#endif // UTILITY_H #endif // UTILITY_H

View File

@@ -29,10 +29,10 @@ using namespace std;
struct Valley struct Valley
{ {
int startIndex; int startIndex;
int endIndex; int endIndex;
int width; int width;
int pixelsWithin; int pixelsWithin;
}; };
enum HistogramDirection { RISING, FALLING, FLAT }; enum HistogramDirection { RISING, FALLING, FLAT };

File diff suppressed because it is too large Load Diff

View File

@@ -27,7 +27,8 @@
#include <string> #include <string>
#include <exception> #include <exception>
namespace TCLAP { namespace TCLAP
{
/** /**
* A simple class that defines and argument exception. Should be caught * A simple class that defines and argument exception. Should be caught
@@ -35,82 +36,85 @@ namespace TCLAP {
*/ */
class ArgException : public std::exception class ArgException : public std::exception
{ {
public: public:
/** /**
* Constructor. * Constructor.
* \param text - The text of the exception. * \param text - The text of the exception.
* \param id - The text identifying the argument source. * \param id - The text identifying the argument source.
* \param td - Text describing the type of ArgException it is. * \param td - Text describing the type of ArgException it is.
* of the exception. * of the exception.
*/ */
ArgException( const std::string& text = "undefined exception", ArgException( const std::string& text = "undefined exception",
const std::string& id = "undefined", const std::string& id = "undefined",
const std::string& td = "Generic ArgException") const std::string& td = "Generic ArgException")
: std::exception(), : std::exception(),
_errorText(text), _errorText(text),
_argId( id ), _argId( id ),
_typeDescription(td) _typeDescription(td)
{ } { }
/** /**
* Destructor. * Destructor.
*/ */
virtual ~ArgException() throw() { } virtual ~ArgException() throw() { }
/** /**
* Returns the error text. * Returns the error text.
*/ */
std::string error() const { return ( _errorText ); } std::string error() const
{
return ( _errorText );
}
/** /**
* Returns the argument id. * Returns the argument id.
*/ */
std::string argId() const std::string argId() const
{ {
if ( _argId == "undefined" ) if ( _argId == "undefined" )
return " "; return " ";
else else
return ( "Argument: " + _argId ); return ( "Argument: " + _argId );
} }
/** /**
* Returns the arg id and error text. * Returns the arg id and error text.
*/ */
const char* what() const throw() const char* what() const throw()
{ {
static std::string ex; static std::string ex;
ex = _argId + " -- " + _errorText; ex = _argId + " -- " + _errorText;
return ex.c_str(); return ex.c_str();
} }
/** /**
* Returns the type of the exception. Used to explain and distinguish * Returns the type of the exception. Used to explain and distinguish
* between different child exceptions. * between different child exceptions.
*/ */
std::string typeDescription() const std::string typeDescription() const
{ {
return _typeDescription; return _typeDescription;
} }
private: private:
/** /**
* The text of the exception message. * The text of the exception message.
*/ */
std::string _errorText; std::string _errorText;
/** /**
* The argument related to this exception. * The argument related to this exception.
*/ */
std::string _argId; std::string _argId;
/** /**
* Describes the type of the exception. Used to distinguish * Describes the type of the exception. Used to distinguish
* between different child exceptions. * between different child exceptions.
*/ */
std::string _typeDescription; std::string _typeDescription;
}; };
@@ -120,20 +124,20 @@ class ArgException : public std::exception
*/ */
class ArgParseException : public ArgException class ArgParseException : public ArgException
{ {
public: public:
/** /**
* Constructor. * Constructor.
* \param text - The text of the exception. * \param text - The text of the exception.
* \param id - The text identifying the argument source * \param id - The text identifying the argument source
* of the exception. * of the exception.
*/ */
ArgParseException( const std::string& text = "undefined exception", ArgParseException( const std::string& text = "undefined exception",
const std::string& id = "undefined" ) const std::string& id = "undefined" )
: ArgException( text, : ArgException( text,
id, id,
std::string( "Exception found while parsing " ) + std::string( "Exception found while parsing " ) +
std::string( "the value the Arg has been passed." )) std::string( "the value the Arg has been passed." ))
{ } { }
}; };
/** /**
@@ -142,22 +146,22 @@ class ArgParseException : public ArgException
*/ */
class CmdLineParseException : public ArgException class CmdLineParseException : public ArgException
{ {
public: public:
/** /**
* Constructor. * Constructor.
* \param text - The text of the exception. * \param text - The text of the exception.
* \param id - The text identifying the argument source * \param id - The text identifying the argument source
* of the exception. * of the exception.
*/ */
CmdLineParseException( const std::string& text = "undefined exception", CmdLineParseException( const std::string& text = "undefined exception",
const std::string& id = "undefined" ) const std::string& id = "undefined" )
: ArgException( text, : ArgException( text,
id, id,
std::string( "Exception found when the values ") + std::string( "Exception found when the values ") +
std::string( "on the command line do not meet ") + std::string( "on the command line do not meet ") +
std::string( "the requirements of the defined ") + std::string( "the requirements of the defined ") +
std::string( "Args." )) std::string( "Args." ))
{ } { }
}; };
/** /**
@@ -166,32 +170,36 @@ class CmdLineParseException : public ArgException
*/ */
class SpecificationException : public ArgException class SpecificationException : public ArgException
{ {
public: public:
/** /**
* Constructor. * Constructor.
* \param text - The text of the exception. * \param text - The text of the exception.
* \param id - The text identifying the argument source * \param id - The text identifying the argument source
* of the exception. * of the exception.
*/ */
SpecificationException( const std::string& text = "undefined exception", SpecificationException( const std::string& text = "undefined exception",
const std::string& id = "undefined" ) const std::string& id = "undefined" )
: ArgException( text, : ArgException( text,
id, id,
std::string("Exception found when an Arg object ")+ std::string("Exception found when an Arg object ")+
std::string("is improperly defined by the ") + std::string("is improperly defined by the ") +
std::string("developer." )) std::string("developer." ))
{ } { }
}; };
class ExitException { class ExitException
public: {
ExitException(int estat) : _estat(estat) {} public:
ExitException(int estat) : _estat(estat) {}
int getExitStatus() const { return _estat; } int getExitStatus() const
{
return _estat;
}
private: private:
int _estat; int _estat;
}; };
} // namespace TCLAP } // namespace TCLAP

View File

@@ -26,7 +26,8 @@
#ifndef TCLAP_ARGTRAITS_H #ifndef TCLAP_ARGTRAITS_H
#define TCLAP_ARGTRAITS_H #define TCLAP_ARGTRAITS_H
namespace TCLAP { namespace TCLAP
{
// We use two empty structs to get compile type specialization // We use two empty structs to get compile type specialization
// function to work // function to work
@@ -35,9 +36,10 @@ namespace TCLAP {
* A value like argument value type is a value that can be set using * A value like argument value type is a value that can be set using
* operator>>. This is the default value type. * operator>>. This is the default value type.
*/ */
struct ValueLike { struct ValueLike
typedef ValueLike ValueCategory; {
virtual ~ValueLike() {} typedef ValueLike ValueCategory;
virtual ~ValueLike() {}
}; };
/** /**
@@ -45,8 +47,9 @@ struct ValueLike {
* operator=(string). Usefull if the value type contains spaces which * operator=(string). Usefull if the value type contains spaces which
* will be broken up into individual tokens by operator>>. * will be broken up into individual tokens by operator>>.
*/ */
struct StringLike { struct StringLike
virtual ~StringLike() {} {
virtual ~StringLike() {}
}; };
/** /**
@@ -54,9 +57,10 @@ struct StringLike {
* traits. This is a compile time thing and does not add any overhead * traits. This is a compile time thing and does not add any overhead
* to the inherenting class. * to the inherenting class.
*/ */
struct StringLikeTrait { struct StringLikeTrait
typedef StringLike ValueCategory; {
virtual ~StringLikeTrait() {} typedef StringLike ValueCategory;
virtual ~StringLikeTrait() {}
}; };
/** /**
@@ -64,9 +68,10 @@ struct StringLikeTrait {
* traits. This is a compile time thing and does not add any overhead * traits. This is a compile time thing and does not add any overhead
* to the inherenting class. * to the inherenting class.
*/ */
struct ValueLikeTrait { struct ValueLikeTrait
typedef ValueLike ValueCategory; {
virtual ~ValueLikeTrait() {} typedef ValueLike ValueCategory;
virtual ~ValueLikeTrait() {}
}; };
/** /**
@@ -76,10 +81,11 @@ struct ValueLikeTrait {
* supported types are StringLike and ValueLike. * supported types are StringLike and ValueLike.
*/ */
template<typename T> template<typename T>
struct ArgTraits { struct ArgTraits
typedef typename T::ValueCategory ValueCategory; {
virtual ~ArgTraits() {} typedef typename T::ValueCategory ValueCategory;
//typedef ValueLike ValueCategory; virtual ~ArgTraits() {}
//typedef ValueLike ValueCategory;
}; };
#endif #endif

View File

@@ -48,18 +48,19 @@
#include <algorithm> #include <algorithm>
#include <stdlib.h> // Needed for exit(), which isn't defined in some envs. #include <stdlib.h> // Needed for exit(), which isn't defined in some envs.
namespace TCLAP { namespace TCLAP
{
template<typename T> void DelPtr(T ptr) template<typename T> void DelPtr(T ptr)
{ {
delete ptr; delete ptr;
} }
template<typename C> void ClearContainer(C &c) template<typename C> void ClearContainer(C &c)
{ {
typedef typename C::value_type value_type; typedef typename C::value_type value_type;
std::for_each(c.begin(), c.end(), DelPtr<value_type>); std::for_each(c.begin(), c.end(), DelPtr<value_type>);
c.clear(); c.clear();
} }
@@ -69,249 +70,249 @@ template<typename C> void ClearContainer(C &c)
*/ */
class CmdLine : public CmdLineInterface class CmdLine : public CmdLineInterface
{ {
protected: protected:
/** /**
* The list of arguments that will be tested against the * The list of arguments that will be tested against the
* command line. * command line.
*/ */
std::list<Arg*> _argList; std::list<Arg*> _argList;
/** /**
* The name of the program. Set to argv[0]. * The name of the program. Set to argv[0].
*/ */
std::string _progName; std::string _progName;
/** /**
* A message used to describe the program. Used in the usage output. * A message used to describe the program. Used in the usage output.
*/ */
std::string _message; std::string _message;
/** /**
* The version to be displayed with the --version switch. * The version to be displayed with the --version switch.
*/ */
std::string _version; std::string _version;
/** /**
* The number of arguments that are required to be present on * The number of arguments that are required to be present on
* the command line. This is set dynamically, based on the * the command line. This is set dynamically, based on the
* Args added to the CmdLine object. * Args added to the CmdLine object.
*/ */
int _numRequired; int _numRequired;
/** /**
* The character that is used to separate the argument flag/name * The character that is used to separate the argument flag/name
* from the value. Defaults to ' ' (space). * from the value. Defaults to ' ' (space).
*/ */
char _delimiter; char _delimiter;
/** /**
* The handler that manages xoring lists of args. * The handler that manages xoring lists of args.
*/ */
XorHandler _xorHandler; XorHandler _xorHandler;
/** /**
* A list of Args to be explicitly deleted when the destructor * A list of Args to be explicitly deleted when the destructor
* is called. At the moment, this only includes the three default * is called. At the moment, this only includes the three default
* Args. * Args.
*/ */
std::list<Arg*> _argDeleteOnExitList; std::list<Arg*> _argDeleteOnExitList;
/** /**
* A list of Visitors to be explicitly deleted when the destructor * A list of Visitors to be explicitly deleted when the destructor
* is called. At the moment, these are the Vistors created for the * is called. At the moment, these are the Vistors created for the
* default Args. * default Args.
*/ */
std::list<Visitor*> _visitorDeleteOnExitList; std::list<Visitor*> _visitorDeleteOnExitList;
/** /**
* Object that handles all output for the CmdLine. * Object that handles all output for the CmdLine.
*/ */
CmdLineOutput* _output; CmdLineOutput* _output;
/** /**
* Should CmdLine handle parsing exceptions internally? * Should CmdLine handle parsing exceptions internally?
*/ */
bool _handleExceptions; bool _handleExceptions;
/** /**
* Throws an exception listing the missing args. * Throws an exception listing the missing args.
*/ */
void missingArgsException(); void missingArgsException();
/** /**
* Checks whether a name/flag string matches entirely matches * Checks whether a name/flag string matches entirely matches
* the Arg::blankChar. Used when multiple switches are combined * the Arg::blankChar. Used when multiple switches are combined
* into a single argument. * into a single argument.
* \param s - The message to be used in the usage. * \param s - The message to be used in the usage.
*/ */
bool _emptyCombined(const std::string& s); bool _emptyCombined(const std::string& s);
/** /**
* Perform a delete ptr; operation on ptr when this object is deleted. * Perform a delete ptr; operation on ptr when this object is deleted.
*/ */
void deleteOnExit(Arg* ptr); void deleteOnExit(Arg* ptr);
/** /**
* Perform a delete ptr; operation on ptr when this object is deleted. * Perform a delete ptr; operation on ptr when this object is deleted.
*/ */
void deleteOnExit(Visitor* ptr); void deleteOnExit(Visitor* ptr);
private: private:
/** /**
* Prevent accidental copying. * Prevent accidental copying.
*/ */
CmdLine(const CmdLine& rhs); CmdLine(const CmdLine& rhs);
CmdLine& operator=(const CmdLine& rhs); CmdLine& operator=(const CmdLine& rhs);
/** /**
* Encapsulates the code common to the constructors * Encapsulates the code common to the constructors
* (which is all of it). * (which is all of it).
*/ */
void _constructor(); void _constructor();
/** /**
* Is set to true when a user sets the output object. We use this so * Is set to true when a user sets the output object. We use this so
* that we don't delete objects that are created outside of this lib. * that we don't delete objects that are created outside of this lib.
*/ */
bool _userSetOutput; bool _userSetOutput;
/** /**
* Whether or not to automatically create help and version switches. * Whether or not to automatically create help and version switches.
*/ */
bool _helpAndVersion; bool _helpAndVersion;
public: public:
/** /**
* Command line constructor. Defines how the arguments will be * Command line constructor. Defines how the arguments will be
* parsed. * parsed.
* \param message - The message to be used in the usage * \param message - The message to be used in the usage
* output. * output.
* \param delimiter - The character that is used to separate * \param delimiter - The character that is used to separate
* the argument flag/name from the value. Defaults to ' ' (space). * the argument flag/name from the value. Defaults to ' ' (space).
* \param version - The version number to be used in the * \param version - The version number to be used in the
* --version switch. * --version switch.
* \param helpAndVersion - Whether or not to create the Help and * \param helpAndVersion - Whether or not to create the Help and
* Version switches. Defaults to true. * Version switches. Defaults to true.
*/ */
CmdLine(const std::string& message, CmdLine(const std::string& message,
const char delimiter = ' ', const char delimiter = ' ',
const std::string& version = "none", const std::string& version = "none",
bool helpAndVersion = true); bool helpAndVersion = true);
/** /**
* Deletes any resources allocated by a CmdLine object. * Deletes any resources allocated by a CmdLine object.
*/ */
virtual ~CmdLine(); virtual ~CmdLine();
/** /**
* Adds an argument to the list of arguments to be parsed. * Adds an argument to the list of arguments to be parsed.
* \param a - Argument to be added. * \param a - Argument to be added.
*/ */
void add( Arg& a ); void add( Arg& a );
/** /**
* An alternative add. Functionally identical. * An alternative add. Functionally identical.
* \param a - Argument to be added. * \param a - Argument to be added.
*/ */
void add( Arg* a ); void add( Arg* a );
/** /**
* Add two Args that will be xor'd. If this method is used, add does * Add two Args that will be xor'd. If this method is used, add does
* not need to be called. * not need to be called.
* \param a - Argument to be added and xor'd. * \param a - Argument to be added and xor'd.
* \param b - Argument to be added and xor'd. * \param b - Argument to be added and xor'd.
*/ */
void xorAdd( Arg& a, Arg& b ); void xorAdd( Arg& a, Arg& b );
/** /**
* Add a list of Args that will be xor'd. If this method is used, * Add a list of Args that will be xor'd. If this method is used,
* add does not need to be called. * add does not need to be called.
* \param xors - List of Args to be added and xor'd. * \param xors - List of Args to be added and xor'd.
*/ */
void xorAdd( std::vector<Arg*>& xors ); void xorAdd( std::vector<Arg*>& xors );
/** /**
* Parses the command line. * Parses the command line.
* \param argc - Number of arguments. * \param argc - Number of arguments.
* \param argv - Array of arguments. * \param argv - Array of arguments.
*/ */
void parse(int argc, const char * const * argv); void parse(int argc, const char * const * argv);
/** /**
* Parses the command line. * Parses the command line.
* \param args - A vector of strings representing the args. * \param args - A vector of strings representing the args.
* args[0] is still the program name. * args[0] is still the program name.
*/ */
void parse(std::vector<std::string>& args); void parse(std::vector<std::string>& args);
/** /**
* *
*/ */
CmdLineOutput* getOutput(); CmdLineOutput* getOutput();
/** /**
* *
*/ */
void setOutput(CmdLineOutput* co); void setOutput(CmdLineOutput* co);
/** /**
* *
*/ */
std::string& getVersion(); std::string& getVersion();
/** /**
* *
*/ */
std::string& getProgramName(); std::string& getProgramName();
/** /**
* *
*/ */
std::list<Arg*>& getArgList(); std::list<Arg*>& getArgList();
/** /**
* *
*/ */
XorHandler& getXorHandler(); XorHandler& getXorHandler();
/** /**
* *
*/ */
char getDelimiter(); char getDelimiter();
/** /**
* *
*/ */
std::string& getMessage(); std::string& getMessage();
/** /**
* *
*/ */
bool hasHelpAndVersion(); bool hasHelpAndVersion();
/** /**
* Disables or enables CmdLine's internal parsing exception handling. * Disables or enables CmdLine's internal parsing exception handling.
* *
* @param state Should CmdLine handle parsing exceptions internally? * @param state Should CmdLine handle parsing exceptions internally?
*/ */
void setExceptionHandling(const bool state); void setExceptionHandling(const bool state);
/** /**
* Returns the current state of the internal exception handling. * Returns the current state of the internal exception handling.
* *
* @retval true Parsing exceptions are handled internally. * @retval true Parsing exceptions are handled internally.
* @retval false Parsing exceptions are propagated to the caller. * @retval false Parsing exceptions are propagated to the caller.
*/ */
bool getExceptionHandling() const; bool getExceptionHandling() const;
/** /**
* Allows the CmdLine object to be reused. * Allows the CmdLine object to be reused.
*/ */
void reset(); void reset();
}; };
@@ -324,7 +325,7 @@ inline CmdLine::CmdLine(const std::string& m,
char delim, char delim,
const std::string& v, const std::string& v,
bool help ) bool help )
: :
_argList(std::list<Arg*>()), _argList(std::list<Arg*>()),
_progName("not_set_yet"), _progName("not_set_yet"),
_message(m), _message(m),
@@ -339,288 +340,272 @@ inline CmdLine::CmdLine(const std::string& m,
_userSetOutput(false), _userSetOutput(false),
_helpAndVersion(help) _helpAndVersion(help)
{ {
_constructor(); _constructor();
} }
inline CmdLine::~CmdLine() inline CmdLine::~CmdLine()
{ {
ClearContainer(_argDeleteOnExitList); ClearContainer(_argDeleteOnExitList);
ClearContainer(_visitorDeleteOnExitList); ClearContainer(_visitorDeleteOnExitList);
if ( !_userSetOutput )
if ( !_userSetOutput ) { {
delete _output; delete _output;
_output = 0; _output = 0;
} }
} }
inline void CmdLine::_constructor() inline void CmdLine::_constructor()
{ {
_output = new StdOutput; _output = new StdOutput;
Arg::setDelimiter( _delimiter );
Arg::setDelimiter( _delimiter ); Visitor* v;
if ( _helpAndVersion )
Visitor* v; {
v = new HelpVisitor( this, &_output );
if ( _helpAndVersion ) SwitchArg* help = new SwitchArg("h","help",
{ "Displays usage information and exits.",
v = new HelpVisitor( this, &_output ); false, v);
SwitchArg* help = new SwitchArg("h","help", add( help );
"Displays usage information and exits.", deleteOnExit(help);
false, v); deleteOnExit(v);
add( help ); v = new VersionVisitor( this, &_output );
deleteOnExit(help); SwitchArg* vers = new SwitchArg("","version",
deleteOnExit(v); "Displays version information and exits.",
false, v);
v = new VersionVisitor( this, &_output ); add( vers );
SwitchArg* vers = new SwitchArg("","version", deleteOnExit(vers);
"Displays version information and exits.", deleteOnExit(v);
false, v); }
add( vers ); v = new IgnoreRestVisitor();
deleteOnExit(vers); SwitchArg* ignore = new SwitchArg(Arg::flagStartString(),
deleteOnExit(v); Arg::ignoreNameString(),
} "Ignores the rest of the labeled arguments following this flag.",
false, v);
v = new IgnoreRestVisitor(); add( ignore );
SwitchArg* ignore = new SwitchArg(Arg::flagStartString(), deleteOnExit(ignore);
Arg::ignoreNameString(), deleteOnExit(v);
"Ignores the rest of the labeled arguments following this flag.",
false, v);
add( ignore );
deleteOnExit(ignore);
deleteOnExit(v);
} }
inline void CmdLine::xorAdd( std::vector<Arg*>& ors ) inline void CmdLine::xorAdd( std::vector<Arg*>& ors )
{ {
_xorHandler.add( ors ); _xorHandler.add( ors );
for (ArgVectorIterator it = ors.begin(); it != ors.end(); it++)
for (ArgVectorIterator it = ors.begin(); it != ors.end(); it++) {
{ (*it)->forceRequired();
(*it)->forceRequired(); (*it)->setRequireLabel( "OR required" );
(*it)->setRequireLabel( "OR required" ); add( *it );
add( *it ); }
}
} }
inline void CmdLine::xorAdd( Arg& a, Arg& b ) inline void CmdLine::xorAdd( Arg& a, Arg& b )
{ {
std::vector<Arg*> ors; std::vector<Arg*> ors;
ors.push_back( &a ); ors.push_back( &a );
ors.push_back( &b ); ors.push_back( &b );
xorAdd( ors ); xorAdd( ors );
} }
inline void CmdLine::add( Arg& a ) inline void CmdLine::add( Arg& a )
{ {
add( &a ); add( &a );
} }
inline void CmdLine::add( Arg* a ) inline void CmdLine::add( Arg* a )
{ {
for( ArgListIterator it = _argList.begin(); it != _argList.end(); it++ ) for( ArgListIterator it = _argList.begin(); it != _argList.end(); it++ )
if ( *a == *(*it) ) if ( *a == *(*it) )
throw( SpecificationException( throw( SpecificationException(
"Argument with same flag/name already exists!", "Argument with same flag/name already exists!",
a->longID() ) ); a->longID() ) );
a->addToList( _argList );
a->addToList( _argList ); if ( a->isRequired() )
_numRequired++;
if ( a->isRequired() )
_numRequired++;
} }
inline void CmdLine::parse(int argc, const char * const * argv) inline void CmdLine::parse(int argc, const char * const * argv)
{ {
// this step is necessary so that we have easy access to // this step is necessary so that we have easy access to
// mutable strings. // mutable strings.
std::vector<std::string> args; std::vector<std::string> args;
for (int i = 0; i < argc; i++) for (int i = 0; i < argc; i++)
args.push_back(argv[i]); args.push_back(argv[i]);
parse(args);
parse(args);
} }
inline void CmdLine::parse(std::vector<std::string>& args) inline void CmdLine::parse(std::vector<std::string>& args)
{ {
bool shouldExit = false; bool shouldExit = false;
int estat = 0; int estat = 0;
try
try { {
_progName = args.front(); _progName = args.front();
args.erase(args.begin()); args.erase(args.begin());
int requiredCount = 0;
int requiredCount = 0; for (int i = 0; static_cast<unsigned int>(i) < args.size(); i++)
{
for (int i = 0; static_cast<unsigned int>(i) < args.size(); i++) bool matched = false;
{ for (ArgListIterator it = _argList.begin();
bool matched = false; it != _argList.end(); it++)
for (ArgListIterator it = _argList.begin(); {
it != _argList.end(); it++) { if ( (*it)->processArg( &i, args ) )
if ( (*it)->processArg( &i, args ) ) {
{ requiredCount += _xorHandler.check( *it );
requiredCount += _xorHandler.check( *it ); matched = true;
matched = true; break;
break; }
} }
} // checks to see if the argument is an empty combined
// switch and if so, then we've actually matched it
// checks to see if the argument is an empty combined if ( !matched && _emptyCombined( args[i] ) )
// switch and if so, then we've actually matched it matched = true;
if ( !matched && _emptyCombined( args[i] ) ) if ( !matched && !Arg::ignoreRest() )
matched = true; throw(CmdLineParseException("Couldn't find match "
"for argument",
if ( !matched && !Arg::ignoreRest() ) args[i]));
throw(CmdLineParseException("Couldn't find match " }
"for argument", if ( requiredCount < _numRequired )
args[i])); missingArgsException();
} if ( requiredCount > _numRequired )
throw(CmdLineParseException("Too many arguments!"));
if ( requiredCount < _numRequired ) }
missingArgsException(); catch ( ArgException& e )
{
if ( requiredCount > _numRequired ) // If we're not handling the exceptions, rethrow.
throw(CmdLineParseException("Too many arguments!")); if ( !_handleExceptions)
{
} catch ( ArgException& e ) { throw;
// If we're not handling the exceptions, rethrow. }
if ( !_handleExceptions) { try
throw; {
} _output->failure(*this,e);
}
try { catch ( ExitException &ee )
_output->failure(*this,e); {
} catch ( ExitException &ee ) { estat = ee.getExitStatus();
estat = ee.getExitStatus(); shouldExit = true;
shouldExit = true; }
} }
} catch (ExitException &ee) { catch (ExitException &ee)
// If we're not handling the exceptions, rethrow. {
if ( !_handleExceptions) { // If we're not handling the exceptions, rethrow.
throw; if ( !_handleExceptions)
} {
throw;
estat = ee.getExitStatus(); }
shouldExit = true; estat = ee.getExitStatus();
} shouldExit = true;
}
if (shouldExit) if (shouldExit)
exit(estat); exit(estat);
} }
inline bool CmdLine::_emptyCombined(const std::string& s) inline bool CmdLine::_emptyCombined(const std::string& s)
{ {
if ( s.length() > 0 && s[0] != Arg::flagStartChar() ) if ( s.length() > 0 && s[0] != Arg::flagStartChar() )
return false; return false;
for ( int i = 1; static_cast<unsigned int>(i) < s.length(); i++ )
for ( int i = 1; static_cast<unsigned int>(i) < s.length(); i++ ) if ( s[i] != Arg::blankChar() )
if ( s[i] != Arg::blankChar() ) return false;
return false; return true;
return true;
} }
inline void CmdLine::missingArgsException() inline void CmdLine::missingArgsException()
{ {
int count = 0; int count = 0;
std::string missingArgList;
std::string missingArgList; for (ArgListIterator it = _argList.begin(); it != _argList.end(); it++)
for (ArgListIterator it = _argList.begin(); it != _argList.end(); it++) {
{ if ( (*it)->isRequired() && !(*it)->isSet() )
if ( (*it)->isRequired() && !(*it)->isSet() ) {
{ missingArgList += (*it)->getName();
missingArgList += (*it)->getName(); missingArgList += ", ";
missingArgList += ", "; count++;
count++; }
} }
} missingArgList = missingArgList.substr(0,missingArgList.length()-2);
missingArgList = missingArgList.substr(0,missingArgList.length()-2); std::string msg;
if ( count > 1 )
std::string msg; msg = "Required arguments missing: ";
if ( count > 1 ) else
msg = "Required arguments missing: "; msg = "Required argument missing: ";
else msg += missingArgList;
msg = "Required argument missing: "; throw(CmdLineParseException(msg));
msg += missingArgList;
throw(CmdLineParseException(msg));
} }
inline void CmdLine::deleteOnExit(Arg* ptr) inline void CmdLine::deleteOnExit(Arg* ptr)
{ {
_argDeleteOnExitList.push_back(ptr); _argDeleteOnExitList.push_back(ptr);
} }
inline void CmdLine::deleteOnExit(Visitor* ptr) inline void CmdLine::deleteOnExit(Visitor* ptr)
{ {
_visitorDeleteOnExitList.push_back(ptr); _visitorDeleteOnExitList.push_back(ptr);
} }
inline CmdLineOutput* CmdLine::getOutput() inline CmdLineOutput* CmdLine::getOutput()
{ {
return _output; return _output;
} }
inline void CmdLine::setOutput(CmdLineOutput* co) inline void CmdLine::setOutput(CmdLineOutput* co)
{ {
if ( !_userSetOutput ) if ( !_userSetOutput )
delete _output; delete _output;
_userSetOutput = true; _userSetOutput = true;
_output = co; _output = co;
} }
inline std::string& CmdLine::getVersion() inline std::string& CmdLine::getVersion()
{ {
return _version; return _version;
} }
inline std::string& CmdLine::getProgramName() inline std::string& CmdLine::getProgramName()
{ {
return _progName; return _progName;
} }
inline std::list<Arg*>& CmdLine::getArgList() inline std::list<Arg*>& CmdLine::getArgList()
{ {
return _argList; return _argList;
} }
inline XorHandler& CmdLine::getXorHandler() inline XorHandler& CmdLine::getXorHandler()
{ {
return _xorHandler; return _xorHandler;
} }
inline char CmdLine::getDelimiter() inline char CmdLine::getDelimiter()
{ {
return _delimiter; return _delimiter;
} }
inline std::string& CmdLine::getMessage() inline std::string& CmdLine::getMessage()
{ {
return _message; return _message;
} }
inline bool CmdLine::hasHelpAndVersion() inline bool CmdLine::hasHelpAndVersion()
{ {
return _helpAndVersion; return _helpAndVersion;
} }
inline void CmdLine::setExceptionHandling(const bool state) inline void CmdLine::setExceptionHandling(const bool state)
{ {
_handleExceptions = state; _handleExceptions = state;
} }
inline bool CmdLine::getExceptionHandling() const inline bool CmdLine::getExceptionHandling() const
{ {
return _handleExceptions; return _handleExceptions;
} }
inline void CmdLine::reset() inline void CmdLine::reset()
{ {
for( ArgListIterator it = _argList.begin(); it != _argList.end(); it++ ) for( ArgListIterator it = _argList.begin(); it != _argList.end(); it++ )
(*it)->reset(); (*it)->reset();
_progName.clear();
_progName.clear();
} }
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////

View File

@@ -30,7 +30,8 @@
#include <algorithm> #include <algorithm>
namespace TCLAP { namespace TCLAP
{
class Arg; class Arg;
class CmdLineOutput; class CmdLineOutput;
@@ -42,106 +43,106 @@ class XorHandler;
*/ */
class CmdLineInterface class CmdLineInterface
{ {
public: public:
/** /**
* Destructor * Destructor
*/ */
virtual ~CmdLineInterface() {} virtual ~CmdLineInterface() {}
/** /**
* Adds an argument to the list of arguments to be parsed. * Adds an argument to the list of arguments to be parsed.
* \param a - Argument to be added. * \param a - Argument to be added.
*/ */
virtual void add( Arg& a )=0; virtual void add( Arg& a )=0;
/** /**
* An alternative add. Functionally identical. * An alternative add. Functionally identical.
* \param a - Argument to be added. * \param a - Argument to be added.
*/ */
virtual void add( Arg* a )=0; virtual void add( Arg* a )=0;
/** /**
* Add two Args that will be xor'd. * Add two Args that will be xor'd.
* If this method is used, add does * If this method is used, add does
* not need to be called. * not need to be called.
* \param a - Argument to be added and xor'd. * \param a - Argument to be added and xor'd.
* \param b - Argument to be added and xor'd. * \param b - Argument to be added and xor'd.
*/ */
virtual void xorAdd( Arg& a, Arg& b )=0; virtual void xorAdd( Arg& a, Arg& b )=0;
/** /**
* Add a list of Args that will be xor'd. If this method is used, * Add a list of Args that will be xor'd. If this method is used,
* add does not need to be called. * add does not need to be called.
* \param xors - List of Args to be added and xor'd. * \param xors - List of Args to be added and xor'd.
*/ */
virtual void xorAdd( std::vector<Arg*>& xors )=0; virtual void xorAdd( std::vector<Arg*>& xors )=0;
/** /**
* Parses the command line. * Parses the command line.
* \param argc - Number of arguments. * \param argc - Number of arguments.
* \param argv - Array of arguments. * \param argv - Array of arguments.
*/ */
virtual void parse(int argc, const char * const * argv)=0; virtual void parse(int argc, const char * const * argv)=0;
/** /**
* Parses the command line. * Parses the command line.
* \param args - A vector of strings representing the args. * \param args - A vector of strings representing the args.
* args[0] is still the program name. * args[0] is still the program name.
*/ */
void parse(std::vector<std::string>& args); void parse(std::vector<std::string>& args);
/** /**
* Returns the CmdLineOutput object. * Returns the CmdLineOutput object.
*/ */
virtual CmdLineOutput* getOutput()=0; virtual CmdLineOutput* getOutput()=0;
/** /**
* \param co - CmdLineOutput object that we want to use instead. * \param co - CmdLineOutput object that we want to use instead.
*/ */
virtual void setOutput(CmdLineOutput* co)=0; virtual void setOutput(CmdLineOutput* co)=0;
/** /**
* Returns the version string. * Returns the version string.
*/ */
virtual std::string& getVersion()=0; virtual std::string& getVersion()=0;
/** /**
* Returns the program name string. * Returns the program name string.
*/ */
virtual std::string& getProgramName()=0; virtual std::string& getProgramName()=0;
/** /**
* Returns the argList. * Returns the argList.
*/ */
virtual std::list<Arg*>& getArgList()=0; virtual std::list<Arg*>& getArgList()=0;
/** /**
* Returns the XorHandler. * Returns the XorHandler.
*/ */
virtual XorHandler& getXorHandler()=0; virtual XorHandler& getXorHandler()=0;
/** /**
* Returns the delimiter string. * Returns the delimiter string.
*/ */
virtual char getDelimiter()=0; virtual char getDelimiter()=0;
/** /**
* Returns the message string. * Returns the message string.
*/ */
virtual std::string& getMessage()=0; virtual std::string& getMessage()=0;
/** /**
* Indicates whether or not the help and version switches were created * Indicates whether or not the help and version switches were created
* automatically. * automatically.
*/ */
virtual bool hasHelpAndVersion()=0; virtual bool hasHelpAndVersion()=0;
/** /**
* Resets the instance as if it had just been constructed so that the * Resets the instance as if it had just been constructed so that the
* instance can be reused. * instance can be reused.
*/ */
virtual void reset()=0; virtual void reset()=0;
}; };
} //namespace } //namespace

View File

@@ -30,7 +30,8 @@
#include <iomanip> #include <iomanip>
#include <algorithm> #include <algorithm>
namespace TCLAP { namespace TCLAP
{
class CmdLineInterface; class CmdLineInterface;
class ArgException; class ArgException;
@@ -41,32 +42,32 @@ class ArgException;
class CmdLineOutput class CmdLineOutput
{ {
public: public:
/** /**
* Virtual destructor. * Virtual destructor.
*/ */
virtual ~CmdLineOutput() {} virtual ~CmdLineOutput() {}
/** /**
* Generates some sort of output for the USAGE. * Generates some sort of output for the USAGE.
* \param c - The CmdLine object the output is generated for. * \param c - The CmdLine object the output is generated for.
*/ */
virtual void usage(CmdLineInterface& c)=0; virtual void usage(CmdLineInterface& c)=0;
/** /**
* Generates some sort of output for the version. * Generates some sort of output for the version.
* \param c - The CmdLine object the output is generated for. * \param c - The CmdLine object the output is generated for.
*/ */
virtual void version(CmdLineInterface& c)=0; virtual void version(CmdLineInterface& c)=0;
/** /**
* Generates some sort of output for a failure. * Generates some sort of output for a failure.
* \param c - The CmdLine object the output is generated for. * \param c - The CmdLine object the output is generated for.
* \param e - The ArgException that caused the failure. * \param e - The ArgException that caused the failure.
*/ */
virtual void failure( CmdLineInterface& c, virtual void failure( CmdLineInterface& c,
ArgException& e )=0; ArgException& e )=0;
}; };

View File

@@ -29,7 +29,8 @@
#include <iomanip> #include <iomanip>
#include <algorithm> #include <algorithm>
namespace TCLAP { namespace TCLAP
{
/** /**
* The interface that defines the interaction between the Arg and Constraint. * The interface that defines the interaction between the Arg and Constraint.
@@ -38,30 +39,33 @@ template<class T>
class Constraint class Constraint
{ {
public: public:
/** /**
* Returns a description of the Constraint. * Returns a description of the Constraint.
*/ */
virtual std::string description() const =0; virtual std::string description() const =0;
/** /**
* Returns the short ID for the Constraint. * Returns the short ID for the Constraint.
*/ */
virtual std::string shortID() const =0; virtual std::string shortID() const =0;
/** /**
* The method used to verify that the value parsed from the command * The method used to verify that the value parsed from the command
* line meets the constraint. * line meets the constraint.
* \param value - The value that will be checked. * \param value - The value that will be checked.
*/ */
virtual bool check(const T& value) const =0; virtual bool check(const T& value) const =0;
/** /**
* Destructor. * Destructor.
* Silences warnings about Constraint being a base class with virtual * Silences warnings about Constraint being a base class with virtual
* functions but without a virtual destructor. * functions but without a virtual destructor.
*/ */
virtual ~Constraint() { ; } virtual ~Constraint()
{
;
}
}; };
} //namespace TCLAP } //namespace TCLAP

View File

@@ -34,7 +34,8 @@
#include <tclap/XorHandler.h> #include <tclap/XorHandler.h>
#include <tclap/Arg.h> #include <tclap/Arg.h>
namespace TCLAP { namespace TCLAP
{
/** /**
* A class that generates DocBook output for usage() method for the * A class that generates DocBook output for usage() method for the
@@ -43,256 +44,226 @@ namespace TCLAP {
class DocBookOutput : public CmdLineOutput class DocBookOutput : public CmdLineOutput
{ {
public: public:
/** /**
* Prints the usage to stdout. Can be overridden to * Prints the usage to stdout. Can be overridden to
* produce alternative behavior. * produce alternative behavior.
* \param c - The CmdLine object the output is generated for. * \param c - The CmdLine object the output is generated for.
*/ */
virtual void usage(CmdLineInterface& c); virtual void usage(CmdLineInterface& c);
/** /**
* Prints the version to stdout. Can be overridden * Prints the version to stdout. Can be overridden
* to produce alternative behavior. * to produce alternative behavior.
* \param c - The CmdLine object the output is generated for. * \param c - The CmdLine object the output is generated for.
*/ */
virtual void version(CmdLineInterface& c); virtual void version(CmdLineInterface& c);
/** /**
* Prints (to stderr) an error message, short usage * Prints (to stderr) an error message, short usage
* Can be overridden to produce alternative behavior. * Can be overridden to produce alternative behavior.
* \param c - The CmdLine object the output is generated for. * \param c - The CmdLine object the output is generated for.
* \param e - The ArgException that caused the failure. * \param e - The ArgException that caused the failure.
*/ */
virtual void failure(CmdLineInterface& c, virtual void failure(CmdLineInterface& c,
ArgException& e ); ArgException& e );
protected: protected:
/** /**
* Substitutes the char r for string x in string s. * Substitutes the char r for string x in string s.
* \param s - The string to operate on. * \param s - The string to operate on.
* \param r - The char to replace. * \param r - The char to replace.
* \param x - What to replace r with. * \param x - What to replace r with.
*/ */
void substituteSpecialChars( std::string& s, char r, std::string& x ); void substituteSpecialChars( std::string& s, char r, std::string& x );
void removeChar( std::string& s, char r); void removeChar( std::string& s, char r);
void basename( std::string& s ); void basename( std::string& s );
void printShortArg(Arg* it); void printShortArg(Arg* it);
void printLongArg(Arg* it); void printLongArg(Arg* it);
char theDelimiter; char theDelimiter;
}; };
inline void DocBookOutput::version(CmdLineInterface& _cmd) inline void DocBookOutput::version(CmdLineInterface& _cmd)
{ {
std::cout << _cmd.getVersion() << std::endl; std::cout << _cmd.getVersion() << std::endl;
} }
inline void DocBookOutput::usage(CmdLineInterface& _cmd ) inline void DocBookOutput::usage(CmdLineInterface& _cmd )
{ {
std::list<Arg*> argList = _cmd.getArgList(); std::list<Arg*> argList = _cmd.getArgList();
std::string progName = _cmd.getProgramName(); std::string progName = _cmd.getProgramName();
std::string xversion = _cmd.getVersion(); std::string xversion = _cmd.getVersion();
theDelimiter = _cmd.getDelimiter(); theDelimiter = _cmd.getDelimiter();
XorHandler xorHandler = _cmd.getXorHandler(); XorHandler xorHandler = _cmd.getXorHandler();
std::vector< std::vector<Arg*> > xorList = xorHandler.getXorList(); std::vector< std::vector<Arg*> > xorList = xorHandler.getXorList();
basename(progName); basename(progName);
std::cout << "<?xml version='1.0'?>" << std::endl;
std::cout << "<?xml version='1.0'?>" << std::endl; std::cout << "<!DOCTYPE refentry PUBLIC \"-//OASIS//DTD DocBook XML V4.2//EN\"" << std::endl;
std::cout << "<!DOCTYPE refentry PUBLIC \"-//OASIS//DTD DocBook XML V4.2//EN\"" << std::endl; std::cout << "\t\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\">" << std::endl << std::endl;
std::cout << "\t\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\">" << std::endl << std::endl; std::cout << "<refentry>" << std::endl;
std::cout << "<refmeta>" << std::endl;
std::cout << "<refentry>" << std::endl; std::cout << "<refentrytitle>" << progName << "</refentrytitle>" << std::endl;
std::cout << "<manvolnum>1</manvolnum>" << std::endl;
std::cout << "<refmeta>" << std::endl; std::cout << "</refmeta>" << std::endl;
std::cout << "<refentrytitle>" << progName << "</refentrytitle>" << std::endl; std::cout << "<refnamediv>" << std::endl;
std::cout << "<manvolnum>1</manvolnum>" << std::endl; std::cout << "<refname>" << progName << "</refname>" << std::endl;
std::cout << "</refmeta>" << std::endl; std::cout << "<refpurpose>" << _cmd.getMessage() << "</refpurpose>" << std::endl;
std::cout << "</refnamediv>" << std::endl;
std::cout << "<refnamediv>" << std::endl; std::cout << "<refsynopsisdiv>" << std::endl;
std::cout << "<refname>" << progName << "</refname>" << std::endl; std::cout << "<cmdsynopsis>" << std::endl;
std::cout << "<refpurpose>" << _cmd.getMessage() << "</refpurpose>" << std::endl; std::cout << "<command>" << progName << "</command>" << std::endl;
std::cout << "</refnamediv>" << std::endl; // xor
for ( int i = 0; (unsigned int)i < xorList.size(); i++ )
std::cout << "<refsynopsisdiv>" << std::endl; {
std::cout << "<cmdsynopsis>" << std::endl; std::cout << "<group choice='req'>" << std::endl;
for ( ArgVectorIterator it = xorList[i].begin();
std::cout << "<command>" << progName << "</command>" << std::endl; it != xorList[i].end(); it++ )
printShortArg((*it));
// xor std::cout << "</group>" << std::endl;
for ( int i = 0; (unsigned int)i < xorList.size(); i++ ) }
{ // rest of args
std::cout << "<group choice='req'>" << std::endl; for (ArgListIterator it = argList.begin(); it != argList.end(); it++)
for ( ArgVectorIterator it = xorList[i].begin(); if ( !xorHandler.contains( (*it) ) )
it != xorList[i].end(); it++ ) printShortArg((*it));
printShortArg((*it)); std::cout << "</cmdsynopsis>" << std::endl;
std::cout << "</refsynopsisdiv>" << std::endl;
std::cout << "</group>" << std::endl; std::cout << "<refsect1>" << std::endl;
} std::cout << "<title>Description</title>" << std::endl;
std::cout << "<para>" << std::endl;
// rest of args std::cout << _cmd.getMessage() << std::endl;
for (ArgListIterator it = argList.begin(); it != argList.end(); it++) std::cout << "</para>" << std::endl;
if ( !xorHandler.contains( (*it) ) ) std::cout << "</refsect1>" << std::endl;
printShortArg((*it)); std::cout << "<refsect1>" << std::endl;
std::cout << "<title>Options</title>" << std::endl;
std::cout << "</cmdsynopsis>" << std::endl; std::cout << "<variablelist>" << std::endl;
std::cout << "</refsynopsisdiv>" << std::endl; for (ArgListIterator it = argList.begin(); it != argList.end(); it++)
printLongArg((*it));
std::cout << "<refsect1>" << std::endl; std::cout << "</variablelist>" << std::endl;
std::cout << "<title>Description</title>" << std::endl; std::cout << "</refsect1>" << std::endl;
std::cout << "<para>" << std::endl; std::cout << "<refsect1>" << std::endl;
std::cout << _cmd.getMessage() << std::endl; std::cout << "<title>Version</title>" << std::endl;
std::cout << "</para>" << std::endl; std::cout << "<para>" << std::endl;
std::cout << "</refsect1>" << std::endl; std::cout << xversion << std::endl;
std::cout << "</para>" << std::endl;
std::cout << "<refsect1>" << std::endl; std::cout << "</refsect1>" << std::endl;
std::cout << "<title>Options</title>" << std::endl; std::cout << "</refentry>" << std::endl;
std::cout << "<variablelist>" << std::endl;
for (ArgListIterator it = argList.begin(); it != argList.end(); it++)
printLongArg((*it));
std::cout << "</variablelist>" << std::endl;
std::cout << "</refsect1>" << std::endl;
std::cout << "<refsect1>" << std::endl;
std::cout << "<title>Version</title>" << std::endl;
std::cout << "<para>" << std::endl;
std::cout << xversion << std::endl;
std::cout << "</para>" << std::endl;
std::cout << "</refsect1>" << std::endl;
std::cout << "</refentry>" << std::endl;
} }
inline void DocBookOutput::failure( CmdLineInterface& _cmd, inline void DocBookOutput::failure( CmdLineInterface& _cmd,
ArgException& e ) ArgException& e )
{ {
static_cast<void>(_cmd); // unused static_cast<void>(_cmd); // unused
std::cout << e.what() << std::endl; std::cout << e.what() << std::endl;
throw ExitException(1); throw ExitException(1);
} }
inline void DocBookOutput::substituteSpecialChars( std::string& s, inline void DocBookOutput::substituteSpecialChars( std::string& s,
char r, char r,
std::string& x ) std::string& x )
{ {
size_t p; size_t p;
while ( (p = s.find_first_of(r)) != std::string::npos ) while ( (p = s.find_first_of(r)) != std::string::npos )
{ {
s.erase(p,1); s.erase(p,1);
s.insert(p,x); s.insert(p,x);
} }
} }
inline void DocBookOutput::removeChar( std::string& s, char r) inline void DocBookOutput::removeChar( std::string& s, char r)
{ {
size_t p; size_t p;
while ( (p = s.find_first_of(r)) != std::string::npos ) while ( (p = s.find_first_of(r)) != std::string::npos )
{ {
s.erase(p,1); s.erase(p,1);
} }
} }
inline void DocBookOutput::basename( std::string& s ) inline void DocBookOutput::basename( std::string& s )
{ {
size_t p = s.find_last_of('/'); size_t p = s.find_last_of('/');
if ( p != std::string::npos ) if ( p != std::string::npos )
{ {
s.erase(0, p + 1); s.erase(0, p + 1);
} }
} }
inline void DocBookOutput::printShortArg(Arg* a) inline void DocBookOutput::printShortArg(Arg* a)
{ {
std::string lt = "&lt;"; std::string lt = "&lt;";
std::string gt = "&gt;"; std::string gt = "&gt;";
std::string id = a->shortID();
std::string id = a->shortID(); substituteSpecialChars(id,'<',lt);
substituteSpecialChars(id,'<',lt); substituteSpecialChars(id,'>',gt);
substituteSpecialChars(id,'>',gt); removeChar(id,'[');
removeChar(id,'['); removeChar(id,']');
removeChar(id,']'); std::string choice = "opt";
if ( a->isRequired() )
std::string choice = "opt"; choice = "plain";
if ( a->isRequired() ) std::cout << "<arg choice='" << choice << '\'';
choice = "plain"; if ( a->acceptsMultipleValues() )
std::cout << " rep='repeat'";
std::cout << "<arg choice='" << choice << '\''; std::cout << '>';
if ( a->acceptsMultipleValues() ) if ( !a->getFlag().empty() )
std::cout << " rep='repeat'"; std::cout << a->flagStartChar() << a->getFlag();
else
std::cout << a->nameStartString() << a->getName();
std::cout << '>'; if ( a->isValueRequired() )
if ( !a->getFlag().empty() ) {
std::cout << a->flagStartChar() << a->getFlag(); std::string arg = a->shortID();
else removeChar(arg,'[');
std::cout << a->nameStartString() << a->getName(); removeChar(arg,']');
if ( a->isValueRequired() ) removeChar(arg,'<');
{ removeChar(arg,'>');
std::string arg = a->shortID(); arg.erase(0, arg.find_last_of(theDelimiter) + 1);
removeChar(arg,'['); std::cout << theDelimiter;
removeChar(arg,']'); std::cout << "<replaceable>" << arg << "</replaceable>";
removeChar(arg,'<'); }
removeChar(arg,'>'); std::cout << "</arg>" << std::endl;
arg.erase(0, arg.find_last_of(theDelimiter) + 1);
std::cout << theDelimiter;
std::cout << "<replaceable>" << arg << "</replaceable>";
}
std::cout << "</arg>" << std::endl;
} }
inline void DocBookOutput::printLongArg(Arg* a) inline void DocBookOutput::printLongArg(Arg* a)
{ {
std::string lt = "&lt;"; std::string lt = "&lt;";
std::string gt = "&gt;"; std::string gt = "&gt;";
std::string desc = a->getDescription();
std::string desc = a->getDescription(); substituteSpecialChars(desc,'<',lt);
substituteSpecialChars(desc,'<',lt); substituteSpecialChars(desc,'>',gt);
substituteSpecialChars(desc,'>',gt); std::cout << "<varlistentry>" << std::endl;
if ( !a->getFlag().empty() )
std::cout << "<varlistentry>" << std::endl; {
std::cout << "<term>" << std::endl;
if ( !a->getFlag().empty() ) std::cout << "<option>";
{ std::cout << a->flagStartChar() << a->getFlag();
std::cout << "<term>" << std::endl; std::cout << "</option>" << std::endl;
std::cout << "<option>"; std::cout << "</term>" << std::endl;
std::cout << a->flagStartChar() << a->getFlag(); }
std::cout << "</option>" << std::endl; std::cout << "<term>" << std::endl;
std::cout << "</term>" << std::endl; std::cout << "<option>";
} std::cout << a->nameStartString() << a->getName();
if ( a->isValueRequired() )
std::cout << "<term>" << std::endl; {
std::cout << "<option>"; std::string arg = a->shortID();
std::cout << a->nameStartString() << a->getName(); removeChar(arg,'[');
if ( a->isValueRequired() ) removeChar(arg,']');
{ removeChar(arg,'<');
std::string arg = a->shortID(); removeChar(arg,'>');
removeChar(arg,'['); arg.erase(0, arg.find_last_of(theDelimiter) + 1);
removeChar(arg,']'); std::cout << theDelimiter;
removeChar(arg,'<'); std::cout << "<replaceable>" << arg << "</replaceable>";
removeChar(arg,'>'); }
arg.erase(0, arg.find_last_of(theDelimiter) + 1); std::cout << "</option>" << std::endl;
std::cout << theDelimiter; std::cout << "</term>" << std::endl;
std::cout << "<replaceable>" << arg << "</replaceable>"; std::cout << "<listitem>" << std::endl;
} std::cout << "<para>" << std::endl;
std::cout << "</option>" << std::endl; std::cout << desc << std::endl;
std::cout << "</term>" << std::endl; std::cout << "</para>" << std::endl;
std::cout << "</listitem>" << std::endl;
std::cout << "<listitem>" << std::endl; std::cout << "</varlistentry>" << std::endl;
std::cout << "<para>" << std::endl;
std::cout << desc << std::endl;
std::cout << "</para>" << std::endl;
std::cout << "</listitem>" << std::endl;
std::cout << "</varlistentry>" << std::endl;
} }
} //namespace TCLAP } //namespace TCLAP

View File

@@ -26,7 +26,8 @@
#include "CmdLineOutput.h" #include "CmdLineOutput.h"
#include "Visitor.h" #include "Visitor.h"
namespace TCLAP { namespace TCLAP
{
/** /**
* A Visitor object that calls the usage method of the given CmdLineOutput * A Visitor object that calls the usage method of the given CmdLineOutput
@@ -34,40 +35,44 @@ namespace TCLAP {
*/ */
class HelpVisitor: public Visitor class HelpVisitor: public Visitor
{ {
private: private:
/** /**
* Prevent accidental copying. * Prevent accidental copying.
*/ */
HelpVisitor(const HelpVisitor& rhs); HelpVisitor(const HelpVisitor& rhs);
HelpVisitor& operator=(const HelpVisitor& rhs); HelpVisitor& operator=(const HelpVisitor& rhs);
protected: protected:
/** /**
* The CmdLine the output will be generated for. * The CmdLine the output will be generated for.
*/ */
CmdLineInterface* _cmd; CmdLineInterface* _cmd;
/** /**
* The output object. * The output object.
*/ */
CmdLineOutput** _out; CmdLineOutput** _out;
public: public:
/** /**
* Constructor. * Constructor.
* \param cmd - The CmdLine the output will be generated for. * \param cmd - The CmdLine the output will be generated for.
* \param out - The type of output. * \param out - The type of output.
*/ */
HelpVisitor(CmdLineInterface* cmd, CmdLineOutput** out) HelpVisitor(CmdLineInterface* cmd, CmdLineOutput** out)
: Visitor(), _cmd( cmd ), _out( out ) { } : Visitor(), _cmd( cmd ), _out( out ) { }
/** /**
* Calls the usage method of the CmdLineOutput for the * Calls the usage method of the CmdLineOutput for the
* specified CmdLine. * specified CmdLine.
*/ */
void visit() { (*_out)->usage(*_cmd); throw ExitException(0); } void visit()
{
(*_out)->usage(*_cmd);
throw ExitException(0);
}
}; };

View File

@@ -26,7 +26,8 @@
#include "Visitor.h" #include "Visitor.h"
#include "Arg.h" #include "Arg.h"
namespace TCLAP { namespace TCLAP
{
/** /**
* A Vistor that tells the CmdLine to begin ignoring arguments after * A Vistor that tells the CmdLine to begin ignoring arguments after
@@ -34,17 +35,20 @@ namespace TCLAP {
*/ */
class IgnoreRestVisitor: public Visitor class IgnoreRestVisitor: public Visitor
{ {
public: public:
/** /**
* Constructor. * Constructor.
*/ */
IgnoreRestVisitor() : Visitor() {} IgnoreRestVisitor() : Visitor() {}
/** /**
* Sets Arg::_ignoreRest. * Sets Arg::_ignoreRest.
*/ */
void visit() { Arg::beginIgnoring(); } void visit()
{
Arg::beginIgnoring();
}
}; };
} }

View File

@@ -29,7 +29,8 @@
#include "Arg.h" #include "Arg.h"
#include "Constraint.h" #include "Constraint.h"
namespace TCLAP { namespace TCLAP
{
/** /**
* An argument that allows multiple values of type T to be specified. Very * An argument that allows multiple values of type T to be specified. Very
* similar to a ValueArg, except a vector of values will be returned * similar to a ValueArg, except a vector of values will be returned
@@ -38,195 +39,201 @@ namespace TCLAP {
template<class T> template<class T>
class MultiArg : public Arg class MultiArg : public Arg
{ {
public: public:
typedef std::vector<T> container_type; typedef std::vector<T> container_type;
typedef typename container_type::iterator iterator; typedef typename container_type::iterator iterator;
typedef typename container_type::const_iterator const_iterator; typedef typename container_type::const_iterator const_iterator;
protected: protected:
/** /**
* The list of values parsed from the CmdLine. * The list of values parsed from the CmdLine.
*/ */
std::vector<T> _values; std::vector<T> _values;
/** /**
* The description of type T to be used in the usage. * The description of type T to be used in the usage.
*/ */
std::string _typeDesc; std::string _typeDesc;
/** /**
* A list of constraint on this Arg. * A list of constraint on this Arg.
*/ */
Constraint<T>* _constraint; Constraint<T>* _constraint;
/** /**
* Extracts the value from the string. * Extracts the value from the string.
* Attempts to parse string as type T, if this fails an exception * Attempts to parse string as type T, if this fails an exception
* is thrown. * is thrown.
* \param val - The string to be read. * \param val - The string to be read.
*/ */
void _extractValue( const std::string& val ); void _extractValue( const std::string& val );
/** /**
* Used by XorHandler to decide whether to keep parsing for this arg. * Used by XorHandler to decide whether to keep parsing for this arg.
*/ */
bool _allowMore; bool _allowMore;
public: public:
/** /**
* Constructor. * Constructor.
* \param flag - The one character flag that identifies this * \param flag - The one character flag that identifies this
* argument on the command line. * argument on the command line.
* \param name - A one word name for the argument. Can be * \param name - A one word name for the argument. Can be
* used as a long flag on the command line. * used as a long flag on the command line.
* \param desc - A description of what the argument is for or * \param desc - A description of what the argument is for or
* does. * does.
* \param req - Whether the argument is required on the command * \param req - Whether the argument is required on the command
* line. * line.
* \param typeDesc - A short, human readable description of the * \param typeDesc - A short, human readable description of the
* type that this object expects. This is used in the generation * type that this object expects. This is used in the generation
* of the USAGE statement. The goal is to be helpful to the end user * of the USAGE statement. The goal is to be helpful to the end user
* of the program. * of the program.
* \param v - An optional visitor. You probably should not * \param v - An optional visitor. You probably should not
* use this unless you have a very good reason. * use this unless you have a very good reason.
*/ */
MultiArg( const std::string& flag, MultiArg( const std::string& flag,
const std::string& name, const std::string& name,
const std::string& desc, const std::string& desc,
bool req, bool req,
const std::string& typeDesc, const std::string& typeDesc,
Visitor* v = NULL); Visitor* v = NULL);
/** /**
* Constructor. * Constructor.
* \param flag - The one character flag that identifies this * \param flag - The one character flag that identifies this
* argument on the command line. * argument on the command line.
* \param name - A one word name for the argument. Can be * \param name - A one word name for the argument. Can be
* used as a long flag on the command line. * used as a long flag on the command line.
* \param desc - A description of what the argument is for or * \param desc - A description of what the argument is for or
* does. * does.
* \param req - Whether the argument is required on the command * \param req - Whether the argument is required on the command
* line. * line.
* \param typeDesc - A short, human readable description of the * \param typeDesc - A short, human readable description of the
* type that this object expects. This is used in the generation * type that this object expects. This is used in the generation
* of the USAGE statement. The goal is to be helpful to the end user * of the USAGE statement. The goal is to be helpful to the end user
* of the program. * of the program.
* \param parser - A CmdLine parser object to add this Arg to * \param parser - A CmdLine parser object to add this Arg to
* \param v - An optional visitor. You probably should not * \param v - An optional visitor. You probably should not
* use this unless you have a very good reason. * use this unless you have a very good reason.
*/ */
MultiArg( const std::string& flag, MultiArg( const std::string& flag,
const std::string& name, const std::string& name,
const std::string& desc, const std::string& desc,
bool req, bool req,
const std::string& typeDesc, const std::string& typeDesc,
CmdLineInterface& parser, CmdLineInterface& parser,
Visitor* v = NULL ); Visitor* v = NULL );
/** /**
* Constructor. * Constructor.
* \param flag - The one character flag that identifies this * \param flag - The one character flag that identifies this
* argument on the command line. * argument on the command line.
* \param name - A one word name for the argument. Can be * \param name - A one word name for the argument. Can be
* used as a long flag on the command line. * used as a long flag on the command line.
* \param desc - A description of what the argument is for or * \param desc - A description of what the argument is for or
* does. * does.
* \param req - Whether the argument is required on the command * \param req - Whether the argument is required on the command
* line. * line.
* \param constraint - A pointer to a Constraint object used * \param constraint - A pointer to a Constraint object used
* to constrain this Arg. * to constrain this Arg.
* \param v - An optional visitor. You probably should not * \param v - An optional visitor. You probably should not
* use this unless you have a very good reason. * use this unless you have a very good reason.
*/ */
MultiArg( const std::string& flag, MultiArg( const std::string& flag,
const std::string& name, const std::string& name,
const std::string& desc, const std::string& desc,
bool req, bool req,
Constraint<T>* constraint, Constraint<T>* constraint,
Visitor* v = NULL ); Visitor* v = NULL );
/** /**
* Constructor. * Constructor.
* \param flag - The one character flag that identifies this * \param flag - The one character flag that identifies this
* argument on the command line. * argument on the command line.
* \param name - A one word name for the argument. Can be * \param name - A one word name for the argument. Can be
* used as a long flag on the command line. * used as a long flag on the command line.
* \param desc - A description of what the argument is for or * \param desc - A description of what the argument is for or
* does. * does.
* \param req - Whether the argument is required on the command * \param req - Whether the argument is required on the command
* line. * line.
* \param constraint - A pointer to a Constraint object used * \param constraint - A pointer to a Constraint object used
* to constrain this Arg. * to constrain this Arg.
* \param parser - A CmdLine parser object to add this Arg to * \param parser - A CmdLine parser object to add this Arg to
* \param v - An optional visitor. You probably should not * \param v - An optional visitor. You probably should not
* use this unless you have a very good reason. * use this unless you have a very good reason.
*/ */
MultiArg( const std::string& flag, MultiArg( const std::string& flag,
const std::string& name, const std::string& name,
const std::string& desc, const std::string& desc,
bool req, bool req,
Constraint<T>* constraint, Constraint<T>* constraint,
CmdLineInterface& parser, CmdLineInterface& parser,
Visitor* v = NULL ); Visitor* v = NULL );
/** /**
* Handles the processing of the argument. * Handles the processing of the argument.
* This re-implements the Arg version of this method to set the * This re-implements the Arg version of this method to set the
* _value of the argument appropriately. It knows the difference * _value of the argument appropriately. It knows the difference
* between labeled and unlabeled. * between labeled and unlabeled.
* \param i - Pointer the the current argument in the list. * \param i - Pointer the the current argument in the list.
* \param args - Mutable list of strings. Passed from main(). * \param args - Mutable list of strings. Passed from main().
*/ */
virtual bool processArg(int* i, std::vector<std::string>& args); virtual bool processArg(int* i, std::vector<std::string>& args);
/** /**
* Returns a vector of type T containing the values parsed from * Returns a vector of type T containing the values parsed from
* the command line. * the command line.
*/ */
const std::vector<T>& getValue(); const std::vector<T>& getValue();
/** /**
* Returns an iterator over the values parsed from the command * Returns an iterator over the values parsed from the command
* line. * line.
*/ */
const_iterator begin() const { return _values.begin(); } const_iterator begin() const
{
return _values.begin();
}
/** /**
* Returns the end of the values parsed from the command * Returns the end of the values parsed from the command
* line. * line.
*/ */
const_iterator end() const { return _values.end(); } const_iterator end() const
{
return _values.end();
}
/** /**
* Returns the a short id string. Used in the usage. * Returns the a short id string. Used in the usage.
* \param val - value to be used. * \param val - value to be used.
*/ */
virtual std::string shortID(const std::string& val="val") const; virtual std::string shortID(const std::string& val="val") const;
/** /**
* Returns the a long id string. Used in the usage. * Returns the a long id string. Used in the usage.
* \param val - value to be used. * \param val - value to be used.
*/ */
virtual std::string longID(const std::string& val="val") const; virtual std::string longID(const std::string& val="val") const;
/** /**
* Once we've matched the first value, then the arg is no longer * Once we've matched the first value, then the arg is no longer
* required. * required.
*/ */
virtual bool isRequired() const; virtual bool isRequired() const;
virtual bool allowMore(); virtual bool allowMore();
virtual void reset(); virtual void reset();
private: private:
/** /**
* Prevent accidental copying * Prevent accidental copying
*/ */
MultiArg<T>(const MultiArg<T>& rhs); MultiArg<T>(const MultiArg<T>& rhs);
MultiArg<T>& operator=(const MultiArg<T>& rhs); MultiArg<T>& operator=(const MultiArg<T>& rhs);
}; };
@@ -237,13 +244,13 @@ MultiArg<T>::MultiArg(const std::string& flag,
bool req, bool req,
const std::string& typeDesc, const std::string& typeDesc,
Visitor* v) : Visitor* v) :
Arg( flag, name, desc, req, true, v ), Arg( flag, name, desc, req, true, v ),
_values(std::vector<T>()), _values(std::vector<T>()),
_typeDesc( typeDesc ), _typeDesc( typeDesc ),
_constraint( NULL ), _constraint( NULL ),
_allowMore(false) _allowMore(false)
{ {
_acceptsMultipleValues = true; _acceptsMultipleValues = true;
} }
template<class T> template<class T>
@@ -254,14 +261,14 @@ MultiArg<T>::MultiArg(const std::string& flag,
const std::string& typeDesc, const std::string& typeDesc,
CmdLineInterface& parser, CmdLineInterface& parser,
Visitor* v) Visitor* v)
: Arg( flag, name, desc, req, true, v ), : Arg( flag, name, desc, req, true, v ),
_values(std::vector<T>()), _values(std::vector<T>()),
_typeDesc( typeDesc ), _typeDesc( typeDesc ),
_constraint( NULL ), _constraint( NULL ),
_allowMore(false) _allowMore(false)
{ {
parser.add( this ); parser.add( this );
_acceptsMultipleValues = true; _acceptsMultipleValues = true;
} }
/** /**
@@ -274,13 +281,13 @@ MultiArg<T>::MultiArg(const std::string& flag,
bool req, bool req,
Constraint<T>* constraint, Constraint<T>* constraint,
Visitor* v) Visitor* v)
: Arg( flag, name, desc, req, true, v ), : Arg( flag, name, desc, req, true, v ),
_values(std::vector<T>()), _values(std::vector<T>()),
_typeDesc( constraint->shortID() ), _typeDesc( constraint->shortID() ),
_constraint( constraint ), _constraint( constraint ),
_allowMore(false) _allowMore(false)
{ {
_acceptsMultipleValues = true; _acceptsMultipleValues = true;
} }
template<class T> template<class T>
@@ -291,68 +298,63 @@ MultiArg<T>::MultiArg(const std::string& flag,
Constraint<T>* constraint, Constraint<T>* constraint,
CmdLineInterface& parser, CmdLineInterface& parser,
Visitor* v) Visitor* v)
: Arg( flag, name, desc, req, true, v ), : Arg( flag, name, desc, req, true, v ),
_values(std::vector<T>()), _values(std::vector<T>()),
_typeDesc( constraint->shortID() ), _typeDesc( constraint->shortID() ),
_constraint( constraint ), _constraint( constraint ),
_allowMore(false) _allowMore(false)
{ {
parser.add( this ); parser.add( this );
_acceptsMultipleValues = true; _acceptsMultipleValues = true;
} }
template<class T> template<class T>
const std::vector<T>& MultiArg<T>::getValue() { return _values; } const std::vector<T>& MultiArg<T>::getValue()
{
return _values;
}
template<class T> template<class T>
bool MultiArg<T>::processArg(int *i, std::vector<std::string>& args) bool MultiArg<T>::processArg(int *i, std::vector<std::string>& args)
{ {
if ( _ignoreable && Arg::ignoreRest() ) if ( _ignoreable && Arg::ignoreRest() )
return false; return false;
if ( _hasBlanks( args[*i] ) )
if ( _hasBlanks( args[*i] ) ) return false;
return false; std::string flag = args[*i];
std::string value = "";
std::string flag = args[*i]; trimFlag( flag, value );
std::string value = ""; if ( argMatches( flag ) )
{
trimFlag( flag, value ); if ( Arg::delimiter() != ' ' && value == "" )
throw( ArgParseException(
if ( argMatches( flag ) ) "Couldn't find delimiter for this argument!",
{ toString() ) );
if ( Arg::delimiter() != ' ' && value == "" ) // always take the first one, regardless of start string
throw( ArgParseException( if ( value == "" )
"Couldn't find delimiter for this argument!", {
toString() ) ); (*i)++;
if ( static_cast<unsigned int>(*i) < args.size() )
// always take the first one, regardless of start string _extractValue( args[*i] );
if ( value == "" ) else
{ throw( ArgParseException("Missing a value for this argument!",
(*i)++; toString() ) );
if ( static_cast<unsigned int>(*i) < args.size() ) }
_extractValue( args[*i] ); else
else _extractValue( value );
throw( ArgParseException("Missing a value for this argument!", /*
toString() ) ); // continuing taking the args until we hit one with a start string
} while ( (unsigned int)(*i)+1 < args.size() &&
else args[(*i)+1].find_first_of( Arg::flagStartString() ) != 0 &&
_extractValue( value ); args[(*i)+1].find_first_of( Arg::nameStartString() ) != 0 )
_extractValue( args[++(*i)] );
/* */
// continuing taking the args until we hit one with a start string _alreadySet = true;
while ( (unsigned int)(*i)+1 < args.size() && _checkWithVisitor();
args[(*i)+1].find_first_of( Arg::flagStartString() ) != 0 && return true;
args[(*i)+1].find_first_of( Arg::nameStartString() ) != 0 ) }
_extractValue( args[++(*i)] ); else
*/ return false;
_alreadySet = true;
_checkWithVisitor();
return true;
}
else
return false;
} }
/** /**
@@ -361,8 +363,8 @@ bool MultiArg<T>::processArg(int *i, std::vector<std::string>& args)
template<class T> template<class T>
std::string MultiArg<T>::shortID(const std::string& val) const std::string MultiArg<T>::shortID(const std::string& val) const
{ {
static_cast<void>(val); // Ignore input, don't warn static_cast<void>(val); // Ignore input, don't warn
return Arg::shortID(_typeDesc) + " ... "; return Arg::shortID(_typeDesc) + " ... ";
} }
/** /**
@@ -371,8 +373,8 @@ std::string MultiArg<T>::shortID(const std::string& val) const
template<class T> template<class T>
std::string MultiArg<T>::longID(const std::string& val) const std::string MultiArg<T>::longID(const std::string& val) const
{ {
static_cast<void>(val); // Ignore input, don't warn static_cast<void>(val); // Ignore input, don't warn
return Arg::longID(_typeDesc) + " (accepted multiple times)"; return Arg::longID(_typeDesc) + " (accepted multiple times)";
} }
/** /**
@@ -382,50 +384,51 @@ std::string MultiArg<T>::longID(const std::string& val) const
template<class T> template<class T>
bool MultiArg<T>::isRequired() const bool MultiArg<T>::isRequired() const
{ {
if ( _required ) if ( _required )
{ {
if ( _values.size() > 1 ) if ( _values.size() > 1 )
return false; return false;
else else
return true; return true;
} }
else else
return false; return false;
} }
template<class T> template<class T>
void MultiArg<T>::_extractValue( const std::string& val ) void MultiArg<T>::_extractValue( const std::string& val )
{ {
try { try
T tmp; {
ExtractValue(tmp, val, typename ArgTraits<T>::ValueCategory()); T tmp;
_values.push_back(tmp); ExtractValue(tmp, val, typename ArgTraits<T>::ValueCategory());
} catch( ArgParseException &e) { _values.push_back(tmp);
throw ArgParseException(e.error(), toString()); }
} catch( ArgParseException &e)
{
if ( _constraint != NULL ) throw ArgParseException(e.error(), toString());
if ( ! _constraint->check( _values.back() ) ) }
throw( CmdLineParseException( "Value '" + val + if ( _constraint != NULL )
"' does not meet constraint: " + if ( ! _constraint->check( _values.back() ) )
_constraint->description(), throw( CmdLineParseException( "Value '" + val +
toString() ) ); "' does not meet constraint: " +
_constraint->description(),
toString() ) );
} }
template<class T> template<class T>
bool MultiArg<T>::allowMore() bool MultiArg<T>::allowMore()
{ {
bool am = _allowMore; bool am = _allowMore;
_allowMore = true; _allowMore = true;
return am; return am;
} }
template<class T> template<class T>
void MultiArg<T>::reset() void MultiArg<T>::reset()
{ {
Arg::reset(); Arg::reset();
_values.clear(); _values.clear();
} }
} // namespace TCLAP } // namespace TCLAP

View File

@@ -30,7 +30,8 @@
#include "SwitchArg.h" #include "SwitchArg.h"
namespace TCLAP { namespace TCLAP
{
/** /**
* A multiple switch argument. If the switch is set on the command line, then * A multiple switch argument. If the switch is set on the command line, then
@@ -38,89 +39,89 @@ namespace TCLAP {
*/ */
class MultiSwitchArg : public SwitchArg class MultiSwitchArg : public SwitchArg
{ {
protected: protected:
/** /**
* The value of the switch. * The value of the switch.
*/ */
int _value; int _value;
/** /**
* Used to support the reset() method so that ValueArg can be * Used to support the reset() method so that ValueArg can be
* reset to their constructed value. * reset to their constructed value.
*/ */
int _default; int _default;
public: public:
/** /**
* MultiSwitchArg constructor. * MultiSwitchArg constructor.
* \param flag - The one character flag that identifies this * \param flag - The one character flag that identifies this
* argument on the command line. * argument on the command line.
* \param name - A one word name for the argument. Can be * \param name - A one word name for the argument. Can be
* used as a long flag on the command line. * used as a long flag on the command line.
* \param desc - A description of what the argument is for or * \param desc - A description of what the argument is for or
* does. * does.
* \param init - Optional. The initial/default value of this Arg. * \param init - Optional. The initial/default value of this Arg.
* Defaults to 0. * Defaults to 0.
* \param v - An optional visitor. You probably should not * \param v - An optional visitor. You probably should not
* use this unless you have a very good reason. * use this unless you have a very good reason.
*/ */
MultiSwitchArg(const std::string& flag, MultiSwitchArg(const std::string& flag,
const std::string& name, const std::string& name,
const std::string& desc, const std::string& desc,
int init = 0, int init = 0,
Visitor* v = NULL); Visitor* v = NULL);
/** /**
* MultiSwitchArg constructor. * MultiSwitchArg constructor.
* \param flag - The one character flag that identifies this * \param flag - The one character flag that identifies this
* argument on the command line. * argument on the command line.
* \param name - A one word name for the argument. Can be * \param name - A one word name for the argument. Can be
* used as a long flag on the command line. * used as a long flag on the command line.
* \param desc - A description of what the argument is for or * \param desc - A description of what the argument is for or
* does. * does.
* \param parser - A CmdLine parser object to add this Arg to * \param parser - A CmdLine parser object to add this Arg to
* \param init - Optional. The initial/default value of this Arg. * \param init - Optional. The initial/default value of this Arg.
* Defaults to 0. * Defaults to 0.
* \param v - An optional visitor. You probably should not * \param v - An optional visitor. You probably should not
* use this unless you have a very good reason. * use this unless you have a very good reason.
*/ */
MultiSwitchArg(const std::string& flag, MultiSwitchArg(const std::string& flag,
const std::string& name, const std::string& name,
const std::string& desc, const std::string& desc,
CmdLineInterface& parser, CmdLineInterface& parser,
int init = 0, int init = 0,
Visitor* v = NULL); Visitor* v = NULL);
/** /**
* Handles the processing of the argument. * Handles the processing of the argument.
* This re-implements the SwitchArg version of this method to set the * This re-implements the SwitchArg version of this method to set the
* _value of the argument appropriately. * _value of the argument appropriately.
* \param i - Pointer the the current argument in the list. * \param i - Pointer the the current argument in the list.
* \param args - Mutable list of strings. Passed * \param args - Mutable list of strings. Passed
* in from main(). * in from main().
*/ */
virtual bool processArg(int* i, std::vector<std::string>& args); virtual bool processArg(int* i, std::vector<std::string>& args);
/** /**
* Returns int, the number of times the switch has been set. * Returns int, the number of times the switch has been set.
*/ */
int getValue(); int getValue();
/** /**
* Returns the shortID for this Arg. * Returns the shortID for this Arg.
*/ */
std::string shortID(const std::string& val) const; std::string shortID(const std::string& val) const;
/** /**
* Returns the longID for this Arg. * Returns the longID for this Arg.
*/ */
std::string longID(const std::string& val) const; std::string longID(const std::string& val) const;
void reset(); void reset();
}; };
@@ -128,83 +129,78 @@ class MultiSwitchArg : public SwitchArg
//BEGIN MultiSwitchArg.cpp //BEGIN MultiSwitchArg.cpp
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
inline MultiSwitchArg::MultiSwitchArg(const std::string& flag, inline MultiSwitchArg::MultiSwitchArg(const std::string& flag,
const std::string& name, const std::string& name,
const std::string& desc, const std::string& desc,
int init, int init,
Visitor* v ) Visitor* v )
: SwitchArg(flag, name, desc, false, v), : SwitchArg(flag, name, desc, false, v),
_value( init ), _value( init ),
_default( init ) _default( init )
{ } { }
inline MultiSwitchArg::MultiSwitchArg(const std::string& flag, inline MultiSwitchArg::MultiSwitchArg(const std::string& flag,
const std::string& name, const std::string& name,
const std::string& desc, const std::string& desc,
CmdLineInterface& parser, CmdLineInterface& parser,
int init, int init,
Visitor* v ) Visitor* v )
: SwitchArg(flag, name, desc, false, v), : SwitchArg(flag, name, desc, false, v),
_value( init ), _value( init ),
_default( init ) _default( init )
{ {
parser.add( this ); parser.add( this );
} }
inline int MultiSwitchArg::getValue() { return _value; } inline int MultiSwitchArg::getValue()
{
return _value;
}
inline bool MultiSwitchArg::processArg(int *i, std::vector<std::string>& args) inline bool MultiSwitchArg::processArg(int *i, std::vector<std::string>& args)
{ {
if ( _ignoreable && Arg::ignoreRest() ) if ( _ignoreable && Arg::ignoreRest() )
return false; return false;
if ( argMatches( args[*i] ))
if ( argMatches( args[*i] )) {
{ // so the isSet() method will work
// so the isSet() method will work _alreadySet = true;
_alreadySet = true; // Matched argument: increment value.
++_value;
// Matched argument: increment value. _checkWithVisitor();
++_value; return true;
}
_checkWithVisitor(); else if ( combinedSwitchesMatch( args[*i] ) )
{
return true; // so the isSet() method will work
} _alreadySet = true;
else if ( combinedSwitchesMatch( args[*i] ) ) // Matched argument: increment value.
{ ++_value;
// so the isSet() method will work // Check for more in argument and increment value.
_alreadySet = true; while ( combinedSwitchesMatch( args[*i] ) )
++_value;
// Matched argument: increment value. _checkWithVisitor();
++_value; return false;
}
// Check for more in argument and increment value. else
while ( combinedSwitchesMatch( args[*i] ) ) return false;
++_value;
_checkWithVisitor();
return false;
}
else
return false;
} }
inline std::string inline std::string
MultiSwitchArg::shortID(const std::string& val) const MultiSwitchArg::shortID(const std::string& val) const
{ {
return Arg::shortID(val) + " ... "; return Arg::shortID(val) + " ... ";
} }
inline std::string inline std::string
MultiSwitchArg::longID(const std::string& val) const MultiSwitchArg::longID(const std::string& val) const
{ {
return Arg::longID(val) + " (accepted multiple times)"; return Arg::longID(val) + " (accepted multiple times)";
} }
inline void inline void
MultiSwitchArg::reset() MultiSwitchArg::reset()
{ {
MultiSwitchArg::_value = MultiSwitchArg::_default; MultiSwitchArg::_value = MultiSwitchArg::_default;
} }
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////

View File

@@ -26,34 +26,44 @@
#include <string> #include <string>
namespace TCLAP { namespace TCLAP
{
class OptionalUnlabeledTracker class OptionalUnlabeledTracker
{ {
public: public:
static void check( bool req, const std::string& argName ); static void check( bool req, const std::string& argName );
static void gotOptional() { alreadyOptionalRef() = true; } static void gotOptional()
{
alreadyOptionalRef() = true;
}
static bool& alreadyOptional() { return alreadyOptionalRef(); } static bool& alreadyOptional()
{
return alreadyOptionalRef();
}
private: private:
static bool& alreadyOptionalRef() { static bool ct = false; return ct; } static bool& alreadyOptionalRef()
{
static bool ct = false;
return ct;
}
}; };
inline void OptionalUnlabeledTracker::check( bool req, const std::string& argName ) inline void OptionalUnlabeledTracker::check( bool req, const std::string& argName )
{ {
if ( OptionalUnlabeledTracker::alreadyOptional() ) if ( OptionalUnlabeledTracker::alreadyOptional() )
throw( SpecificationException( throw( SpecificationException(
"You can't specify ANY Unlabeled Arg following an optional Unlabeled Arg", "You can't specify ANY Unlabeled Arg following an optional Unlabeled Arg",
argName ) ); argName ) );
if ( !req )
if ( !req ) OptionalUnlabeledTracker::gotOptional();
OptionalUnlabeledTracker::gotOptional();
} }

View File

@@ -39,7 +39,8 @@
#endif #endif
#endif #endif
namespace TCLAP { namespace TCLAP
{
// ====================================================================== // ======================================================================
// Integer types // Integer types
@@ -49,32 +50,36 @@ namespace TCLAP {
* longs have value-like semantics. * longs have value-like semantics.
*/ */
template<> template<>
struct ArgTraits<long> { struct ArgTraits<long>
typedef ValueLike ValueCategory; {
typedef ValueLike ValueCategory;
}; };
/** /**
* ints have value-like semantics. * ints have value-like semantics.
*/ */
template<> template<>
struct ArgTraits<int> { struct ArgTraits<int>
typedef ValueLike ValueCategory; {
typedef ValueLike ValueCategory;
}; };
/** /**
* shorts have value-like semantics. * shorts have value-like semantics.
*/ */
template<> template<>
struct ArgTraits<short> { struct ArgTraits<short>
typedef ValueLike ValueCategory; {
typedef ValueLike ValueCategory;
}; };
/** /**
* chars have value-like semantics. * chars have value-like semantics.
*/ */
template<> template<>
struct ArgTraits<char> { struct ArgTraits<char>
typedef ValueLike ValueCategory; {
typedef ValueLike ValueCategory;
}; };
#ifdef HAVE_LONG_LONG #ifdef HAVE_LONG_LONG
@@ -82,8 +87,9 @@ struct ArgTraits<char> {
* long longs have value-like semantics. * long longs have value-like semantics.
*/ */
template<> template<>
struct ArgTraits<long long> { struct ArgTraits<long long>
typedef ValueLike ValueCategory; {
typedef ValueLike ValueCategory;
}; };
#endif #endif
@@ -95,32 +101,36 @@ struct ArgTraits<long long> {
* unsigned longs have value-like semantics. * unsigned longs have value-like semantics.
*/ */
template<> template<>
struct ArgTraits<unsigned long> { struct ArgTraits<unsigned long>
typedef ValueLike ValueCategory; {
typedef ValueLike ValueCategory;
}; };
/** /**
* unsigned ints have value-like semantics. * unsigned ints have value-like semantics.
*/ */
template<> template<>
struct ArgTraits<unsigned int> { struct ArgTraits<unsigned int>
typedef ValueLike ValueCategory; {
typedef ValueLike ValueCategory;
}; };
/** /**
* unsigned shorts have value-like semantics. * unsigned shorts have value-like semantics.
*/ */
template<> template<>
struct ArgTraits<unsigned short> { struct ArgTraits<unsigned short>
typedef ValueLike ValueCategory; {
typedef ValueLike ValueCategory;
}; };
/** /**
* unsigned chars have value-like semantics. * unsigned chars have value-like semantics.
*/ */
template<> template<>
struct ArgTraits<unsigned char> { struct ArgTraits<unsigned char>
typedef ValueLike ValueCategory; {
typedef ValueLike ValueCategory;
}; };
// Microsoft implements size_t awkwardly. // Microsoft implements size_t awkwardly.
@@ -129,8 +139,9 @@ struct ArgTraits<unsigned char> {
* size_ts have value-like semantics. * size_ts have value-like semantics.
*/ */
template<> template<>
struct ArgTraits<size_t> { struct ArgTraits<size_t>
typedef ValueLike ValueCategory; {
typedef ValueLike ValueCategory;
}; };
#endif #endif
@@ -140,8 +151,9 @@ struct ArgTraits<size_t> {
* unsigned long longs have value-like semantics. * unsigned long longs have value-like semantics.
*/ */
template<> template<>
struct ArgTraits<unsigned long long> { struct ArgTraits<unsigned long long>
typedef ValueLike ValueCategory; {
typedef ValueLike ValueCategory;
}; };
#endif #endif
@@ -153,16 +165,18 @@ struct ArgTraits<unsigned long long> {
* floats have value-like semantics. * floats have value-like semantics.
*/ */
template<> template<>
struct ArgTraits<float> { struct ArgTraits<float>
typedef ValueLike ValueCategory; {
typedef ValueLike ValueCategory;
}; };
/** /**
* doubles have value-like semantics. * doubles have value-like semantics.
*/ */
template<> template<>
struct ArgTraits<double> { struct ArgTraits<double>
typedef ValueLike ValueCategory; {
typedef ValueLike ValueCategory;
}; };
// ====================================================================== // ======================================================================
@@ -173,8 +187,9 @@ struct ArgTraits<double> {
* bools have value-like semantics. * bools have value-like semantics.
*/ */
template<> template<>
struct ArgTraits<bool> { struct ArgTraits<bool>
typedef ValueLike ValueCategory; {
typedef ValueLike ValueCategory;
}; };
@@ -183,8 +198,9 @@ struct ArgTraits<bool> {
*/ */
#ifndef TCLAP_DONT_DECLARE_WCHAR_T_ARGTRAITS #ifndef TCLAP_DONT_DECLARE_WCHAR_T_ARGTRAITS
template<> template<>
struct ArgTraits<wchar_t> { struct ArgTraits<wchar_t>
typedef ValueLike ValueCategory; {
typedef ValueLike ValueCategory;
}; };
#endif #endif
@@ -192,14 +208,15 @@ struct ArgTraits<wchar_t> {
* Strings have string like argument traits. * Strings have string like argument traits.
*/ */
template<> template<>
struct ArgTraits<std::string> { struct ArgTraits<std::string>
typedef StringLike ValueCategory; {
typedef StringLike ValueCategory;
}; };
template<typename T> template<typename T>
void SetString(T &dst, const std::string &src) void SetString(T &dst, const std::string &src)
{ {
dst = src; dst = src;
} }
} // namespace } // namespace

View File

@@ -34,7 +34,8 @@
#include "XorHandler.h" #include "XorHandler.h"
#include "Arg.h" #include "Arg.h"
namespace TCLAP { namespace TCLAP
{
/** /**
* A class that isolates any output from the CmdLine object so that it * A class that isolates any output from the CmdLine object so that it
@@ -43,255 +44,223 @@ namespace TCLAP {
class StdOutput : public CmdLineOutput class StdOutput : public CmdLineOutput
{ {
public: public:
/** /**
* Prints the usage to stdout. Can be overridden to * Prints the usage to stdout. Can be overridden to
* produce alternative behavior. * produce alternative behavior.
* \param c - The CmdLine object the output is generated for. * \param c - The CmdLine object the output is generated for.
*/ */
virtual void usage(CmdLineInterface& c); virtual void usage(CmdLineInterface& c);
/** /**
* Prints the version to stdout. Can be overridden * Prints the version to stdout. Can be overridden
* to produce alternative behavior. * to produce alternative behavior.
* \param c - The CmdLine object the output is generated for. * \param c - The CmdLine object the output is generated for.
*/ */
virtual void version(CmdLineInterface& c); virtual void version(CmdLineInterface& c);
/** /**
* Prints (to stderr) an error message, short usage * Prints (to stderr) an error message, short usage
* Can be overridden to produce alternative behavior. * Can be overridden to produce alternative behavior.
* \param c - The CmdLine object the output is generated for. * \param c - The CmdLine object the output is generated for.
* \param e - The ArgException that caused the failure. * \param e - The ArgException that caused the failure.
*/ */
virtual void failure(CmdLineInterface& c, virtual void failure(CmdLineInterface& c,
ArgException& e ); ArgException& e );
protected: protected:
/** /**
* Writes a brief usage message with short args. * Writes a brief usage message with short args.
* \param c - The CmdLine object the output is generated for. * \param c - The CmdLine object the output is generated for.
* \param os - The stream to write the message to. * \param os - The stream to write the message to.
*/ */
void _shortUsage( CmdLineInterface& c, std::ostream& os ) const; void _shortUsage( CmdLineInterface& c, std::ostream& os ) const;
/** /**
* Writes a longer usage message with long and short args, * Writes a longer usage message with long and short args,
* provides descriptions and prints message. * provides descriptions and prints message.
* \param c - The CmdLine object the output is generated for. * \param c - The CmdLine object the output is generated for.
* \param os - The stream to write the message to. * \param os - The stream to write the message to.
*/ */
void _longUsage( CmdLineInterface& c, std::ostream& os ) const; void _longUsage( CmdLineInterface& c, std::ostream& os ) const;
/** /**
* This function inserts line breaks and indents long strings * This function inserts line breaks and indents long strings
* according the params input. It will only break lines at spaces, * according the params input. It will only break lines at spaces,
* commas and pipes. * commas and pipes.
* \param os - The stream to be printed to. * \param os - The stream to be printed to.
* \param s - The string to be printed. * \param s - The string to be printed.
* \param maxWidth - The maxWidth allowed for the output line. * \param maxWidth - The maxWidth allowed for the output line.
* \param indentSpaces - The number of spaces to indent the first line. * \param indentSpaces - The number of spaces to indent the first line.
* \param secondLineOffset - The number of spaces to indent the second * \param secondLineOffset - The number of spaces to indent the second
* and all subsequent lines in addition to indentSpaces. * and all subsequent lines in addition to indentSpaces.
*/ */
void spacePrint( std::ostream& os, void spacePrint( std::ostream& os,
const std::string& s, const std::string& s,
int maxWidth, int maxWidth,
int indentSpaces, int indentSpaces,
int secondLineOffset ) const; int secondLineOffset ) const;
}; };
inline void StdOutput::version(CmdLineInterface& _cmd) inline void StdOutput::version(CmdLineInterface& _cmd)
{ {
std::string progName = _cmd.getProgramName(); std::string progName = _cmd.getProgramName();
std::string xversion = _cmd.getVersion(); std::string xversion = _cmd.getVersion();
std::cout << std::endl << progName << " version: "
std::cout << std::endl << progName << " version: " << xversion << std::endl << std::endl;
<< xversion << std::endl << std::endl;
} }
inline void StdOutput::usage(CmdLineInterface& _cmd ) inline void StdOutput::usage(CmdLineInterface& _cmd )
{ {
std::cout << std::endl << "USAGE: " << std::endl << std::endl; std::cout << std::endl << "USAGE: " << std::endl << std::endl;
_shortUsage( _cmd, std::cout );
_shortUsage( _cmd, std::cout ); std::cout << std::endl << std::endl << "Where: " << std::endl << std::endl;
_longUsage( _cmd, std::cout );
std::cout << std::endl << std::endl << "Where: " << std::endl << std::endl; std::cout << std::endl;
_longUsage( _cmd, std::cout );
std::cout << std::endl;
} }
inline void StdOutput::failure( CmdLineInterface& _cmd, inline void StdOutput::failure( CmdLineInterface& _cmd,
ArgException& e ) ArgException& e )
{ {
std::string progName = _cmd.getProgramName(); std::string progName = _cmd.getProgramName();
std::cerr << "PARSE ERROR: " << e.argId() << std::endl
std::cerr << "PARSE ERROR: " << e.argId() << std::endl << " " << e.error() << std::endl << std::endl;
<< " " << e.error() << std::endl << std::endl; if ( _cmd.hasHelpAndVersion() )
{
if ( _cmd.hasHelpAndVersion() ) std::cerr << "Brief USAGE: " << std::endl;
{ _shortUsage( _cmd, std::cerr );
std::cerr << "Brief USAGE: " << std::endl; std::cerr << std::endl << "For complete USAGE and HELP type: "
<< std::endl << " " << progName << " --help"
_shortUsage( _cmd, std::cerr ); << std::endl << std::endl;
}
std::cerr << std::endl << "For complete USAGE and HELP type: " else
<< std::endl << " " << progName << " --help" usage(_cmd);
<< std::endl << std::endl; throw ExitException(1);
}
else
usage(_cmd);
throw ExitException(1);
} }
inline void inline void
StdOutput::_shortUsage( CmdLineInterface& _cmd, StdOutput::_shortUsage( CmdLineInterface& _cmd,
std::ostream& os ) const std::ostream& os ) const
{ {
std::list<Arg*> argList = _cmd.getArgList(); std::list<Arg*> argList = _cmd.getArgList();
std::string progName = _cmd.getProgramName(); std::string progName = _cmd.getProgramName();
XorHandler xorHandler = _cmd.getXorHandler(); XorHandler xorHandler = _cmd.getXorHandler();
std::vector< std::vector<Arg*> > xorList = xorHandler.getXorList(); std::vector< std::vector<Arg*> > xorList = xorHandler.getXorList();
std::string s = progName + " ";
std::string s = progName + " "; // first the xor
for ( int i = 0; static_cast<unsigned int>(i) < xorList.size(); i++ )
// first the xor {
for ( int i = 0; static_cast<unsigned int>(i) < xorList.size(); i++ ) s += " {";
{ for ( ArgVectorIterator it = xorList[i].begin();
s += " {"; it != xorList[i].end(); it++ )
for ( ArgVectorIterator it = xorList[i].begin(); s += (*it)->shortID() + "|";
it != xorList[i].end(); it++ ) s[s.length()-1] = '}';
s += (*it)->shortID() + "|"; }
// then the rest
s[s.length()-1] = '}'; for (ArgListIterator it = argList.begin(); it != argList.end(); it++)
} if ( !xorHandler.contains( (*it) ) )
s += " " + (*it)->shortID();
// then the rest // if the program name is too long, then adjust the second line offset
for (ArgListIterator it = argList.begin(); it != argList.end(); it++) int secondLineOffset = static_cast<int>(progName.length()) + 2;
if ( !xorHandler.contains( (*it) ) ) if ( secondLineOffset > 75/2 )
s += " " + (*it)->shortID(); secondLineOffset = static_cast<int>(75/2);
spacePrint( os, s, 75, 3, secondLineOffset );
// if the program name is too long, then adjust the second line offset
int secondLineOffset = static_cast<int>(progName.length()) + 2;
if ( secondLineOffset > 75/2 )
secondLineOffset = static_cast<int>(75/2);
spacePrint( os, s, 75, 3, secondLineOffset );
} }
inline void inline void
StdOutput::_longUsage( CmdLineInterface& _cmd, StdOutput::_longUsage( CmdLineInterface& _cmd,
std::ostream& os ) const std::ostream& os ) const
{ {
std::list<Arg*> argList = _cmd.getArgList(); std::list<Arg*> argList = _cmd.getArgList();
std::string message = _cmd.getMessage(); std::string message = _cmd.getMessage();
XorHandler xorHandler = _cmd.getXorHandler(); XorHandler xorHandler = _cmd.getXorHandler();
std::vector< std::vector<Arg*> > xorList = xorHandler.getXorList(); std::vector< std::vector<Arg*> > xorList = xorHandler.getXorList();
// first the xor
// first the xor for ( int i = 0; static_cast<unsigned int>(i) < xorList.size(); i++ )
for ( int i = 0; static_cast<unsigned int>(i) < xorList.size(); i++ ) {
{ for ( ArgVectorIterator it = xorList[i].begin();
for ( ArgVectorIterator it = xorList[i].begin(); it != xorList[i].end();
it != xorList[i].end(); it++ )
it++ ) {
{ spacePrint( os, (*it)->longID(), 75, 3, 3 );
spacePrint( os, (*it)->longID(), 75, 3, 3 ); spacePrint( os, (*it)->getDescription(), 75, 5, 0 );
spacePrint( os, (*it)->getDescription(), 75, 5, 0 ); if ( it+1 != xorList[i].end() )
spacePrint(os, "-- OR --", 75, 9, 0);
if ( it+1 != xorList[i].end() ) }
spacePrint(os, "-- OR --", 75, 9, 0); os << std::endl << std::endl;
} }
os << std::endl << std::endl; // then the rest
} for (ArgListIterator it = argList.begin(); it != argList.end(); it++)
if ( !xorHandler.contains( (*it) ) )
// then the rest {
for (ArgListIterator it = argList.begin(); it != argList.end(); it++) spacePrint( os, (*it)->longID(), 75, 3, 3 );
if ( !xorHandler.contains( (*it) ) ) spacePrint( os, (*it)->getDescription(), 75, 5, 0 );
{ os << std::endl;
spacePrint( os, (*it)->longID(), 75, 3, 3 ); }
spacePrint( os, (*it)->getDescription(), 75, 5, 0 ); os << std::endl;
os << std::endl; spacePrint( os, message, 75, 3, 0 );
}
os << std::endl;
spacePrint( os, message, 75, 3, 0 );
} }
inline void StdOutput::spacePrint( std::ostream& os, inline void StdOutput::spacePrint( std::ostream& os,
const std::string& s, const std::string& s,
int maxWidth, int maxWidth,
int indentSpaces, int indentSpaces,
int secondLineOffset ) const int secondLineOffset ) const
{ {
int len = static_cast<int>(s.length()); int len = static_cast<int>(s.length());
if ( (len + indentSpaces > maxWidth) && maxWidth > 0 )
if ( (len + indentSpaces > maxWidth) && maxWidth > 0 ) {
{ int allowedLen = maxWidth - indentSpaces;
int allowedLen = maxWidth - indentSpaces; int start = 0;
int start = 0; while ( start < len )
while ( start < len ) {
{ // find the substring length
// find the substring length // int stringLen = std::min<int>( len - start, allowedLen );
// int stringLen = std::min<int>( len - start, allowedLen ); // doing it this way to support a VisualC++ 2005 bug
// doing it this way to support a VisualC++ 2005 bug using namespace std;
using namespace std; int stringLen = min<int>( len - start, allowedLen );
int stringLen = min<int>( len - start, allowedLen ); // trim the length so it doesn't end in middle of a word
if ( stringLen == allowedLen )
// trim the length so it doesn't end in middle of a word while ( stringLen >= 0 &&
if ( stringLen == allowedLen ) s[stringLen+start] != ' ' &&
while ( stringLen >= 0 && s[stringLen+start] != ',' &&
s[stringLen+start] != ' ' && s[stringLen+start] != '|' )
s[stringLen+start] != ',' && stringLen--;
s[stringLen+start] != '|' ) // ok, the word is longer than the line, so just split
stringLen--; // wherever the line ends
if ( stringLen <= 0 )
// ok, the word is longer than the line, so just split stringLen = allowedLen;
// wherever the line ends // check for newlines
if ( stringLen <= 0 ) for ( int i = 0; i < stringLen; i++ )
stringLen = allowedLen; if ( s[start+i] == '\n' )
stringLen = i+1;
// check for newlines // print the indent
for ( int i = 0; i < stringLen; i++ ) for ( int i = 0; i < indentSpaces; i++ )
if ( s[start+i] == '\n' ) os << " ";
stringLen = i+1; if ( start == 0 )
{
// print the indent // handle second line offsets
for ( int i = 0; i < indentSpaces; i++ ) indentSpaces += secondLineOffset;
os << " "; // adjust allowed len
allowedLen -= secondLineOffset;
if ( start == 0 ) }
{ os << s.substr(start,stringLen) << std::endl;
// handle second line offsets // so we don't start a line with a space
indentSpaces += secondLineOffset; while ( s[stringLen+start] == ' ' && start < len )
start++;
// adjust allowed len start += stringLen;
allowedLen -= secondLineOffset; }
} }
else
os << s.substr(start,stringLen) << std::endl; {
for ( int i = 0; i < indentSpaces; i++ )
// so we don't start a line with a space os << " ";
while ( s[stringLen+start] == ' ' && start < len ) os << s << std::endl;
start++; }
start += stringLen;
}
}
else
{
for ( int i = 0; i < indentSpaces; i++ )
os << " ";
os << s << std::endl;
}
} }
} //namespace TCLAP } //namespace TCLAP

View File

@@ -29,7 +29,8 @@
#include "Arg.h" #include "Arg.h"
namespace TCLAP { namespace TCLAP
{
/** /**
* A simple switch argument. If the switch is set on the command line, then * A simple switch argument. If the switch is set on the command line, then
@@ -38,95 +39,95 @@ namespace TCLAP {
*/ */
class SwitchArg : public Arg class SwitchArg : public Arg
{ {
protected: protected:
/** /**
* The value of the switch. * The value of the switch.
*/ */
bool _value; bool _value;
/** /**
* Used to support the reset() method so that ValueArg can be * Used to support the reset() method so that ValueArg can be
* reset to their constructed value. * reset to their constructed value.
*/ */
bool _default; bool _default;
public: public:
/** /**
* SwitchArg constructor. * SwitchArg constructor.
* \param flag - The one character flag that identifies this * \param flag - The one character flag that identifies this
* argument on the command line. * argument on the command line.
* \param name - A one word name for the argument. Can be * \param name - A one word name for the argument. Can be
* used as a long flag on the command line. * used as a long flag on the command line.
* \param desc - A description of what the argument is for or * \param desc - A description of what the argument is for or
* does. * does.
* \param def - The default value for this Switch. * \param def - The default value for this Switch.
* \param v - An optional visitor. You probably should not * \param v - An optional visitor. You probably should not
* use this unless you have a very good reason. * use this unless you have a very good reason.
*/ */
SwitchArg(const std::string& flag, SwitchArg(const std::string& flag,
const std::string& name, const std::string& name,
const std::string& desc, const std::string& desc,
bool def = false, bool def = false,
Visitor* v = NULL); Visitor* v = NULL);
/** /**
* SwitchArg constructor. * SwitchArg constructor.
* \param flag - The one character flag that identifies this * \param flag - The one character flag that identifies this
* argument on the command line. * argument on the command line.
* \param name - A one word name for the argument. Can be * \param name - A one word name for the argument. Can be
* used as a long flag on the command line. * used as a long flag on the command line.
* \param desc - A description of what the argument is for or * \param desc - A description of what the argument is for or
* does. * does.
* \param parser - A CmdLine parser object to add this Arg to * \param parser - A CmdLine parser object to add this Arg to
* \param def - The default value for this Switch. * \param def - The default value for this Switch.
* \param v - An optional visitor. You probably should not * \param v - An optional visitor. You probably should not
* use this unless you have a very good reason. * use this unless you have a very good reason.
*/ */
SwitchArg(const std::string& flag, SwitchArg(const std::string& flag,
const std::string& name, const std::string& name,
const std::string& desc, const std::string& desc,
CmdLineInterface& parser, CmdLineInterface& parser,
bool def = false, bool def = false,
Visitor* v = NULL); Visitor* v = NULL);
/** /**
* Handles the processing of the argument. * Handles the processing of the argument.
* This re-implements the Arg version of this method to set the * This re-implements the Arg version of this method to set the
* _value of the argument appropriately. * _value of the argument appropriately.
* \param i - Pointer the the current argument in the list. * \param i - Pointer the the current argument in the list.
* \param args - Mutable list of strings. Passed * \param args - Mutable list of strings. Passed
* in from main(). * in from main().
*/ */
virtual bool processArg(int* i, std::vector<std::string>& args); virtual bool processArg(int* i, std::vector<std::string>& args);
/** /**
* Checks a string to see if any of the chars in the string * Checks a string to see if any of the chars in the string
* match the flag for this Switch. * match the flag for this Switch.
*/ */
bool combinedSwitchesMatch(std::string& combined); bool combinedSwitchesMatch(std::string& combined);
/** /**
* Returns bool, whether or not the switch has been set. * Returns bool, whether or not the switch has been set.
*/ */
bool getValue(); bool getValue();
virtual void reset(); virtual void reset();
private: private:
/** /**
* Checks to see if we've found the last match in * Checks to see if we've found the last match in
* a combined string. * a combined string.
*/ */
bool lastCombined(std::string& combined); bool lastCombined(std::string& combined);
/** /**
* Does the common processing of processArg. * Does the common processing of processArg.
*/ */
void commonProcessing(); void commonProcessing();
}; };
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
@@ -137,9 +138,9 @@ inline SwitchArg::SwitchArg(const std::string& flag,
const std::string& desc, const std::string& desc,
bool default_val, bool default_val,
Visitor* v ) Visitor* v )
: Arg(flag, name, desc, false, false, v), : Arg(flag, name, desc, false, false, v),
_value( default_val ), _value( default_val ),
_default( default_val ) _default( default_val )
{ } { }
inline SwitchArg::SwitchArg(const std::string& flag, inline SwitchArg::SwitchArg(const std::string& flag,
@@ -148,114 +149,104 @@ inline SwitchArg::SwitchArg(const std::string& flag,
CmdLineInterface& parser, CmdLineInterface& parser,
bool default_val, bool default_val,
Visitor* v ) Visitor* v )
: Arg(flag, name, desc, false, false, v), : Arg(flag, name, desc, false, false, v),
_value( default_val ), _value( default_val ),
_default(default_val) _default(default_val)
{ {
parser.add( this ); parser.add( this );
} }
inline bool SwitchArg::getValue() { return _value; } inline bool SwitchArg::getValue()
{
return _value;
}
inline bool SwitchArg::lastCombined(std::string& combinedSwitches ) inline bool SwitchArg::lastCombined(std::string& combinedSwitches )
{ {
for ( unsigned int i = 1; i < combinedSwitches.length(); i++ ) for ( unsigned int i = 1; i < combinedSwitches.length(); i++ )
if ( combinedSwitches[i] != Arg::blankChar() ) if ( combinedSwitches[i] != Arg::blankChar() )
return false; return false;
return true;
return true;
} }
inline bool SwitchArg::combinedSwitchesMatch(std::string& combinedSwitches ) inline bool SwitchArg::combinedSwitchesMatch(std::string& combinedSwitches )
{ {
// make sure this is actually a combined switch // make sure this is actually a combined switch
if ( combinedSwitches.length() > 0 && if ( combinedSwitches.length() > 0 &&
combinedSwitches[0] != Arg::flagStartString()[0] ) combinedSwitches[0] != Arg::flagStartString()[0] )
return false; return false;
// make sure it isn't a long name
// make sure it isn't a long name if ( combinedSwitches.substr( 0, Arg::nameStartString().length() ) ==
if ( combinedSwitches.substr( 0, Arg::nameStartString().length() ) == Arg::nameStartString() )
Arg::nameStartString() ) return false;
return false; // make sure the delimiter isn't in the string
if ( combinedSwitches.find_first_of( Arg::delimiter() ) != std::string::npos )
// make sure the delimiter isn't in the string return false;
if ( combinedSwitches.find_first_of( Arg::delimiter() ) != std::string::npos ) // ok, we're not specifying a ValueArg, so we know that we have
return false; // a combined switch list.
for ( unsigned int i = 1; i < combinedSwitches.length(); i++ )
// ok, we're not specifying a ValueArg, so we know that we have if ( _flag.length() > 0 &&
// a combined switch list. combinedSwitches[i] == _flag[0] &&
for ( unsigned int i = 1; i < combinedSwitches.length(); i++ ) _flag[0] != Arg::flagStartString()[0] )
if ( _flag.length() > 0 && {
combinedSwitches[i] == _flag[0] && // update the combined switches so this one is no longer present
_flag[0] != Arg::flagStartString()[0] ) // this is necessary so that no unlabeled args are matched
{ // later in the processing.
// update the combined switches so this one is no longer present //combinedSwitches.erase(i,1);
// this is necessary so that no unlabeled args are matched combinedSwitches[i] = Arg::blankChar();
// later in the processing. return true;
//combinedSwitches.erase(i,1); }
combinedSwitches[i] = Arg::blankChar(); // none of the switches passed in the list match.
return true; return false;
}
// none of the switches passed in the list match.
return false;
} }
inline void SwitchArg::commonProcessing() inline void SwitchArg::commonProcessing()
{ {
if ( _xorSet ) if ( _xorSet )
throw(CmdLineParseException( throw(CmdLineParseException(
"Mutually exclusive argument already set!", toString())); "Mutually exclusive argument already set!", toString()));
if ( _alreadySet )
if ( _alreadySet ) throw(CmdLineParseException("Argument already set!", toString()));
throw(CmdLineParseException("Argument already set!", toString())); _alreadySet = true;
if ( _value == true )
_alreadySet = true; _value = false;
else
if ( _value == true ) _value = true;
_value = false; _checkWithVisitor();
else
_value = true;
_checkWithVisitor();
} }
inline bool SwitchArg::processArg(int *i, std::vector<std::string>& args) inline bool SwitchArg::processArg(int *i, std::vector<std::string>& args)
{ {
if ( _ignoreable && Arg::ignoreRest() ) if ( _ignoreable && Arg::ignoreRest() )
return false; return false;
// if the whole string matches the flag or name string
// if the whole string matches the flag or name string if ( argMatches( args[*i] ) )
if ( argMatches( args[*i] ) ) {
{ commonProcessing();
commonProcessing(); return true;
}
return true; // if a substring matches the flag as part of a combination
} else if ( combinedSwitchesMatch( args[*i] ) )
// if a substring matches the flag as part of a combination {
else if ( combinedSwitchesMatch( args[*i] ) ) // check again to ensure we don't misinterpret
{ // this as a MultiSwitchArg
// check again to ensure we don't misinterpret if ( combinedSwitchesMatch( args[*i] ) )
// this as a MultiSwitchArg throw(CmdLineParseException("Argument already set!",
if ( combinedSwitchesMatch( args[*i] ) ) toString()));
throw(CmdLineParseException("Argument already set!", commonProcessing();
toString())); // We only want to return true if we've found the last combined
// match in the string, otherwise we return true so that other
commonProcessing(); // switches in the combination will have a chance to match.
return lastCombined( args[*i] );
// We only want to return true if we've found the last combined }
// match in the string, otherwise we return true so that other else
// switches in the combination will have a chance to match. return false;
return lastCombined( args[*i] );
}
else
return false;
} }
inline void SwitchArg::reset() inline void SwitchArg::reset()
{ {
Arg::reset(); Arg::reset();
_value = _default; _value = _default;
} }
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
//End SwitchArg.cpp //End SwitchArg.cpp

View File

@@ -29,7 +29,8 @@
#include "MultiArg.h" #include "MultiArg.h"
#include "OptionalUnlabeledTracker.h" #include "OptionalUnlabeledTracker.h"
namespace TCLAP { namespace TCLAP
{
/** /**
* Just like a MultiArg, except that the arguments are unlabeled. Basically, * Just like a MultiArg, except that the arguments are unlabeled. Basically,
@@ -40,260 +41,253 @@ template<class T>
class UnlabeledMultiArg : public MultiArg<T> class UnlabeledMultiArg : public MultiArg<T>
{ {
// If compiler has two stage name lookup (as gcc >= 3.4 does) // If compiler has two stage name lookup (as gcc >= 3.4 does)
// this is requried to prevent undef. symbols // this is requried to prevent undef. symbols
using MultiArg<T>::_ignoreable; using MultiArg<T>::_ignoreable;
using MultiArg<T>::_hasBlanks; using MultiArg<T>::_hasBlanks;
using MultiArg<T>::_extractValue; using MultiArg<T>::_extractValue;
using MultiArg<T>::_typeDesc; using MultiArg<T>::_typeDesc;
using MultiArg<T>::_name; using MultiArg<T>::_name;
using MultiArg<T>::_description; using MultiArg<T>::_description;
using MultiArg<T>::_alreadySet; using MultiArg<T>::_alreadySet;
using MultiArg<T>::toString; using MultiArg<T>::toString;
public: public:
/** /**
* Constructor. * Constructor.
* \param name - The name of the Arg. Note that this is used for * \param name - The name of the Arg. Note that this is used for
* identification, not as a long flag. * identification, not as a long flag.
* \param desc - A description of what the argument is for or * \param desc - A description of what the argument is for or
* does. * does.
* \param req - Whether the argument is required on the command * \param req - Whether the argument is required on the command
* line. * line.
* \param typeDesc - A short, human readable description of the * \param typeDesc - A short, human readable description of the
* type that this object expects. This is used in the generation * type that this object expects. This is used in the generation
* of the USAGE statement. The goal is to be helpful to the end user * of the USAGE statement. The goal is to be helpful to the end user
* of the program. * of the program.
* \param ignoreable - Whether or not this argument can be ignored * \param ignoreable - Whether or not this argument can be ignored
* using the "--" flag. * using the "--" flag.
* \param v - An optional visitor. You probably should not * \param v - An optional visitor. You probably should not
* use this unless you have a very good reason. * use this unless you have a very good reason.
*/ */
UnlabeledMultiArg( const std::string& name, UnlabeledMultiArg( const std::string& name,
const std::string& desc, const std::string& desc,
bool req, bool req,
const std::string& typeDesc, const std::string& typeDesc,
bool ignoreable = false, bool ignoreable = false,
Visitor* v = NULL ); Visitor* v = NULL );
/** /**
* Constructor. * Constructor.
* \param name - The name of the Arg. Note that this is used for * \param name - The name of the Arg. Note that this is used for
* identification, not as a long flag. * identification, not as a long flag.
* \param desc - A description of what the argument is for or * \param desc - A description of what the argument is for or
* does. * does.
* \param req - Whether the argument is required on the command * \param req - Whether the argument is required on the command
* line. * line.
* \param typeDesc - A short, human readable description of the * \param typeDesc - A short, human readable description of the
* type that this object expects. This is used in the generation * type that this object expects. This is used in the generation
* of the USAGE statement. The goal is to be helpful to the end user * of the USAGE statement. The goal is to be helpful to the end user
* of the program. * of the program.
* \param parser - A CmdLine parser object to add this Arg to * \param parser - A CmdLine parser object to add this Arg to
* \param ignoreable - Whether or not this argument can be ignored * \param ignoreable - Whether or not this argument can be ignored
* using the "--" flag. * using the "--" flag.
* \param v - An optional visitor. You probably should not * \param v - An optional visitor. You probably should not
* use this unless you have a very good reason. * use this unless you have a very good reason.
*/ */
UnlabeledMultiArg( const std::string& name, UnlabeledMultiArg( const std::string& name,
const std::string& desc, const std::string& desc,
bool req, bool req,
const std::string& typeDesc, const std::string& typeDesc,
CmdLineInterface& parser, CmdLineInterface& parser,
bool ignoreable = false, bool ignoreable = false,
Visitor* v = NULL ); Visitor* v = NULL );
/** /**
* Constructor. * Constructor.
* \param name - The name of the Arg. Note that this is used for * \param name - The name of the Arg. Note that this is used for
* identification, not as a long flag. * identification, not as a long flag.
* \param desc - A description of what the argument is for or * \param desc - A description of what the argument is for or
* does. * does.
* \param req - Whether the argument is required on the command * \param req - Whether the argument is required on the command
* line. * line.
* \param constraint - A pointer to a Constraint object used * \param constraint - A pointer to a Constraint object used
* to constrain this Arg. * to constrain this Arg.
* \param ignoreable - Whether or not this argument can be ignored * \param ignoreable - Whether or not this argument can be ignored
* using the "--" flag. * using the "--" flag.
* \param v - An optional visitor. You probably should not * \param v - An optional visitor. You probably should not
* use this unless you have a very good reason. * use this unless you have a very good reason.
*/ */
UnlabeledMultiArg( const std::string& name, UnlabeledMultiArg( const std::string& name,
const std::string& desc, const std::string& desc,
bool req, bool req,
Constraint<T>* constraint, Constraint<T>* constraint,
bool ignoreable = false, bool ignoreable = false,
Visitor* v = NULL ); Visitor* v = NULL );
/** /**
* Constructor. * Constructor.
* \param name - The name of the Arg. Note that this is used for * \param name - The name of the Arg. Note that this is used for
* identification, not as a long flag. * identification, not as a long flag.
* \param desc - A description of what the argument is for or * \param desc - A description of what the argument is for or
* does. * does.
* \param req - Whether the argument is required on the command * \param req - Whether the argument is required on the command
* line. * line.
* \param constraint - A pointer to a Constraint object used * \param constraint - A pointer to a Constraint object used
* to constrain this Arg. * to constrain this Arg.
* \param parser - A CmdLine parser object to add this Arg to * \param parser - A CmdLine parser object to add this Arg to
* \param ignoreable - Whether or not this argument can be ignored * \param ignoreable - Whether or not this argument can be ignored
* using the "--" flag. * using the "--" flag.
* \param v - An optional visitor. You probably should not * \param v - An optional visitor. You probably should not
* use this unless you have a very good reason. * use this unless you have a very good reason.
*/ */
UnlabeledMultiArg( const std::string& name, UnlabeledMultiArg( const std::string& name,
const std::string& desc, const std::string& desc,
bool req, bool req,
Constraint<T>* constraint, Constraint<T>* constraint,
CmdLineInterface& parser, CmdLineInterface& parser,
bool ignoreable = false, bool ignoreable = false,
Visitor* v = NULL ); Visitor* v = NULL );
/** /**
* Handles the processing of the argument. * Handles the processing of the argument.
* This re-implements the Arg version of this method to set the * This re-implements the Arg version of this method to set the
* _value of the argument appropriately. It knows the difference * _value of the argument appropriately. It knows the difference
* between labeled and unlabeled. * between labeled and unlabeled.
* \param i - Pointer the the current argument in the list. * \param i - Pointer the the current argument in the list.
* \param args - Mutable list of strings. Passed from main(). * \param args - Mutable list of strings. Passed from main().
*/ */
virtual bool processArg(int* i, std::vector<std::string>& args); virtual bool processArg(int* i, std::vector<std::string>& args);
/** /**
* Returns the a short id string. Used in the usage. * Returns the a short id string. Used in the usage.
* \param val - value to be used. * \param val - value to be used.
*/ */
virtual std::string shortID(const std::string& val="val") const; virtual std::string shortID(const std::string& val="val") const;
/** /**
* Returns the a long id string. Used in the usage. * Returns the a long id string. Used in the usage.
* \param val - value to be used. * \param val - value to be used.
*/ */
virtual std::string longID(const std::string& val="val") const; virtual std::string longID(const std::string& val="val") const;
/** /**
* Opertor ==. * Opertor ==.
* \param a - The Arg to be compared to this. * \param a - The Arg to be compared to this.
*/ */
virtual bool operator==(const Arg& a) const; virtual bool operator==(const Arg& a) const;
/** /**
* Pushes this to back of list rather than front. * Pushes this to back of list rather than front.
* \param argList - The list this should be added to. * \param argList - The list this should be added to.
*/ */
virtual void addToList( std::list<Arg*>& argList ) const; virtual void addToList( std::list<Arg*>& argList ) const;
}; };
template<class T> template<class T>
UnlabeledMultiArg<T>::UnlabeledMultiArg(const std::string& name, UnlabeledMultiArg<T>::UnlabeledMultiArg(const std::string& name,
const std::string& desc, const std::string& desc,
bool req, bool req,
const std::string& typeDesc, const std::string& typeDesc,
bool ignoreable, bool ignoreable,
Visitor* v) Visitor* v)
: MultiArg<T>("", name, desc, req, typeDesc, v) : MultiArg<T>("", name, desc, req, typeDesc, v)
{ {
_ignoreable = ignoreable; _ignoreable = ignoreable;
OptionalUnlabeledTracker::check(true, toString()); OptionalUnlabeledTracker::check(true, toString());
} }
template<class T> template<class T>
UnlabeledMultiArg<T>::UnlabeledMultiArg(const std::string& name, UnlabeledMultiArg<T>::UnlabeledMultiArg(const std::string& name,
const std::string& desc, const std::string& desc,
bool req, bool req,
const std::string& typeDesc, const std::string& typeDesc,
CmdLineInterface& parser, CmdLineInterface& parser,
bool ignoreable, bool ignoreable,
Visitor* v) Visitor* v)
: MultiArg<T>("", name, desc, req, typeDesc, v) : MultiArg<T>("", name, desc, req, typeDesc, v)
{ {
_ignoreable = ignoreable; _ignoreable = ignoreable;
OptionalUnlabeledTracker::check(true, toString()); OptionalUnlabeledTracker::check(true, toString());
parser.add( this ); parser.add( this );
} }
template<class T> template<class T>
UnlabeledMultiArg<T>::UnlabeledMultiArg(const std::string& name, UnlabeledMultiArg<T>::UnlabeledMultiArg(const std::string& name,
const std::string& desc, const std::string& desc,
bool req, bool req,
Constraint<T>* constraint, Constraint<T>* constraint,
bool ignoreable, bool ignoreable,
Visitor* v) Visitor* v)
: MultiArg<T>("", name, desc, req, constraint, v) : MultiArg<T>("", name, desc, req, constraint, v)
{ {
_ignoreable = ignoreable; _ignoreable = ignoreable;
OptionalUnlabeledTracker::check(true, toString()); OptionalUnlabeledTracker::check(true, toString());
} }
template<class T> template<class T>
UnlabeledMultiArg<T>::UnlabeledMultiArg(const std::string& name, UnlabeledMultiArg<T>::UnlabeledMultiArg(const std::string& name,
const std::string& desc, const std::string& desc,
bool req, bool req,
Constraint<T>* constraint, Constraint<T>* constraint,
CmdLineInterface& parser, CmdLineInterface& parser,
bool ignoreable, bool ignoreable,
Visitor* v) Visitor* v)
: MultiArg<T>("", name, desc, req, constraint, v) : MultiArg<T>("", name, desc, req, constraint, v)
{ {
_ignoreable = ignoreable; _ignoreable = ignoreable;
OptionalUnlabeledTracker::check(true, toString()); OptionalUnlabeledTracker::check(true, toString());
parser.add( this ); parser.add( this );
} }
template<class T> template<class T>
bool UnlabeledMultiArg<T>::processArg(int *i, std::vector<std::string>& args) bool UnlabeledMultiArg<T>::processArg(int *i, std::vector<std::string>& args)
{ {
if ( _hasBlanks( args[*i] ) )
if ( _hasBlanks( args[*i] ) ) return false;
return false; // never ignore an unlabeled multi arg
// always take the first value, regardless of the start string
// never ignore an unlabeled multi arg _extractValue( args[(*i)] );
/*
// continue taking args until we hit the end or a start string
// always take the first value, regardless of the start string while ( (unsigned int)(*i)+1 < args.size() &&
_extractValue( args[(*i)] ); args[(*i)+1].find_first_of( Arg::flagStartString() ) != 0 &&
/*
// continue taking args until we hit the end or a start string
while ( (unsigned int)(*i)+1 < args.size() &&
args[(*i)+1].find_first_of( Arg::flagStartString() ) != 0 &&
args[(*i)+1].find_first_of( Arg::nameStartString() ) != 0 ) args[(*i)+1].find_first_of( Arg::nameStartString() ) != 0 )
_extractValue( args[++(*i)] ); _extractValue( args[++(*i)] );
*/ */
_alreadySet = true;
_alreadySet = true; return true;
return true;
} }
template<class T> template<class T>
std::string UnlabeledMultiArg<T>::shortID(const std::string& val) const std::string UnlabeledMultiArg<T>::shortID(const std::string& val) const
{ {
static_cast<void>(val); // Ignore input, don't warn static_cast<void>(val); // Ignore input, don't warn
return std::string("<") + _typeDesc + "> ..."; return std::string("<") + _typeDesc + "> ...";
} }
template<class T> template<class T>
std::string UnlabeledMultiArg<T>::longID(const std::string& val) const std::string UnlabeledMultiArg<T>::longID(const std::string& val) const
{ {
static_cast<void>(val); // Ignore input, don't warn static_cast<void>(val); // Ignore input, don't warn
return std::string("<") + _typeDesc + "> (accepted multiple times)"; return std::string("<") + _typeDesc + "> (accepted multiple times)";
} }
template<class T> template<class T>
bool UnlabeledMultiArg<T>::operator==(const Arg& a) const bool UnlabeledMultiArg<T>::operator==(const Arg& a) const
{ {
if ( _name == a.getName() || _description == a.getDescription() ) if ( _name == a.getName() || _description == a.getDescription() )
return true; return true;
else else
return false; return false;
} }
template<class T> template<class T>
void UnlabeledMultiArg<T>::addToList( std::list<Arg*>& argList ) const void UnlabeledMultiArg<T>::addToList( std::list<Arg*>& argList ) const
{ {
argList.push_back( const_cast<Arg*>(static_cast<const Arg* const>(this)) ); argList.push_back( const_cast<Arg*>(static_cast<const Arg* const>(this)) );
} }
} }

View File

@@ -31,7 +31,8 @@
#include "OptionalUnlabeledTracker.h" #include "OptionalUnlabeledTracker.h"
namespace TCLAP { namespace TCLAP
{
/** /**
* The basic unlabeled argument that parses a value. * The basic unlabeled argument that parses a value.
@@ -43,166 +44,166 @@ template<class T>
class UnlabeledValueArg : public ValueArg<T> class UnlabeledValueArg : public ValueArg<T>
{ {
// If compiler has two stage name lookup (as gcc >= 3.4 does) // If compiler has two stage name lookup (as gcc >= 3.4 does)
// this is requried to prevent undef. symbols // this is requried to prevent undef. symbols
using ValueArg<T>::_ignoreable; using ValueArg<T>::_ignoreable;
using ValueArg<T>::_hasBlanks; using ValueArg<T>::_hasBlanks;
using ValueArg<T>::_extractValue; using ValueArg<T>::_extractValue;
using ValueArg<T>::_typeDesc; using ValueArg<T>::_typeDesc;
using ValueArg<T>::_name; using ValueArg<T>::_name;
using ValueArg<T>::_description; using ValueArg<T>::_description;
using ValueArg<T>::_alreadySet; using ValueArg<T>::_alreadySet;
using ValueArg<T>::toString; using ValueArg<T>::toString;
public: public:
/** /**
* UnlabeledValueArg constructor. * UnlabeledValueArg constructor.
* \param name - A one word name for the argument. Note that this is used for * \param name - A one word name for the argument. Note that this is used for
* identification, not as a long flag. * identification, not as a long flag.
* \param desc - A description of what the argument is for or * \param desc - A description of what the argument is for or
* does. * does.
* \param req - Whether the argument is required on the command * \param req - Whether the argument is required on the command
* line. * line.
* \param value - The default value assigned to this argument if it * \param value - The default value assigned to this argument if it
* is not present on the command line. * is not present on the command line.
* \param typeDesc - A short, human readable description of the * \param typeDesc - A short, human readable description of the
* type that this object expects. This is used in the generation * type that this object expects. This is used in the generation
* of the USAGE statement. The goal is to be helpful to the end user * of the USAGE statement. The goal is to be helpful to the end user
* of the program. * of the program.
* \param ignoreable - Allows you to specify that this argument can be * \param ignoreable - Allows you to specify that this argument can be
* ignored if the '--' flag is set. This defaults to false (cannot * ignored if the '--' flag is set. This defaults to false (cannot
* be ignored) and should generally stay that way unless you have * be ignored) and should generally stay that way unless you have
* some special need for certain arguments to be ignored. * some special need for certain arguments to be ignored.
* \param v - Optional Vistor. You should leave this blank unless * \param v - Optional Vistor. You should leave this blank unless
* you have a very good reason. * you have a very good reason.
*/ */
UnlabeledValueArg( const std::string& name, UnlabeledValueArg( const std::string& name,
const std::string& desc, const std::string& desc,
bool req, bool req,
T value, T value,
const std::string& typeDesc, const std::string& typeDesc,
bool ignoreable = false, bool ignoreable = false,
Visitor* v = NULL); Visitor* v = NULL);
/** /**
* UnlabeledValueArg constructor. * UnlabeledValueArg constructor.
* \param name - A one word name for the argument. Note that this is used for * \param name - A one word name for the argument. Note that this is used for
* identification, not as a long flag. * identification, not as a long flag.
* \param desc - A description of what the argument is for or * \param desc - A description of what the argument is for or
* does. * does.
* \param req - Whether the argument is required on the command * \param req - Whether the argument is required on the command
* line. * line.
* \param value - The default value assigned to this argument if it * \param value - The default value assigned to this argument if it
* is not present on the command line. * is not present on the command line.
* \param typeDesc - A short, human readable description of the * \param typeDesc - A short, human readable description of the
* type that this object expects. This is used in the generation * type that this object expects. This is used in the generation
* of the USAGE statement. The goal is to be helpful to the end user * of the USAGE statement. The goal is to be helpful to the end user
* of the program. * of the program.
* \param parser - A CmdLine parser object to add this Arg to * \param parser - A CmdLine parser object to add this Arg to
* \param ignoreable - Allows you to specify that this argument can be * \param ignoreable - Allows you to specify that this argument can be
* ignored if the '--' flag is set. This defaults to false (cannot * ignored if the '--' flag is set. This defaults to false (cannot
* be ignored) and should generally stay that way unless you have * be ignored) and should generally stay that way unless you have
* some special need for certain arguments to be ignored. * some special need for certain arguments to be ignored.
* \param v - Optional Vistor. You should leave this blank unless * \param v - Optional Vistor. You should leave this blank unless
* you have a very good reason. * you have a very good reason.
*/ */
UnlabeledValueArg( const std::string& name, UnlabeledValueArg( const std::string& name,
const std::string& desc, const std::string& desc,
bool req, bool req,
T value, T value,
const std::string& typeDesc, const std::string& typeDesc,
CmdLineInterface& parser, CmdLineInterface& parser,
bool ignoreable = false, bool ignoreable = false,
Visitor* v = NULL ); Visitor* v = NULL );
/** /**
* UnlabeledValueArg constructor. * UnlabeledValueArg constructor.
* \param name - A one word name for the argument. Note that this is used for * \param name - A one word name for the argument. Note that this is used for
* identification, not as a long flag. * identification, not as a long flag.
* \param desc - A description of what the argument is for or * \param desc - A description of what the argument is for or
* does. * does.
* \param req - Whether the argument is required on the command * \param req - Whether the argument is required on the command
* line. * line.
* \param value - The default value assigned to this argument if it * \param value - The default value assigned to this argument if it
* is not present on the command line. * is not present on the command line.
* \param constraint - A pointer to a Constraint object used * \param constraint - A pointer to a Constraint object used
* to constrain this Arg. * to constrain this Arg.
* \param ignoreable - Allows you to specify that this argument can be * \param ignoreable - Allows you to specify that this argument can be
* ignored if the '--' flag is set. This defaults to false (cannot * ignored if the '--' flag is set. This defaults to false (cannot
* be ignored) and should generally stay that way unless you have * be ignored) and should generally stay that way unless you have
* some special need for certain arguments to be ignored. * some special need for certain arguments to be ignored.
* \param v - Optional Vistor. You should leave this blank unless * \param v - Optional Vistor. You should leave this blank unless
* you have a very good reason. * you have a very good reason.
*/ */
UnlabeledValueArg( const std::string& name, UnlabeledValueArg( const std::string& name,
const std::string& desc, const std::string& desc,
bool req, bool req,
T value, T value,
Constraint<T>* constraint, Constraint<T>* constraint,
bool ignoreable = false, bool ignoreable = false,
Visitor* v = NULL ); Visitor* v = NULL );
/** /**
* UnlabeledValueArg constructor. * UnlabeledValueArg constructor.
* \param name - A one word name for the argument. Note that this is used for * \param name - A one word name for the argument. Note that this is used for
* identification, not as a long flag. * identification, not as a long flag.
* \param desc - A description of what the argument is for or * \param desc - A description of what the argument is for or
* does. * does.
* \param req - Whether the argument is required on the command * \param req - Whether the argument is required on the command
* line. * line.
* \param value - The default value assigned to this argument if it * \param value - The default value assigned to this argument if it
* is not present on the command line. * is not present on the command line.
* \param constraint - A pointer to a Constraint object used * \param constraint - A pointer to a Constraint object used
* to constrain this Arg. * to constrain this Arg.
* \param parser - A CmdLine parser object to add this Arg to * \param parser - A CmdLine parser object to add this Arg to
* \param ignoreable - Allows you to specify that this argument can be * \param ignoreable - Allows you to specify that this argument can be
* ignored if the '--' flag is set. This defaults to false (cannot * ignored if the '--' flag is set. This defaults to false (cannot
* be ignored) and should generally stay that way unless you have * be ignored) and should generally stay that way unless you have
* some special need for certain arguments to be ignored. * some special need for certain arguments to be ignored.
* \param v - Optional Vistor. You should leave this blank unless * \param v - Optional Vistor. You should leave this blank unless
* you have a very good reason. * you have a very good reason.
*/ */
UnlabeledValueArg( const std::string& name, UnlabeledValueArg( const std::string& name,
const std::string& desc, const std::string& desc,
bool req, bool req,
T value, T value,
Constraint<T>* constraint, Constraint<T>* constraint,
CmdLineInterface& parser, CmdLineInterface& parser,
bool ignoreable = false, bool ignoreable = false,
Visitor* v = NULL); Visitor* v = NULL);
/** /**
* Handles the processing of the argument. * Handles the processing of the argument.
* This re-implements the Arg version of this method to set the * This re-implements the Arg version of this method to set the
* _value of the argument appropriately. Handling specific to * _value of the argument appropriately. Handling specific to
* unlabled arguments. * unlabled arguments.
* \param i - Pointer the the current argument in the list. * \param i - Pointer the the current argument in the list.
* \param args - Mutable list of strings. * \param args - Mutable list of strings.
*/ */
virtual bool processArg(int* i, std::vector<std::string>& args); virtual bool processArg(int* i, std::vector<std::string>& args);
/** /**
* Overrides shortID for specific behavior. * Overrides shortID for specific behavior.
*/ */
virtual std::string shortID(const std::string& val="val") const; virtual std::string shortID(const std::string& val="val") const;
/** /**
* Overrides longID for specific behavior. * Overrides longID for specific behavior.
*/ */
virtual std::string longID(const std::string& val="val") const; virtual std::string longID(const std::string& val="val") const;
/** /**
* Overrides operator== for specific behavior. * Overrides operator== for specific behavior.
*/ */
virtual bool operator==(const Arg& a ) const; virtual bool operator==(const Arg& a ) const;
/** /**
* Instead of pushing to the front of list, push to the back. * Instead of pushing to the front of list, push to the back.
* \param argList - The list to add this to. * \param argList - The list to add this to.
*/ */
virtual void addToList( std::list<Arg*>& argList ) const; virtual void addToList( std::list<Arg*>& argList ) const;
}; };
@@ -211,34 +212,32 @@ class UnlabeledValueArg : public ValueArg<T>
*/ */
template<class T> template<class T>
UnlabeledValueArg<T>::UnlabeledValueArg(const std::string& name, UnlabeledValueArg<T>::UnlabeledValueArg(const std::string& name,
const std::string& desc, const std::string& desc,
bool req, bool req,
T val, T val,
const std::string& typeDesc, const std::string& typeDesc,
bool ignoreable, bool ignoreable,
Visitor* v) Visitor* v)
: ValueArg<T>("", name, desc, req, val, typeDesc, v) : ValueArg<T>("", name, desc, req, val, typeDesc, v)
{ {
_ignoreable = ignoreable; _ignoreable = ignoreable;
OptionalUnlabeledTracker::check(req, toString());
OptionalUnlabeledTracker::check(req, toString());
} }
template<class T> template<class T>
UnlabeledValueArg<T>::UnlabeledValueArg(const std::string& name, UnlabeledValueArg<T>::UnlabeledValueArg(const std::string& name,
const std::string& desc, const std::string& desc,
bool req, bool req,
T val, T val,
const std::string& typeDesc, const std::string& typeDesc,
CmdLineInterface& parser, CmdLineInterface& parser,
bool ignoreable, bool ignoreable,
Visitor* v) Visitor* v)
: ValueArg<T>("", name, desc, req, val, typeDesc, v) : ValueArg<T>("", name, desc, req, val, typeDesc, v)
{ {
_ignoreable = ignoreable; _ignoreable = ignoreable;
OptionalUnlabeledTracker::check(req, toString()); OptionalUnlabeledTracker::check(req, toString());
parser.add( this ); parser.add( this );
} }
/** /**
@@ -247,31 +246,31 @@ UnlabeledValueArg<T>::UnlabeledValueArg(const std::string& name,
template<class T> template<class T>
UnlabeledValueArg<T>::UnlabeledValueArg(const std::string& name, UnlabeledValueArg<T>::UnlabeledValueArg(const std::string& name,
const std::string& desc, const std::string& desc,
bool req, bool req,
T val, T val,
Constraint<T>* constraint, Constraint<T>* constraint,
bool ignoreable, bool ignoreable,
Visitor* v) Visitor* v)
: ValueArg<T>("", name, desc, req, val, constraint, v) : ValueArg<T>("", name, desc, req, val, constraint, v)
{ {
_ignoreable = ignoreable; _ignoreable = ignoreable;
OptionalUnlabeledTracker::check(req, toString()); OptionalUnlabeledTracker::check(req, toString());
} }
template<class T> template<class T>
UnlabeledValueArg<T>::UnlabeledValueArg(const std::string& name, UnlabeledValueArg<T>::UnlabeledValueArg(const std::string& name,
const std::string& desc, const std::string& desc,
bool req, bool req,
T val, T val,
Constraint<T>* constraint, Constraint<T>* constraint,
CmdLineInterface& parser, CmdLineInterface& parser,
bool ignoreable, bool ignoreable,
Visitor* v) Visitor* v)
: ValueArg<T>("", name, desc, req, val, constraint, v) : ValueArg<T>("", name, desc, req, val, constraint, v)
{ {
_ignoreable = ignoreable; _ignoreable = ignoreable;
OptionalUnlabeledTracker::check(req, toString()); OptionalUnlabeledTracker::check(req, toString());
parser.add( this ); parser.add( this );
} }
/** /**
@@ -280,18 +279,14 @@ UnlabeledValueArg<T>::UnlabeledValueArg(const std::string& name,
template<class T> template<class T>
bool UnlabeledValueArg<T>::processArg(int *i, std::vector<std::string>& args) bool UnlabeledValueArg<T>::processArg(int *i, std::vector<std::string>& args)
{ {
if ( _alreadySet )
if ( _alreadySet ) return false;
return false; if ( _hasBlanks( args[*i] ) )
return false;
if ( _hasBlanks( args[*i] ) ) // never ignore an unlabeled arg
return false; _extractValue( args[*i] );
_alreadySet = true;
// never ignore an unlabeled arg return true;
_extractValue( args[*i] );
_alreadySet = true;
return true;
} }
/** /**
@@ -300,8 +295,8 @@ bool UnlabeledValueArg<T>::processArg(int *i, std::vector<std::string>& args)
template<class T> template<class T>
std::string UnlabeledValueArg<T>::shortID(const std::string& val) const std::string UnlabeledValueArg<T>::shortID(const std::string& val) const
{ {
static_cast<void>(val); // Ignore input, don't warn static_cast<void>(val); // Ignore input, don't warn
return std::string("<") + _typeDesc + ">"; return std::string("<") + _typeDesc + ">";
} }
/** /**
@@ -310,12 +305,11 @@ std::string UnlabeledValueArg<T>::shortID(const std::string& val) const
template<class T> template<class T>
std::string UnlabeledValueArg<T>::longID(const std::string& val) const std::string UnlabeledValueArg<T>::longID(const std::string& val) const
{ {
static_cast<void>(val); // Ignore input, don't warn static_cast<void>(val); // Ignore input, don't warn
// Ideally we would like to be able to use RTTI to return the name
// Ideally we would like to be able to use RTTI to return the name // of the type required for this argument. However, g++ at least,
// of the type required for this argument. However, g++ at least, // doesn't appear to return terribly useful "names" of the types.
// doesn't appear to return terribly useful "names" of the types. return std::string("<") + _typeDesc + ">";
return std::string("<") + _typeDesc + ">";
} }
/** /**
@@ -324,16 +318,16 @@ std::string UnlabeledValueArg<T>::longID(const std::string& val) const
template<class T> template<class T>
bool UnlabeledValueArg<T>::operator==(const Arg& a ) const bool UnlabeledValueArg<T>::operator==(const Arg& a ) const
{ {
if ( _name == a.getName() || _description == a.getDescription() ) if ( _name == a.getName() || _description == a.getDescription() )
return true; return true;
else else
return false; return false;
} }
template<class T> template<class T>
void UnlabeledValueArg<T>::addToList( std::list<Arg*>& argList ) const void UnlabeledValueArg<T>::addToList( std::list<Arg*>& argList ) const
{ {
argList.push_back( const_cast<Arg*>(static_cast<const Arg* const>(this)) ); argList.push_back( const_cast<Arg*>(static_cast<const Arg* const>(this)) );
} }
} }

View File

@@ -29,7 +29,8 @@
#include "Arg.h" #include "Arg.h"
#include "Constraint.h" #include "Constraint.h"
namespace TCLAP { namespace TCLAP
{
/** /**
* The basic labeled argument that parses a value. * The basic labeled argument that parses a value.
@@ -42,206 +43,206 @@ namespace TCLAP {
template<class T> template<class T>
class ValueArg : public Arg class ValueArg : public Arg
{ {
protected: protected:
/** /**
* The value parsed from the command line. * The value parsed from the command line.
* Can be of any type, as long as the >> operator for the type * Can be of any type, as long as the >> operator for the type
* is defined. * is defined.
*/ */
T _value; T _value;
/** /**
* Used to support the reset() method so that ValueArg can be * Used to support the reset() method so that ValueArg can be
* reset to their constructed value. * reset to their constructed value.
*/ */
T _default; T _default;
/** /**
* A human readable description of the type to be parsed. * A human readable description of the type to be parsed.
* This is a hack, plain and simple. Ideally we would use RTTI to * This is a hack, plain and simple. Ideally we would use RTTI to
* return the name of type T, but until there is some sort of * return the name of type T, but until there is some sort of
* consistent support for human readable names, we are left to our * consistent support for human readable names, we are left to our
* own devices. * own devices.
*/ */
std::string _typeDesc; std::string _typeDesc;
/** /**
* A Constraint this Arg must conform to. * A Constraint this Arg must conform to.
*/ */
Constraint<T>* _constraint; Constraint<T>* _constraint;
/** /**
* Extracts the value from the string. * Extracts the value from the string.
* Attempts to parse string as type T, if this fails an exception * Attempts to parse string as type T, if this fails an exception
* is thrown. * is thrown.
* \param val - value to be parsed. * \param val - value to be parsed.
*/ */
void _extractValue( const std::string& val ); void _extractValue( const std::string& val );
public: public:
/** /**
* Labeled ValueArg constructor. * Labeled ValueArg constructor.
* You could conceivably call this constructor with a blank flag, * You could conceivably call this constructor with a blank flag,
* but that would make you a bad person. It would also cause * but that would make you a bad person. It would also cause
* an exception to be thrown. If you want an unlabeled argument, * an exception to be thrown. If you want an unlabeled argument,
* use the other constructor. * use the other constructor.
* \param flag - The one character flag that identifies this * \param flag - The one character flag that identifies this
* argument on the command line. * argument on the command line.
* \param name - A one word name for the argument. Can be * \param name - A one word name for the argument. Can be
* used as a long flag on the command line. * used as a long flag on the command line.
* \param desc - A description of what the argument is for or * \param desc - A description of what the argument is for or
* does. * does.
* \param req - Whether the argument is required on the command * \param req - Whether the argument is required on the command
* line. * line.
* \param value - The default value assigned to this argument if it * \param value - The default value assigned to this argument if it
* is not present on the command line. * is not present on the command line.
* \param typeDesc - A short, human readable description of the * \param typeDesc - A short, human readable description of the
* type that this object expects. This is used in the generation * type that this object expects. This is used in the generation
* of the USAGE statement. The goal is to be helpful to the end user * of the USAGE statement. The goal is to be helpful to the end user
* of the program. * of the program.
* \param v - An optional visitor. You probably should not * \param v - An optional visitor. You probably should not
* use this unless you have a very good reason. * use this unless you have a very good reason.
*/ */
ValueArg( const std::string& flag, ValueArg( const std::string& flag,
const std::string& name, const std::string& name,
const std::string& desc, const std::string& desc,
bool req, bool req,
T value, T value,
const std::string& typeDesc, const std::string& typeDesc,
Visitor* v = NULL); Visitor* v = NULL);
/** /**
* Labeled ValueArg constructor. * Labeled ValueArg constructor.
* You could conceivably call this constructor with a blank flag, * You could conceivably call this constructor with a blank flag,
* but that would make you a bad person. It would also cause * but that would make you a bad person. It would also cause
* an exception to be thrown. If you want an unlabeled argument, * an exception to be thrown. If you want an unlabeled argument,
* use the other constructor. * use the other constructor.
* \param flag - The one character flag that identifies this * \param flag - The one character flag that identifies this
* argument on the command line. * argument on the command line.
* \param name - A one word name for the argument. Can be * \param name - A one word name for the argument. Can be
* used as a long flag on the command line. * used as a long flag on the command line.
* \param desc - A description of what the argument is for or * \param desc - A description of what the argument is for or
* does. * does.
* \param req - Whether the argument is required on the command * \param req - Whether the argument is required on the command
* line. * line.
* \param value - The default value assigned to this argument if it * \param value - The default value assigned to this argument if it
* is not present on the command line. * is not present on the command line.
* \param typeDesc - A short, human readable description of the * \param typeDesc - A short, human readable description of the
* type that this object expects. This is used in the generation * type that this object expects. This is used in the generation
* of the USAGE statement. The goal is to be helpful to the end user * of the USAGE statement. The goal is to be helpful to the end user
* of the program. * of the program.
* \param parser - A CmdLine parser object to add this Arg to * \param parser - A CmdLine parser object to add this Arg to
* \param v - An optional visitor. You probably should not * \param v - An optional visitor. You probably should not
* use this unless you have a very good reason. * use this unless you have a very good reason.
*/ */
ValueArg( const std::string& flag, ValueArg( const std::string& flag,
const std::string& name, const std::string& name,
const std::string& desc, const std::string& desc,
bool req, bool req,
T value, T value,
const std::string& typeDesc, const std::string& typeDesc,
CmdLineInterface& parser, CmdLineInterface& parser,
Visitor* v = NULL ); Visitor* v = NULL );
/** /**
* Labeled ValueArg constructor. * Labeled ValueArg constructor.
* You could conceivably call this constructor with a blank flag, * You could conceivably call this constructor with a blank flag,
* but that would make you a bad person. It would also cause * but that would make you a bad person. It would also cause
* an exception to be thrown. If you want an unlabeled argument, * an exception to be thrown. If you want an unlabeled argument,
* use the other constructor. * use the other constructor.
* \param flag - The one character flag that identifies this * \param flag - The one character flag that identifies this
* argument on the command line. * argument on the command line.
* \param name - A one word name for the argument. Can be * \param name - A one word name for the argument. Can be
* used as a long flag on the command line. * used as a long flag on the command line.
* \param desc - A description of what the argument is for or * \param desc - A description of what the argument is for or
* does. * does.
* \param req - Whether the argument is required on the command * \param req - Whether the argument is required on the command
* line. * line.
* \param value - The default value assigned to this argument if it * \param value - The default value assigned to this argument if it
* is not present on the command line. * is not present on the command line.
* \param constraint - A pointer to a Constraint object used * \param constraint - A pointer to a Constraint object used
* to constrain this Arg. * to constrain this Arg.
* \param parser - A CmdLine parser object to add this Arg to. * \param parser - A CmdLine parser object to add this Arg to.
* \param v - An optional visitor. You probably should not * \param v - An optional visitor. You probably should not
* use this unless you have a very good reason. * use this unless you have a very good reason.
*/ */
ValueArg( const std::string& flag, ValueArg( const std::string& flag,
const std::string& name, const std::string& name,
const std::string& desc, const std::string& desc,
bool req, bool req,
T value, T value,
Constraint<T>* constraint, Constraint<T>* constraint,
CmdLineInterface& parser, CmdLineInterface& parser,
Visitor* v = NULL ); Visitor* v = NULL );
/** /**
* Labeled ValueArg constructor. * Labeled ValueArg constructor.
* You could conceivably call this constructor with a blank flag, * You could conceivably call this constructor with a blank flag,
* but that would make you a bad person. It would also cause * but that would make you a bad person. It would also cause
* an exception to be thrown. If you want an unlabeled argument, * an exception to be thrown. If you want an unlabeled argument,
* use the other constructor. * use the other constructor.
* \param flag - The one character flag that identifies this * \param flag - The one character flag that identifies this
* argument on the command line. * argument on the command line.
* \param name - A one word name for the argument. Can be * \param name - A one word name for the argument. Can be
* used as a long flag on the command line. * used as a long flag on the command line.
* \param desc - A description of what the argument is for or * \param desc - A description of what the argument is for or
* does. * does.
* \param req - Whether the argument is required on the command * \param req - Whether the argument is required on the command
* line. * line.
* \param value - The default value assigned to this argument if it * \param value - The default value assigned to this argument if it
* is not present on the command line. * is not present on the command line.
* \param constraint - A pointer to a Constraint object used * \param constraint - A pointer to a Constraint object used
* to constrain this Arg. * to constrain this Arg.
* \param v - An optional visitor. You probably should not * \param v - An optional visitor. You probably should not
* use this unless you have a very good reason. * use this unless you have a very good reason.
*/ */
ValueArg( const std::string& flag, ValueArg( const std::string& flag,
const std::string& name, const std::string& name,
const std::string& desc, const std::string& desc,
bool req, bool req,
T value, T value,
Constraint<T>* constraint, Constraint<T>* constraint,
Visitor* v = NULL ); Visitor* v = NULL );
/** /**
* Handles the processing of the argument. * Handles the processing of the argument.
* This re-implements the Arg version of this method to set the * This re-implements the Arg version of this method to set the
* _value of the argument appropriately. It knows the difference * _value of the argument appropriately. It knows the difference
* between labeled and unlabeled. * between labeled and unlabeled.
* \param i - Pointer the the current argument in the list. * \param i - Pointer the the current argument in the list.
* \param args - Mutable list of strings. Passed * \param args - Mutable list of strings. Passed
* in from main(). * in from main().
*/ */
virtual bool processArg(int* i, std::vector<std::string>& args); virtual bool processArg(int* i, std::vector<std::string>& args);
/** /**
* Returns the value of the argument. * Returns the value of the argument.
*/ */
T& getValue() ; T& getValue() ;
/** /**
* Specialization of shortID. * Specialization of shortID.
* \param val - value to be used. * \param val - value to be used.
*/ */
virtual std::string shortID(const std::string& val = "val") const; virtual std::string shortID(const std::string& val = "val") const;
/** /**
* Specialization of longID. * Specialization of longID.
* \param val - value to be used. * \param val - value to be used.
*/ */
virtual std::string longID(const std::string& val = "val") const; virtual std::string longID(const std::string& val = "val") const;
virtual void reset() ; virtual void reset() ;
private: private:
/** /**
* Prevent accidental copying * Prevent accidental copying
*/ */
ValueArg<T>(const ValueArg<T>& rhs); ValueArg<T>(const ValueArg<T>& rhs);
ValueArg<T>& operator=(const ValueArg<T>& rhs); ValueArg<T>& operator=(const ValueArg<T>& rhs);
}; };
@@ -256,11 +257,11 @@ ValueArg<T>::ValueArg(const std::string& flag,
T val, T val,
const std::string& typeDesc, const std::string& typeDesc,
Visitor* v) Visitor* v)
: Arg(flag, name, desc, req, true, v), : Arg(flag, name, desc, req, true, v),
_value( val ), _value( val ),
_default( val ), _default( val ),
_typeDesc( typeDesc ), _typeDesc( typeDesc ),
_constraint( NULL ) _constraint( NULL )
{ } { }
template<class T> template<class T>
@@ -272,13 +273,13 @@ ValueArg<T>::ValueArg(const std::string& flag,
const std::string& typeDesc, const std::string& typeDesc,
CmdLineInterface& parser, CmdLineInterface& parser,
Visitor* v) Visitor* v)
: Arg(flag, name, desc, req, true, v), : Arg(flag, name, desc, req, true, v),
_value( val ), _value( val ),
_default( val ), _default( val ),
_typeDesc( typeDesc ), _typeDesc( typeDesc ),
_constraint( NULL ) _constraint( NULL )
{ {
parser.add( this ); parser.add( this );
} }
template<class T> template<class T>
@@ -289,11 +290,11 @@ ValueArg<T>::ValueArg(const std::string& flag,
T val, T val,
Constraint<T>* constraint, Constraint<T>* constraint,
Visitor* v) Visitor* v)
: Arg(flag, name, desc, req, true, v), : Arg(flag, name, desc, req, true, v),
_value( val ), _value( val ),
_default( val ), _default( val ),
_typeDesc( constraint->shortID() ), _typeDesc( constraint->shortID() ),
_constraint( constraint ) _constraint( constraint )
{ } { }
template<class T> template<class T>
@@ -305,13 +306,13 @@ ValueArg<T>::ValueArg(const std::string& flag,
Constraint<T>* constraint, Constraint<T>* constraint,
CmdLineInterface& parser, CmdLineInterface& parser,
Visitor* v) Visitor* v)
: Arg(flag, name, desc, req, true, v), : Arg(flag, name, desc, req, true, v),
_value( val ), _value( val ),
_default( val ), _default( val ),
_typeDesc( constraint->shortID() ), _typeDesc( constraint->shortID() ),
_constraint( constraint ) _constraint( constraint )
{ {
parser.add( this ); parser.add( this );
} }
@@ -319,7 +320,10 @@ ValueArg<T>::ValueArg(const std::string& flag,
* Implementation of getValue(). * Implementation of getValue().
*/ */
template<class T> template<class T>
T& ValueArg<T>::getValue() { return _value; } T& ValueArg<T>::getValue()
{
return _value;
}
/** /**
* Implementation of processArg(). * Implementation of processArg().
@@ -327,53 +331,46 @@ T& ValueArg<T>::getValue() { return _value; }
template<class T> template<class T>
bool ValueArg<T>::processArg(int *i, std::vector<std::string>& args) bool ValueArg<T>::processArg(int *i, std::vector<std::string>& args)
{ {
if ( _ignoreable && Arg::ignoreRest() ) if ( _ignoreable && Arg::ignoreRest() )
return false; return false;
if ( _hasBlanks( args[*i] ) )
if ( _hasBlanks( args[*i] ) ) return false;
return false; std::string flag = args[*i];
std::string value = "";
std::string flag = args[*i]; trimFlag( flag, value );
if ( argMatches( flag ) )
std::string value = ""; {
trimFlag( flag, value ); if ( _alreadySet )
if ( argMatches( flag ) )
{ {
if ( _alreadySet ) if ( _xorSet )
{ throw( CmdLineParseException(
if ( _xorSet ) "Mutually exclusive argument already set!",
throw( CmdLineParseException( toString()) );
"Mutually exclusive argument already set!", else
toString()) ); throw( CmdLineParseException("Argument already set!",
else toString()) );
throw( CmdLineParseException("Argument already set!", }
toString()) ); if ( Arg::delimiter() != ' ' && value == "" )
} throw( ArgParseException(
"Couldn't find delimiter for this argument!",
if ( Arg::delimiter() != ' ' && value == "" ) toString() ) );
throw( ArgParseException( if ( value == "" )
"Couldn't find delimiter for this argument!", {
toString() ) ); (*i)++;
if ( static_cast<unsigned int>(*i) < args.size() )
if ( value == "" ) _extractValue( args[*i] );
{ else
(*i)++; throw( ArgParseException("Missing a value for this argument!",
if ( static_cast<unsigned int>(*i) < args.size() ) toString() ) );
_extractValue( args[*i] );
else
throw( ArgParseException("Missing a value for this argument!",
toString() ) );
}
else
_extractValue( value );
_alreadySet = true;
_checkWithVisitor();
return true;
} }
else else
return false; _extractValue( value );
_alreadySet = true;
_checkWithVisitor();
return true;
}
else
return false;
} }
/** /**
@@ -382,8 +379,8 @@ bool ValueArg<T>::processArg(int *i, std::vector<std::string>& args)
template<class T> template<class T>
std::string ValueArg<T>::shortID(const std::string& val) const std::string ValueArg<T>::shortID(const std::string& val) const
{ {
static_cast<void>(val); // Ignore input, don't warn static_cast<void>(val); // Ignore input, don't warn
return Arg::shortID( _typeDesc ); return Arg::shortID( _typeDesc );
} }
/** /**
@@ -392,32 +389,34 @@ std::string ValueArg<T>::shortID(const std::string& val) const
template<class T> template<class T>
std::string ValueArg<T>::longID(const std::string& val) const std::string ValueArg<T>::longID(const std::string& val) const
{ {
static_cast<void>(val); // Ignore input, don't warn static_cast<void>(val); // Ignore input, don't warn
return Arg::longID( _typeDesc ); return Arg::longID( _typeDesc );
} }
template<class T> template<class T>
void ValueArg<T>::_extractValue( const std::string& val ) void ValueArg<T>::_extractValue( const std::string& val )
{ {
try { try
ExtractValue(_value, val, typename ArgTraits<T>::ValueCategory()); {
} catch( ArgParseException &e) { ExtractValue(_value, val, typename ArgTraits<T>::ValueCategory());
throw ArgParseException(e.error(), toString()); }
} catch( ArgParseException &e)
{
if ( _constraint != NULL ) throw ArgParseException(e.error(), toString());
if ( ! _constraint->check( _value ) ) }
throw( CmdLineParseException( "Value '" + val + if ( _constraint != NULL )
+ "' does not meet constraint: " if ( ! _constraint->check( _value ) )
+ _constraint->description(), throw( CmdLineParseException( "Value '" + val +
toString() ) ); + "' does not meet constraint: "
+ _constraint->description(),
toString() ) );
} }
template<class T> template<class T>
void ValueArg<T>::reset() void ValueArg<T>::reset()
{ {
Arg::reset(); Arg::reset();
_value = _default; _value = _default;
} }
} // namespace TCLAP } // namespace TCLAP

View File

@@ -41,7 +41,8 @@
#error "Need a stringstream (sstream or strstream) to compile!" #error "Need a stringstream (sstream or strstream) to compile!"
#endif #endif
namespace TCLAP { namespace TCLAP
{
/** /**
* A Constraint that constrains the Arg to only those values specified * A Constraint that constrains the Arg to only those values specified
@@ -51,95 +52,91 @@ template<class T>
class ValuesConstraint : public Constraint<T> class ValuesConstraint : public Constraint<T>
{ {
public: public:
/** /**
* Constructor. * Constructor.
* \param allowed - vector of allowed values. * \param allowed - vector of allowed values.
*/ */
ValuesConstraint(std::vector<T>& allowed); ValuesConstraint(std::vector<T>& allowed);
/** /**
* Virtual destructor. * Virtual destructor.
*/ */
virtual ~ValuesConstraint() {} virtual ~ValuesConstraint() {}
/** /**
* Returns a description of the Constraint. * Returns a description of the Constraint.
*/ */
virtual std::string description() const; virtual std::string description() const;
/** /**
* Returns the short ID for the Constraint. * Returns the short ID for the Constraint.
*/ */
virtual std::string shortID() const; virtual std::string shortID() const;
/** /**
* The method used to verify that the value parsed from the command * The method used to verify that the value parsed from the command
* line meets the constraint. * line meets the constraint.
* \param value - The value that will be checked. * \param value - The value that will be checked.
*/ */
virtual bool check(const T& value) const; virtual bool check(const T& value) const;
protected: protected:
/** /**
* The list of valid values. * The list of valid values.
*/ */
std::vector<T> _allowed; std::vector<T> _allowed;
/** /**
* The string used to describe the allowed values of this constraint. * The string used to describe the allowed values of this constraint.
*/ */
std::string _typeDesc; std::string _typeDesc;
}; };
template<class T> template<class T>
ValuesConstraint<T>::ValuesConstraint(std::vector<T>& allowed) ValuesConstraint<T>::ValuesConstraint(std::vector<T>& allowed)
: _allowed(allowed), : _allowed(allowed),
_typeDesc("") _typeDesc("")
{ {
for ( unsigned int i = 0; i < _allowed.size(); i++ ) for ( unsigned int i = 0; i < _allowed.size(); i++ )
{ {
#if defined(HAVE_SSTREAM) #if defined(HAVE_SSTREAM)
std::ostringstream os; std::ostringstream os;
#elif defined(HAVE_STRSTREAM) #elif defined(HAVE_STRSTREAM)
std::ostrstream os; std::ostrstream os;
#else #else
#error "Need a stringstream (sstream or strstream) to compile!" #error "Need a stringstream (sstream or strstream) to compile!"
#endif #endif
os << _allowed[i];
os << _allowed[i]; std::string temp( os.str() );
if ( i > 0 )
std::string temp( os.str() ); _typeDesc += "|";
_typeDesc += temp;
if ( i > 0 ) }
_typeDesc += "|";
_typeDesc += temp;
}
} }
template<class T> template<class T>
bool ValuesConstraint<T>::check( const T& val ) const bool ValuesConstraint<T>::check( const T& val ) const
{ {
if ( std::find(_allowed.begin(),_allowed.end(),val) == _allowed.end() ) if ( std::find(_allowed.begin(),_allowed.end(),val) == _allowed.end() )
return false; return false;
else else
return true; return true;
} }
template<class T> template<class T>
std::string ValuesConstraint<T>::shortID() const std::string ValuesConstraint<T>::shortID() const
{ {
return _typeDesc; return _typeDesc;
} }
template<class T> template<class T>
std::string ValuesConstraint<T>::description() const std::string ValuesConstraint<T>::description() const
{ {
return _typeDesc; return _typeDesc;
} }

View File

@@ -28,7 +28,8 @@
#include "CmdLineOutput.h" #include "CmdLineOutput.h"
#include "Visitor.h" #include "Visitor.h"
namespace TCLAP { namespace TCLAP
{
/** /**
* A Vistor that will call the version method of the given CmdLineOutput * A Vistor that will call the version method of the given CmdLineOutput
@@ -36,43 +37,44 @@ namespace TCLAP {
*/ */
class VersionVisitor: public Visitor class VersionVisitor: public Visitor
{ {
private: private:
/** /**
* Prevent accidental copying * Prevent accidental copying
*/ */
VersionVisitor(const VersionVisitor& rhs); VersionVisitor(const VersionVisitor& rhs);
VersionVisitor& operator=(const VersionVisitor& rhs); VersionVisitor& operator=(const VersionVisitor& rhs);
protected: protected:
/** /**
* The CmdLine of interest. * The CmdLine of interest.
*/ */
CmdLineInterface* _cmd; CmdLineInterface* _cmd;
/** /**
* The output object. * The output object.
*/ */
CmdLineOutput** _out; CmdLineOutput** _out;
public: public:
/** /**
* Constructor. * Constructor.
* \param cmd - The CmdLine the output is generated for. * \param cmd - The CmdLine the output is generated for.
* \param out - The type of output. * \param out - The type of output.
*/ */
VersionVisitor( CmdLineInterface* cmd, CmdLineOutput** out ) VersionVisitor( CmdLineInterface* cmd, CmdLineOutput** out )
: Visitor(), _cmd( cmd ), _out( out ) { } : Visitor(), _cmd( cmd ), _out( out ) { }
/** /**
* Calls the version method of the output object using the * Calls the version method of the output object using the
* specified CmdLine. * specified CmdLine.
*/ */
void visit() { void visit()
(*_out)->version(*_cmd); {
throw ExitException(0); (*_out)->version(*_cmd);
} throw ExitException(0);
}
}; };

View File

@@ -23,29 +23,30 @@
#ifndef TCLAP_VISITOR_H #ifndef TCLAP_VISITOR_H
#define TCLAP_VISITOR_H #define TCLAP_VISITOR_H
namespace TCLAP { namespace TCLAP
{
/** /**
* A base class that defines the interface for visitors. * A base class that defines the interface for visitors.
*/ */
class Visitor class Visitor
{ {
public: public:
/** /**
* Constructor. Does nothing. * Constructor. Does nothing.
*/ */
Visitor() { } Visitor() { }
/** /**
* Destructor. Does nothing. * Destructor. Does nothing.
*/ */
virtual ~Visitor() { } virtual ~Visitor() { }
/** /**
* Does nothing. Should be overridden by child. * Does nothing. Should be overridden by child.
*/ */
virtual void visit() { } virtual void visit() { }
}; };
} }

View File

@@ -29,7 +29,8 @@
#include <algorithm> #include <algorithm>
#include <iostream> #include <iostream>
namespace TCLAP { namespace TCLAP
{
/** /**
* This class handles lists of Arg's that are to be XOR'd on the command * This class handles lists of Arg's that are to be XOR'd on the command
@@ -37,54 +38,54 @@ namespace TCLAP {
*/ */
class XorHandler class XorHandler
{ {
protected: protected:
/** /**
* The list of of lists of Arg's to be or'd together. * The list of of lists of Arg's to be or'd together.
*/ */
std::vector< std::vector<Arg*> > _orList; std::vector< std::vector<Arg*> > _orList;
public: public:
/** /**
* Constructor. Does nothing. * Constructor. Does nothing.
*/ */
XorHandler( ) : _orList(std::vector< std::vector<Arg*> >()) {} XorHandler( ) : _orList(std::vector< std::vector<Arg*> >()) {}
/** /**
* Add a list of Arg*'s that will be orred together. * Add a list of Arg*'s that will be orred together.
* \param ors - list of Arg* that will be xor'd. * \param ors - list of Arg* that will be xor'd.
*/ */
void add( std::vector<Arg*>& ors ); void add( std::vector<Arg*>& ors );
/** /**
* Checks whether the specified Arg is in one of the xor lists and * Checks whether the specified Arg is in one of the xor lists and
* if it does match one, returns the size of the xor list that the * if it does match one, returns the size of the xor list that the
* Arg matched. If the Arg matches, then it also sets the rest of * Arg matched. If the Arg matches, then it also sets the rest of
* the Arg's in the list. You shouldn't use this. * the Arg's in the list. You shouldn't use this.
* \param a - The Arg to be checked. * \param a - The Arg to be checked.
*/ */
int check( const Arg* a ); int check( const Arg* a );
/** /**
* Returns the XOR specific short usage. * Returns the XOR specific short usage.
*/ */
std::string shortUsage(); std::string shortUsage();
/** /**
* Prints the XOR specific long usage. * Prints the XOR specific long usage.
* \param os - Stream to print to. * \param os - Stream to print to.
*/ */
void printLongUsage(std::ostream& os); void printLongUsage(std::ostream& os);
/** /**
* Simply checks whether the Arg is contained in one of the arg * Simply checks whether the Arg is contained in one of the arg
* lists. * lists.
* \param a - The Arg to be checked. * \param a - The Arg to be checked.
*/ */
bool contains( const Arg* a ); bool contains( const Arg* a );
std::vector< std::vector<Arg*> >& getXorList(); std::vector< std::vector<Arg*> >& getXorList();
}; };
@@ -94,65 +95,61 @@ class XorHandler
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
inline void XorHandler::add( std::vector<Arg*>& ors ) inline void XorHandler::add( std::vector<Arg*>& ors )
{ {
_orList.push_back( ors ); _orList.push_back( ors );
} }
inline int XorHandler::check( const Arg* a ) inline int XorHandler::check( const Arg* a )
{ {
// iterate over each XOR list // iterate over each XOR list
for ( int i = 0; static_cast<unsigned int>(i) < _orList.size(); i++ ) for ( int i = 0; static_cast<unsigned int>(i) < _orList.size(); i++ )
{ {
// if the XOR list contains the arg.. // if the XOR list contains the arg..
ArgVectorIterator ait = std::find( _orList[i].begin(), ArgVectorIterator ait = std::find( _orList[i].begin(),
_orList[i].end(), a ); _orList[i].end(), a );
if ( ait != _orList[i].end() ) if ( ait != _orList[i].end() )
{ {
// first check to see if a mutually exclusive switch // first check to see if a mutually exclusive switch
// has not already been set // has not already been set
for ( ArgVectorIterator it = _orList[i].begin(); for ( ArgVectorIterator it = _orList[i].begin();
it != _orList[i].end(); it != _orList[i].end();
it++ ) it++ )
if ( a != (*it) && (*it)->isSet() ) if ( a != (*it) && (*it)->isSet() )
throw(CmdLineParseException( throw(CmdLineParseException(
"Mutually exclusive argument already set!", "Mutually exclusive argument already set!",
(*it)->toString())); (*it)->toString()));
// go through and set each arg that is not a
// go through and set each arg that is not a for ( ArgVectorIterator it = _orList[i].begin();
for ( ArgVectorIterator it = _orList[i].begin(); it != _orList[i].end();
it != _orList[i].end(); it++ )
it++ ) if ( a != (*it) )
if ( a != (*it) ) (*it)->xorSet();
(*it)->xorSet(); // return the number of required args that have now been set
if ( (*ait)->allowMore() )
// return the number of required args that have now been set return 0;
if ( (*ait)->allowMore() ) else
return 0; return static_cast<int>(_orList[i].size());
else }
return static_cast<int>(_orList[i].size()); }
} if ( a->isRequired() )
} return 1;
else
if ( a->isRequired() ) return 0;
return 1;
else
return 0;
} }
inline bool XorHandler::contains( const Arg* a ) inline bool XorHandler::contains( const Arg* a )
{ {
for ( int i = 0; static_cast<unsigned int>(i) < _orList.size(); i++ ) for ( int i = 0; static_cast<unsigned int>(i) < _orList.size(); i++ )
for ( ArgVectorIterator it = _orList[i].begin(); for ( ArgVectorIterator it = _orList[i].begin();
it != _orList[i].end(); it != _orList[i].end();
it++ ) it++ )
if ( a == (*it) ) if ( a == (*it) )
return true; return true;
return false;
return false;
} }
inline std::vector< std::vector<Arg*> >& XorHandler::getXorList() inline std::vector< std::vector<Arg*> >& XorHandler::getXorList()
{ {
return _orList; return _orList;
} }

View File

@@ -34,7 +34,8 @@
#include <tclap/XorHandler.h> #include <tclap/XorHandler.h>
#include <tclap/Arg.h> #include <tclap/Arg.h>
namespace TCLAP { namespace TCLAP
{
/** /**
* A class that generates a Zsh completion function as output from the usage() * A class that generates a Zsh completion function as output from the usage()
@@ -43,280 +44,266 @@ namespace TCLAP {
class ZshCompletionOutput : public CmdLineOutput class ZshCompletionOutput : public CmdLineOutput
{ {
public: public:
ZshCompletionOutput(); ZshCompletionOutput();
/** /**
* Prints the usage to stdout. Can be overridden to * Prints the usage to stdout. Can be overridden to
* produce alternative behavior. * produce alternative behavior.
* \param c - The CmdLine object the output is generated for. * \param c - The CmdLine object the output is generated for.
*/ */
virtual void usage(CmdLineInterface& c); virtual void usage(CmdLineInterface& c);
/** /**
* Prints the version to stdout. Can be overridden * Prints the version to stdout. Can be overridden
* to produce alternative behavior. * to produce alternative behavior.
* \param c - The CmdLine object the output is generated for. * \param c - The CmdLine object the output is generated for.
*/ */
virtual void version(CmdLineInterface& c); virtual void version(CmdLineInterface& c);
/** /**
* Prints (to stderr) an error message, short usage * Prints (to stderr) an error message, short usage
* Can be overridden to produce alternative behavior. * Can be overridden to produce alternative behavior.
* \param c - The CmdLine object the output is generated for. * \param c - The CmdLine object the output is generated for.
* \param e - The ArgException that caused the failure. * \param e - The ArgException that caused the failure.
*/ */
virtual void failure(CmdLineInterface& c, virtual void failure(CmdLineInterface& c,
ArgException& e ); ArgException& e );
protected: protected:
void basename( std::string& s ); void basename( std::string& s );
void quoteSpecialChars( std::string& s ); void quoteSpecialChars( std::string& s );
std::string getMutexList( CmdLineInterface& _cmd, Arg* a ); std::string getMutexList( CmdLineInterface& _cmd, Arg* a );
void printOption( Arg* it, std::string mutex ); void printOption( Arg* it, std::string mutex );
void printArg( Arg* it ); void printArg( Arg* it );
std::map<std::string, std::string> common; std::map<std::string, std::string> common;
char theDelimiter; char theDelimiter;
}; };
ZshCompletionOutput::ZshCompletionOutput() ZshCompletionOutput::ZshCompletionOutput()
: common(std::map<std::string, std::string>()), : common(std::map<std::string, std::string>()),
theDelimiter('=') theDelimiter('=')
{ {
common["host"] = "_hosts"; common["host"] = "_hosts";
common["hostname"] = "_hosts"; common["hostname"] = "_hosts";
common["file"] = "_files"; common["file"] = "_files";
common["filename"] = "_files"; common["filename"] = "_files";
common["user"] = "_users"; common["user"] = "_users";
common["username"] = "_users"; common["username"] = "_users";
common["directory"] = "_directories"; common["directory"] = "_directories";
common["path"] = "_directories"; common["path"] = "_directories";
common["url"] = "_urls"; common["url"] = "_urls";
} }
inline void ZshCompletionOutput::version(CmdLineInterface& _cmd) inline void ZshCompletionOutput::version(CmdLineInterface& _cmd)
{ {
std::cout << _cmd.getVersion() << std::endl; std::cout << _cmd.getVersion() << std::endl;
} }
inline void ZshCompletionOutput::usage(CmdLineInterface& _cmd ) inline void ZshCompletionOutput::usage(CmdLineInterface& _cmd )
{ {
std::list<Arg*> argList = _cmd.getArgList(); std::list<Arg*> argList = _cmd.getArgList();
std::string progName = _cmd.getProgramName(); std::string progName = _cmd.getProgramName();
std::string xversion = _cmd.getVersion(); std::string xversion = _cmd.getVersion();
theDelimiter = _cmd.getDelimiter(); theDelimiter = _cmd.getDelimiter();
basename(progName); basename(progName);
std::cout << "#compdef " << progName << std::endl << std::endl <<
std::cout << "#compdef " << progName << std::endl << std::endl << "# " << progName << " version " << _cmd.getVersion() << std::endl << std::endl <<
"# " << progName << " version " << _cmd.getVersion() << std::endl << std::endl << "_arguments -s -S";
"_arguments -s -S"; for (ArgListIterator it = argList.begin(); it != argList.end(); it++)
{
for (ArgListIterator it = argList.begin(); it != argList.end(); it++) if ( (*it)->shortID().at(0) == '<' )
{ printArg((*it));
if ( (*it)->shortID().at(0) == '<' ) else if ( (*it)->getFlag() != "-" )
printArg((*it)); printOption((*it), getMutexList(_cmd, *it));
else if ( (*it)->getFlag() != "-" ) }
printOption((*it), getMutexList(_cmd, *it)); std::cout << std::endl;
}
std::cout << std::endl;
} }
inline void ZshCompletionOutput::failure( CmdLineInterface& _cmd, inline void ZshCompletionOutput::failure( CmdLineInterface& _cmd,
ArgException& e ) ArgException& e )
{ {
static_cast<void>(_cmd); // unused static_cast<void>(_cmd); // unused
std::cout << e.what() << std::endl; std::cout << e.what() << std::endl;
} }
inline void ZshCompletionOutput::quoteSpecialChars( std::string& s ) inline void ZshCompletionOutput::quoteSpecialChars( std::string& s )
{ {
size_t idx = s.find_last_of(':'); size_t idx = s.find_last_of(':');
while ( idx != std::string::npos ) while ( idx != std::string::npos )
{ {
s.insert(idx, 1, '\\'); s.insert(idx, 1, '\\');
idx = s.find_last_of(':', idx); idx = s.find_last_of(':', idx);
} }
idx = s.find_last_of('\''); idx = s.find_last_of('\'');
while ( idx != std::string::npos ) while ( idx != std::string::npos )
{ {
s.insert(idx, "'\\'"); s.insert(idx, "'\\'");
if (idx == 0) if (idx == 0)
idx = std::string::npos; idx = std::string::npos;
else else
idx = s.find_last_of('\'', --idx); idx = s.find_last_of('\'', --idx);
} }
} }
inline void ZshCompletionOutput::basename( std::string& s ) inline void ZshCompletionOutput::basename( std::string& s )
{ {
size_t p = s.find_last_of('/'); size_t p = s.find_last_of('/');
if ( p != std::string::npos ) if ( p != std::string::npos )
{ {
s.erase(0, p + 1); s.erase(0, p + 1);
} }
} }
inline void ZshCompletionOutput::printArg(Arg* a) inline void ZshCompletionOutput::printArg(Arg* a)
{ {
static int count = 1; static int count = 1;
std::cout << " \\" << std::endl << " '";
std::cout << " \\" << std::endl << " '"; if ( a->acceptsMultipleValues() )
if ( a->acceptsMultipleValues() ) std::cout << '*';
std::cout << '*'; else
else std::cout << count++;
std::cout << count++; std::cout << ':';
std::cout << ':'; if ( !a->isRequired() )
if ( !a->isRequired() ) std::cout << ':';
std::cout << ':'; std::cout << a->getName() << ':';
std::map<std::string, std::string>::iterator compArg = common.find(a->getName());
std::cout << a->getName() << ':'; if ( compArg != common.end() )
std::map<std::string, std::string>::iterator compArg = common.find(a->getName()); {
if ( compArg != common.end() ) std::cout << compArg->second;
{ }
std::cout << compArg->second; else
} {
else std::cout << "_guard \"^-*\" " << a->getName();
{ }
std::cout << "_guard \"^-*\" " << a->getName(); std::cout << '\'';
}
std::cout << '\'';
} }
inline void ZshCompletionOutput::printOption(Arg* a, std::string mutex) inline void ZshCompletionOutput::printOption(Arg* a, std::string mutex)
{ {
std::string flag = a->flagStartChar() + a->getFlag(); std::string flag = a->flagStartChar() + a->getFlag();
std::string name = a->nameStartString() + a->getName(); std::string name = a->nameStartString() + a->getName();
std::string desc = a->getDescription(); std::string desc = a->getDescription();
// remove full stop and capitalisation from description as
// remove full stop and capitalisation from description as // this is the convention for zsh function
// this is the convention for zsh function if (!desc.compare(0, 12, "(required) "))
if (!desc.compare(0, 12, "(required) ")) {
{ desc.erase(0, 12);
desc.erase(0, 12); }
} if (!desc.compare(0, 15, "(OR required) "))
if (!desc.compare(0, 15, "(OR required) ")) {
{ desc.erase(0, 15);
desc.erase(0, 15); }
} size_t len = desc.length();
size_t len = desc.length(); if (len && desc.at(--len) == '.')
if (len && desc.at(--len) == '.') {
{ desc.erase(len);
desc.erase(len); }
} if (len)
if (len) {
{ desc.replace(0, 1, 1, tolower(desc.at(0)));
desc.replace(0, 1, 1, tolower(desc.at(0))); }
} std::cout << " \\" << std::endl << " '" << mutex;
if ( a->getFlag().empty() )
std::cout << " \\" << std::endl << " '" << mutex; {
std::cout << name;
if ( a->getFlag().empty() ) }
{ else
std::cout << name; {
} std::cout << "'{" << flag << ',' << name << "}'";
else }
{ if ( theDelimiter == '=' && a->isValueRequired() )
std::cout << "'{" << flag << ',' << name << "}'"; std::cout << "=-";
} quoteSpecialChars(desc);
if ( theDelimiter == '=' && a->isValueRequired() ) std::cout << '[' << desc << ']';
std::cout << "=-"; if ( a->isValueRequired() )
quoteSpecialChars(desc); {
std::cout << '[' << desc << ']'; std::string arg = a->shortID();
arg.erase(0, arg.find_last_of(theDelimiter) + 1);
if ( a->isValueRequired() ) if ( arg.at(arg.length()-1) == ']' )
{ arg.erase(arg.length()-1);
std::string arg = a->shortID(); if ( arg.at(arg.length()-1) == ']' )
arg.erase(0, arg.find_last_of(theDelimiter) + 1); {
if ( arg.at(arg.length()-1) == ']' ) arg.erase(arg.length()-1);
arg.erase(arg.length()-1); }
if ( arg.at(arg.length()-1) == ']' ) if ( arg.at(0) == '<' )
{ {
arg.erase(arg.length()-1); arg.erase(arg.length()-1);
} arg.erase(0, 1);
if ( arg.at(0) == '<' ) }
{ size_t p = arg.find('|');
arg.erase(arg.length()-1); if ( p != std::string::npos )
arg.erase(0, 1); {
} do
size_t p = arg.find('|'); {
if ( p != std::string::npos ) arg.replace(p, 1, 1, ' ');
{ }
do while ( (p = arg.find_first_of('|', p)) != std::string::npos );
{ quoteSpecialChars(arg);
arg.replace(p, 1, 1, ' '); std::cout << ": :(" << arg << ')';
} }
while ( (p = arg.find_first_of('|', p)) != std::string::npos ); else
quoteSpecialChars(arg); {
std::cout << ": :(" << arg << ')'; std::cout << ':' << arg;
} std::map<std::string, std::string>::iterator compArg = common.find(arg);
else if ( compArg != common.end() )
{ {
std::cout << ':' << arg; std::cout << ':' << compArg->second;
std::map<std::string, std::string>::iterator compArg = common.find(arg); }
if ( compArg != common.end() ) }
{ }
std::cout << ':' << compArg->second; std::cout << '\'';
}
}
}
std::cout << '\'';
} }
inline std::string ZshCompletionOutput::getMutexList( CmdLineInterface& _cmd, Arg* a) inline std::string ZshCompletionOutput::getMutexList( CmdLineInterface& _cmd, Arg* a)
{ {
XorHandler xorHandler = _cmd.getXorHandler(); XorHandler xorHandler = _cmd.getXorHandler();
std::vector< std::vector<Arg*> > xorList = xorHandler.getXorList(); std::vector< std::vector<Arg*> > xorList = xorHandler.getXorList();
if (a->getName() == "help" || a->getName() == "version")
if (a->getName() == "help" || a->getName() == "version") {
{ return "(-)";
return "(-)"; }
} std::ostringstream list;
if ( a->acceptsMultipleValues() )
std::ostringstream list; {
if ( a->acceptsMultipleValues() ) list << '*';
{ }
list << '*'; for ( int i = 0; static_cast<unsigned int>(i) < xorList.size(); i++ )
} {
for ( ArgVectorIterator it = xorList[i].begin();
for ( int i = 0; static_cast<unsigned int>(i) < xorList.size(); i++ ) it != xorList[i].end();
{ it++)
for ( ArgVectorIterator it = xorList[i].begin(); if ( a == (*it) )
it != xorList[i].end(); {
it++) list << '(';
if ( a == (*it) ) for ( ArgVectorIterator iu = xorList[i].begin();
{ iu != xorList[i].end();
list << '('; iu++ )
for ( ArgVectorIterator iu = xorList[i].begin(); {
iu != xorList[i].end(); bool notCur = (*iu) != a;
iu++ ) bool hasFlag = !(*iu)->getFlag().empty();
{ if ( iu != xorList[i].begin() && (notCur || hasFlag) )
bool notCur = (*iu) != a; list << ' ';
bool hasFlag = !(*iu)->getFlag().empty(); if (hasFlag)
if ( iu != xorList[i].begin() && (notCur || hasFlag) ) list << (*iu)->flagStartChar() << (*iu)->getFlag() << ' ';
list << ' '; if ( notCur || hasFlag )
if (hasFlag) list << (*iu)->nameStartString() << (*iu)->getName();
list << (*iu)->flagStartChar() << (*iu)->getFlag() << ' '; }
if ( notCur || hasFlag ) list << ')';
list << (*iu)->nameStartString() << (*iu)->getName(); return list.str();
} }
list << ')'; }
return list.str(); // wasn't found in xor list
} if (!a->getFlag().empty())
} {
list << "(" << a->flagStartChar() << a->getFlag() << ' ' <<
// wasn't found in xor list a->nameStartString() << a->getName() << ')';
if (!a->getFlag().empty()) { }
list << "(" << a->flagStartChar() << a->getFlag() << ' ' << return list.str();
a->nameStartString() << a->getName() << ')';
}
return list.str();
} }
} //namespace TCLAP } //namespace TCLAP