Home | History | Annotate | Download | only in base
      1 // Copyright (c) 2011 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 
      5 // This class works with command lines: building and parsing.
      6 // Switches can optionally have a value attached using an equals sign, as in
      7 // "-switch=value". Arguments that aren't prefixed with a switch prefix are
      8 // saved as extra arguments. An argument of "--" will terminate switch parsing,
      9 // causing everything after to be considered as extra arguments.
     10 
     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 
     14 #ifndef BASE_COMMAND_LINE_H_
     15 #define BASE_COMMAND_LINE_H_
     16 #pragma once
     17 
     18 #include <stddef.h>
     19 #include <map>
     20 #include <string>
     21 #include <vector>
     22 
     23 #include "base/base_api.h"
     24 #include "build/build_config.h"
     25 
     26 class FilePath;
     27 
     28 class BASE_API CommandLine {
     29  public:
     30 #if defined(OS_WIN)
     31   // The native command line string type.
     32   typedef std::wstring StringType;
     33 #elif defined(OS_POSIX)
     34   typedef std::string StringType;
     35 #endif
     36 
     37   typedef std::vector<StringType> StringVector;
     38   // The type of map for parsed-out switch key and values.
     39   typedef std::map<std::string, StringType> SwitchMap;
     40 
     41   // A constructor for CommandLines that only carry switches and arguments.
     42   enum NoProgram { NO_PROGRAM };
     43   explicit CommandLine(NoProgram no_program);
     44 
     45   // Construct a new command line with |program| as argv[0].
     46   explicit CommandLine(const FilePath& program);
     47 
     48 #if defined(OS_POSIX)
     49   CommandLine(int argc, const char* const* argv);
     50   explicit CommandLine(const StringVector& argv);
     51 #endif
     52 
     53   ~CommandLine();
     54 
     55   // Initialize the current process CommandLine singleton. On Windows, ignores
     56   // its arguments (we instead parse GetCommandLineW() directly) because we
     57   // don't trust the CRT's parsing of the command line, but it still must be
     58   // called to set up the command line.
     59   static void Init(int argc, const char* const* argv);
     60 
     61   // Destroys the current process CommandLine singleton. This is necessary if
     62   // you want to reset the base library to its initial state (for example, in an
     63   // outer library that needs to be able to terminate, and be re-initialized).
     64   // If Init is called only once, as in main(), Reset() is not necessary.
     65   static void Reset();
     66 
     67   // Get the singleton CommandLine representing the current process's
     68   // command line. Note: returned value is mutable, but not thread safe;
     69   // only mutate if you know what you're doing!
     70   static CommandLine* ForCurrentProcess();
     71 
     72 #if defined(OS_WIN)
     73   static CommandLine FromString(const std::wstring& command_line);
     74 #endif
     75 
     76 #if defined(OS_POSIX)
     77   // Initialize from an argv vector.
     78   void InitFromArgv(int argc, const char* const* argv);
     79   void InitFromArgv(const StringVector& argv);
     80 #endif
     81 
     82   // Returns the represented command line string.
     83   // CAUTION! This should be avoided because quoting behavior is unclear.
     84   StringType command_line_string() const;
     85 
     86 #if defined(OS_POSIX)
     87   // Returns the original command line string as a vector of strings.
     88   const StringVector& argv() const { return argv_; }
     89 #endif
     90 
     91   // Returns the program part of the command line string (the first item).
     92   FilePath GetProgram() const;
     93 
     94   // Returns true if this command line contains the given switch.
     95   // (Switch names are case-insensitive).
     96   bool HasSwitch(const std::string& switch_string) const;
     97 
     98   // Returns the value associated with the given switch. If the switch has no
     99   // value or isn't present, this method returns the empty string.
    100   std::string GetSwitchValueASCII(const std::string& switch_string) const;
    101   FilePath GetSwitchValuePath(const std::string& switch_string) const;
    102   StringType GetSwitchValueNative(const std::string& switch_string) const;
    103 
    104   // Get the number of switches in this process.
    105   // TODO(msw): Remove unnecessary API.
    106   size_t GetSwitchCount() const;
    107 
    108   // Get a copy of all switches, along with their values.
    109   const SwitchMap& GetSwitches() const { return switches_; }
    110 
    111   // Append a switch [with optional value] to the command line.
    112   // CAUTION! Appending a switch after the "--" switch terminator is futile!
    113   void AppendSwitch(const std::string& switch_string);
    114   void AppendSwitchPath(const std::string& switch_string, const FilePath& path);
    115   void AppendSwitchNative(const std::string& switch_string,
    116                           const StringType& value);
    117   void AppendSwitchASCII(const std::string& switch_string,
    118                          const std::string& value);
    119   void AppendSwitches(const CommandLine& other);
    120 
    121   // Copy a set of switches (and any values) from another command line.
    122   // Commonly used when launching a subprocess.
    123   void CopySwitchesFrom(const CommandLine& source, const char* const switches[],
    124                         size_t count);
    125 
    126   // Get the remaining arguments to the command.
    127   const StringVector& args() const { return args_; }
    128 
    129   // Append an argument to the command line. Note that the argument is quoted
    130   // properly such that it is interpreted as one argument to the target command.
    131   // AppendArg is primarily for ASCII; non-ASCII input is interpreted as UTF-8.
    132   void AppendArg(const std::string& value);
    133   void AppendArgPath(const FilePath& value);
    134   void AppendArgNative(const StringType& value);
    135   void AppendArgs(const CommandLine& other);
    136 
    137   // Append the arguments from another command line to this one.
    138   // If |include_program| is true, include |other|'s program as well.
    139   void AppendArguments(const CommandLine& other,
    140                        bool include_program);
    141 
    142   // Insert a command before the current command.
    143   // Common for debuggers, like "valgrind" or "gdb --args".
    144   void PrependWrapper(const StringType& wrapper);
    145 
    146 #if defined(OS_WIN)
    147   // Initialize by parsing the given command line string.
    148   // The program name is assumed to be the first item in the string.
    149   void ParseFromString(const std::wstring& command_line);
    150 #endif
    151 
    152  private:
    153   // Disallow public default construction; a program name must be specified.
    154   CommandLine();
    155 
    156   // The singleton CommandLine representing the current process's command line.
    157   static CommandLine* current_process_commandline_;
    158 
    159   // We store a platform-native version of the command line, used when building
    160   // up a new command line to be executed. This ifdef delimits that code.
    161 #if defined(OS_WIN)
    162   // The quoted, space-separated command line string.
    163   StringType command_line_string_;
    164   // The name of the program.
    165   StringType program_;
    166 #elif defined(OS_POSIX)
    167   // The argv array, with the program name in argv_[0].
    168   StringVector argv_;
    169 #endif
    170 
    171   // Parsed-out switch keys and values.
    172   SwitchMap switches_;
    173 
    174   // Non-switch command line arguments.
    175   StringVector args_;
    176 
    177   // Allow the copy constructor. A common pattern is to copy the current
    178   // process's command line and then add some flags to it. For example:
    179   //   CommandLine cl(*CommandLine::ForCurrentProcess());
    180   //   cl.AppendSwitch(...);
    181 };
    182 
    183 #endif  // BASE_COMMAND_LINE_H_
    184