Return a string which is a relative path from directory to dest such that directory/bestrelpath == dest. The paths must be either both absolute or both relative. If no such path can be determined, returns dest.
(directory: Path, dest: Path)
| 678 | |
| 679 | |
| 680 | def bestrelpath(directory: Path, dest: Path) -> str: |
| 681 | """Return a string which is a relative path from directory to dest such |
| 682 | that directory/bestrelpath == dest. |
| 683 | |
| 684 | The paths must be either both absolute or both relative. |
| 685 | |
| 686 | If no such path can be determined, returns dest. |
| 687 | """ |
| 688 | assert isinstance(directory, Path) |
| 689 | assert isinstance(dest, Path) |
| 690 | if dest == directory: |
| 691 | return os.curdir |
| 692 | # Find the longest common directory. |
| 693 | base = commonpath(directory, dest) |
| 694 | # Can be the case on Windows for two absolute paths on different drives. |
| 695 | # Can be the case for two relative paths without common prefix. |
| 696 | # Can be the case for a relative path and an absolute path. |
| 697 | if not base: |
| 698 | return str(dest) |
| 699 | reldirectory = directory.relative_to(base) |
| 700 | reldest = dest.relative_to(base) |
| 701 | return os.path.join( |
| 702 | # Back from directory to base. |
| 703 | *([os.pardir] * len(reldirectory.parts)), |
| 704 | # Forward from base to dest. |
| 705 | *reldest.parts, |
| 706 | ) |
| 707 | |
| 708 | |
| 709 | # Originates from py. path.local.copy(), with siginficant trims and adjustments. |