1# Copyright 2017 The Bazel Authors. All rights reserved. 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# http://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14 15"""Skylib module containing shell utility functions.""" 16 17def _array_literal(iterable): 18 """Creates a string from a sequence that can be used as a shell array. 19 20 For example, `shell.array_literal(["a", "b", "c"])` would return the string 21 `("a" "b" "c")`, which can be used in a shell script wherever an array 22 literal is needed. 23 24 Note that all elements in the array are quoted (using `shell.quote`) for 25 safety, even if they do not need to be. 26 27 Args: 28 iterable: A sequence of elements. Elements that are not strings will be 29 converted to strings first, by calling `str()`. 30 31 Returns: 32 A string that represents the sequence as a shell array; that is, 33 parentheses containing the quoted elements. 34 """ 35 return "(" + " ".join([_quote(str(i)) for i in iterable]) + ")" 36 37def _quote(s): 38 """Quotes the given string for use in a shell command. 39 40 This function quotes the given string (in case it contains spaces or other 41 shell metacharacters.) 42 43 Args: 44 s: The string to quote. 45 46 Returns: 47 A quoted version of the string that can be passed to a shell command. 48 """ 49 return "'" + s.replace("'", "'\\''") + "'" 50 51shell = struct( 52 array_literal = _array_literal, 53 quote = _quote, 54) 55