Record error when CreateDir fails.
[chromium-blink-merge.git] / base / command_line.cc
blob7d137f266cb3e5488be5d9ae7607c35be58e67e7
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.
5 #include "base/command_line.h"
7 #include <algorithm>
8 #include <ostream>
10 #include "base/basictypes.h"
11 #include "base/files/file_path.h"
12 #include "base/logging.h"
13 #include "base/strings/string_split.h"
14 #include "base/strings/string_util.h"
15 #include "base/strings/utf_string_conversions.h"
16 #include "build/build_config.h"
18 #if defined(OS_WIN)
19 #include <windows.h>
20 #include <shellapi.h>
21 #endif
23 using base::FilePath;
25 CommandLine* CommandLine::current_process_commandline_ = NULL;
27 namespace {
28 const CommandLine::CharType kSwitchTerminator[] = FILE_PATH_LITERAL("--");
29 const CommandLine::CharType kSwitchValueSeparator[] = FILE_PATH_LITERAL("=");
30 // Since we use a lazy match, make sure that longer versions (like "--") are
31 // listed before shorter versions (like "-") of similar prefixes.
32 #if defined(OS_WIN)
33 const CommandLine::CharType* const kSwitchPrefixes[] = {L"--", L"-", L"/"};
34 #elif defined(OS_POSIX)
35 // Unixes don't use slash as a switch.
36 const CommandLine::CharType* const kSwitchPrefixes[] = {"--", "-"};
37 #endif
39 size_t GetSwitchPrefixLength(const CommandLine::StringType& string) {
40 for (size_t i = 0; i < arraysize(kSwitchPrefixes); ++i) {
41 CommandLine::StringType prefix(kSwitchPrefixes[i]);
42 if (string.compare(0, prefix.length(), prefix) == 0)
43 return prefix.length();
45 return 0;
48 // Fills in |switch_string| and |switch_value| if |string| is a switch.
49 // This will preserve the input switch prefix in the output |switch_string|.
50 bool IsSwitch(const CommandLine::StringType& string,
51 CommandLine::StringType* switch_string,
52 CommandLine::StringType* switch_value) {
53 switch_string->clear();
54 switch_value->clear();
55 size_t prefix_length = GetSwitchPrefixLength(string);
56 if (prefix_length == 0 || prefix_length == string.length())
57 return false;
59 const size_t equals_position = string.find(kSwitchValueSeparator);
60 *switch_string = string.substr(0, equals_position);
61 if (equals_position != CommandLine::StringType::npos)
62 *switch_value = string.substr(equals_position + 1);
63 return true;
66 // Append switches and arguments, keeping switches before arguments.
67 void AppendSwitchesAndArguments(CommandLine& command_line,
68 const CommandLine::StringVector& argv) {
69 bool parse_switches = true;
70 for (size_t i = 1; i < argv.size(); ++i) {
71 CommandLine::StringType arg = argv[i];
72 TrimWhitespace(arg, TRIM_ALL, &arg);
74 CommandLine::StringType switch_string;
75 CommandLine::StringType switch_value;
76 parse_switches &= (arg != kSwitchTerminator);
77 if (parse_switches && IsSwitch(arg, &switch_string, &switch_value)) {
78 #if defined(OS_WIN)
79 command_line.AppendSwitchNative(WideToASCII(switch_string), switch_value);
80 #elif defined(OS_POSIX)
81 command_line.AppendSwitchNative(switch_string, switch_value);
82 #endif
83 } else {
84 command_line.AppendArgNative(arg);
89 // Lowercase switches for backwards compatiblity *on Windows*.
90 std::string LowerASCIIOnWindows(const std::string& string) {
91 #if defined(OS_WIN)
92 return StringToLowerASCII(string);
93 #elif defined(OS_POSIX)
94 return string;
95 #endif
99 #if defined(OS_WIN)
100 // Quote a string as necessary for CommandLineToArgvW compatiblity *on Windows*.
101 std::wstring QuoteForCommandLineToArgvW(const std::wstring& arg) {
102 // We follow the quoting rules of CommandLineToArgvW.
103 // http://msdn.microsoft.com/en-us/library/17w5ykft.aspx
104 if (arg.find_first_of(L" \\\"") == std::wstring::npos) {
105 // No quoting necessary.
106 return arg;
109 std::wstring out;
110 out.push_back(L'"');
111 for (size_t i = 0; i < arg.size(); ++i) {
112 if (arg[i] == '\\') {
113 // Find the extent of this run of backslashes.
114 size_t start = i, end = start + 1;
115 for (; end < arg.size() && arg[end] == '\\'; ++end)
116 /* empty */;
117 size_t backslash_count = end - start;
119 // Backslashes are escapes only if the run is followed by a double quote.
120 // Since we also will end the string with a double quote, we escape for
121 // either a double quote or the end of the string.
122 if (end == arg.size() || arg[end] == '"') {
123 // To quote, we need to output 2x as many backslashes.
124 backslash_count *= 2;
126 for (size_t j = 0; j < backslash_count; ++j)
127 out.push_back('\\');
129 // Advance i to one before the end to balance i++ in loop.
130 i = end - 1;
131 } else if (arg[i] == '"') {
132 out.push_back('\\');
133 out.push_back('"');
134 } else {
135 out.push_back(arg[i]);
138 out.push_back('"');
140 return out;
142 #endif
144 } // namespace
146 CommandLine::CommandLine(NoProgram no_program)
147 : argv_(1),
148 begin_args_(1) {
151 CommandLine::CommandLine(const FilePath& program)
152 : argv_(1),
153 begin_args_(1) {
154 SetProgram(program);
157 CommandLine::CommandLine(int argc, const CommandLine::CharType* const* argv)
158 : argv_(1),
159 begin_args_(1) {
160 InitFromArgv(argc, argv);
163 CommandLine::CommandLine(const StringVector& argv)
164 : argv_(1),
165 begin_args_(1) {
166 InitFromArgv(argv);
169 CommandLine::~CommandLine() {
172 // static
173 bool CommandLine::Init(int argc, const char* const* argv) {
174 if (current_process_commandline_) {
175 // If this is intentional, Reset() must be called first. If we are using
176 // the shared build mode, we have to share a single object across multiple
177 // shared libraries.
178 return false;
181 current_process_commandline_ = new CommandLine(NO_PROGRAM);
182 #if defined(OS_WIN)
183 current_process_commandline_->ParseFromString(::GetCommandLineW());
184 #elif defined(OS_POSIX)
185 current_process_commandline_->InitFromArgv(argc, argv);
186 #endif
188 return true;
191 // static
192 void CommandLine::Reset() {
193 DCHECK(current_process_commandline_);
194 delete current_process_commandline_;
195 current_process_commandline_ = NULL;
198 // static
199 CommandLine* CommandLine::ForCurrentProcess() {
200 DCHECK(current_process_commandline_);
201 return current_process_commandline_;
204 #if defined(OS_WIN)
205 // static
206 CommandLine CommandLine::FromString(const std::wstring& command_line) {
207 CommandLine cmd(NO_PROGRAM);
208 cmd.ParseFromString(command_line);
209 return cmd;
211 #endif
213 void CommandLine::InitFromArgv(int argc,
214 const CommandLine::CharType* const* argv) {
215 StringVector new_argv;
216 for (int i = 0; i < argc; ++i)
217 new_argv.push_back(argv[i]);
218 InitFromArgv(new_argv);
221 void CommandLine::InitFromArgv(const StringVector& argv) {
222 argv_ = StringVector(1);
223 switches_.clear();
224 begin_args_ = 1;
225 SetProgram(argv.empty() ? FilePath() : FilePath(argv[0]));
226 AppendSwitchesAndArguments(*this, argv);
229 CommandLine::StringType CommandLine::GetCommandLineString() const {
230 StringType string(argv_[0]);
231 #if defined(OS_WIN)
232 string = QuoteForCommandLineToArgvW(string);
233 #endif
234 StringType params(GetArgumentsString());
235 if (!params.empty()) {
236 string.append(StringType(FILE_PATH_LITERAL(" ")));
237 string.append(params);
239 return string;
242 CommandLine::StringType CommandLine::GetArgumentsString() const {
243 StringType params;
244 // Append switches and arguments.
245 bool parse_switches = true;
246 for (size_t i = 1; i < argv_.size(); ++i) {
247 StringType arg = argv_[i];
248 StringType switch_string;
249 StringType switch_value;
250 parse_switches &= arg != kSwitchTerminator;
251 if (i > 1)
252 params.append(StringType(FILE_PATH_LITERAL(" ")));
253 if (parse_switches && IsSwitch(arg, &switch_string, &switch_value)) {
254 params.append(switch_string);
255 if (!switch_value.empty()) {
256 #if defined(OS_WIN)
257 switch_value = QuoteForCommandLineToArgvW(switch_value);
258 #endif
259 params.append(kSwitchValueSeparator + switch_value);
262 else {
263 #if defined(OS_WIN)
264 arg = QuoteForCommandLineToArgvW(arg);
265 #endif
266 params.append(arg);
269 return params;
272 FilePath CommandLine::GetProgram() const {
273 return FilePath(argv_[0]);
276 void CommandLine::SetProgram(const FilePath& program) {
277 TrimWhitespace(program.value(), TRIM_ALL, &argv_[0]);
280 bool CommandLine::HasSwitch(const std::string& switch_string) const {
281 return switches_.find(LowerASCIIOnWindows(switch_string)) != switches_.end();
284 std::string CommandLine::GetSwitchValueASCII(
285 const std::string& switch_string) const {
286 StringType value = GetSwitchValueNative(switch_string);
287 if (!IsStringASCII(value)) {
288 DLOG(WARNING) << "Value of switch (" << switch_string << ") must be ASCII.";
289 return std::string();
291 #if defined(OS_WIN)
292 return WideToASCII(value);
293 #else
294 return value;
295 #endif
298 FilePath CommandLine::GetSwitchValuePath(
299 const std::string& switch_string) const {
300 return FilePath(GetSwitchValueNative(switch_string));
303 CommandLine::StringType CommandLine::GetSwitchValueNative(
304 const std::string& switch_string) const {
305 SwitchMap::const_iterator result = switches_.end();
306 result = switches_.find(LowerASCIIOnWindows(switch_string));
307 return result == switches_.end() ? StringType() : result->second;
310 void CommandLine::AppendSwitch(const std::string& switch_string) {
311 AppendSwitchNative(switch_string, StringType());
314 void CommandLine::AppendSwitchPath(const std::string& switch_string,
315 const FilePath& path) {
316 AppendSwitchNative(switch_string, path.value());
319 void CommandLine::AppendSwitchNative(const std::string& switch_string,
320 const CommandLine::StringType& value) {
321 std::string switch_key(LowerASCIIOnWindows(switch_string));
322 #if defined(OS_WIN)
323 StringType combined_switch_string(ASCIIToWide(switch_key));
324 #elif defined(OS_POSIX)
325 StringType combined_switch_string(switch_string);
326 #endif
327 size_t prefix_length = GetSwitchPrefixLength(combined_switch_string);
328 switches_[switch_key.substr(prefix_length)] = value;
329 // Preserve existing switch prefixes in |argv_|; only append one if necessary.
330 if (prefix_length == 0)
331 combined_switch_string = kSwitchPrefixes[0] + combined_switch_string;
332 if (!value.empty())
333 combined_switch_string += kSwitchValueSeparator + value;
334 // Append the switch and update the switches/arguments divider |begin_args_|.
335 argv_.insert(argv_.begin() + begin_args_++, combined_switch_string);
338 void CommandLine::AppendSwitchASCII(const std::string& switch_string,
339 const std::string& value_string) {
340 #if defined(OS_WIN)
341 AppendSwitchNative(switch_string, ASCIIToWide(value_string));
342 #elif defined(OS_POSIX)
343 AppendSwitchNative(switch_string, value_string);
344 #endif
347 void CommandLine::CopySwitchesFrom(const CommandLine& source,
348 const char* const switches[],
349 size_t count) {
350 for (size_t i = 0; i < count; ++i) {
351 if (source.HasSwitch(switches[i]))
352 AppendSwitchNative(switches[i], source.GetSwitchValueNative(switches[i]));
356 CommandLine::StringVector CommandLine::GetArgs() const {
357 // Gather all arguments after the last switch (may include kSwitchTerminator).
358 StringVector args(argv_.begin() + begin_args_, argv_.end());
359 // Erase only the first kSwitchTerminator (maybe "--" is a legitimate page?)
360 StringVector::iterator switch_terminator =
361 std::find(args.begin(), args.end(), kSwitchTerminator);
362 if (switch_terminator != args.end())
363 args.erase(switch_terminator);
364 return args;
367 void CommandLine::AppendArg(const std::string& value) {
368 #if defined(OS_WIN)
369 DCHECK(IsStringUTF8(value));
370 AppendArgNative(UTF8ToWide(value));
371 #elif defined(OS_POSIX)
372 AppendArgNative(value);
373 #endif
376 void CommandLine::AppendArgPath(const FilePath& path) {
377 AppendArgNative(path.value());
380 void CommandLine::AppendArgNative(const CommandLine::StringType& value) {
381 argv_.push_back(value);
384 void CommandLine::AppendArguments(const CommandLine& other,
385 bool include_program) {
386 if (include_program)
387 SetProgram(other.GetProgram());
388 AppendSwitchesAndArguments(*this, other.argv());
391 void CommandLine::PrependWrapper(const CommandLine::StringType& wrapper) {
392 if (wrapper.empty())
393 return;
394 // The wrapper may have embedded arguments (like "gdb --args"). In this case,
395 // we don't pretend to do anything fancy, we just split on spaces.
396 StringVector wrapper_argv;
397 base::SplitString(wrapper, FILE_PATH_LITERAL(' '), &wrapper_argv);
398 // Prepend the wrapper and update the switches/arguments |begin_args_|.
399 argv_.insert(argv_.begin(), wrapper_argv.begin(), wrapper_argv.end());
400 begin_args_ += wrapper_argv.size();
403 #if defined(OS_WIN)
404 void CommandLine::ParseFromString(const std::wstring& command_line) {
405 std::wstring command_line_string;
406 TrimWhitespace(command_line, TRIM_ALL, &command_line_string);
407 if (command_line_string.empty())
408 return;
410 int num_args = 0;
411 wchar_t** args = NULL;
412 args = ::CommandLineToArgvW(command_line_string.c_str(), &num_args);
414 DPLOG_IF(FATAL, !args) << "CommandLineToArgvW failed on command line: "
415 << command_line;
416 InitFromArgv(num_args, args);
417 LocalFree(args);
419 #endif