command_line.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. // Copyright (c) 2012 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. // This class works with command lines: building and parsing.
  5. // Arguments with prefixes ('--', '-', and on Windows, '/') are switches.
  6. // Switches will precede all other arguments without switch prefixes.
  7. // Switches can optionally have values, delimited by '=', e.g., "-switch=value".
  8. // If a switch is specified multiple times, only the last value is used.
  9. // An argument of "--" will terminate switch parsing during initialization,
  10. // interpreting subsequent tokens as non-switch arguments, regardless of prefix.
  11. // There is a singleton read-only CommandLine that represents the command line
  12. // that the current process was started with. It must be initialized in main().
  13. #ifndef BASE_COMMAND_LINE_H_
  14. #define BASE_COMMAND_LINE_H_
  15. #include <stddef.h>
  16. #include <map>
  17. #include <string>
  18. #include <vector>
  19. #include "base/base_export.h"
  20. #include "base/strings/string16.h"
  21. #include "base/strings/string_piece.h"
  22. #include "build/build_config.h"
  23. namespace base {
  24. class FilePath;
  25. class BASE_EXPORT CommandLine {
  26. public:
  27. #if defined(OS_WIN)
  28. // The native command line string type.
  29. using StringType = std::wstring;
  30. #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
  31. using StringType = std::string;
  32. #endif
  33. using StringPieceType = base::BasicStringPiece<StringType>;
  34. using CharType = StringType::value_type;
  35. using StringVector = std::vector<StringType>;
  36. using SwitchMap = std::map<std::string, StringType, std::less<>>;
  37. // A constructor for CommandLines that only carry switches and arguments.
  38. enum NoProgram { NO_PROGRAM };
  39. explicit CommandLine(NoProgram no_program);
  40. // Construct a new command line with |program| as argv[0].
  41. explicit CommandLine(const FilePath& program);
  42. // Construct a new command line from an argument list.
  43. CommandLine(int argc, const CharType* const* argv);
  44. explicit CommandLine(const StringVector& argv);
  45. CommandLine(const CommandLine& other);
  46. CommandLine& operator=(const CommandLine& other);
  47. ~CommandLine();
  48. #if defined(OS_WIN)
  49. // By default this class will treat command-line arguments beginning with
  50. // slashes as switches on Windows, but not other platforms.
  51. //
  52. // If this behavior is inappropriate for your application, you can call this
  53. // function BEFORE initializing the current process' global command line
  54. // object and the behavior will be the same as Posix systems (only hyphens
  55. // begin switches, everything else will be an arg).
  56. static void set_slash_is_not_a_switch();
  57. // Normally when the CommandLine singleton is initialized it gets the command
  58. // line via the GetCommandLineW API and then uses the shell32 API
  59. // CommandLineToArgvW to parse the command line and convert it back to
  60. // argc and argv. Tests who don't want this dependency on shell32 and need
  61. // to honor the arguments passed in should use this function.
  62. static void InitUsingArgvForTesting(int argc, const char* const* argv);
  63. #endif
  64. // Initialize the current process CommandLine singleton. On Windows, ignores
  65. // its arguments (we instead parse GetCommandLineW() directly) because we
  66. // don't trust the CRT's parsing of the command line, but it still must be
  67. // called to set up the command line. Returns false if initialization has
  68. // already occurred, and true otherwise. Only the caller receiving a 'true'
  69. // return value should take responsibility for calling Reset.
  70. static bool Init(int argc, const char* const* argv);
  71. // Destroys the current process CommandLine singleton. This is necessary if
  72. // you want to reset the base library to its initial state (for example, in an
  73. // outer library that needs to be able to terminate, and be re-initialized).
  74. // If Init is called only once, as in main(), Reset() is not necessary.
  75. // Do not call this in tests. Use base::test::ScopedCommandLine instead.
  76. static void Reset();
  77. // Get the singleton CommandLine representing the current process's
  78. // command line. Note: returned value is mutable, but not thread safe;
  79. // only mutate if you know what you're doing!
  80. static CommandLine* ForCurrentProcess();
  81. // Returns true if the CommandLine has been initialized for the given process.
  82. static bool InitializedForCurrentProcess();
  83. #if defined(OS_WIN)
  84. static CommandLine FromString(StringPieceType command_line);
  85. #endif
  86. // Initialize from an argv vector.
  87. void InitFromArgv(int argc, const CharType* const* argv);
  88. void InitFromArgv(const StringVector& argv);
  89. // Constructs and returns the represented command line string.
  90. // CAUTION! This should be avoided on POSIX because quoting behavior is
  91. // unclear.
  92. // CAUTION! If writing a command line to the Windows registry, use
  93. // GetCommandLineStringForShell() instead.
  94. StringType GetCommandLineString() const;
  95. #if defined(OS_WIN)
  96. // Returns the command-line string in the proper format for the Windows shell,
  97. // ending with the argument placeholder "--single-argument %1". The single-
  98. // argument switch prevents unexpected parsing of arguments from other
  99. // software that cannot be trusted to escape double quotes when substituting
  100. // into a placeholder (e.g., "%1" placeholders populated by the Windows
  101. // shell).
  102. // NOTE: this must be used to generate the command-line string for the shell
  103. // even if this command line was parsed from a string with the proper syntax,
  104. // because the --single-argument switch is not preserved during parsing.
  105. StringType GetCommandLineStringForShell() const;
  106. #endif
  107. // Constructs and returns the represented arguments string.
  108. // CAUTION! This should be avoided on POSIX because quoting behavior is
  109. // unclear.
  110. StringType GetArgumentsString() const;
  111. // Returns the original command line string as a vector of strings.
  112. const StringVector& argv() const { return argv_; }
  113. // Get and Set the program part of the command line string (the first item).
  114. FilePath GetProgram() const;
  115. void SetProgram(const FilePath& program);
  116. // Returns true if this command line contains the given switch.
  117. // Switch names must be lowercase.
  118. // The second override provides an optimized version to avoid inlining codegen
  119. // at every callsite to find the length of the constant and construct a
  120. // StringPiece.
  121. bool HasSwitch(const StringPiece& switch_string) const;
  122. bool HasSwitch(const char switch_constant[]) const;
  123. // Returns the value associated with the given switch. If the switch has no
  124. // value or isn't present, this method returns the empty string.
  125. // Switch names must be lowercase.
  126. std::string GetSwitchValueASCII(const StringPiece& switch_string) const;
  127. FilePath GetSwitchValuePath(const StringPiece& switch_string) const;
  128. StringType GetSwitchValueNative(const StringPiece& switch_string) const;
  129. // Get a copy of all switches, along with their values.
  130. const SwitchMap& GetSwitches() const { return switches_; }
  131. // Append a switch [with optional value] to the command line.
  132. // Note: Switches will precede arguments regardless of appending order.
  133. void AppendSwitch(const std::string& switch_string);
  134. void AppendSwitchPath(const std::string& switch_string,
  135. const FilePath& path);
  136. void AppendSwitchNative(const std::string& switch_string,
  137. StringPieceType value);
  138. void AppendSwitchASCII(const std::string& switch_string,
  139. const std::string& value);
  140. // Removes the switch that matches |switch_key_without_prefix|, regardless of
  141. // prefix and value. If no such switch is present, this has no effect.
  142. void RemoveSwitch(const base::StringPiece switch_key_without_prefix);
  143. // Copy a set of switches (and any values) from another command line.
  144. // Commonly used when launching a subprocess.
  145. void CopySwitchesFrom(const CommandLine& source,
  146. const char* const switches[],
  147. size_t count);
  148. // Get the remaining arguments to the command.
  149. StringVector GetArgs() const;
  150. // Append an argument to the command line. Note that the argument is quoted
  151. // properly such that it is interpreted as one argument to the target command.
  152. // AppendArg is primarily for ASCII; non-ASCII input is interpreted as UTF-8.
  153. // Note: Switches will precede arguments regardless of appending order.
  154. void AppendArg(const std::string& value);
  155. void AppendArgPath(const FilePath& value);
  156. void AppendArgNative(const StringType& value);
  157. // Append the switches and arguments from another command line to this one.
  158. // If |include_program| is true, include |other|'s program as well.
  159. void AppendArguments(const CommandLine& other, bool include_program);
  160. // Insert a command before the current command.
  161. // Common for debuggers, like "gdb --args".
  162. void PrependWrapper(const StringType& wrapper);
  163. #if defined(OS_WIN)
  164. // Initialize by parsing the given command line string.
  165. // The program name is assumed to be the first item in the string.
  166. void ParseFromString(StringPieceType command_line);
  167. #endif
  168. private:
  169. // Disallow default constructor; a program name must be explicitly specified.
  170. CommandLine() = delete;
  171. // Allow the copy constructor. A common pattern is to copy of the current
  172. // process's command line and then add some flags to it. For example:
  173. // CommandLine cl(*CommandLine::ForCurrentProcess());
  174. // cl.AppendSwitch(...);
  175. // Append switches and arguments, keeping switches before arguments.
  176. void AppendSwitchesAndArguments(const StringVector& argv);
  177. #if defined(OS_WIN)
  178. // Initializes by parsing |raw_command_line_string_|, treating everything
  179. // after |single_arg_switch_string| + <a single character> as the command
  180. // line's single argument, and dropping any arguments previously parsed. The
  181. // command line must contain |single_arg_switch_string|, and the argument, if
  182. // present, must be separated from |single_arg_switch_string| by one
  183. // character.
  184. // NOTE: the single-argument switch is not preserved after parsing;
  185. // GetCommandLineStringForShell() must be used to reproduce the original
  186. // command-line string with single-argument switch.
  187. void ParseAsSingleArgument(const StringType& single_arg_switch_string);
  188. // The string returned by GetCommandLineW(), to be parsed via
  189. // ParseFromString(). Empty if this command line was not parsed from a string,
  190. // or if ParseFromString() has finished executing.
  191. StringPieceType raw_command_line_string_;
  192. #endif
  193. // The singleton CommandLine representing the current process's command line.
  194. static CommandLine* current_process_commandline_;
  195. // The argv array: { program, [(--|-|/)switch[=value]]*, [--], [argument]* }
  196. StringVector argv_;
  197. // Parsed-out switch keys and values.
  198. SwitchMap switches_;
  199. // The index after the program and switches, any arguments start here.
  200. size_t begin_args_;
  201. };
  202. } // namespace base
  203. #endif // BASE_COMMAND_LINE_H_