|
28 | 28 | ###########################################################
|
29 | 29 |
|
30 | 30 |
|
| 31 | +def safe_path(path: Path | str, max_name_length: int = 50) -> Path | str: |
| 32 | + r""" |
| 33 | + Return a safe version of the provided path or string. |
| 34 | + Only the last part is considered if a path is provided. |
| 35 | +
|
| 36 | + >>> str(safe_path(Path("a/."))) |
| 37 | + 'a' |
| 38 | + >>> str(safe_path(Path("ab\x00c"))) |
| 39 | + 'ab_c' |
| 40 | + >>> str(safe_path(Path("CON"))) |
| 41 | + 'CON_' |
| 42 | + >>> str(safe_path(Path("LPT7"))) |
| 43 | + 'LPT7_' |
| 44 | + >>> str(safe_path(Path("bc."))) |
| 45 | + 'bc_' |
| 46 | + >>> safe_path("b:c") |
| 47 | + 'b_c' |
| 48 | + >>> str(safe_path(Path("b*c"))) |
| 49 | + 'b_c' |
| 50 | + >>> safe_path("a/b/c") |
| 51 | + 'a_b_c' |
| 52 | + >>> safe_path("") # doctest:+ELLIPSIS |
| 53 | + 'unnamed_...' |
| 54 | + >>> safe_path("g" * 50, max_name_length=4) |
| 55 | + 'gggg' |
| 56 | + """ |
| 57 | + safe_name = path if isinstance(path, str) else path.name |
| 58 | + if safe_name == "": |
| 59 | + return unique_title() |
| 60 | + |
| 61 | + # https://stackoverflow.com/a/31976060 |
| 62 | + # Windows restrictions |
| 63 | + # fmt: off |
| 64 | + forbidden_chars = [ |
| 65 | + "<", ">", ":", "\"", "/", "\\", "|", "?", "*", |
| 66 | + ] + [chr(value) for value in range(32)] |
| 67 | + # fmt: on |
| 68 | + for char in forbidden_chars: |
| 69 | + safe_name = safe_name.replace(char, "_") |
| 70 | + |
| 71 | + forbidden_names = ( |
| 72 | + ["CON", "PRN", "AUX", "NUL"] |
| 73 | + + [f"COM{i}" for i in range(1, 10)] |
| 74 | + + [f"LPT{i}" for i in range(1, 10)] |
| 75 | + ) |
| 76 | + if safe_name in forbidden_names: |
| 77 | + safe_name += "_" |
| 78 | + |
| 79 | + forbidden_last_chars = [" ", "."] |
| 80 | + if safe_name[-1] in forbidden_last_chars: |
| 81 | + safe_name = safe_name[:-1] + "_" |
| 82 | + |
| 83 | + # Linux and MacOS restrictions |
| 84 | + forbidden_chars = ["/", "\x00"] |
| 85 | + for char in forbidden_chars: |
| 86 | + safe_name = safe_name.replace(char, "_") |
| 87 | + |
| 88 | + forbidden_names = [".", ".."] |
| 89 | + if safe_name in forbidden_names: |
| 90 | + safe_name += "_" |
| 91 | + |
| 92 | + # Limit filename length: https://serverfault.com/a/9548 |
| 93 | + safe_name = safe_name[:max_name_length] |
| 94 | + |
| 95 | + return safe_name if isinstance(path, str) else path.with_name(safe_name) |
| 96 | + |
| 97 | + |
31 | 98 | def get_available_formats() -> dict:
|
32 | 99 | formats_dict = {}
|
33 | 100 | for module in pkgutil.iter_modules(formats.__path__):
|
|
0 commit comments