Sanitize URL to create a valid filesystem path name. Simply strips protocol and replaces invalid filesystem characters. Args: url: URL to sanitize Returns: Sanitized Path suitable for use as a filesystem path component Example: >>> sanitize_url_for_pat
(url: str)
| 11 | |
| 12 | |
| 13 | def sanitize_url_for_path(url: str) -> Path: |
| 14 | """ |
| 15 | Sanitize URL to create a valid filesystem path name. |
| 16 | Simply strips protocol and replaces invalid filesystem characters. |
| 17 | |
| 18 | Args: |
| 19 | url: URL to sanitize |
| 20 | |
| 21 | Returns: |
| 22 | Sanitized Path suitable for use as a filesystem path component |
| 23 | |
| 24 | Example: |
| 25 | >>> sanitize_url_for_path("https://github.com/owner/repo/releases/download/v1.0.0/file.zip") |
| 26 | Path('github_com_owner_repo_releases_download_v1_0_0_file_zip') |
| 27 | """ |
| 28 | # Remove protocol (http://, https://, ftp://, etc.) |
| 29 | if "://" in url: |
| 30 | url = url.split("://", 1)[1] |
| 31 | |
| 32 | # Replace invalid filesystem characters with underscores |
| 33 | # Invalid characters: / \ : * ? " < > | |
| 34 | invalid_chars = ["/", "\\", ":", "*", "?", '"', "<", ">", "|"] |
| 35 | result = url |
| 36 | for char in invalid_chars: |
| 37 | result = result.replace(char, "_") |
| 38 | |
| 39 | # Replace dots with underscores to avoid issues with file extensions |
| 40 | result = result.replace(".", "_") |
| 41 | |
| 42 | # Replace spaces and dashes with underscores for consistency |
| 43 | result = result.replace(" ", "_").replace("-", "_") |
| 44 | |
| 45 | # Remove any remaining non-alphanumeric characters except underscores |
| 46 | result = "".join(c if c.isalnum() or c == "_" else "_" for c in result) |
| 47 | |
| 48 | # Remove multiple consecutive underscores |
| 49 | while "__" in result: |
| 50 | result = result.replace("__", "_") |
| 51 | |
| 52 | # Remove leading/trailing underscores |
| 53 | result = result.strip("_") |
| 54 | |
| 55 | # Ensure reasonable length (max 100 chars) |
| 56 | if len(result) > 100: |
| 57 | # Keep first 70 chars and add a short hash |
| 58 | result = result[:70] + "_" + hashlib.sha256(url.encode()).hexdigest()[:8] |
| 59 | |
| 60 | return Path(result) |
no outgoing calls