Skip to content

Instantly share code, notes, and snippets.

@gicmo
Created December 15, 2019 22:22
Show Gist options
  • Save gicmo/66963bbfc948d5e7aa7c308a3631cac0 to your computer and use it in GitHub Desktop.
Save gicmo/66963bbfc948d5e7aa7c308a3631cac0 to your computer and use it in GitHub Desktop.
#!/usr/bin/python3
import os
import json
import sys
all_partitions = [
{"start": 2048, "size": 972800, "type": "C12A7328-F81F-11D2-BA4B-00A0C93EC93B",
"filesystem": {"type": "vfat", "uuid": "46BB-8120", "label": "EFI System Partition",
"mountpoint": "/boot/efi"}},
{"start": 976896,
"filesystem": {"type": "ext4", "uuid": "7acfe2cc-4134-482a-a9d4-4979a5a87569",
"mountpoint": "/"}}
]
def path_split(path):
"""Split the path into its components (folders)"""
path = os.path.normpath(path)
folders = []
while True:
path, comp = os.path.split(path)
if not comp:
break
folders.append(comp)
return ["/"] + list(reversed(folders))
def path_contains(base, target):
"""Check if base contains target"""
k = len(base)
n = len(target)
if k > n:
return False
for i in range(k): # must: k <= n
b, t = base[i], target[i]
if b != t:
return False
return True
def partitions_sort_fs(partitions):
"""Sort partitions by file system hierarchy"""
def mountpoint_len(p):
return len(p["filesystem"]["mountpoint"])
parts_fs = filter(lambda p: "filesystem" in p, partitions)
return sorted(parts_fs, key=mountpoint_len)
def partitions_find_for_path(partitions, path):
parts = partitions_sort_fs(partitions)
folders = path_split(path)
candidate = None
for part in parts:
mountpoint = part["filesystem"]["mountpoint"]
f = path_split(mountpoint)
if len(f) > len(folders):
break
elif path_contains(f, folders):
candidate = part
return {"ref": path, "comps": path_split(path), "candidate": candidate}
def main():
json.dump(partitions_sort_fs(all_partitions), sys.stdout)
json.dump(partitions_find_for_path(all_partitions, "/////"), sys.stdout)
json.dump(partitions_find_for_path(all_partitions, "/boot"), sys.stdout)
json.dump(partitions_find_for_path(all_partitions, "/boot/foo/bar"), sys.stdout)
json.dump(partitions_find_for_path(all_partitions, "/boot/efi"), sys.stdout)
json.dump(partitions_find_for_path(all_partitions, "/boot/efi//"), sys.stdout)
json.dump(partitions_find_for_path(all_partitions, "/boot/efi/foo"), sys.stdout)
json.dump(partitions_find_for_path(all_partitions, "/boot/efi///foo"), sys.stdout)
json.dump(partitions_find_for_path(all_partitions, "/////"), sys.stdout)
json.dump(partitions_find_for_path(all_partitions, "/////boot/efi///"), sys.stdout)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment