create new file_helpers.get_mount_info
authorChristian Herdtweck <christian.herdtweck@intra2net.com>
Thu, 4 Feb 2016 13:47:44 +0000 (14:47 +0100)
committerChristian Herdtweck <christian.herdtweck@intra2net.com>
Thu, 4 Feb 2016 13:47:44 +0000 (14:47 +0100)
src/file_helpers.py

index a682a6e..cafeaea 100644 (file)
@@ -22,7 +22,9 @@ Featuring::
 
 * the cd context manager pwd(); with cd(other_dir): pwd();   pwd();
   will print current working dir, then other_dir, then first dir again
-* class MountPoint and function to get all mount points
+* class MountPoint and functions to:
+* * get all mount points
+* * find mount point that contains a given path
 * class FilesystemFillState and 2 methods to determine it:
 * * a wrapper around "df"
 * * a wrapper around statvfs (default since faster without forking)
@@ -89,7 +91,7 @@ class FilesystemFillState:
 
     def __str__(self):
         return '[Filesystem {0} mounted at {1}: {2}% used]' \
-               .format(self.name, self.mount_point, self.capacity)
+               .format(self.name, self.mount_point, int(round(self.capacity)))
 
 
 def get_filesystem_fill_states(method=FS_FILL_METHOD_STATVFS, *args, **kwargs):
@@ -320,6 +322,28 @@ def get_all_mounts():
     return result
 
 
+def get_mount_info(path):
+    """ get MountPoint with file system info for given path """
+
+    mount_point = find_mount_point(path)
+
+    with open('/proc/mounts', 'rt') as file_handle:
+        for line in file_handle:
+            parts = line.split()
+            matches = re.match(MOUNT_REGEXP, line)
+            if not matches:
+                raise ValueError('failed to interpret mount line "{0}"!'
+                                 .format(line))
+            if matches.group('file') != mount_point:
+                continue
+            new_mount = MountPoint()
+            for field_name, value in matches.groupdict().items():
+                setattr(new_mount, field_name, value)
+            return new_mount
+
+    raise NotImplementedError('impossible: mount point not found in fstab!')
+
+
 def find_mount_point(path):
     """ repeat os.ismount of parent's parent's parent... until returns true