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 #if wxUSE_CMDLINE_PARSER
34 #include "wx/string.h"
38 #include "wx/dynarray.h"
39 #include "wx/filefn.h"
44 #include "wx/datetime.h"
45 #include "wx/cmdline.h"
47 // ----------------------------------------------------------------------------
49 // ----------------------------------------------------------------------------
51 static wxString
GetTypeName(wxCmdLineParamType type
);
53 // ----------------------------------------------------------------------------
55 // ----------------------------------------------------------------------------
57 // an internal representation of an option
58 struct wxCmdLineOption
60 wxCmdLineOption(wxCmdLineEntryType k
,
64 wxCmdLineParamType typ
,
79 // can't use union easily here, so just store all possible data fields, we
80 // don't waste much (might still use union later if the number of supported
81 // types increases, so always use the accessor functions and don't access
82 // the fields directly!)
84 void Check(wxCmdLineParamType
WXUNUSED_UNLESS_DEBUG(typ
)) const
86 wxASSERT_MSG( type
== typ
, _T("type mismatch in wxCmdLineOption") );
89 long GetLongVal() const
90 { Check(wxCMD_LINE_VAL_NUMBER
); return m_longVal
; }
91 const wxString
& GetStrVal() const
92 { Check(wxCMD_LINE_VAL_STRING
); return m_strVal
; }
93 const wxDateTime
& GetDateVal() const
94 { Check(wxCMD_LINE_VAL_DATE
); return m_dateVal
; }
96 void SetLongVal(long val
)
97 { Check(wxCMD_LINE_VAL_NUMBER
); m_longVal
= val
; m_hasVal
= TRUE
; }
98 void SetStrVal(const wxString
& val
)
99 { Check(wxCMD_LINE_VAL_STRING
); m_strVal
= val
; m_hasVal
= TRUE
; }
100 void SetDateVal(const wxDateTime val
)
101 { Check(wxCMD_LINE_VAL_DATE
); m_dateVal
= val
; m_hasVal
= TRUE
; }
103 void SetHasValue(bool hasValue
= TRUE
) { m_hasVal
= hasValue
; }
104 bool HasValue() const { return m_hasVal
; }
107 wxCmdLineEntryType kind
;
108 wxString shortName
, longName
, description
;
109 wxCmdLineParamType type
;
117 wxDateTime m_dateVal
;
120 struct wxCmdLineParam
122 wxCmdLineParam(const wxString
& desc
,
123 wxCmdLineParamType typ
,
131 wxString description
;
132 wxCmdLineParamType type
;
136 WX_DECLARE_OBJARRAY(wxCmdLineOption
, wxArrayOptions
);
137 WX_DECLARE_OBJARRAY(wxCmdLineParam
, wxArrayParams
);
139 #include "wx/arrimpl.cpp"
141 WX_DEFINE_OBJARRAY(wxArrayOptions
);
142 WX_DEFINE_OBJARRAY(wxArrayParams
);
144 // the parser internal state
145 struct wxCmdLineParserData
148 wxString m_switchChars
; // characters which may start an option
149 bool m_enableLongOptions
; // TRUE if long options are enabled
150 wxString m_logo
; // some extra text to show in Usage()
153 wxArrayString m_arguments
; // == argv, argc == m_arguments.GetCount()
154 wxArrayOptions m_options
; // all possible options and switchrs
155 wxArrayParams m_paramDesc
; // description of all possible params
156 wxArrayString m_parameters
; // all params found
159 wxCmdLineParserData();
160 void SetArguments(int argc
, char **argv
);
161 void SetArguments(const wxString
& cmdline
);
163 int FindOption(const wxString
& name
);
164 int FindOptionByLongName(const wxString
& name
);
167 // ============================================================================
169 // ============================================================================
171 // ----------------------------------------------------------------------------
172 // wxCmdLineParserData
173 // ----------------------------------------------------------------------------
175 wxCmdLineParserData::wxCmdLineParserData()
177 m_enableLongOptions
= TRUE
;
179 m_switchChars
= _T("-");
181 m_switchChars
= _T("/-");
185 void wxCmdLineParserData::SetArguments(int argc
, char **argv
)
189 for ( int n
= 0; n
< argc
; n
++ )
191 m_arguments
.Add(argv
[n
]);
195 void wxCmdLineParserData::SetArguments(const wxString
& cmdLine
)
199 m_arguments
.Add(wxTheApp
->GetAppName());
202 // Treat strings enclosed in double-quotes as single arguments
204 int len
= cmdLine
.Length();
208 while ((i
< len
) && wxIsspace(cmdLine
.GetChar(i
)))
213 if (cmdLine
.GetChar(i
) == wxT('"')) // We found the start of a string
217 while ((i
< len
) && (cmdLine
.GetChar(i
) != wxT('"')))
220 wxString
arg(cmdLine
.Mid(first
, (i
- first
)));
222 m_arguments
.Add(arg
);
225 i
++; // Skip past 2nd quote
227 else // Unquoted argument
230 while ((i
< len
) && !wxIsspace(cmdLine
.GetChar(i
)))
233 wxString
arg(cmdLine
.Mid(first
, (i
- first
)));
235 m_arguments
.Add(arg
);
241 int wxCmdLineParserData::FindOption(const wxString
& name
)
243 size_t count
= m_options
.GetCount();
244 for ( size_t n
= 0; n
< count
; n
++ )
246 if ( m_options
[n
].shortName
== name
)
256 int wxCmdLineParserData::FindOptionByLongName(const wxString
& name
)
258 size_t count
= m_options
.GetCount();
259 for ( size_t n
= 0; n
< count
; n
++ )
261 if ( m_options
[n
].longName
== name
)
271 // ----------------------------------------------------------------------------
272 // construction and destruction
273 // ----------------------------------------------------------------------------
275 void wxCmdLineParser::Init()
277 m_data
= new wxCmdLineParserData
;
280 void wxCmdLineParser::SetCmdLine(int argc
, char **argv
)
282 m_data
->SetArguments(argc
, argv
);
285 void wxCmdLineParser::SetCmdLine(const wxString
& cmdline
)
287 m_data
->SetArguments(cmdline
);
290 wxCmdLineParser::~wxCmdLineParser()
295 // ----------------------------------------------------------------------------
297 // ----------------------------------------------------------------------------
299 void wxCmdLineParser::SetSwitchChars(const wxString
& switchChars
)
301 m_data
->m_switchChars
= switchChars
;
304 void wxCmdLineParser::EnableLongOptions(bool enable
)
306 m_data
->m_enableLongOptions
= enable
;
309 void wxCmdLineParser::SetLogo(const wxString
& logo
)
311 m_data
->m_logo
= logo
;
314 // ----------------------------------------------------------------------------
315 // command line construction
316 // ----------------------------------------------------------------------------
318 void wxCmdLineParser::SetDesc(const wxCmdLineEntryDesc
*desc
)
322 switch ( desc
->kind
)
324 case wxCMD_LINE_SWITCH
:
325 AddSwitch(desc
->shortName
, desc
->longName
, desc
->description
,
329 case wxCMD_LINE_OPTION
:
330 AddOption(desc
->shortName
, desc
->longName
, desc
->description
,
331 desc
->type
, desc
->flags
);
334 case wxCMD_LINE_PARAM
:
335 AddParam(desc
->description
, desc
->type
, desc
->flags
);
339 wxFAIL_MSG( _T("unknown command line entry type") );
340 // still fall through
342 case wxCMD_LINE_NONE
:
348 void wxCmdLineParser::AddSwitch(const wxString
& shortName
,
349 const wxString
& longName
,
350 const wxString
& desc
,
353 wxASSERT_MSG( m_data
->FindOption(shortName
) == wxNOT_FOUND
,
354 _T("duplicate switch") );
356 wxCmdLineOption
*option
= new wxCmdLineOption(wxCMD_LINE_SWITCH
,
357 shortName
, longName
, desc
,
358 wxCMD_LINE_VAL_NONE
, flags
);
360 m_data
->m_options
.Add(option
);
363 void wxCmdLineParser::AddOption(const wxString
& shortName
,
364 const wxString
& longName
,
365 const wxString
& desc
,
366 wxCmdLineParamType type
,
369 wxASSERT_MSG( m_data
->FindOption(shortName
) == wxNOT_FOUND
,
370 _T("duplicate option") );
372 wxCmdLineOption
*option
= new wxCmdLineOption(wxCMD_LINE_OPTION
,
373 shortName
, longName
, desc
,
376 m_data
->m_options
.Add(option
);
379 void wxCmdLineParser::AddParam(const wxString
& desc
,
380 wxCmdLineParamType type
,
383 // do some consistency checks: a required parameter can't follow an
384 // optional one and nothing should follow a parameter with MULTIPLE flag
386 if ( !m_data
->m_paramDesc
.IsEmpty() )
388 wxCmdLineParam
& param
= m_data
->m_paramDesc
.Last();
390 wxASSERT_MSG( !(param
.flags
& wxCMD_LINE_PARAM_MULTIPLE
),
391 _T("all parameters after the one with wxCMD_LINE_PARAM_MULTIPLE style will be ignored") );
393 if ( !(flags
& wxCMD_LINE_PARAM_OPTIONAL
) )
395 wxASSERT_MSG( !(param
.flags
& wxCMD_LINE_PARAM_OPTIONAL
),
396 _T("a required parameter can't follow an optional one") );
401 wxCmdLineParam
*param
= new wxCmdLineParam(desc
, type
, flags
);
403 m_data
->m_paramDesc
.Add(param
);
406 // ----------------------------------------------------------------------------
407 // access to parse command line
408 // ----------------------------------------------------------------------------
410 bool wxCmdLineParser::Found(const wxString
& name
) const
412 int i
= m_data
->FindOption(name
);
413 wxCHECK_MSG( i
!= wxNOT_FOUND
, FALSE
, _T("unknown switch") );
415 wxCmdLineOption
& opt
= m_data
->m_options
[(size_t)i
];
416 if ( !opt
.HasValue() )
422 bool wxCmdLineParser::Found(const wxString
& name
, wxString
*value
) const
424 int i
= m_data
->FindOption(name
);
425 wxCHECK_MSG( i
!= wxNOT_FOUND
, FALSE
, _T("unknown option") );
427 wxCmdLineOption
& opt
= m_data
->m_options
[(size_t)i
];
428 if ( !opt
.HasValue() )
431 wxCHECK_MSG( value
, FALSE
, _T("NULL pointer in wxCmdLineOption::Found") );
433 *value
= opt
.GetStrVal();
438 bool wxCmdLineParser::Found(const wxString
& name
, long *value
) const
440 int i
= m_data
->FindOption(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
.GetLongVal();
454 bool wxCmdLineParser::Found(const wxString
& name
, wxDateTime
*value
) const
456 int i
= m_data
->FindOption(name
);
457 wxCHECK_MSG( i
!= wxNOT_FOUND
, FALSE
, _T("unknown option") );
459 wxCmdLineOption
& opt
= m_data
->m_options
[(size_t)i
];
460 if ( !opt
.HasValue() )
463 wxCHECK_MSG( value
, FALSE
, _T("NULL pointer in wxCmdLineOption::Found") );
465 *value
= opt
.GetDateVal();
470 size_t wxCmdLineParser::GetParamCount() const
472 return m_data
->m_parameters
.GetCount();
475 wxString
wxCmdLineParser::GetParam(size_t n
) const
477 return m_data
->m_parameters
[n
];
480 // Resets switches and options
481 void wxCmdLineParser::Reset()
483 for ( size_t i
= 0; i
< m_data
->m_options
.Count(); i
++ )
485 wxCmdLineOption
& opt
= m_data
->m_options
[i
];
486 opt
.SetHasValue(FALSE
);
491 // ----------------------------------------------------------------------------
492 // the real work is done here
493 // ----------------------------------------------------------------------------
495 int wxCmdLineParser::Parse()
497 bool maybeOption
= TRUE
; // can the following arg be an option?
498 bool ok
= TRUE
; // TRUE until an error is detected
499 bool helpRequested
= FALSE
; // TRUE if "-h" was given
500 bool hadRepeatableParam
= FALSE
; // TRUE if found param with MULTIPLE flag
502 size_t currentParam
= 0; // the index in m_paramDesc
504 size_t countParam
= m_data
->m_paramDesc
.GetCount();
510 size_t count
= m_data
->m_arguments
.GetCount();
511 for ( size_t n
= 1; ok
&& (n
< count
); n
++ ) // 0 is program name
513 arg
= m_data
->m_arguments
[n
];
515 // special case: "--" should be discarded and all following arguments
516 // should be considered as parameters, even if they start with '-' and
517 // not like options (this is POSIX-like)
518 if ( arg
== _T("--") )
525 // empty argument or just '-' is not an option but a parameter
526 if ( maybeOption
&& arg
.length() > 1 &&
527 wxStrchr(m_data
->m_switchChars
, arg
[0u]) )
531 int optInd
= wxNOT_FOUND
; // init to suppress warnings
533 // an option or a switch: find whether it's a long or a short one
534 if ( m_data
->m_enableLongOptions
&&
535 arg
[0u] == _T('-') && arg
[1u] == _T('-') )
540 const wxChar
*p
= arg
.c_str() + 2;
541 while ( wxIsalnum(*p
) || (*p
== _T('_')) || (*p
== _T('-')) )
546 optInd
= m_data
->FindOptionByLongName(name
);
547 if ( optInd
== wxNOT_FOUND
)
549 wxLogError(_("Unknown long option '%s'"), name
.c_str());
556 // a short one: as they can be cumulated, we try to find the
557 // longest substring which is a valid option
558 const wxChar
*p
= arg
.c_str() + 1;
559 while ( wxIsalnum(*p
) || (*p
== _T('_')) )
564 size_t len
= name
.length();
569 // we couldn't find a valid option name in the
570 // beginning of this string
571 wxLogError(_("Unknown option '%s'"), name
.c_str());
577 optInd
= m_data
->FindOption(name
.Left(len
));
579 // will try with one character less the next time
583 while ( optInd
== wxNOT_FOUND
);
585 len
++; // compensates extra len-- above
586 if ( (optInd
!= wxNOT_FOUND
) && (len
!= name
.length()) )
588 // first of all, the option name is only part of this
590 name
= name
.Left(len
);
592 // our option is only part of this argument, there is
593 // something else in it - it is either the value of this
594 // option or other switches if it is a switch
595 if ( m_data
->m_options
[(size_t)optInd
].kind
596 == wxCMD_LINE_SWITCH
)
598 // pretend that all the rest of the argument is the
599 // next argument, in fact
600 wxString arg2
= arg
[0u];
601 arg2
+= arg
.Mid(len
+ 1); // +1 for leading '-'
603 m_data
->m_arguments
.Insert(arg2
, n
+ 1);
606 //else: it's our value, we'll deal with it below
610 if ( optInd
== wxNOT_FOUND
)
614 continue; // will break, in fact
617 wxCmdLineOption
& opt
= m_data
->m_options
[(size_t)optInd
];
618 if ( opt
.kind
== wxCMD_LINE_SWITCH
)
620 // nothing more to do
623 if ( opt
.flags
& wxCMD_LINE_OPTION_HELP
)
625 helpRequested
= TRUE
;
627 // it's not an error, but we still stop here
635 // +1 for leading '-'
636 const wxChar
*p
= arg
.c_str() + 1 + name
.length();
639 p
++; // for another leading '-'
641 if ( *p
++ != _T('=') )
643 wxLogError(_("Option '%s' requires a value, '=' expected."), name
.c_str());
659 // the value is in the next argument
662 // ... but there is none
663 wxLogError(_("Option '%s' requires a value."),
670 // ... take it from there
671 p
= m_data
->m_arguments
[n
].c_str();
676 // the value is right here: this may be legal or
677 // not depending on the option style
678 if ( opt
.flags
& wxCMD_LINE_NEEDS_SEPARATOR
)
680 wxLogError(_("Separator expected after the option '%s'."),
694 wxFAIL_MSG( _T("unknown option type") );
695 // still fall through
697 case wxCMD_LINE_VAL_STRING
:
698 opt
.SetStrVal(value
);
701 case wxCMD_LINE_VAL_NUMBER
:
704 if ( value
.ToLong(&val
) )
710 wxLogError(_("'%s' is not a correct numeric value for option '%s'."),
711 value
.c_str(), name
.c_str());
718 case wxCMD_LINE_VAL_DATE
:
721 const wxChar
*res
= dt
.ParseDate(value
);
724 wxLogError(_("Option '%s': '%s' cannot be converted to a date."),
725 name
.c_str(), value
.c_str());
742 if ( currentParam
< countParam
)
744 wxCmdLineParam
& param
= m_data
->m_paramDesc
[currentParam
];
746 // TODO check the param type
748 m_data
->m_parameters
.Add(arg
);
750 if ( !(param
.flags
& wxCMD_LINE_PARAM_MULTIPLE
) )
756 wxASSERT_MSG( currentParam
== countParam
- 1,
757 _T("all parameters after the one with wxCMD_LINE_PARAM_MULTIPLE style are ignored") );
759 // remember that we did have this last repeatable parameter
760 hadRepeatableParam
= TRUE
;
765 wxLogError(_("Unexpected parameter '%s'"), arg
.c_str());
772 // verify that all mandatory options were given
775 size_t countOpt
= m_data
->m_options
.GetCount();
776 for ( size_t n
= 0; ok
&& (n
< countOpt
); n
++ )
778 wxCmdLineOption
& opt
= m_data
->m_options
[n
];
779 if ( (opt
.flags
& wxCMD_LINE_OPTION_MANDATORY
) && !opt
.HasValue() )
784 optName
= opt
.shortName
;
788 optName
.Printf(_("%s (or %s)"),
789 opt
.shortName
.c_str(),
790 opt
.longName
.c_str());
793 wxLogError(_("The value for the option '%s' must be specified."),
800 for ( ; ok
&& (currentParam
< countParam
); currentParam
++ )
802 wxCmdLineParam
& param
= m_data
->m_paramDesc
[currentParam
];
803 if ( (currentParam
== countParam
- 1) &&
804 (param
.flags
& wxCMD_LINE_PARAM_MULTIPLE
) &&
807 // special case: currentParam wasn't incremented, but we did
808 // have it, so don't give error
812 if ( !(param
.flags
& wxCMD_LINE_PARAM_OPTIONAL
) )
814 wxLogError(_("The required parameter '%s' was not specified."),
815 param
.description
.c_str());
827 return ok
? 0 : helpRequested
? -1 : 1;
830 // ----------------------------------------------------------------------------
831 // give the usage message
832 // ----------------------------------------------------------------------------
834 void wxCmdLineParser::Usage()
836 wxString appname
= wxTheApp
->GetAppName();
839 wxCHECK_RET( !m_data
->m_arguments
.IsEmpty(), _T("no program name") );
841 appname
= wxFileNameFromPath(m_data
->m_arguments
[0]);
842 wxStripExtension(appname
);
845 // we construct the brief cmd line desc on the fly, but not the detailed
846 // help message below because we want to align the options descriptions
847 // and for this we must first know the longest one of them
849 wxArrayString namesOptions
, descOptions
;
850 brief
.Printf(_("Usage: %s"), appname
.c_str());
852 // the switch char is usually '-' but this can be changed with
853 // SetSwitchChars() and then the first one of possible chars is used
854 wxChar chSwitch
= !m_data
->m_switchChars
? _T('-')
855 : m_data
->m_switchChars
[0u];
857 size_t n
, count
= m_data
->m_options
.GetCount();
858 for ( n
= 0; n
< count
; n
++ )
860 wxCmdLineOption
& opt
= m_data
->m_options
[n
];
863 if ( !(opt
.flags
& wxCMD_LINE_OPTION_MANDATORY
) )
868 brief
<< chSwitch
<< opt
.shortName
;
871 option
<< _T(" ") << chSwitch
<< opt
.shortName
;
872 if ( !!opt
.longName
)
874 option
<< _T(" --") << opt
.longName
;
877 if ( opt
.kind
!= wxCMD_LINE_SWITCH
)
880 val
<< _T('<') << GetTypeName(opt
.type
) << _T('>');
881 brief
<< _T(' ') << val
;
882 option
<< (!opt
.longName
? _T(':') : _T('=')) << val
;
885 if ( !(opt
.flags
& wxCMD_LINE_OPTION_MANDATORY
) )
890 namesOptions
.Add(option
);
891 descOptions
.Add(opt
.description
);
894 count
= m_data
->m_paramDesc
.GetCount();
895 for ( n
= 0; n
< count
; n
++ )
897 wxCmdLineParam
& param
= m_data
->m_paramDesc
[n
];
900 if ( param
.flags
& wxCMD_LINE_PARAM_OPTIONAL
)
905 brief
<< param
.description
;
907 if ( param
.flags
& wxCMD_LINE_PARAM_MULTIPLE
)
912 if ( param
.flags
& wxCMD_LINE_PARAM_OPTIONAL
)
918 if ( !!m_data
->m_logo
)
920 wxLogMessage(m_data
->m_logo
);
925 // now construct the detailed help message
926 size_t len
, lenMax
= 0;
927 count
= namesOptions
.GetCount();
928 for ( n
= 0; n
< count
; n
++ )
930 len
= namesOptions
[n
].length();
936 for ( n
= 0; n
< count
; n
++ )
938 len
= namesOptions
[n
].length();
939 detailed
<< namesOptions
[n
]
940 << wxString(_T(' '), lenMax
- len
) << _T('\t')
945 wxLogMessage(detailed
);
948 // ----------------------------------------------------------------------------
950 // ----------------------------------------------------------------------------
952 static wxString
GetTypeName(wxCmdLineParamType type
)
958 wxFAIL_MSG( _T("unknown option type") );
959 // still fall through
961 case wxCMD_LINE_VAL_STRING
: s
= _("str"); break;
962 case wxCMD_LINE_VAL_NUMBER
: s
= _("num"); break;
963 case wxCMD_LINE_VAL_DATE
: s
= _("date"); break;
969 #endif // wxUSE_CMDLINE_PARSER