import pathlib


def _common_subdir_in_zip(model_zip):
    """Given a zip file, return the common_subdir that all files have (if there is one)."""

    # get the names of all files (not directories)
    namelist = [f.filename for f in model_zip.infolist() if not f.is_dir()]
    if not namelist:
        return None

    parts = pathlib.PurePath(namelist[0]).parts
    same_parts = []

    # loop through all parts (except final one, since that's the file name)
    # and confirm they are the same for all files
    for part_num, part in enumerate(parts[:-1]):
        if all(pathlib.PurePath(name).parts[part_num] == part for name in namelist):
            same_parts.append(part)
        else:
            break

    if same_parts:
        return pathlib.PurePath(*same_parts)

    return None