Drop "." and ".." segments from a URL path. For example: normalize_path("/path/./to/somewhere/..") == "/path/to"
(path: str)
| 445 | |
| 446 | |
| 447 | def normalize_path(path: str) -> str: |
| 448 | """ |
| 449 | Drop "." and ".." segments from a URL path. |
| 450 | |
| 451 | For example: |
| 452 | |
| 453 | normalize_path("/path/./to/somewhere/..") == "/path/to" |
| 454 | """ |
| 455 | # Fast return when no '.' characters in the path. |
| 456 | if "." not in path: |
| 457 | return path |
| 458 | |
| 459 | components = path.split("/") |
| 460 | |
| 461 | # Fast return when no '.' or '..' components in the path. |
| 462 | if "." not in components and ".." not in components: |
| 463 | return path |
| 464 | |
| 465 | # https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.4 |
| 466 | output: list[str] = [] |
| 467 | for component in components: |
| 468 | if component == ".": |
| 469 | pass |
| 470 | elif component == "..": |
| 471 | if output and output != [""]: |
| 472 | output.pop() |
| 473 | else: |
| 474 | output.append(component) |
| 475 | return "/".join(output) |
| 476 | |
| 477 | |
| 478 | def PERCENT(string: str) -> str: |