Determines if the given path is a script. A script is a file that starts with a shebang (#!...) line. :param path: The path to check. :param pattern: Optional pattern to match against the shebang line (excluding the leading #! and trailing \n). :param check_exec
(
path, # type: Text
pattern=None, # type: Optional[bytes]
check_executable=True, # type: bool
extra_check=None, # type: Optional[Callable[[bytes, BinaryIO], bool]]
)
| 34 | |
| 35 | |
| 36 | def is_script( |
| 37 | path, # type: Text |
| 38 | pattern=None, # type: Optional[bytes] |
| 39 | check_executable=True, # type: bool |
| 40 | extra_check=None, # type: Optional[Callable[[bytes, BinaryIO], bool]] |
| 41 | ): |
| 42 | # type: (...) -> bool |
| 43 | """Determines if the given path is a script. |
| 44 | |
| 45 | A script is a file that starts with a shebang (#!...) line. |
| 46 | |
| 47 | :param path: The path to check. |
| 48 | :param pattern: Optional pattern to match against the shebang line (excluding the leading #! |
| 49 | and trailing \n). |
| 50 | :param check_executable: Check that the script is executable by the current user. |
| 51 | :param extra_check: Optional callable accepting the shebang line (excluding the leading #! and |
| 52 | trailing \n) and a file opened for binary read pointing just after that |
| 53 | line. |
| 54 | :return: True if the given path is a script. |
| 55 | """ |
| 56 | path = os.path.realpath(path) |
| 57 | if check_executable and not is_exe(path): |
| 58 | return False |
| 59 | elif not os.path.isfile(path): |
| 60 | return False |
| 61 | |
| 62 | with open(path, "rb") as fp: |
| 63 | if _SHEBANG_MAGIC != fp.read(len(_SHEBANG_MAGIC)): |
| 64 | return False |
| 65 | if not pattern: |
| 66 | return True |
| 67 | shebang_suffix = fp.readline().rstrip() |
| 68 | if bool(re.match(pattern, shebang_suffix)): |
| 69 | return True |
| 70 | if extra_check: |
| 71 | return extra_check(shebang_suffix, fp) |
| 72 | return False |
| 73 | |
| 74 | |
| 75 | def create_sh_python_redirector_shebang(sh_script_content): |