formatting support for `Subprocess::shellify`
[folly.git] / folly / Shell.h
1 /*
2  * Copyright 2016 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /**
18  * `Shell` provides a collection of functions to use with `Subprocess` that make
19  * it easier to safely run processes in a unix shell.
20  *
21  * Note: use this rarely and carefully. By default you should use `Subprocess`
22  * with a vector of arguments.
23  */
24
25 #pragma once
26
27 #include <string>
28 #include <vector>
29
30 #include <folly/Format.h>
31 #include <folly/Range.h>
32
33 namespace folly {
34
35 /**
36  * Quotes an argument to make it suitable for use as shell command arguments.
37  */
38 std::string shellQuote(StringPiece argument) {
39   std::string quoted = "'";
40   for (auto c : argument) {
41     if (c == '\'') {
42       quoted += "'\\''";
43     } else {
44       quoted += c;
45     }
46   }
47   return quoted + "'";
48 }
49
50 /**
51   * Create argument array for `Subprocess()` for a process running in a
52   * shell.
53   *
54   * The shell to use is taken from the environment variable $SHELL,
55   * or /bin/sh if $SHELL is unset.
56   *
57   * The format string should always be a string literal to protect against
58   * shell injections. Arguments will automatically be escaped with `'`.
59   *
60   * TODO(dominik): find a way to ensure statically determined format strings.
61   */
62 template <typename... Arguments>
63 std::vector<std::string> shellify(
64     const StringPiece format,
65     Arguments&&... arguments) {
66   const char* shell = getenv("SHELL");
67   if (!shell) {
68     shell = "/bin/sh";
69   }
70   auto command = sformat(
71       format,
72       shellQuote(to<std::string>(std::forward<Arguments>(arguments)))...);
73   return {shell, "-c", command};
74 }
75
76 } // folly