📄 ncbiargs.hpp
字号:
/* * =========================================================================== * PRODUCTION $Log: ncbiargs.hpp,v $ * PRODUCTION Revision 1000.0 2003/10/29 15:02:47 gouriano * PRODUCTION PRODUCTION: IMPORTED [ORIGINAL] Dev-tree R1.33 * PRODUCTION * =========================================================================== */#ifndef NCBIARGS__HPP#define NCBIARGS__HPP/* $Id: ncbiargs.hpp,v 1000.0 2003/10/29 15:02:47 gouriano Exp $ * =========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * * Author: Denis Vakatov * * *//// @file ncbiargs.hpp/// Defines command line argument related classes.////// The CArgDescriptions and CArgDesc classes are used for describing/// unparsed arguments; CArgs and CArgValue for parsed argument values;/// CArgException and CArgHelpException for argument exceptions; and CArgAllow, /// CArgAllow_{Strings, ..., Integers, Doubles} for argument constraints.////// The following description is included as applies to several classes in/// this file:////// Parsing and validation of command-line arguments are done according to/// user-provided descriptions. The command line has the following syntax:////// Command string:////// progname {arg_key, arg_key_opt, arg_key_dflt, arg_flag} [--]/// {arg_pos} {arg_pos_opt, arg_pos_dflt}/// {arg_extra} {arg_extra_opt}////// where:////// arg_key := -<key> <value> -- (mandatory)/// arg_key_opt := [-<key> <value>] -- (optional, without default value)/// arg_key_dflt := [-<key> <value>] -- (optional, with default value)/// arg_flag := -<flag> -- (always optional)/// "--" is an optional delimiter to indicate the beginning of pos. args/// arg_pos := <value> -- (mandatory)/// arg_pos_opt := [<value>] -- (optional, without default value)/// arg_pos_dflt := [<value>] -- (optional, with default value)/// arg_extra := <value> -- (dep. on the constraint policy)/// arg_extra_opt := [<value>] -- (dep. on the constraint policy)////// and:////// <key> must be followed by <value>/// <flag> and <key> are case-sensitive, and they can contain/// only alphanumeric characters/// <value> is an arbitrary string (additional constraints can/// be applied in the argument description, see "EType")////// {arg_pos***} and {arg_extra***} -- position-dependent arguments, with/// no tag preceding them./// {arg_pos***} -- have individual names and descriptions (see methods/// AddPositional***)./// {arg_extra***} have one description for all (see method AddExtra)./// User can apply constraints on the number of mandatory and optional/// {arg_extra***} arguments.#include <corelib/ncbistd.hpp>#include <corelib/ncbiobj.hpp>#include <corelib/ncbi_limits.h>#include <memory>#include <set>#include <list>#include <vector>/** @addtogroup Args * * @{ */BEGIN_NCBI_SCOPE// Some necessary forward declarations.class CNcbiArguments;class CArgAllow;/////////////////////////////////////////////////////////////////////////////////// CArgException --////// Define exceptions class for incorrectly formed arguments.////// CArgException inherits its basic functionality from CCoreException/// and defines additional error codes for malformed arguments.class NCBI_XNCBI_EXPORT CArgException : public CCoreException{public: /// Error types for improperly formatted arguments. /// /// These error conditions are checked for and caught when processing /// arguments. enum EErrCode { eInvalidArg, ///< Invalid argument eNoValue, ///< Expecting an argument value eWrongCast, ///< Incorrect cast for an argument eConvert, ///< Conversion problem eNoFile, ///< Expecting a file eConstraint, ///< Argument value outside constraints eArgType, ///< Wrong argument type eNoArg, ///< No argument eSynopsis ///< Synopois error }; /// Translate from the error code value to its string representation. virtual const char* GetErrCodeString(void) const { switch (GetErrCode()) { case eInvalidArg: return "eInvalidArg"; case eNoValue: return "eNoValue"; case eWrongCast: return "eWrongCast"; case eConvert: return "eConvert"; case eNoFile: return "eNoFile"; case eConstraint: return "eConstraint"; case eArgType: return "eArgType"; case eNoArg: return "eNoArg"; case eSynopsis: return "eSynopsis"; default: return CException::GetErrCodeString(); } } // Standard exception bolier plate code. NCBI_EXCEPTION_DEFAULT(CArgException, CCoreException);};/////////////////////////////////////////////////////////////////////////////////// CArgHelpException --////// Define exception class that gets thrown for Help messages.////// CArgException inherits its basic functionality from CArgException/// and defines an additional error code for help.class NCBI_XNCBI_EXPORT CArgHelpException : public CArgException{public: /// Error type for help exception. enum EErrCode { eHelp ///< Error code for help message }; /// Translate from the error code value to its string representation. virtual const char* GetErrCodeString(void) const { switch (GetErrCode()) { case eHelp: return "eHelp"; default: return CException::GetErrCodeString(); } } // Standard exception bolier plate code. NCBI_EXCEPTION_DEFAULT(CArgHelpException, CArgException);};/////////////////////////////////////////////////////////////////////////////////// CArgValue --////// Generic abstract base class for argument values.class NCBI_XNCBI_EXPORT CArgValue : public CObject{public: /// Get argument name. const string& GetName(void) const { return m_Name; } /// Check if argument holds a value. /// /// Argument does not hold value if it was described as optional argument /// without default value, and if it was not passed a value in the command /// line. On attempt to retrieve the value from such "no-value" argument, /// exception will be thrown. virtual bool HasValue(void) const = 0; /// Operator () form of HasValue() method. /// /// @sa /// HasValue() operator bool (void) const { return HasValue(); } /// Operator !() returns the value of !HasValue() method. /// /// @sa /// HasValue() bool operator!(void) const { return !HasValue(); } /// Get the argument's string value. /// /// If it is a value of a flag argument, then return either "true" /// or "false". /// @sa /// AsInteger(), AsDouble(), AsBoolean() virtual const string& AsString(void) const = 0; /// Get the argument's integer value. /// /// If you request a wrong value type, such as a call to "AsInteger()" /// for a "boolean" argument, an exception is thrown. /// @sa /// AsString(), AsDouble, AsBoolean() virtual int AsInteger(void) const = 0; /// Get the argument's double value. /// /// If you request a wrong value type, such as a call to "AsDouble()" /// for a "boolean" argument, an exception is thrown. /// @sa /// AsString(), AsInteger, AsBoolean() virtual double AsDouble (void) const = 0; /// Get the argument's boolean value. /// /// If you request a wrong value type, such as a call to "AsBoolean()" /// for a "integer" argument, an exception is thrown. /// @sa /// AsString(), AsInteger, AsDouble() virtual bool AsBoolean(void) const = 0; /// Get the argument as an input file stream. virtual CNcbiIstream& AsInputFile (void) const = 0; /// Get the argument as an output file stream. virtual CNcbiOstream& AsOutputFile(void) const = 0; /// Close the file. virtual void CloseFile (void) const = 0;protected: friend class CArgs; /// Protected constructor and destructor. /// /// Prohibit explicit instantiation of CArgValue with name. CArgValue(const string& name); virtual ~CArgValue(void); string m_Name; ///< Argument name};/////////////////////////////////////////////////////////////////////////////////// CArgs --////// Defines parsed arguments.////// Argument values are obtained from the unprocessed command-line arguments/// (via CNcbiArguments) and then verified and processed according to the/// argument descriptions defined by user in "CArgDescriptions".////// NOTE: the extra arguments can be accessed using virtual names:/// "#1", "#2", "#3", ..., "#<GetNExtra()>"/// in the order of insertion (by method Add).///class NCBI_XNCBI_EXPORT CArgs{public: /// Constructor. CArgs(void); /// Destructor. ~CArgs(void); /// Check existence of argument description. /// /// Return TRUE if arg "name" was described in the parent CArgDescriptions. bool Exist(const string& name) const; /// Get value of argument by name. /// /// Throw an exception if such argument does not exist. /// @sa /// Exist() above. const CArgValue& operator[] (const string& name) const; /// Get the number of unnamed positional (a.k.a. extra) args. size_t GetNExtra(void) const { return m_nExtra; } /// Return N-th extra arg value, N = 1 to GetNExtra(). const CArgValue& operator[] (size_t idx) const; /// Print (append) all arguments to the string "str" and return "str". string& Print(string& str) const; /// Add new argument name and value. /// /// Throw an exception if the "name" is not an empty string, and if /// there is an argument with this name already. /// /// HINT: Use empty "name" to add extra (unnamed) args, and they will be /// automagically assigned with the virtual names: "#1", "#2", "#3", etc. void Add(CArgValue* arg); /// Check if there are no arguments in this container. bool IsEmpty(void) const;private: typedef set< CRef<CArgValue> > TArgs; ///< Type for arguments typedef TArgs::iterator TArgsI; ///< Type for iterator typedef TArgs::const_iterator TArgsCI; ///< Type for const iterator TArgs m_Args; ///< Assoc. map of arguments' name/value size_t m_nExtra; ///< Cached # of unnamed positional arguments /// Find argument value with name "name". TArgsCI x_Find(const string& name) const;};class CArgDesc;/////////////////////////////////////////////////////////////////////////////////// CArgDescriptions --////// Description of unparsed arguments.////// Container to store the command-line argument descriptions. Provides the/// means for the parsing and verification of command-line arguments against/// the contained descriptions.////// Example: Translating "CNcbiArguments" ---> "CArgs"./// Can also be used to compose and print out the USAGE info.class NCBI_XNCBI_EXPORT CArgDescriptions{public: /// Constructor. /// /// If "auto_help" is passed TRUE, then a special flag "-h" will be added /// to the list of accepted arguments. Passing "-h" in the command line /// will printout USAGE and ignore all other passed arguments. CArgDescriptions(bool auto_help = true); /// Destructor. virtual ~CArgDescriptions(void);
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -