1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: common/cmdline.cpp
3 // Purpose: wxCmdLineParser implementation
4 // Author: Vadim Zeitlin
8 // Copyright: (c) 2000 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // Licence: wxWindows license
10 ///////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
21 #pragma implementation "cmdline.h"
24 // For compilers that support precompilation, includes "wx.h".
25 #include "wx/wxprec.h"
31 #include "wx/cmdline.h"
33 #if wxUSE_CMDLINE_PARSER
36 #include "wx/string.h"
40 #include "wx/dynarray.h"
41 #include "wx/filefn.h"
46 #include "wx/datetime.h"
48 // ----------------------------------------------------------------------------
50 // ----------------------------------------------------------------------------
52 static wxString
GetTypeName(wxCmdLineParamType type
);
54 // ----------------------------------------------------------------------------
56 // ----------------------------------------------------------------------------
58 // an internal representation of an option
59 struct wxCmdLineOption
61 wxCmdLineOption(wxCmdLineEntryType k
,
65 wxCmdLineParamType typ
,
68 wxASSERT_MSG( !shrt
.empty() || !lng
.empty(),
69 _T("option should have at least one name") );
83 // can't use union easily here, so just store all possible data fields, we
84 // don't waste much (might still use union later if the number of supported
85 // types increases, so always use the accessor functions and don't access
86 // the fields directly!)
88 void Check(wxCmdLineParamType
WXUNUSED_UNLESS_DEBUG(typ
)) const
90 wxASSERT_MSG( type
== typ
, _T("type mismatch in wxCmdLineOption") );
93 long GetLongVal() const
94 { Check(wxCMD_LINE_VAL_NUMBER
); return m_longVal
; }
95 const wxString
& GetStrVal() const
96 { Check(wxCMD_LINE_VAL_STRING
); return m_strVal
; }
97 const wxDateTime
& GetDateVal() const
98 { Check(wxCMD_LINE_VAL_DATE
); return m_dateVal
; }
100 void SetLongVal(long val
)
101 { Check(wxCMD_LINE_VAL_NUMBER
); m_longVal
= val
; m_hasVal
= TRUE
; }
102 void SetStrVal(const wxString
& val
)
103 { Check(wxCMD_LINE_VAL_STRING
); m_strVal
= val
; m_hasVal
= TRUE
; }
104 void SetDateVal(const wxDateTime val
)
105 { Check(wxCMD_LINE_VAL_DATE
); m_dateVal
= val
; m_hasVal
= TRUE
; }
107 void SetHasValue(bool hasValue
= TRUE
) { m_hasVal
= hasValue
; }
108 bool HasValue() const { return m_hasVal
; }
111 wxCmdLineEntryType kind
;
112 wxString shortName
, longName
, description
;
113 wxCmdLineParamType type
;
121 wxDateTime m_dateVal
;
124 struct wxCmdLineParam
126 wxCmdLineParam(const wxString
& desc
,
127 wxCmdLineParamType typ
,
135 wxString description
;
136 wxCmdLineParamType type
;
140 WX_DECLARE_OBJARRAY(wxCmdLineOption
, wxArrayOptions
);
141 WX_DECLARE_OBJARRAY(wxCmdLineParam
, wxArrayParams
);
143 #include "wx/arrimpl.cpp"
145 WX_DEFINE_OBJARRAY(wxArrayOptions
);
146 WX_DEFINE_OBJARRAY(wxArrayParams
);
148 // the parser internal state
149 struct wxCmdLineParserData
152 wxString m_switchChars
; // characters which may start an option
153 bool m_enableLongOptions
; // TRUE if long options are enabled
154 wxString m_logo
; // some extra text to show in Usage()
157 wxArrayString m_arguments
; // == argv, argc == m_arguments.GetCount()
158 wxArrayOptions m_options
; // all possible options and switchrs
159 wxArrayParams m_paramDesc
; // description of all possible params
160 wxArrayString m_parameters
; // all params found
163 wxCmdLineParserData();
164 void SetArguments(int argc
, wxChar
**argv
);
165 void SetArguments(const wxString
& cmdline
);
167 int FindOption(const wxString
& name
);
168 int FindOptionByLongName(const wxString
& name
);
171 // ============================================================================
173 // ============================================================================
175 // ----------------------------------------------------------------------------
176 // wxCmdLineParserData
177 // ----------------------------------------------------------------------------
179 wxCmdLineParserData::wxCmdLineParserData()
181 m_enableLongOptions
= TRUE
;
183 m_switchChars
= _T("-");
185 m_switchChars
= _T("/-");
189 void wxCmdLineParserData::SetArguments(int argc
, wxChar
**argv
)
193 for ( int n
= 0; n
< argc
; n
++ )
195 m_arguments
.Add(argv
[n
]);
199 void wxCmdLineParserData::SetArguments(const wxString
& cmdLine
)
203 m_arguments
.Add(wxTheApp
->GetAppName());
205 wxArrayString args
= wxCmdLineParser::ConvertStringToArgs(cmdLine
);
207 WX_APPEND_ARRAY(m_arguments
, args
);
210 int wxCmdLineParserData::FindOption(const wxString
& name
)
214 size_t count
= m_options
.GetCount();
215 for ( size_t n
= 0; n
< count
; n
++ )
217 if ( m_options
[n
].shortName
== name
)
228 int wxCmdLineParserData::FindOptionByLongName(const wxString
& name
)
230 size_t count
= m_options
.GetCount();
231 for ( size_t n
= 0; n
< count
; n
++ )
233 if ( m_options
[n
].longName
== name
)
243 // ----------------------------------------------------------------------------
244 // construction and destruction
245 // ----------------------------------------------------------------------------
247 void wxCmdLineParser::Init()
249 m_data
= new wxCmdLineParserData
;
252 void wxCmdLineParser::SetCmdLine(int argc
, wxChar
**argv
)
254 m_data
->SetArguments(argc
, argv
);
257 void wxCmdLineParser::SetCmdLine(const wxString
& cmdline
)
259 m_data
->SetArguments(cmdline
);
262 wxCmdLineParser::~wxCmdLineParser()
267 // ----------------------------------------------------------------------------
269 // ----------------------------------------------------------------------------
271 void wxCmdLineParser::SetSwitchChars(const wxString
& switchChars
)
273 m_data
->m_switchChars
= switchChars
;
276 void wxCmdLineParser::EnableLongOptions(bool enable
)
278 m_data
->m_enableLongOptions
= enable
;
281 void wxCmdLineParser::SetLogo(const wxString
& logo
)
283 m_data
->m_logo
= logo
;
286 // ----------------------------------------------------------------------------
287 // command line construction
288 // ----------------------------------------------------------------------------
290 void wxCmdLineParser::SetDesc(const wxCmdLineEntryDesc
*desc
)
294 switch ( desc
->kind
)
296 case wxCMD_LINE_SWITCH
:
297 AddSwitch(desc
->shortName
, desc
->longName
, desc
->description
,
301 case wxCMD_LINE_OPTION
:
302 AddOption(desc
->shortName
, desc
->longName
, desc
->description
,
303 desc
->type
, desc
->flags
);
306 case wxCMD_LINE_PARAM
:
307 AddParam(desc
->description
, desc
->type
, desc
->flags
);
311 wxFAIL_MSG( _T("unknown command line entry type") );
312 // still fall through
314 case wxCMD_LINE_NONE
:
320 void wxCmdLineParser::AddSwitch(const wxString
& shortName
,
321 const wxString
& longName
,
322 const wxString
& desc
,
325 wxASSERT_MSG( m_data
->FindOption(shortName
) == wxNOT_FOUND
,
326 _T("duplicate switch") );
328 wxCmdLineOption
*option
= new wxCmdLineOption(wxCMD_LINE_SWITCH
,
329 shortName
, longName
, desc
,
330 wxCMD_LINE_VAL_NONE
, flags
);
332 m_data
->m_options
.Add(option
);
335 void wxCmdLineParser::AddOption(const wxString
& shortName
,
336 const wxString
& longName
,
337 const wxString
& desc
,
338 wxCmdLineParamType type
,
341 wxASSERT_MSG( m_data
->FindOption(shortName
) == wxNOT_FOUND
,
342 _T("duplicate option") );
344 wxCmdLineOption
*option
= new wxCmdLineOption(wxCMD_LINE_OPTION
,
345 shortName
, longName
, desc
,
348 m_data
->m_options
.Add(option
);
351 void wxCmdLineParser::AddParam(const wxString
& desc
,
352 wxCmdLineParamType type
,
355 // do some consistency checks: a required parameter can't follow an
356 // optional one and nothing should follow a parameter with MULTIPLE flag
358 if ( !m_data
->m_paramDesc
.IsEmpty() )
360 wxCmdLineParam
& param
= m_data
->m_paramDesc
.Last();
362 wxASSERT_MSG( !(param
.flags
& wxCMD_LINE_PARAM_MULTIPLE
),
363 _T("all parameters after the one with wxCMD_LINE_PARAM_MULTIPLE style will be ignored") );
365 if ( !(flags
& wxCMD_LINE_PARAM_OPTIONAL
) )
367 wxASSERT_MSG( !(param
.flags
& wxCMD_LINE_PARAM_OPTIONAL
),
368 _T("a required parameter can't follow an optional one") );
373 wxCmdLineParam
*param
= new wxCmdLineParam(desc
, type
, flags
);
375 m_data
->m_paramDesc
.Add(param
);
378 // ----------------------------------------------------------------------------
379 // access to parse command line
380 // ----------------------------------------------------------------------------
382 bool wxCmdLineParser::Found(const wxString
& name
) const
384 int i
= m_data
->FindOption(name
);
385 if ( i
== wxNOT_FOUND
)
386 i
= m_data
->FindOptionByLongName(name
);
388 wxCHECK_MSG( i
!= wxNOT_FOUND
, FALSE
, _T("unknown switch") );
390 wxCmdLineOption
& opt
= m_data
->m_options
[(size_t)i
];
391 if ( !opt
.HasValue() )
397 bool wxCmdLineParser::Found(const wxString
& name
, wxString
*value
) const
399 int i
= m_data
->FindOption(name
);
400 if ( i
== wxNOT_FOUND
)
401 i
= m_data
->FindOptionByLongName(name
);
403 wxCHECK_MSG( i
!= wxNOT_FOUND
, FALSE
, _T("unknown option") );
405 wxCmdLineOption
& opt
= m_data
->m_options
[(size_t)i
];
406 if ( !opt
.HasValue() )
409 wxCHECK_MSG( value
, FALSE
, _T("NULL pointer in wxCmdLineOption::Found") );
411 *value
= opt
.GetStrVal();
416 bool wxCmdLineParser::Found(const wxString
& name
, long *value
) const
418 int i
= m_data
->FindOption(name
);
419 if ( i
== wxNOT_FOUND
)
420 i
= m_data
->FindOptionByLongName(name
);
422 wxCHECK_MSG( i
!= wxNOT_FOUND
, FALSE
, _T("unknown option") );
424 wxCmdLineOption
& opt
= m_data
->m_options
[(size_t)i
];
425 if ( !opt
.HasValue() )
428 wxCHECK_MSG( value
, FALSE
, _T("NULL pointer in wxCmdLineOption::Found") );
430 *value
= opt
.GetLongVal();
435 bool wxCmdLineParser::Found(const wxString
& name
, wxDateTime
*value
) const
437 int i
= m_data
->FindOption(name
);
438 if ( i
== wxNOT_FOUND
)
439 i
= m_data
->FindOptionByLongName(name
);
441 wxCHECK_MSG( i
!= wxNOT_FOUND
, FALSE
, _T("unknown option") );
443 wxCmdLineOption
& opt
= m_data
->m_options
[(size_t)i
];
444 if ( !opt
.HasValue() )
447 wxCHECK_MSG( value
, FALSE
, _T("NULL pointer in wxCmdLineOption::Found") );
449 *value
= opt
.GetDateVal();
454 size_t wxCmdLineParser::GetParamCount() const
456 return m_data
->m_parameters
.GetCount();
459 wxString
wxCmdLineParser::GetParam(size_t n
) const
461 return m_data
->m_parameters
[n
];
464 // Resets switches and options
465 void wxCmdLineParser::Reset()
467 for ( size_t i
= 0; i
< m_data
->m_options
.Count(); i
++ )
469 wxCmdLineOption
& opt
= m_data
->m_options
[i
];
470 opt
.SetHasValue(FALSE
);
475 // ----------------------------------------------------------------------------
476 // the real work is done here
477 // ----------------------------------------------------------------------------
479 int wxCmdLineParser::Parse()
481 bool maybeOption
= TRUE
; // can the following arg be an option?
482 bool ok
= TRUE
; // TRUE until an error is detected
483 bool helpRequested
= FALSE
; // TRUE if "-h" was given
484 bool hadRepeatableParam
= FALSE
; // TRUE if found param with MULTIPLE flag
486 size_t currentParam
= 0; // the index in m_paramDesc
488 size_t countParam
= m_data
->m_paramDesc
.GetCount();
494 size_t count
= m_data
->m_arguments
.GetCount();
495 for ( size_t n
= 1; ok
&& (n
< count
); n
++ ) // 0 is program name
497 arg
= m_data
->m_arguments
[n
];
499 // special case: "--" should be discarded and all following arguments
500 // should be considered as parameters, even if they start with '-' and
501 // not like options (this is POSIX-like)
502 if ( arg
== _T("--") )
509 // empty argument or just '-' is not an option but a parameter
510 if ( maybeOption
&& arg
.length() > 1 &&
511 wxStrchr(m_data
->m_switchChars
, arg
[0u]) )
515 int optInd
= wxNOT_FOUND
; // init to suppress warnings
517 // an option or a switch: find whether it's a long or a short one
518 if ( m_data
->m_enableLongOptions
&&
519 arg
[0u] == _T('-') && arg
[1u] == _T('-') )
524 const wxChar
*p
= arg
.c_str() + 2;
525 while ( wxIsalnum(*p
) || (*p
== _T('_')) || (*p
== _T('-')) )
530 optInd
= m_data
->FindOptionByLongName(name
);
531 if ( optInd
== wxNOT_FOUND
)
533 wxLogError(_("Unknown long option '%s'"), name
.c_str());
540 // a short one: as they can be cumulated, we try to find the
541 // longest substring which is a valid option
542 const wxChar
*p
= arg
.c_str() + 1;
543 while ( wxIsalnum(*p
) || (*p
== _T('_')) )
548 size_t len
= name
.length();
553 // we couldn't find a valid option name in the
554 // beginning of this string
555 wxLogError(_("Unknown option '%s'"), name
.c_str());
561 optInd
= m_data
->FindOption(name
.Left(len
));
563 // will try with one character less the next time
567 while ( optInd
== wxNOT_FOUND
);
569 len
++; // compensates extra len-- above
570 if ( (optInd
!= wxNOT_FOUND
) && (len
!= name
.length()) )
572 // first of all, the option name is only part of this
574 name
= name
.Left(len
);
576 // our option is only part of this argument, there is
577 // something else in it - it is either the value of this
578 // option or other switches if it is a switch
579 if ( m_data
->m_options
[(size_t)optInd
].kind
580 == wxCMD_LINE_SWITCH
)
582 // pretend that all the rest of the argument is the
583 // next argument, in fact
584 wxString arg2
= arg
[0u];
585 arg2
+= arg
.Mid(len
+ 1); // +1 for leading '-'
587 m_data
->m_arguments
.Insert(arg2
, n
+ 1);
590 //else: it's our value, we'll deal with it below
594 if ( optInd
== wxNOT_FOUND
)
598 continue; // will break, in fact
601 wxCmdLineOption
& opt
= m_data
->m_options
[(size_t)optInd
];
602 if ( opt
.kind
== wxCMD_LINE_SWITCH
)
604 // nothing more to do
607 if ( opt
.flags
& wxCMD_LINE_OPTION_HELP
)
609 helpRequested
= TRUE
;
611 // it's not an error, but we still stop here
619 // +1 for leading '-'
620 const wxChar
*p
= arg
.c_str() + 1 + name
.length();
623 p
++; // for another leading '-'
625 if ( *p
++ != _T('=') )
627 wxLogError(_("Option '%s' requires a value, '=' expected."), name
.c_str());
643 // the value is in the next argument
646 // ... but there is none
647 wxLogError(_("Option '%s' requires a value."),
654 // ... take it from there
655 p
= m_data
->m_arguments
[n
].c_str();
660 // the value is right here: this may be legal or
661 // not depending on the option style
662 if ( opt
.flags
& wxCMD_LINE_NEEDS_SEPARATOR
)
664 wxLogError(_("Separator expected after the option '%s'."),
678 wxFAIL_MSG( _T("unknown option type") );
679 // still fall through
681 case wxCMD_LINE_VAL_STRING
:
682 opt
.SetStrVal(value
);
685 case wxCMD_LINE_VAL_NUMBER
:
688 if ( value
.ToLong(&val
) )
694 wxLogError(_("'%s' is not a correct numeric value for option '%s'."),
695 value
.c_str(), name
.c_str());
702 case wxCMD_LINE_VAL_DATE
:
705 const wxChar
*res
= dt
.ParseDate(value
);
708 wxLogError(_("Option '%s': '%s' cannot be converted to a date."),
709 name
.c_str(), value
.c_str());
726 if ( currentParam
< countParam
)
728 wxCmdLineParam
& param
= m_data
->m_paramDesc
[currentParam
];
730 // TODO check the param type
732 m_data
->m_parameters
.Add(arg
);
734 if ( !(param
.flags
& wxCMD_LINE_PARAM_MULTIPLE
) )
740 wxASSERT_MSG( currentParam
== countParam
- 1,
741 _T("all parameters after the one with wxCMD_LINE_PARAM_MULTIPLE style are ignored") );
743 // remember that we did have this last repeatable parameter
744 hadRepeatableParam
= TRUE
;
749 wxLogError(_("Unexpected parameter '%s'"), arg
.c_str());
756 // verify that all mandatory options were given
759 size_t countOpt
= m_data
->m_options
.GetCount();
760 for ( size_t n
= 0; ok
&& (n
< countOpt
); n
++ )
762 wxCmdLineOption
& opt
= m_data
->m_options
[n
];
763 if ( (opt
.flags
& wxCMD_LINE_OPTION_MANDATORY
) && !opt
.HasValue() )
768 optName
= opt
.shortName
;
772 optName
.Printf(_("%s (or %s)"),
773 opt
.shortName
.c_str(),
774 opt
.longName
.c_str());
777 wxLogError(_("The value for the option '%s' must be specified."),
784 for ( ; ok
&& (currentParam
< countParam
); currentParam
++ )
786 wxCmdLineParam
& param
= m_data
->m_paramDesc
[currentParam
];
787 if ( (currentParam
== countParam
- 1) &&
788 (param
.flags
& wxCMD_LINE_PARAM_MULTIPLE
) &&
791 // special case: currentParam wasn't incremented, but we did
792 // have it, so don't give error
796 if ( !(param
.flags
& wxCMD_LINE_PARAM_OPTIONAL
) )
798 wxLogError(_("The required parameter '%s' was not specified."),
799 param
.description
.c_str());
811 return ok
? 0 : helpRequested
? -1 : 1;
814 // ----------------------------------------------------------------------------
815 // give the usage message
816 // ----------------------------------------------------------------------------
818 void wxCmdLineParser::Usage()
820 wxString appname
= wxTheApp
->GetAppName();
823 wxCHECK_RET( !m_data
->m_arguments
.IsEmpty(), _T("no program name") );
825 appname
= wxFileNameFromPath(m_data
->m_arguments
[0]);
826 wxStripExtension(appname
);
829 // we construct the brief cmd line desc on the fly, but not the detailed
830 // help message below because we want to align the options descriptions
831 // and for this we must first know the longest one of them
833 wxArrayString namesOptions
, descOptions
;
834 brief
.Printf(_("Usage: %s"), appname
.c_str());
836 // the switch char is usually '-' but this can be changed with
837 // SetSwitchChars() and then the first one of possible chars is used
838 wxChar chSwitch
= !m_data
->m_switchChars
? _T('-')
839 : m_data
->m_switchChars
[0u];
841 size_t n
, count
= m_data
->m_options
.GetCount();
842 for ( n
= 0; n
< count
; n
++ )
844 wxCmdLineOption
& opt
= m_data
->m_options
[n
];
847 if ( !(opt
.flags
& wxCMD_LINE_OPTION_MANDATORY
) )
852 brief
<< chSwitch
<< opt
.shortName
;
855 option
<< _T(" ") << chSwitch
<< opt
.shortName
;
856 if ( !!opt
.longName
)
858 option
<< _T(" --") << opt
.longName
;
861 if ( opt
.kind
!= wxCMD_LINE_SWITCH
)
864 val
<< _T('<') << GetTypeName(opt
.type
) << _T('>');
865 brief
<< _T(' ') << val
;
866 option
<< (!opt
.longName
? _T(':') : _T('=')) << val
;
869 if ( !(opt
.flags
& wxCMD_LINE_OPTION_MANDATORY
) )
874 namesOptions
.Add(option
);
875 descOptions
.Add(opt
.description
);
878 count
= m_data
->m_paramDesc
.GetCount();
879 for ( n
= 0; n
< count
; n
++ )
881 wxCmdLineParam
& param
= m_data
->m_paramDesc
[n
];
884 if ( param
.flags
& wxCMD_LINE_PARAM_OPTIONAL
)
889 brief
<< param
.description
;
891 if ( param
.flags
& wxCMD_LINE_PARAM_MULTIPLE
)
896 if ( param
.flags
& wxCMD_LINE_PARAM_OPTIONAL
)
902 if ( !!m_data
->m_logo
)
904 wxLogMessage(m_data
->m_logo
);
909 // now construct the detailed help message
910 size_t len
, lenMax
= 0;
911 count
= namesOptions
.GetCount();
912 for ( n
= 0; n
< count
; n
++ )
914 len
= namesOptions
[n
].length();
920 for ( n
= 0; n
< count
; n
++ )
922 len
= namesOptions
[n
].length();
923 detailed
<< namesOptions
[n
]
924 << wxString(_T(' '), lenMax
- len
) << _T('\t')
929 wxLogMessage(detailed
);
932 // ----------------------------------------------------------------------------
934 // ----------------------------------------------------------------------------
936 static wxString
GetTypeName(wxCmdLineParamType type
)
942 wxFAIL_MSG( _T("unknown option type") );
943 // still fall through
945 case wxCMD_LINE_VAL_STRING
: s
= _("str"); break;
946 case wxCMD_LINE_VAL_NUMBER
: s
= _("num"); break;
947 case wxCMD_LINE_VAL_DATE
: s
= _("date"); break;
953 #endif // wxUSE_CMDLINE_PARSER
955 // ----------------------------------------------------------------------------
957 // ----------------------------------------------------------------------------
960 wxArrayString
wxCmdLineParser::ConvertStringToArgs(const wxChar
*p
)
967 bool isInsideQuotes
= FALSE
;
971 while ( *p
== _T(' ') || *p
== _T('\t') )
975 if ( *p
== _T('\0') )
978 // parse this parameter
982 // do we have a (lone) backslash?
983 bool isQuotedByBS
= FALSE
;
984 while ( *p
== _T('\\') )
988 // if we have 2 backslashes in a row, output one
992 isQuotedByBS
= FALSE
;
994 else // the next char is quoted
1000 bool skipChar
= FALSE
,
1005 if ( !isQuotedByBS
)
1007 // don't put the quote itself in the arg
1010 isInsideQuotes
= !isInsideQuotes
;
1012 //else: insert a literal quote
1018 if ( isInsideQuotes
|| isQuotedByBS
)
1020 // preserve it, skip endParam below
1023 //else: fall through
1032 // ignore backslash before an ordinary character - this
1033 // is needed to properly handle the file names under
1034 // Windows appearing in the command line
1043 // otherwise copy this char to arg