75dbe0a2e3ce23e55f0482e134d3cb8eccbaf0ed
[htsworkflow.git] / htsworkflow / util / mount.py
1 """
2 Utilities for working with unix-style mounts.
3 """
4 import os
5 import subprocess
6
7 def list_mount_points():
8     """
9     Return list of current mount points
10
11     Note: unix-like OS specific
12     """
13     mount_points = []
14     likely_locations = ['/sbin/mount', '/bin/mount']
15     for mount in likely_locations:
16         if os.path.exists(mount):
17             p = subprocess.Popen(mount, stdout=subprocess.PIPE)
18             p.wait()
19             for l in p.stdout.readlines():
20                 rec = l.split()
21                 device = rec[0]            
22                 mount_point = rec[2]
23                 assert rec[1] == 'on'
24                 # looking at the output of mount on linux, osx, and 
25                 # sunos, the first 3 elements are always the same
26                 # devicename on path
27                 # everything after that displays the attributes
28                 # of the mount points in wildly differing formats
29                 mount_points.append(mount_point)
30             return mount_points
31     else:
32         raise RuntimeError("Couldn't find a mount executable")
33
34 def is_mounted(point_to_check):
35     """
36     Return true if argument exactly matches a current mount point.
37     """
38     for mount_point in list_mount_points():
39         if point_to_check == mount_point:
40             return True
41     else:
42         return False
43
44 def find_mount_point_for(pathname):
45     """
46     Find the deepest mount point pathname is located on
47     """
48     realpath = os.path.realpath(pathname)
49     mount_points = list_mount_points()
50
51     prefixes = set()
52     for current_mount in mount_points:
53         cp = os.path.commonprefix([current_mount, realpath])
54         prefixes.add((len(cp), cp))
55
56     prefixes = list(prefixes)
57     prefixes.sort()
58     if len(prefixes) == 0:
59         return None
60     else:
61         print prefixes
62         # return longest common prefix
63         return prefixes[-1][1]
64
65