From 62a10cee03515d8f0ece843a889d036fd02b860e Mon Sep 17 00:00:00 2001 From: pithikos Date: Thu, 7 May 2015 15:06:57 +0100 Subject: [PATCH] cmd validation added for both relpaths and abspaths cmd validation is run before executing a command. The validation assures that the command resolves to a file that is executable. This --- workspace_tools/utils.py | 45 ++++++++++++++++++++++++++++++++++++---- 1 file changed, 41 insertions(+), 4 deletions(-) diff --git a/workspace_tools/utils.py b/workspace_tools/utils.py index 1b1c8080a7..f68c376a20 100644 --- a/workspace_tools/utils.py +++ b/workspace_tools/utils.py @@ -15,6 +15,8 @@ See the License for the specific language governing permissions and limitations under the License. """ import sys +import inspect +import os from os import listdir, remove, makedirs from shutil import copyfile from os.path import isdir, join, exists, split, relpath, splitext @@ -31,21 +33,48 @@ def cmd(l, check=True, verbose=False, shell=False, cwd=None): def run_cmd(command, wd=None, redirect=False): - if not exists(command[0]): - error('run_cmd(): %s path does not exist' % command[0]) + assert is_cmd_valid(command[0]) p = Popen(command, stdout=PIPE, stderr=STDOUT if redirect else PIPE, cwd=wd) _stdout, _stderr = p.communicate() return _stdout, _stderr, p.returncode def run_cmd_ext(command): - if not exists(command[0]): - error('run_cmd_ext(): %s path does not exist' % command[0]) + assert is_cmd_valid(command[0]) p = Popen(command, stdout=PIPE, stderr=PIPE) _stdout, _stderr = p.communicate() return _stdout, _stderr, p.returncode +def is_cmd_valid(cmd): + caller = get_caller_name() + abspath = find_cmd_abspath(cmd) + if not abspath: + error("%s: Command '%s' can't be found" % (caller, cmd)) + if not is_exec(abspath): + error("%s: Command '%s' resolves to file '%s' which is not executable" % (caller, cmd, abspath)) + return True + + +def is_exec(path): + return os.access(path, os.X_OK) + + +def find_cmd_abspath(cmd): + """ Returns the absolute path to a command. + None is returned if no absolute path was found. + """ + if exists(cmd): + return '%s/%s' % (os.getcwd(), cmd) + if not 'PATH' in os.environ: + raise Exception("Can't find command path for current platform ('%s')" % sys.platform) + PATH=os.environ['PATH'] + for path in PATH.split(os.pathsep): + abspath = '%s/%s' % (path, cmd) + if exists(abspath): + return abspath + + def mkdir(path): if not exists(path): makedirs(path) @@ -71,6 +100,14 @@ def delete_dir_files(dir): remove(file) +def get_caller_name(steps=2): + """ + When called inside a function, it returns the name + of the caller of that function. + """ + return inspect.stack()[steps][3] + + def error(msg): print msg sys.exit(1)