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#ifndef TOOLS_GN_ESCAPE_H_
6#define TOOLS_GN_ESCAPE_H_
7
8#include <iosfwd>
9
10#include "base/strings/string_piece.h"
11
12enum EscapingMode {
13  // No escaping.
14  ESCAPE_NONE,
15
16  // Ninja string escaping.
17  ESCAPE_NINJA,
18
19  // For writing commands to ninja files. This assumes the output is "one
20  // thing" like a filename, so will escape or quote spaces as necessary for
21  // both Ninja and the shell to keep that thing together.
22  ESCAPE_NINJA_COMMAND,
23
24  // For writing preformatted shell commands to Ninja files. This assumes the
25  // output already has the proper quoting and may include special shell
26  // shell characters which we want to pass to the shell (like when writing
27  // tool commands). Only Ninja "$" are escaped.
28  ESCAPE_NINJA_PREFORMATTED_COMMAND,
29};
30
31enum EscapingPlatform {
32  // Do escaping for the current platform.
33  ESCAPE_PLATFORM_CURRENT,
34
35  // Force escaping for the given platform.
36  ESCAPE_PLATFORM_POSIX,
37  ESCAPE_PLATFORM_WIN,
38};
39
40struct EscapeOptions {
41  EscapeOptions()
42      : mode(ESCAPE_NONE),
43        platform(ESCAPE_PLATFORM_CURRENT),
44        inhibit_quoting(false) {
45  }
46
47  EscapingMode mode;
48
49  // Controls how "fork" escaping is done. You will generally want to keep the
50  // default "current" platform.
51  EscapingPlatform platform;
52
53  // When the escaping mode is ESCAPE_SHELL, the escaper will normally put
54  // quotes around things with spaces. If this value is set to true, we'll
55  // disable the quoting feature and just add the spaces.
56  //
57  // This mode is for when quoting is done at some higher-level. Defaults to
58  // false. Note that Windows has strange behavior where the meaning of the
59  // backslashes changes according to if it is followed by a quote. The
60  // escaping rules assume that a double-quote will be appended to the result.
61  bool inhibit_quoting;
62};
63
64// Escapes the given input, returnining the result.
65//
66// If needed_quoting is non-null, whether the string was or should have been
67// (if inhibit_quoting was set) quoted will be written to it. This value should
68// be initialized to false by the caller and will be written to only if it's
69// true (the common use-case is for chaining calls).
70std::string EscapeString(const base::StringPiece& str,
71                         const EscapeOptions& options,
72                         bool* needed_quoting);
73
74// Same as EscapeString but writes the results to the given stream, saving a
75// copy.
76void EscapeStringToStream(std::ostream& out,
77                          const base::StringPiece& str,
78                          const EscapeOptions& options);
79
80#endif  // TOOLS_GN_ESCAPE_H_
81