Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code | Sign in
(95210)

Unified Diff: Lib/posixpath.py

Issue 10395: new os.path function to extract common prefix based on path components
Patch Set: Created 6 years, 9 months ago
Use n/p to move between diff chunks; N/P to move between comments. Please Sign in to add in-line comments.
Jump to:
View side-by-side diff with in-line comments
Download patch
« no previous file with comments | « Doc/library/os.path.rst ('k') | Lib/test/test_posixpath.py » ('j') | no next file with comments »
Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
--- a/Lib/posixpath.py Mon Nov 05 00:56:02 2012 +1000
+++ b/Lib/posixpath.py Sun Nov 04 11:05:17 2012 -0500
@@ -22,7 +22,8 @@
"ismount", "expanduser","expandvars","normpath","abspath",
"samefile","sameopenfile","samestat",
"curdir","pardir","sep","pathsep","defpath","altsep","extsep",
- "devnull","realpath","supports_unicode_filenames","relpath"]
+ "devnull","realpath","supports_unicode_filenames","relpath",
+ "commonpath"]
# Strings representing various path-related bits and pieces.
# These are primarily for export; internally, they are hardcoded.
@@ -467,3 +468,36 @@
if not rel_list:
return curdir
return join(*rel_list)
+
+
+def commonpath(paths):
+ """Given a sequence of absolute path names, returns the longest common
+ sub-path."""
+
+ if not paths:
+ return None
+
+ if not all(isabs(p) for p in paths):
+ raise ValueError('All paths must be absolute')
storchaka 2012/11/04 17:39:05 I think this is too strict limitation. The functio
rafik 2012/11/05 21:44:26 Done.
+
+ sep = _get_sep(paths[0])
+
+ try:
+ split_paths = [path.split(sep) for path in paths]
storchaka 2012/11/04 17:39:05 What is the longest common sub-path for '/usr/log/
rafik 2012/11/05 21:44:26 I do not know if the responsibility of providing "
+ except TypeError:
+ valid_types = all(isinstance(p, (str, bytes, bytearray))
+ for p in paths)
+ if valid_types:
+ # Must have a mixture of text and binary data
+ raise TypeError("Can't mix strings and bytes in path "
+ "components.") from None
+ raise
+
+ zipped_components = list(zip(*split_paths))
storchaka 2012/11/04 17:39:05 You can use same simple and effective approach as
rafik 2012/11/05 21:44:26 Done.
+ for i, cs in enumerate(zipped_components):
+ first = cs[0]
+ if not all(c == first for c in cs):
+ i = i - 1 # last matching index
+ break
+ common = [cs[0] for cs in zipped_components[:i+1]]
+ return sep + join(*common)
« no previous file with comments | « Doc/library/os.path.rst ('k') | Lib/test/test_posixpath.py » ('j') | no next file with comments »

RSS Feeds Recent Issues | This issue
This is Rietveld 894c83f36cb7+