Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/xdg/util.py: 16%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

37 statements  

1import sys 

2 

3PY3 = sys.version_info[0] >= 3 

4 

5if PY3: 

6 def u(s): 

7 return s 

8else: 

9 # Unicode-like literals 

10 def u(s): 

11 return s.decode('utf-8') 

12 

13try: 

14 # which() is available from Python 3.3 

15 from shutil import which 

16except ImportError: 

17 import os 

18 # This is a copy of which() from Python 3.3 

19 def which(cmd, mode=os.F_OK | os.X_OK, path=None): 

20 """Given a command, mode, and a PATH string, return the path which 

21 conforms to the given mode on the PATH, or None if there is no such 

22 file. 

23 

24 `mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result 

25 of os.environ.get("PATH"), or can be overridden with a custom search 

26 path. 

27 

28 """ 

29 # Check that a given file can be accessed with the correct mode. 

30 # Additionally check that `file` is not a directory, as on Windows 

31 # directories pass the os.access check. 

32 def _access_check(fn, mode): 

33 return (os.path.exists(fn) and os.access(fn, mode) 

34 and not os.path.isdir(fn)) 

35 

36 # If we're given a path with a directory part, look it up directly rather 

37 # than referring to PATH directories. This includes checking relative to the 

38 # current directory, e.g. ./script 

39 if os.path.dirname(cmd): 

40 if _access_check(cmd, mode): 

41 return cmd 

42 return None 

43 

44 path = (path or os.environ.get("PATH", os.defpath)).split(os.pathsep) 

45 

46 if sys.platform == "win32": 

47 # The current directory takes precedence on Windows. 

48 if not os.curdir in path: 

49 path.insert(0, os.curdir) 

50 

51 # PATHEXT is necessary to check on Windows. 

52 pathext = os.environ.get("PATHEXT", "").split(os.pathsep) 

53 # See if the given file matches any of the expected path extensions. 

54 # This will allow us to short circuit when given "python.exe". 

55 # If it does match, only test that one, otherwise we have to try 

56 # others. 

57 if any(cmd.lower().endswith(ext.lower()) for ext in pathext): 

58 files = [cmd] 

59 else: 

60 files = [cmd + ext for ext in pathext] 

61 else: 

62 # On other platforms you don't have things like PATHEXT to tell you 

63 # what file suffixes are executable, so just pass on cmd as-is. 

64 files = [cmd] 

65 

66 seen = set() 

67 for dir in path: 

68 normdir = os.path.normcase(dir) 

69 if not normdir in seen: 

70 seen.add(normdir) 

71 for thefile in files: 

72 name = os.path.join(dir, thefile) 

73 if _access_check(name, mode): 

74 return name 

75 return None