[Lazarus] Parsing command line options

michael.vancanneyt at wisa.be michael.vancanneyt at wisa.be
Mon Sep 10 17:39:20 CEST 2012



On Mon, 10 Sep 2012, J.A. de Vries wrote:

> On 2012-09-10 15:19, patspiper wrote:
>
>>>
>>> Your message is a very good example why the whole splitting and escaping
>>> approach was abandonned.  Every issue was considered to be "just add
>>> this,
>>> since then it works for me now", but after multiple years of such
>>> changes,
>>> there are still corner cases left.
>> Separating based on unquoted spaces is the 1st step. The 2nd step is to
>> remove the 1st and last matching quote from each parsed parameter (even
>> on *nix). The 3rd step is to add each parameter using
>> TProcess.Parameters.Add. It is kind of a middle ground though I
>> definitely support your suggestion if doable. Parsing a command line is
>> a can of worms!
>
> Might I make a suggestion? Why try and invent the wheel ourselves?
> There's a very good library named getopts that has been used by masses
> of programmers for years now. Maybe we could learn from that and
> re-implement the choices made in there?

We have this unit (getopt, it is documented?). 
But the code for that is for the receiving end, i.e. used by the program 
that is started. Not for the program that starts another program.

The main problem is the Windows API, which has only 1 string in which 
to pass all command-line options. The started program simply gets this
string, and must split it into options. How this string is split (quotes,
spaces, whatnot) depends on the started program and is governed by custom. 
It may be using getopts, or something else. 
(Look at the GetParamStr routine in the system unit to see how Delphi does it).

On Unix-like systems, there is simply no problem: At the API level, Options are passed in an
array of strings. Whether or not there are quotes, spaces or whatnot in this
string, is irrelevant: the strings are passed on as-is and need no
interpretation.

What causes confusion on unix systems is the use of a shell (bash, csh, sh): 
It receives commands from the user as a single line. 
It must split a command-line into the various elements that make up the array
used in the Unix API.  To be able to do so, the shell needs quotes.
The API itself does not need it.

The TProcess interface has been reworked so it conforms more to the Unix
API, since it is easier to convert that to something that Windows understands
than vice versa.

Michael.




More information about the Lazarus mailing list