1// Copyright (c) 2013 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#include "tools/gn/escape.h"
6
7#include "base/containers/stack_container.h"
8
9namespace {
10
11template<typename DestString>
12void EscapeStringToString(const base::StringPiece& str,
13                          const EscapeOptions& options,
14                          DestString* dest) {
15  bool used_quotes = false;
16
17  for (size_t i = 0; i < str.size(); i++) {
18    if (str[i] == '$' && options.mode == ESCAPE_NINJA) {
19      // Escape dollars signs since ninja treats these specially.
20      dest->push_back('$');
21      dest->push_back('$');
22    } else if (str[i] == '"' && options.mode == ESCAPE_SHELL) {
23      // Escape quotes with backslashes for the command-line (Ninja doesn't
24      // care).
25      dest->push_back('\\');
26      dest->push_back('"');
27    } else if (str[i] == ' ') {
28      if (options.mode == ESCAPE_NINJA) {
29        // For ninja just escape spaces with $.
30        dest->push_back('$');
31      } else if (options.mode == ESCAPE_SHELL && !options.inhibit_quoting) {
32        // For the shell, quote the whole string.
33        if (!used_quotes) {
34          used_quotes = true;
35          dest->insert(dest->begin(), '"');
36        }
37      }
38      dest->push_back(' ');
39#if defined(OS_WIN)
40    } else if (str[i] == '/' && options.convert_slashes) {
41      // Convert slashes on Windows if requested.
42      dest->push_back('\\');
43#else
44    } else if (str[i] == '\\' && options.mode == ESCAPE_SHELL) {
45      // For non-Windows shell, escape backslashes.
46      dest->push_back('\\');
47      dest->push_back('\\');
48#endif
49    } else {
50      dest->push_back(str[i]);
51    }
52  }
53
54  if (used_quotes)
55    dest->push_back('"');
56}
57
58}  // namespace
59
60std::string EscapeString(const base::StringPiece& str,
61                         const EscapeOptions& options) {
62  std::string result;
63  result.reserve(str.size() + 4);  // Guess we'll add a couple of extra chars.
64  EscapeStringToString(str, options, &result);
65  return result;
66}
67
68void EscapeStringToStream(std::ostream& out,
69                          const base::StringPiece& str,
70                          const EscapeOptions& options) {
71  // Escape to a stack buffer and then write out to the stream.
72  base::StackVector<char, 256> result;
73  result->reserve(str.size() + 4);  // Guess we'll add a couple of extra chars.
74  EscapeStringToString(str, options, &result.container());
75  if (!result->empty())
76    out.write(result->data(), result->size());
77}
78