1 ------------------------------------------------------------------------------
3 -- GNAT COMPILER COMPONENTS --
5 -- G N A T . C O M M A N D _ L I N E --
9 -- Copyright (C) 1999-2010, AdaCore --
11 -- GNAT is free software; you can redistribute it and/or modify it under --
12 -- terms of the GNU General Public License as published by the Free Soft- --
13 -- ware Foundation; either version 2, or (at your option) any later ver- --
14 -- sion. GNAT is distributed in the hope that it will be useful, but WITH- --
15 -- OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY --
16 -- or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License --
17 -- for more details. You should have received a copy of the GNU General --
18 -- Public License distributed with GNAT; see file COPYING. If not, write --
19 -- to the Free Software Foundation, 51 Franklin Street, Fifth Floor, --
20 -- Boston, MA 02110-1301, USA. --
22 -- As a special exception, if other files instantiate generics from this --
23 -- unit, or you link this unit with other files to produce an executable, --
24 -- this unit does not by itself cause the resulting executable to be --
25 -- covered by the GNU General Public License. This exception does not --
26 -- however invalidate any other reasons why the executable file might be --
27 -- covered by the GNU Public License. --
29 -- GNAT was originally developed by the GNAT team at New York University. --
30 -- Extensive contributions were provided by Ada Core Technologies Inc. --
32 ------------------------------------------------------------------------------
34 -- High level package for command line parsing and manipulation
36 ----------------------------------------
37 -- Simple Parsing of the Command Line --
38 ----------------------------------------
40 -- This package provides an interface for parsing command line arguments,
41 -- when they are either read from Ada.Command_Line or read from a string list.
42 -- As shown in the example below, one should first retrieve the switches
43 -- (special command line arguments starting with '-' by default) and their
44 -- parameters, and then the rest of the command line arguments.
46 -- While it may appear easy to parse the command line arguments with
47 -- Ada.Command_Line, there are in fact lots of special cases to handle in some
48 -- applications. Those are fully managed by GNAT.Command_Line. Among these are
49 -- switches with optional parameters, grouping switches (for instance "-ab"
50 -- might mean the same as "-a -b"), various characters to separate a switch
51 -- and its parameter (or none: "-a 1" and "-a1" are generally the same, which
52 -- can introduce confusion with grouped switches),...
56 -- case Getopt ("a b: ad") is -- Accepts '-a', '-ad', or '-b argument'
57 -- when ASCII.NUL => exit;
60 -- if Full_Switch = "a" then
61 -- Put_Line ("Got a");
63 -- Put_Line ("Got ad");
66 -- when 'b' => Put_Line ("Got b + " & Parameter);
69 -- raise Program_Error; -- cannot occur!
75 -- S : constant String := Get_Argument (Do_Expansion => True);
77 -- exit when S'Length = 0;
78 -- Put_Line ("Got " & S);
83 -- when Invalid_Switch => Put_Line ("Invalid Switch " & Full_Switch);
84 -- when Invalid_Parameter => Put_Line ("No parameter for " & Full_Switch);
91 -- A more complicated example would involve the use of sections for the
92 -- switches, as for instance in gnatmake. The same command line is used to
93 -- provide switches for several tools. Each tool recognizes its switches by
94 -- separating them with special switches that act as section separators.
95 -- Each section acts as a command line of its own.
98 -- Initialize_Option_Scan ('-', False, "largs bargs cargs");
100 -- -- Same loop as above to get switches and arguments
103 -- Goto_Section ("bargs");
105 -- -- Same loop as above to get switches and arguments
106 -- -- The supported switches in Getopt might be different
109 -- Goto_Section ("cargs");
111 -- -- Same loop as above to get switches and arguments
112 -- -- The supported switches in Getopt might be different
116 -------------------------------
117 -- Parsing a List of Strings --
118 -------------------------------
120 -- The examples above show how to parse the command line when the arguments
121 -- are read directly from Ada.Command_Line. However, these arguments can also
122 -- be read from a list of strings. This can be useful in several contexts,
123 -- either because your system does not support Ada.Command_Line, or because
124 -- you are manipulating other tools and creating their command lines by hand,
125 -- or for any other reason.
127 -- To create the list of strings, it is recommended to use
128 -- GNAT.OS_Lib.Argument_String_To_List.
130 -- The example below shows how to get the parameters from such a list. Note
131 -- also the use of '*' to get all the switches, and not report errors when an
132 -- unexpected switch was used by the user
135 -- Parser : Opt_Parser;
136 -- Args : constant Argument_List_Access :=
137 -- GNAT.OS_Lib.Argument_String_To_List ("-g -O1 -Ipath");
139 -- Initialize_Option_Scan (Parser, Args);
140 -- while Getopt ("* g O! I=", Parser) /= ASCII.NUL loop
141 -- Put_Line ("Switch " & Full_Switch (Parser)
142 -- & " param=" & Parameter (Parser));
147 -------------------------------------------
148 -- High-Level Command Line Configuration --
149 -------------------------------------------
151 -- As shown above, the code is still relatively low-level. For instance, there
152 -- is no way to indicate which switches are related (thus if "-l" and "--long"
153 -- should have the same effect, your code will need to test for both cases).
154 -- Likewise, it is difficult to handle more advanced constructs, like:
156 -- * Specifying -gnatwa is the same as specifying -gnatwu -gnatwv, but
157 -- shorter and more readable
159 -- * All switches starting with -gnatw can be grouped, for instance one
160 -- can write -gnatwcd instead of -gnatwc -gnatwd.
161 -- Of course, this can be combined with the above and -gnatwacd is the
162 -- same as -gnatwc -gnatwd -gnatwu -gnatwv
164 -- * The switch -T is the same as -gnatwAB (same as -gnatwA -gnatwB)
166 -- With the above form of Getopt, you would receive "-gnatwa", "-T" or
167 -- "-gnatwcd" in the examples above, and thus you require additional manual
168 -- parsing of the switch.
170 -- Instead, this package provides the type Command_Line_Configuration, which
171 -- stores all the knowledge above. For instance:
173 -- Config : Command_Line_Configuration;
174 -- Define_Alias (Config, "-gnatwa", "-gnatwu -gnatwv");
175 -- Define_Prefix (Config, "-gnatw");
176 -- Define_Alias (Config, "-T", "-gnatwAB");
178 -- You then need to specify all possible switches in your application by
179 -- calling Define_Switch, for instance:
181 -- Define_Switch (Config, "-gnatwu", Help => "warn on unused entities");
182 -- Define_Switch (Config, "-gnatwv", Help => "warn on unassigned var");
185 -- Specifying the help message is optional, but makes it easy to then call
187 -- Display_Help (Config);
188 -- that will display a properly formatted help message for your application,
189 -- listing all possible switches. That way you have a single place in which
190 -- to maintain the list of switches and their meaning, rather than maintaing
191 -- both the string to pass to Getopt and a subprogram to display the help.
192 -- Both will properly stay synchronized.
194 -- Once you have this Config, you just have to call
195 -- Getopt (Config, Callback'Access);
196 -- to parse the command line. The Callback will be called for each switch
197 -- found on the command line (in the case of our example, that is "-gnatwu"
198 -- and then "-gnatwv", not "-gnatwa" itself). This simplifies command line
201 -- In fact, this can be further automated for the most command case where the
202 -- parameter passed to a switch is stored in a variable in the application.
203 -- When a switch is defined, you only have to indicate where to store the
204 -- value, and let Getopt do the rest. For instance:
206 -- Optimization : aliased Integer;
207 -- Verbose : aliased Boolean;
209 -- Define_Switch (Config, Verbose'Access,
210 -- "-v", Long_Switch => "--verbose",
211 -- Help => "Output extra verbose information");
212 -- Define_Switch (Config, Optimization'Access,
213 -- "-O?", Help => "Optimization level");
215 -- Getopt (Config); -- No callback
217 -- Since all switches are handled automatically, we don't even need to pass
218 -- a callback to Getopt. Once getopt has been called, the two variables
219 -- Optimization and Verbose have been properly initialized, either to the
220 -- default value or to the value found on the command line.
222 ------------------------------------------------
223 -- Creating and Manipulating the Command Line --
224 ------------------------------------------------
226 -- This package provides mechanisms to create and modify command lines by
227 -- adding or removing arguments from them. The resulting command line is kept
228 -- as short as possible by coalescing arguments whenever possible.
230 -- Complex command lines can thus be constructed, for example from a GUI
231 -- (although this package does not by itself depend upon any specific GUI
234 -- Using the configuration defined earlier, one can then construct a command
235 -- line for the tool with:
237 -- Cmd : Command_Line;
238 -- Set_Configuration (Cmd, Config); -- Config created earlier
239 -- Add_Switch (Cmd, "-bar");
240 -- Add_Switch (Cmd, "-gnatwu");
241 -- Add_Switch (Cmd, "-gnatwv"); -- will be grouped with the above
242 -- Add_Switch (Cmd, "-T");
244 -- The resulting command line can be iterated over to get all its switches,
245 -- There are two modes for this iteration: either you want to get the
246 -- shortest possible command line, which would be:
250 -- or on the other hand you want each individual switch (so that your own
251 -- tool does not have to do further complex processing), which would be:
253 -- -bar -gnatwu -gnatwv -gnatwA -gnatwB
255 -- Of course, we can assume that the tool you want to spawn would understand
256 -- both of these, since they are both compatible with the description we gave
257 -- above. However, the first result is useful if you want to show the user
258 -- what you are spawning (since that keeps the output shorter), and the second
259 -- output is more useful for a tool that would check whether -gnatwu was
260 -- passed (which isn't obvious in the first output). Likewise, the second
261 -- output is more useful if you have a graphical interface since each switch
262 -- can be associated with a widget, and you immediately know whether -gnatwu
265 -- Some command line arguments can have parameters, which on a command line
266 -- appear as a separate argument that must immediately follow the switch.
267 -- Since the subprograms in this package will reorganize the switches to group
268 -- them, you need to indicate what is a command line
269 -- parameter, and what is a switch argument.
271 -- This is done by passing an extra argument to Add_Switch, as in:
273 -- Add_Switch (Cmd, "-foo", Parameter => "arg1");
275 -- This ensures that "arg1" will always be treated as the argument to -foo,
276 -- and will not be grouped with other parts of the command line.
278 with Ada.Command_Line;
280 with GNAT.Directory_Operations;
285 package GNAT.Command_Line is
291 type Opt_Parser is private;
292 Command_Line_Parser : constant Opt_Parser;
293 -- This object is responsible for parsing a list of arguments, which by
294 -- default are the standard command line arguments from Ada.Command_Line.
295 -- This is really a pointer to actual data, which must therefore be
296 -- initialized through a call to Initialize_Option_Scan, and must be freed
297 -- with a call to Free.
299 -- As a special case, Command_Line_Parser does not need to be either
300 -- initialized or free-ed.
302 procedure Initialize_Option_Scan
303 (Switch_Char : Character := '-';
304 Stop_At_First_Non_Switch : Boolean := False;
305 Section_Delimiters : String := "");
306 procedure Initialize_Option_Scan
307 (Parser : out Opt_Parser;
308 Command_Line : GNAT.OS_Lib.Argument_List_Access;
309 Switch_Char : Character := '-';
310 Stop_At_First_Non_Switch : Boolean := False;
311 Section_Delimiters : String := "");
312 -- The first procedure resets the internal state of the package to prepare
313 -- to rescan the parameters. It does not need to be called before the first
314 -- use of Getopt (but it could be), but it must be called if you want to
315 -- start rescanning the command line parameters from the start. The
316 -- optional parameter Switch_Char can be used to reset the switch
317 -- character, e.g. to '/' for use in DOS-like systems.
319 -- The second subprogram initializes a parser that takes its arguments from
320 -- an array of strings rather than directly from the command line. In this
321 -- case, the parser is responsible for freeing the strings stored in
322 -- Command_Line. If you pass null to Command_Line, this will in fact create
323 -- a second parser for Ada.Command_Line, which doesn't share any data with
324 -- the default parser. This parser must be free-ed.
326 -- The optional parameter Stop_At_First_Non_Switch indicates if Getopt is
327 -- to look for switches on the whole command line, or if it has to stop as
328 -- soon as a non-switch argument is found.
332 -- Arguments: my_application file1 -c
334 -- If Stop_At_First_Non_Switch is False, then -c will be considered
335 -- as a switch (returned by getopt), otherwise it will be considered
336 -- as a normal argument (returned by Get_Argument).
338 -- If Section_Delimiters is set, then every following subprogram
339 -- (Getopt and Get_Argument) will only operate within a section, which
340 -- is delimited by any of these delimiters or the end of the command line.
343 -- Initialize_Option_Scan (Section_Delimiters => "largs bargs cargs");
345 -- Arguments on command line : my_application -c -bargs -d -e -largs -f
346 -- This line contains three sections, the first one is the default one
347 -- and includes only the '-c' switch, the second one is between -bargs
348 -- and -largs and includes '-d -e' and the last one includes '-f'.
350 procedure Free (Parser : in out Opt_Parser);
351 -- Free the memory used by the parser. Calling this is not mandatory for
352 -- the Command_Line_Parser
354 procedure Goto_Section
355 (Name : String := "";
356 Parser : Opt_Parser := Command_Line_Parser);
357 -- Change the current section. The next Getopt or Get_Argument will start
358 -- looking at the beginning of the section. An empty name ("") refers to
359 -- the first section between the program name and the first section
360 -- delimiter. If the section does not exist in Section_Delimiters, then
361 -- Invalid_Section is raised. If the section does not appear on the command
362 -- line, then it is treated as an empty section.
365 (Parser : Opt_Parser := Command_Line_Parser) return String;
366 -- Returns the full name of the last switch found (Getopt only returns the
367 -- first character). Does not include the Switch_Char ('-' by default),
368 -- unless the "*" option of Getopt is used (see below).
370 function Current_Section
371 (Parser : Opt_Parser := Command_Line_Parser) return String;
372 -- Return the name of the current section.
373 -- The list of valid sections is defined through Initialize_Option_Scan
377 Concatenate : Boolean := True;
378 Parser : Opt_Parser := Command_Line_Parser) return Character;
379 -- This function moves to the next switch on the command line (defined as
380 -- switch character followed by a character within Switches, casing being
381 -- significant). The result returned is the first character of the switch
382 -- that is located. If there are no more switches in the current section,
383 -- returns ASCII.NUL. If Concatenate is True (the default), the switches do
384 -- not need to be separated by spaces (they can be concatenated if they do
385 -- not require an argument, e.g. -ab is the same as two separate arguments
388 -- Switches is a string of all the possible switches, separated by
389 -- spaces. A switch can be followed by one of the following characters:
391 -- ':' The switch requires a parameter. There can optionally be a space
392 -- on the command line between the switch and its parameter.
394 -- '=' The switch requires a parameter. There can either be a '=' or a
395 -- space on the command line between the switch and its parameter.
397 -- '!' The switch requires a parameter, but there can be no space on the
398 -- command line between the switch and its parameter.
400 -- '?' The switch may have an optional parameter. There can be no space
401 -- between the switch and its argument.
403 -- e.g. if Switches has the following value : "a? b",
404 -- The command line can be:
406 -- -afoo : -a switch with 'foo' parameter
407 -- -a foo : -a switch and another element on the
408 -- command line 'foo', returned by Get_Argument
410 -- Example: if Switches is "-a: -aO:", you can have the following
413 -- -aarg : 'a' switch with 'arg' parameter
414 -- -a arg : 'a' switch with 'arg' parameter
415 -- -aOarg : 'aO' switch with 'arg' parameter
416 -- -aO arg : 'aO' switch with 'arg' parameter
420 -- Getopt ("a b: ac ad?")
422 -- accept either 'a' or 'ac' with no argument,
423 -- accept 'b' with a required argument
424 -- accept 'ad' with an optional argument
426 -- If the first item in switches is '*', then Getopt will catch
427 -- every element on the command line that was not caught by any other
428 -- switch. The character returned by GetOpt is '*', but Full_Switch
429 -- contains the full command line argument, including leading '-' if there
430 -- is one. If this character was not returned, there would be no way of
431 -- knowing whether it is there or not.
435 -- If the command line is '-a -c toto.o -b', Getopt will return
436 -- successively 'a', '*', '*' and 'b', with Full_Switch returning
437 -- "a", "-c", "toto.o", and "b".
439 -- When Getopt encounters an invalid switch, it raises the exception
440 -- Invalid_Switch and sets Full_Switch to return the invalid switch.
441 -- When Getopt cannot find the parameter associated with a switch, it
442 -- raises Invalid_Parameter, and sets Full_Switch to return the invalid
445 -- Note: in case of ambiguity, e.g. switches a ab abc, then the longest
446 -- matching switch is returned.
448 -- Arbitrary characters are allowed for switches, although it is
449 -- strongly recommended to use only letters and digits for portability
452 -- When Concatenate is False, individual switches need to be separated by
456 -- Getopt ("a b", Concatenate => False)
457 -- If the command line is '-ab', exception Invalid_Switch will be
458 -- raised and Full_Switch will return "ab".
460 function Get_Argument
461 (Do_Expansion : Boolean := False;
462 Parser : Opt_Parser := Command_Line_Parser) return String;
463 -- Returns the next element on the command line that is not a switch. This
464 -- function should not be called before Getopt has returned ASCII.NUL.
466 -- If Do_Expansion is True, then the parameter on the command line will
467 -- be considered as a filename with wild cards, and will be expanded. The
468 -- matching file names will be returned one at a time. This is useful in
469 -- non-Unix systems for obtaining normal expansion of wild card references.
470 -- When there are no more arguments on the command line, this function
471 -- returns an empty string.
474 (Parser : Opt_Parser := Command_Line_Parser) return String;
475 -- Returns parameter associated with the last switch returned by Getopt.
476 -- If no parameter was associated with the last switch, or no previous call
477 -- has been made to Get_Argument, raises Invalid_Parameter. If the last
478 -- switch was associated with an optional argument and this argument was
479 -- not found on the command line, Parameter returns an empty string.
482 (Parser : Opt_Parser := Command_Line_Parser) return Character;
483 -- The separator that was between the switch and its parameter. This is
484 -- useful if you want to know exactly what was on the command line. This
485 -- is in general a single character, set to ASCII.NUL if the switch and
486 -- the parameter were concatenated. A space is returned if the switch and
487 -- its argument were in two separate arguments.
489 Invalid_Section : exception;
490 -- Raised when an invalid section is selected by Goto_Section
492 Invalid_Switch : exception;
493 -- Raised when an invalid switch is detected in the command line
495 Invalid_Parameter : exception;
496 -- Raised when a parameter is missing, or an attempt is made to obtain a
497 -- parameter for a switch that does not allow a parameter
499 -----------------------------------------
500 -- Expansion of command line arguments --
501 -----------------------------------------
502 -- These subprograms take care of of expanding globbing patterns on the
503 -- command line. On Unix, such expansion is done by the shell before your
504 -- application is called. But on Windows you must do this expansion
507 type Expansion_Iterator is limited private;
508 -- Type used during expansion of file names
510 procedure Start_Expansion
511 (Iterator : out Expansion_Iterator;
513 Directory : String := "";
514 Basic_Regexp : Boolean := True);
515 -- Initialize a wild card expansion. The next calls to Expansion will
516 -- return the next file name in Directory which match Pattern (Pattern
517 -- is a regular expression, using only the Unix shell and DOS syntax if
518 -- Basic_Regexp is True). When Directory is an empty string, the current
519 -- directory is searched.
521 -- Pattern may contain directory separators (as in "src/*/*.ada").
522 -- Subdirectories of Directory will also be searched, up to one
523 -- hundred levels deep.
525 -- When Start_Expansion has been called, function Expansion should
526 -- be called repeatedly until it returns an empty string, before
527 -- Start_Expansion can be called again with the same Expansion_Iterator
530 function Expansion (Iterator : Expansion_Iterator) return String;
531 -- Returns the next file in the directory matching the parameters given
532 -- to Start_Expansion and updates Iterator to point to the next entry.
533 -- Returns an empty string when there are no more files.
535 -- If Expansion is called again after an empty string has been returned,
536 -- then the exception GNAT.Directory_Operations.Directory_Error is raised.
542 -- The following subprograms are used to manipulate a command line
543 -- represented as a string (for instance "-g -O2"), as well as parsing
544 -- the switches from such a string. They provide high-level configurations
545 -- to define aliases (a switch is equivalent to one or more other switches)
546 -- or grouping of switches ("-gnatyac" is equivalent to "-gnatya" and
549 -- See the top of this file for examples on how to use these subprograms
551 type Command_Line_Configuration is private;
553 procedure Define_Section
554 (Config : in out Command_Line_Configuration;
556 -- Indicates a new switch section. All switches belonging to the same
557 -- section are ordered together, preceded by the section. They are placed
558 -- at the end of the command line (as in "gnatmake somefile.adb -cargs -g")
560 -- The section name should not include the leading '-'. So for instance in
561 -- the case of gnatmake we would use:
563 -- Define_Section (Config, "cargs");
564 -- Define_Section (Config, "bargs");
566 procedure Define_Alias
567 (Config : in out Command_Line_Configuration;
570 Section : String := "");
571 -- Indicates that whenever Switch appears on the command line, it should
572 -- be expanded as Expanded. For instance, for the GNAT compiler switches,
573 -- we would define "-gnatwa" as an alias for "-gnatwcfijkmopruvz", ie some
574 -- default warnings to be activated.
576 -- This expansion is only done within the specified section, which must
577 -- have been defined first through a call to [Define_Section].
579 procedure Define_Prefix
580 (Config : in out Command_Line_Configuration;
582 -- Indicates that all switches starting with the given prefix should be
583 -- grouped. For instance, for the GNAT compiler we would define "-gnatw" as
584 -- a prefix, so that "-gnatwu -gnatwv" can be grouped into "-gnatwuv" It is
585 -- assumed that the remainder of the switch ("uv") is a set of characters
586 -- whose order is irrelevant. In fact, this package will sort them
589 procedure Define_Switch
590 (Config : in out Command_Line_Configuration;
591 Switch : String := "";
592 Long_Switch : String := "";
594 Section : String := "");
595 -- Indicates a new switch. The format of this switch follows the getopt
596 -- format (trailing ':', '?', etc for defining a switch with parameters).
598 -- Switch should also start with the leading '-' (or any other characters).
599 -- They should all start with the same character, though. If this
600 -- character is not '-', you will need to call Initialize_Option_Scan to
601 -- set the proper character for the parser.
603 -- The switches defined in the command_line_configuration object are used
604 -- when ungrouping switches with more that one character after the prefix.
606 -- Switch and Long_Switch (when specified) are aliases and can be used
607 -- interchangeably. There is no check that they both take an argument or
608 -- both take no argument.
609 -- Switch can be set to "*" to indicate that any switch is supported (in
610 -- which case Getopt will return '*', see its documentation).
612 -- Help is used by the Display_Help procedure to describe the supported
615 -- In_Section indicates in which section the switch is valid (you need to
616 -- first define the section through a call to Define_Section).
618 procedure Define_Switch
619 (Config : in out Command_Line_Configuration;
620 Output : access Boolean;
621 Switch : String := "";
622 Long_Switch : String := "";
624 Section : String := "";
625 Value : Boolean := True);
626 -- See Define_Switch for a description of the parameters.
627 -- When the switch is found on the command line, Getopt will set
628 -- Output.all to Value.
629 -- Output is always initially set to "not Value", so that if the switch is
630 -- not found on the command line, Output still has a valid value.
631 -- The switch must not take any parameter.
632 -- Output must exist at least as long as Config, otherwise erroneous memory
633 -- access may happen.
635 procedure Define_Switch
636 (Config : in out Command_Line_Configuration;
637 Output : access Integer;
638 Switch : String := "";
639 Long_Switch : String := "";
641 Section : String := "";
642 Initial : Integer := 0;
643 Default : Integer := 1);
644 -- See Define_Switch for a description of the parameters.
645 -- When the switch is found on the command line, Getopt will set
646 -- Output.all to the value of the switch's parameter. If the parameter is
647 -- not an integer, Invalid_Parameter is raised.
648 -- Output is always initialized to Initial. If the switch has an optional
649 -- argument which isn't specified by the user, then Output will be set to
652 procedure Define_Switch
653 (Config : in out Command_Line_Configuration;
654 Output : access GNAT.Strings.String_Access;
655 Switch : String := "";
656 Long_Switch : String := "";
658 Section : String := "");
659 -- Set Output to the value of the switch's parameter when the switch is
660 -- found on the command line.
661 -- Output is always initialized to the empty string.
664 (Config : in out Command_Line_Configuration;
665 Usage : String := "[switches] [arguments]";
666 Help : String := "");
667 -- Defines the general format of the call to the application, and a short
668 -- help text. These are both displayed by Display_Help
670 procedure Display_Help (Config : Command_Line_Configuration);
671 -- Display the help for the tool (ie its usage, and its supported switches)
673 function Get_Switches
674 (Config : Command_Line_Configuration;
675 Switch_Char : Character := '-';
676 Section : String := "") return String;
677 -- Get the switches list as expected by Getopt, for a specific section of
678 -- the command line. This list is built using all switches defined
679 -- previously via Define_Switch above.
681 function Section_Delimiters
682 (Config : Command_Line_Configuration) return String;
683 -- Return a string suitable for use in Initialize_Option_Scan
685 procedure Free (Config : in out Command_Line_Configuration);
686 -- Free the memory used by Config
688 type Switch_Handler is access procedure
692 -- Called when a switch is found on the command line.
693 -- [Switch] includes any leading '-' that was specified in Define_Switch.
694 -- This is slightly different from the functional version of Getopt above,
695 -- for which Full_Switch omits the first leading '-'.
697 Exit_From_Command_Line : exception;
698 -- Emitted when the program should exit.
699 -- This is called when Getopt below has seen -h, --help or an invalid
703 (Config : Command_Line_Configuration;
704 Callback : Switch_Handler := null;
705 Parser : Opt_Parser := Command_Line_Parser);
706 -- Similar to the standard Getopt function.
707 -- For each switch found on the command line, this calls Callback.
709 -- The list of valid switches are the ones from the configuration. The
710 -- switches that were declared through Define_Switch with an Output
711 -- parameter are never returned (and result in a modification of the Output
712 -- variable). This function will in fact never call [Callback] if all
713 -- switches were handled automatically and there is nothing left to do.
715 -- This procedure automatically adds -h and --help to the valid switches,
716 -- to display the help message and raises Exit_From_Command_Line.
717 -- If an invalid switch is specified on the command line, this procedure
718 -- will display an error message and raises Invalid_Switch again.
720 -- This function automatically expands switches:
721 -- * If Define_Prefix was called (for instance "-gnaty") and the user
722 -- specifies "-gnatycb" on the command line, then Getopt returns
723 -- "-gnatyc" and "-gnatyb" separately.
724 -- * If Define_Alias was called (for instance "-gnatya = -gnatycb") then
725 -- the latter is returned (in this case it also expands -gnaty as per
727 -- The goal is to make handling as easy as possible by leaving as much
728 -- work as possible to this package.
730 -- As opposed to the standard Getopt, this one will analyze all sections
731 -- as defined by Define_Section, and automatically jump from one section to
734 ------------------------------
735 -- Generating command lines --
736 ------------------------------
738 -- Once the command line configuration has been created, you can build your
739 -- own command line. This will be done in general because you need to spawn
740 -- external tools from your application.
742 -- Although it could be done by concatenating strings, the following
743 -- subprograms will properly take care of grouping switches when possible,
744 -- so as to keep the command line as short as possible. They also provide a
745 -- way to remove a switch from an existing command line.
749 -- Config : Command_Line_Configuration;
750 -- Line : Command_Line;
751 -- Args : Argument_List_Access;
753 -- Define_Switch (Config, "-gnatyc");
754 -- Define_Switch (Config, ...); -- for all valid switches
755 -- Define_Prefix (Config, "-gnaty");
757 -- Set_Configuration (Line, Config);
758 -- Add_Switch (Line, "-O2");
759 -- Add_Switch (Line, "-gnatyc");
760 -- Add_Switch (Line, "-gnatyd");
762 -- Build (Line, Args);
763 -- -- Args is now ["-O2", "-gnatycd"]
766 type Command_Line is private;
768 procedure Set_Configuration
769 (Cmd : in out Command_Line;
770 Config : Command_Line_Configuration);
771 function Get_Configuration
772 (Cmd : Command_Line) return Command_Line_Configuration;
773 -- Set or retrieve the configuration used for that command line
775 procedure Set_Command_Line
776 (Cmd : in out Command_Line;
778 Getopt_Description : String := "";
779 Switch_Char : Character := '-');
780 -- Set the new content of the command line, by replacing the current
781 -- version with Switches.
783 -- The parsing of Switches is done through calls to Getopt, by passing
784 -- Getopt_Description as an argument. (A "*" is automatically prepended so
785 -- that all switches and command line arguments are accepted).
787 -- To properly handle switches that take parameters, you should document
788 -- them in Getopt_Description. Otherwise, the switch and its parameter will
789 -- be recorded as two separate command line arguments as returned by a
790 -- Command_Line_Iterator (which might be fine depending on your
793 -- If the command line has sections (such as -bargs -cargs), then they
794 -- should be listed in the Sections parameter (as "-bargs -cargs").
796 -- This function can be used to reset Cmd by passing an empty string.
799 (Cmd : in out Command_Line;
801 Parameter : String := "";
802 Separator : Character := ' ';
803 Section : String := "";
804 Add_Before : Boolean := False);
805 -- Add a new switch to the command line, and combine/group it with existing
806 -- switches if possible. Nothing is done if the switch already exists with
807 -- the same parameter.
809 -- If the Switch takes a parameter, the latter should be specified
810 -- separately, so that the association between the two is always correctly
811 -- recognized even if the order of switches on the command line changes.
812 -- For instance, you should pass "--check=full" as ("--check", "full") so
813 -- that Remove_Switch below can simply take "--check" in parameter. That
814 -- will automatically remove "full" as well. The value of the parameter is
815 -- never modified by this package.
817 -- On the other hand, you could decide to simply pass "--check=full" as
818 -- the Switch above, and then pass no parameter. This means that you need
819 -- to pass "--check=full" to Remove_Switch as well.
821 -- A Switch with a parameter will never be grouped with another switch to
822 -- avoid ambiguities as to what the parameter applies to.
824 -- If the switch is part of a section, then it should be specified so that
825 -- the switch is correctly placed in the command line, and the section
826 -- added if not already present. For example, to add the -g switch into the
827 -- -cargs section, you need to call (Cmd, "-g", Section => "-cargs").
829 -- [Separator] is ignored, and kept for backward compatibility only.
830 -- ??? It might be removed in future versions.
832 -- Invalid_Section is raised if Section was not defined in the
833 -- configuration of the command line.
835 -- Add_Before allows insertion of the switch at the beginning of the
839 (Cmd : in out Command_Line;
841 Parameter : String := "";
842 Separator : Character := ' ';
843 Section : String := "";
844 Add_Before : Boolean := False;
845 Success : out Boolean);
846 -- Same as above, returning the status of the operation
848 procedure Remove_Switch
849 (Cmd : in out Command_Line;
851 Remove_All : Boolean := False;
852 Has_Parameter : Boolean := False;
853 Section : String := "");
854 -- Remove Switch from the command line, and ungroup existing switches if
857 -- The actual parameter to the switches are ignored. If for instance
858 -- you are removing "-foo", then "-foo param1" and "-foo param2" can
861 -- If Remove_All is True, then all matching switches are removed, otherwise
862 -- only the first matching one is removed.
864 -- If Has_Parameter is set to True, then only switches having a parameter
867 -- If the switch belongs to a section, then this section should be
868 -- specified: Remove_Switch (Cmd_Line, "-g", Section => "-cargs") called
869 -- on the command line "-g -cargs -g" will result in "-g", while if
870 -- called with (Cmd_Line, "-g") this will result in "-cargs -g".
871 -- If Remove_All is set, then both "-g" will be removed.
873 procedure Remove_Switch
874 (Cmd : in out Command_Line;
876 Remove_All : Boolean := False;
877 Has_Parameter : Boolean := False;
878 Section : String := "";
879 Success : out Boolean);
880 -- Same as above, reporting the success of the operation (Success is False
881 -- if no switch was removed).
883 procedure Remove_Switch
884 (Cmd : in out Command_Line;
887 Section : String := "");
888 -- Remove a switch with a specific parameter. If Parameter is the empty
889 -- string, then only a switch with no parameter will be removed.
891 procedure Free (Cmd : in out Command_Line);
892 -- Free the memory used by Cmd
897 -- When a command line was created with the above, you can then iterate
898 -- over its contents using the following iterator.
900 type Command_Line_Iterator is private;
903 (Cmd : in out Command_Line;
904 Iter : in out Command_Line_Iterator;
905 Expanded : Boolean := False);
906 -- Start iterating over the command line arguments. If Expanded is true,
907 -- then the arguments are not grouped and no alias is used. For instance,
908 -- "-gnatwv" and "-gnatwu" would be returned instead of "-gnatwuv".
910 -- The iterator becomes invalid if the command line is changed through a
911 -- call to Add_Switch, Remove_Switch or Set_Command_Line.
913 function Current_Switch (Iter : Command_Line_Iterator) return String;
914 function Is_New_Section (Iter : Command_Line_Iterator) return Boolean;
915 function Current_Section (Iter : Command_Line_Iterator) return String;
916 function Current_Separator (Iter : Command_Line_Iterator) return String;
917 function Current_Parameter (Iter : Command_Line_Iterator) return String;
918 -- Return the current switch and its parameter (or the empty string if
919 -- there is no parameter or the switch was added through Add_Switch
920 -- without specifying the parameter.
922 -- Separator is the string that goes between the switch and its separator.
923 -- It could be the empty string if they should be concatenated, or a space
924 -- for instance. When printing, you should not add any other character.
926 function Has_More (Iter : Command_Line_Iterator) return Boolean;
927 -- Return True if there are more switches to be returned
929 procedure Next (Iter : in out Command_Line_Iterator);
930 -- Move to the next switch
933 (Line : in out Command_Line;
934 Args : out GNAT.OS_Lib.Argument_List_Access;
935 Expanded : Boolean := False;
936 Switch_Char : Character := '-');
937 -- This is a wrapper using the Command_Line_Iterator. It provides a simple
938 -- way to get all switches (grouped as much as possible), and possibly
939 -- create an Opt_Parser.
941 -- Args must be freed by the caller.
942 -- Expanded has the same meaning as in Start.
946 Max_Depth : constant := 100;
947 -- Maximum depth of subdirectories
949 Max_Path_Length : constant := 1024;
950 -- Maximum length of relative path
952 type Depth is range 1 .. Max_Depth;
955 Name_Last : Natural := 0;
956 Dir : GNAT.Directory_Operations.Dir_Type;
959 type Level_Array is array (Depth) of Level;
961 type Section_Number is new Natural range 0 .. 65534;
962 for Section_Number'Size use 16;
964 type Parameter_Type is record
971 type Is_Switch_Type is array (Natural range <>) of Boolean;
972 pragma Pack (Is_Switch_Type);
974 type Section_Type is array (Natural range <>) of Section_Number;
975 pragma Pack (Section_Type);
977 type Expansion_Iterator is limited record
978 Start : Positive := 1;
979 -- Position of the first character of the relative path to check against
982 Dir_Name : String (1 .. Max_Path_Length);
984 Current_Depth : Depth := 1;
986 Levels : Level_Array;
988 Regexp : GNAT.Regexp.Regexp;
989 -- Regular expression built with the pattern
991 Maximum_Depth : Depth := 1;
992 -- The maximum depth of directories, reflecting the number of directory
993 -- separators in the pattern.
996 type Opt_Parser_Data (Arg_Count : Natural) is record
997 Arguments : GNAT.OS_Lib.Argument_List_Access;
998 -- null if reading from the command line
1000 The_Parameter : Parameter_Type;
1001 The_Separator : Character;
1002 The_Switch : Parameter_Type;
1003 -- This type and this variable are provided to store the current switch
1006 Is_Switch : Is_Switch_Type (1 .. Arg_Count) := (others => False);
1007 -- Indicates wich arguments on the command line are considered not be
1008 -- switches or parameters to switches (leaving e.g. filenames,...)
1010 Section : Section_Type (1 .. Arg_Count) := (others => 1);
1011 -- Contains the number of the section associated with the current
1012 -- switch. If this number is 0, then it is a section delimiter, which is
1013 -- never returned by GetOpt.
1015 Current_Argument : Natural := 1;
1016 -- Number of the current argument parsed on the command line
1018 Current_Index : Natural := 1;
1019 -- Index in the current argument of the character to be processed
1021 Current_Section : Section_Number := 1;
1023 Expansion_It : aliased Expansion_Iterator;
1024 -- When Get_Argument is expanding a file name, this is the iterator used
1026 In_Expansion : Boolean := False;
1027 -- True if we are expanding a file
1029 Switch_Character : Character := '-';
1030 -- The character at the beginning of the command line arguments,
1031 -- indicating the beginning of a switch.
1033 Stop_At_First : Boolean := False;
1034 -- If it is True then Getopt stops at the first non-switch argument
1037 Command_Line_Parser_Data : aliased Opt_Parser_Data
1038 (Ada.Command_Line.Argument_Count);
1039 -- The internal data used when parsing the command line
1041 type Opt_Parser is access all Opt_Parser_Data;
1042 Command_Line_Parser : constant Opt_Parser :=
1043 Command_Line_Parser_Data'Access;
1045 type Switch_Type is (Switch_Untyped,
1050 type Switch_Definition (Typ : Switch_Type := Switch_Untyped) is record
1051 Switch : GNAT.OS_Lib.String_Access;
1052 Long_Switch : GNAT.OS_Lib.String_Access;
1053 Section : GNAT.OS_Lib.String_Access;
1054 Help : GNAT.OS_Lib.String_Access;
1057 when Switch_Untyped =>
1059 when Switch_Boolean =>
1060 Boolean_Output : access Boolean;
1061 Boolean_Value : Boolean; -- will set Output to that value
1062 when Switch_Integer =>
1063 Integer_Output : access Integer;
1064 Integer_Initial : Integer;
1065 Integer_Default : Integer;
1066 when Switch_String =>
1067 String_Output : access GNAT.Strings.String_Access;
1070 type Switch_Definitions is array (Natural range <>) of Switch_Definition;
1071 type Switch_Definitions_List is access all Switch_Definitions;
1072 -- [Switch] includes the leading '-'
1074 type Alias_Definition is record
1075 Alias : GNAT.OS_Lib.String_Access;
1076 Expansion : GNAT.OS_Lib.String_Access;
1077 Section : GNAT.OS_Lib.String_Access;
1079 type Alias_Definitions is array (Natural range <>) of Alias_Definition;
1080 type Alias_Definitions_List is access all Alias_Definitions;
1082 type Command_Line_Configuration_Record is record
1083 Prefixes : GNAT.OS_Lib.Argument_List_Access;
1084 -- The list of prefixes
1086 Sections : GNAT.OS_Lib.Argument_List_Access;
1087 -- The list of sections
1089 Aliases : Alias_Definitions_List;
1090 Usage : GNAT.OS_Lib.String_Access;
1091 Help : GNAT.OS_Lib.String_Access;
1092 Switches : Switch_Definitions_List;
1093 -- List of expected switches (Used when expanding switch groups)
1095 type Command_Line_Configuration is access Command_Line_Configuration_Record;
1097 type Command_Line is record
1098 Config : Command_Line_Configuration;
1099 Expanded : GNAT.OS_Lib.Argument_List_Access;
1101 Params : GNAT.OS_Lib.Argument_List_Access;
1102 -- Parameter for the corresponding switch in Expanded. The first
1103 -- character is the separator (or ASCII.NUL if there is no separator).
1105 Sections : GNAT.OS_Lib.Argument_List_Access;
1106 -- The list of sections
1108 Coalesce : GNAT.OS_Lib.Argument_List_Access;
1109 Coalesce_Params : GNAT.OS_Lib.Argument_List_Access;
1110 Coalesce_Sections : GNAT.OS_Lib.Argument_List_Access;
1111 -- Cached version of the command line. This is recomputed every time
1112 -- the command line changes. Switches are grouped as much as possible,
1113 -- and aliases are used to reduce the length of the command line. The
1114 -- parameters are not allocated, they point into Params, so they must
1118 type Command_Line_Iterator is record
1119 List : GNAT.OS_Lib.Argument_List_Access;
1120 Sections : GNAT.OS_Lib.Argument_List_Access;
1121 Params : GNAT.OS_Lib.Argument_List_Access;
1125 end GNAT.Command_Line;