summaryrefslogtreecommitdiff
path: root/src/optparser.h
blob: acfb35d4010b0ea06a5158aac376036bdd0543b7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#ifndef BU_OPT_PARSER_H
#define BU_OPT_PARSER_H

#include "bu/fstring.h"
#include "bu/list.h"
#include "bu/hash.h"
#include "bu/signals.h"
#include "bu/array.h"
#include "bu/membuf.h"
#include "bu/formatter.h"

namespace Bu
{
	typedef Bu::Array<Bu::FString> StrArray;
	class OptParser
	{
	public:
		class _ValueProxy
		{
		public:
			_ValueProxy();
			virtual ~_ValueProxy();

			virtual void setValue( const Bu::FString & )=0;
			virtual _ValueProxy *clone()=0;
		};

		template<typename ptype>
		class ValueProxy : public _ValueProxy
		{
		public:
			ValueProxy( ptype &v ) :
				v( v )
			{
			}

			virtual ~ValueProxy()
			{
			}

			virtual void setValue( const Bu::FString &sVal )
			{
				Bu::MemBuf mb( sVal );
				Bu::Formatter f( mb );
				f >> v;
			}
			
			virtual _ValueProxy *clone()
			{
				return new ValueProxy<ptype>( v );
			}

		private:
			ptype &v;
		};

		typedef Signal1<int, StrArray> OptionSignal;
		class Option
		{
		public:
			Option();
			Option( const Option &rSrc );
			virtual ~Option();

			char cOpt;
			Bu::FString sOpt;
			Bu::FString sHelp;
			OptionSignal sUsed;
			bool bShortHasParams;
			_ValueProxy *pProxy;
			Bu::FString sOverride;
		};

	public:
		OptParser();
		virtual ~OptParser();

		void parse( int argc, char **argv );

		void addOption( const Option &opt );
		
		template<typename vtype>
		void addOption( char cOpt, const Bu::FString &sOpt, vtype &var,
				const Bu::FString &sHelp="", const Bu::FString &sOverride="" )
		{
			Option o;
			o.cOpt = cOpt;
			o.sOpt = sOpt;
			o.pProxy = new ValueProxy<vtype>( var );
			o.bShortHasParams = true;
			o.sHelp = sHelp;
			o.sOverride = sOverride;
			addOption( o );
		}
		
		void addHelpOption( char c, const Bu::FString &s, const Bu::FString &sHelp );

		int optHelp( StrArray aParams );

	private:
		Bu::FString format( const Bu::FString &sIn, int iWidth, int iIndent );

		typedef Bu::List<Option> OptionList;
		typedef Bu::Hash<char, Option *> ShortOptionHash;
		typedef Bu::Hash<Bu::FString, Option *> LongOptionHash;

		OptionList lOption;
		ShortOptionHash hsOption;
		LongOptionHash hlOption;
	};
};

#endif