1 """Display models and utility functions"""
2 from __future__
import absolute_import
, division
, print_function
, unicode_literals
6 def shorten_paths(source_paths
):
7 """Shorten a sequence of paths into unique strings for display"""
9 # Start by assuming that all paths are in conflict.
10 # On each iteration we will collect all the path suffixes, move the newly
11 # unique entries to the result, and repeat until no conflicts remain.
13 conflicts
= list(source_paths
)
17 # Gather the suffixes for the current paths in conflict
18 suffixes
= collections
.defaultdict(list)
19 for path
in conflicts
:
20 suffix
= path_suffix(path
, count
)
21 suffixes
[suffix
].append(path
)
23 # Loop over the suffixes to gather new conflicts and unique entries.
27 for suffix
, paths
in suffixes
.items():
28 # If only a single path exists for the suffix then no conflict
29 # exists, and the suffix is valid.
31 result
[paths
[0]] = suffix
32 # If this loop runs too long then bail out by using the full path.
36 # If multiple paths map to the same suffix then the paths are
37 # considered in conflict, and will be reprocessed.
39 conflicts
.extend(paths
)
45 def path_suffix(path
, count
):
46 """Return `count` number of trailing path components"""
47 path
= normalize_path(path
)
48 components
= path
.split('/')[-count
:]
49 return '/'.join(components
)
52 def normalize_path(path
):
53 """Normalize a path so that only "/" is used as a separator"""
54 return path
.replace('\\', '/')