Given a sequence of path names, returns the longest common sub-path.
(paths)
| 795 | # stripped from the returned path. |
| 796 | |
| 797 | def commonpath(paths): |
| 798 | """Given a sequence of path names, returns the longest common sub-path.""" |
| 799 | |
| 800 | if not paths: |
| 801 | raise ValueError('commonpath() arg is an empty sequence') |
| 802 | |
| 803 | paths = tuple(map(os.fspath, paths)) |
| 804 | if isinstance(paths[0], bytes): |
| 805 | sep = b'\\' |
| 806 | altsep = b'/' |
| 807 | curdir = b'.' |
| 808 | else: |
| 809 | sep = '\\' |
| 810 | altsep = '/' |
| 811 | curdir = '.' |
| 812 | |
| 813 | try: |
| 814 | drivesplits = [splitdrive(p.replace(altsep, sep).lower()) for p in paths] |
| 815 | split_paths = [p.split(sep) for d, p in drivesplits] |
| 816 | |
| 817 | try: |
| 818 | isabs, = set(p[:1] == sep for d, p in drivesplits) |
| 819 | except ValueError: |
| 820 | raise ValueError("Can't mix absolute and relative paths") from None |
| 821 | |
| 822 | # Check that all drive letters or UNC paths match. The check is made only |
| 823 | # now otherwise type errors for mixing strings and bytes would not be |
| 824 | # caught. |
| 825 | if len(set(d for d, p in drivesplits)) != 1: |
| 826 | raise ValueError("Paths don't have the same drive") |
| 827 | |
| 828 | drive, path = splitdrive(paths[0].replace(altsep, sep)) |
| 829 | common = path.split(sep) |
| 830 | common = [c for c in common if c and c != curdir] |
| 831 | |
| 832 | split_paths = [[c for c in s if c and c != curdir] for s in split_paths] |
| 833 | s1 = min(split_paths) |
| 834 | s2 = max(split_paths) |
| 835 | for i, c in enumerate(s1): |
| 836 | if c != s2[i]: |
| 837 | common = common[:i] |
| 838 | break |
| 839 | else: |
| 840 | common = common[:len(s1)] |
| 841 | |
| 842 | prefix = drive + sep if isabs else drive |
| 843 | return prefix + sep.join(common) |
| 844 | except (TypeError, AttributeError): |
| 845 | genericpath._check_arg_types('commonpath', *paths) |
| 846 | raise |
| 847 | |
| 848 | |
| 849 | try: |