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