Skip to content

Commit 62a10ce

Browse files
committed
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
1 parent f9e30bb commit 62a10ce

File tree

1 file changed

+41
-4
lines changed

1 file changed

+41
-4
lines changed

workspace_tools/utils.py

Lines changed: 41 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@
1515
limitations under the License.
1616
"""
1717
import sys
18+
import inspect
19+
import os
1820
from os import listdir, remove, makedirs
1921
from shutil import copyfile
2022
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):
3133

3234

3335
def run_cmd(command, wd=None, redirect=False):
34-
if not exists(command[0]):
35-
error('run_cmd(): %s path does not exist' % command[0])
36+
assert is_cmd_valid(command[0])
3637
p = Popen(command, stdout=PIPE, stderr=STDOUT if redirect else PIPE, cwd=wd)
3738
_stdout, _stderr = p.communicate()
3839
return _stdout, _stderr, p.returncode
3940

4041

4142
def run_cmd_ext(command):
42-
if not exists(command[0]):
43-
error('run_cmd_ext(): %s path does not exist' % command[0])
43+
assert is_cmd_valid(command[0])
4444
p = Popen(command, stdout=PIPE, stderr=PIPE)
4545
_stdout, _stderr = p.communicate()
4646
return _stdout, _stderr, p.returncode
4747

4848

49+
def is_cmd_valid(cmd):
50+
caller = get_caller_name()
51+
abspath = find_cmd_abspath(cmd)
52+
if not abspath:
53+
error("%s: Command '%s' can't be found" % (caller, cmd))
54+
if not is_exec(abspath):
55+
error("%s: Command '%s' resolves to file '%s' which is not executable" % (caller, cmd, abspath))
56+
return True
57+
58+
59+
def is_exec(path):
60+
return os.access(path, os.X_OK)
61+
62+
63+
def find_cmd_abspath(cmd):
64+
""" Returns the absolute path to a command.
65+
None is returned if no absolute path was found.
66+
"""
67+
if exists(cmd):
68+
return '%s/%s' % (os.getcwd(), cmd)
69+
if not 'PATH' in os.environ:
70+
raise Exception("Can't find command path for current platform ('%s')" % sys.platform)
71+
PATH=os.environ['PATH']
72+
for path in PATH.split(os.pathsep):
73+
abspath = '%s/%s' % (path, cmd)
74+
if exists(abspath):
75+
return abspath
76+
77+
4978
def mkdir(path):
5079
if not exists(path):
5180
makedirs(path)
@@ -71,6 +100,14 @@ def delete_dir_files(dir):
71100
remove(file)
72101

73102

103+
def get_caller_name(steps=2):
104+
"""
105+
When called inside a function, it returns the name
106+
of the caller of that function.
107+
"""
108+
return inspect.stack()[steps][3]
109+
110+
74111
def error(msg):
75112
print msg
76113
sys.exit(1)

0 commit comments

Comments
 (0)