util.executable.which: handle path separators like /bin/which (#17668)

* util.executable.which: handle path separators like /bin/which

Co-authored-by: Massimiliano Culpo <massimiliano.culpo@gmail.com>
This commit is contained in:
Greg Becker 2020-07-23 10:54:25 -07:00 committed by GitHub
parent f42394daf5
commit e8aa737b09
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 37 additions and 2 deletions

View file

@ -40,6 +40,36 @@ def test_read_unicode(tmpdir, working_env):
assert u'\xc3' == script(output=str).strip()
def test_which_relative_path_with_slash(tmpdir, working_env):
tmpdir.ensure('exe')
path = str(tmpdir.join('exe'))
os.environ['PATH'] = ''
with tmpdir.as_cwd():
no_exe = ex.which('./exe')
assert no_exe is None
fs.set_executable(path)
exe = ex.which('./exe')
assert exe.path == path
def test_which_with_slash_ignores_path(tmpdir, working_env):
tmpdir.ensure('exe')
tmpdir.ensure('bin{0}exe'.format(os.path.sep))
path = str(tmpdir.join('exe'))
wrong_path = str(tmpdir.join('bin', 'exe'))
os.environ['PATH'] = os.path.dirname(wrong_path)
fs.set_executable(path)
fs.set_executable(wrong_path)
with tmpdir.as_cwd():
exe = ex.which('./exe')
assert exe.path == path
def test_which(tmpdir):
os.environ["PATH"] = str(tmpdir)
assert ex.which("spack-test-exe") is None

View file

@ -233,6 +233,11 @@ def which_string(*args, **kwargs):
path = path.split(os.pathsep)
for name in args:
if os.path.sep in name:
exe = os.path.abspath(name)
if os.path.isfile(exe) and os.access(exe, os.X_OK):
return exe
else:
for directory in path:
exe = os.path.join(directory, name)
if os.path.isfile(exe) and os.access(exe, os.X_OK):