Commit 7fd39ba4 authored by Paul McCarthy's avatar Paul McCarthy 🚵
Browse files

ENH: New function in path module - commonBase

parent 4e87cbf9
...@@ -22,12 +22,14 @@ paths. ...@@ -22,12 +22,14 @@ paths.
getFileGroup getFileGroup
removeDuplicates removeDuplicates
uniquePrefix uniquePrefix
commonBase
""" """
import os.path as op import os.path as op
import os import os
import glob import glob
import operator
class PathError(Exception): class PathError(Exception):
...@@ -471,3 +473,27 @@ def uniquePrefix(path): ...@@ -471,3 +473,27 @@ def uniquePrefix(path):
hits = [h for h in hits if h.startswith(prefix)] hits = [h for h in hits if h.startswith(prefix)]
return prefix return prefix
def commonBase(paths):
"""Identifies the deepest common base directory shared by all files
in ``paths``.
Raises a :exc:`PathError` if the paths have no common base. This will
never happen for absolute paths (as the base will be e.g. ``'/'``).
"""
depths = [len(p.split(op.sep)) for p in paths]
base = max(zip(depths, paths), key=operator.itemgetter(0))[1]
while True:
base = op.split(base)[0]
if len(base) == 0:
break
if all([p.startswith(base) for p in paths]):
return base
raise PathError('No common base')
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment