2 * Copyright 2016 Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 * `Shell` provides a collection of functions to use with `Subprocess` that make
19 * it easier to safely run processes in a unix shell.
21 * Note: use this rarely and carefully. By default you should use `Subprocess`
22 * with a vector of arguments.
30 #include <folly/Conv.h>
31 #include <folly/Format.h>
32 #include <folly/Range.h>
37 * Quotes an argument to make it suitable for use as shell command arguments.
39 std::string shellQuote(StringPiece argument);
42 * Create argument array for `Subprocess()` for a process running in a
45 * The shell to use is always going to be `/bin/sh`.
47 * The format string should always be a string literal to protect against
48 * shell injections. Arguments will automatically be escaped with `'`.
50 * TODO(dominik): find a way to ensure statically determined format strings.
52 template <typename... Arguments>
53 std::vector<std::string> shellify(
54 const StringPiece format,
55 Arguments&&... arguments) {
56 auto command = sformat(
58 shellQuote(to<std::string>(std::forward<Arguments>(arguments)))...);
59 return {"/bin/sh", "-c", command};