Python Library FS-Tools
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

__init__.py 8.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #
  4. """
  5. fstools (Filesystem Tools)
  6. ==========================
  7. **Author:**
  8. * Dirk Alders <sudo-dirk@mount-mockery.de>
  9. **Description:**
  10. This module supports functions and classes to handle files and paths
  11. **Submodules:**
  12. * :mod:`mmod.module.sub1`
  13. * :class:`mmod.module.sub2`
  14. * :func:`mmod.module.sub2`
  15. **Unittest:**
  16. See also the :download:`unittest <../../fstools/_testresults_/unittest.pdf>` documentation.
  17. """
  18. __DEPENDENCIES__ = []
  19. import glob
  20. import hashlib
  21. import logging
  22. from functools import partial
  23. import hmac
  24. import os
  25. import sys
  26. import time
  27. logger_name = 'FSTOOLS'
  28. logger = logging.getLogger(logger_name)
  29. __DESCRIPTION__ = """The Module {\\tt %s} is designed to help on all issues with files and folders.
  30. For more Information read the documentation.""" % __name__.replace('_', '\_')
  31. """The Module Description"""
  32. __INTERPRETER__ = (2, 3)
  33. """The Tested Interpreter-Versions"""
  34. def uid(pathname, max_staleness=3600):
  35. """
  36. Function returning a unique id for a given file or path.
  37. :param str pathname: File or Path name for generation of the uid.
  38. :param int max_staleness: If a file or path is older than that, we may consider
  39. it stale and return a different uid - this is a
  40. dirty trick to work around changes never being
  41. detected. Default is 3600 seconds, use None to
  42. disable this trickery. See below for more details.
  43. :returns: An object that changes value if the file changed,
  44. None is returned if there were problems accessing the file
  45. :rtype: str
  46. .. note:: Depending on the operating system capabilities and the way the
  47. file update is done, this function might return the same value
  48. even if the file has changed. It should be better than just
  49. using file's mtime though.
  50. max_staleness tries to avoid the worst for these cases.
  51. .. note:: If this function is used for a path, it will stat all pathes and files rekursively.
  52. Using just the file's mtime to determine if the file has changed is
  53. not reliable - if file updates happen faster than the file system's
  54. mtime granularity, then the modification is not detectable because
  55. the mtime is still the same.
  56. This function tries to improve by using not only the mtime, but also
  57. other metadata values like file size and inode to improve reliability.
  58. For the calculation of this value, we of course only want to use data
  59. that we can get rather fast, thus we use file metadata, not file data
  60. (file content).
  61. >>> print 'UID:', uid(__file__)
  62. UID: 16a65cc78e1344e596ef1c9536dab2193a402934
  63. """
  64. if os.path.isdir(pathname):
  65. pathlist = dirlist(pathname) + filelist(pathname)
  66. pathlist.sort()
  67. else:
  68. pathlist = [pathname]
  69. uid = []
  70. for element in pathlist:
  71. try:
  72. st = os.stat(element)
  73. except (IOError, OSError):
  74. uid.append(None) # for permanent errors on stat() this does not change, but
  75. # having a changing value would be pointless because if we
  76. # can't even stat the file, it is unlikely we can read it.
  77. else:
  78. fake_mtime = int(st.st_mtime)
  79. if not st.st_ino and max_staleness:
  80. # st_ino being 0 likely means that we run on a platform not
  81. # supporting it (e.g. win32) - thus we likely need this dirty
  82. # trick
  83. now = int(time.time())
  84. if now >= st.st_mtime + max_staleness:
  85. # keep same fake_mtime for each max_staleness interval
  86. fake_mtime = int(now / max_staleness) * max_staleness
  87. uid.append((
  88. st.st_mtime, # might have a rather rough granularity, e.g. 2s
  89. # on FAT, 1s on ext3 and might not change on fast
  90. # updates
  91. st.st_ino, # inode number (will change if the update is done
  92. # by e.g. renaming a temp file to the real file).
  93. # not supported on win32 (0 ever)
  94. st.st_size, # likely to change on many updates, but not
  95. # sufficient alone
  96. fake_mtime) # trick to workaround file system / platform
  97. # limitations causing permanent trouble
  98. )
  99. if sys.version_info < (3, 0):
  100. secret = ''
  101. return hmac.new(secret, repr(uid), hashlib.sha1).hexdigest()
  102. else:
  103. secret = b''
  104. return hmac.new(secret, bytes(repr(uid), 'latin-1'), hashlib.sha1).hexdigest()
  105. def uid_filelist(path='.', expression='*', rekursive=True):
  106. SHAhash = hashlib.md5()
  107. #
  108. fl = filelist(path, expression, rekursive)
  109. fl.sort()
  110. for f in fl:
  111. if sys.version_info < (3, 0):
  112. with open(f, 'rb') as fh:
  113. SHAhash.update(hashlib.md5(fh.read()).hexdigest())
  114. else:
  115. with open(f, mode='rb') as fh:
  116. d = hashlib.md5()
  117. for buf in iter(partial(fh.read, 128), b''):
  118. d.update(buf)
  119. SHAhash.update(d.hexdigest().encode())
  120. #
  121. return SHAhash.hexdigest()
  122. def filelist(path='.', expression='*', rekursive=True):
  123. """
  124. Function returning a list of files below a given path.
  125. :param str path: folder which is the basepath for searching files.
  126. :param str expression: expression to fit including shell-style wildcards.
  127. :param bool rekursive: search all subfolders if True.
  128. :returns: list of filenames including the pathe
  129. :rtype: list
  130. .. note:: The returned filenames could be relative pathes depending on argument path.
  131. >>> for filename in filelist(path='.', expression='*.py*', rekursive=True):
  132. ... print filename
  133. ./__init__.py
  134. ./__init__.pyc
  135. """
  136. li = list()
  137. if os.path.exists(path):
  138. logger.debug('FILELIST: path (%s) exists - looking for files to append', path)
  139. for filename in glob.glob(os.path.join(path, expression)):
  140. if os.path.isfile(filename):
  141. li.append(filename)
  142. for directory in os.listdir(path):
  143. directory = os.path.join(path, directory)
  144. if os.path.isdir(directory) and rekursive and not os.path.islink(directory):
  145. li.extend(filelist(directory, expression))
  146. else:
  147. logger.warning('FILELIST: path (%s) does not exist - empty filelist will be returned', path)
  148. return li
  149. def dirlist(path='.', rekursive=True):
  150. """
  151. Function returning a list of directories below a given path.
  152. :param str path: folder which is the basepath for searching files.
  153. :param bool rekursive: search all subfolders if True.
  154. :returns: list of filenames including the pathe
  155. :rtype: list
  156. .. note:: The returned filenames could be relative pathes depending on argument path.
  157. >>> for dirname in dirlist(path='..', rekursive=True):
  158. ... print dirname
  159. ../caching
  160. ../fstools
  161. """
  162. li = list()
  163. if os.path.exists(path):
  164. logger.debug('DIRLIST: path (%s) exists - looking for directories to append', path)
  165. for dirname in os.listdir(path):
  166. fulldir = os.path.join(path, dirname)
  167. if os.path.isdir(fulldir):
  168. li.append(fulldir)
  169. if rekursive:
  170. li.extend(dirlist(fulldir))
  171. else:
  172. logger.warning('DIRLIST: path (%s) does not exist - empty filelist will be returned', path)
  173. return li
  174. def is_writeable(path):
  175. """.. warning:: Needs to be documented
  176. """
  177. if os.access(path, os.W_OK):
  178. # path is writable whatever it is, file or directory
  179. return True
  180. else:
  181. # path is not writable whatever it is, file or directory
  182. return False
  183. def mkdir(path):
  184. """.. warning:: Needs to be documented
  185. """
  186. path = os.path.abspath(path)
  187. if not os.path.exists(os.path.dirname(path)):
  188. mkdir(os.path.dirname(path))
  189. if not os.path.exists(path):
  190. os.mkdir(path)
  191. return os.path.isdir(path)
  192. def open_locked_non_blocking(*args, **kwargs):
  193. """.. warning:: Needs to be documented (acquire exclusive lock file access). Throws an exception, if file is locked!
  194. """
  195. import fcntl
  196. locked_file_descriptor = open(*args, **kwargs)
  197. fcntl.lockf(locked_file_descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB)
  198. return locked_file_descriptor
  199. def open_locked_blocking(*args, **kwargs):
  200. """.. warning:: Needs to be documented (acquire exclusive lock file access). Blocks until file is free. deadlock!
  201. """
  202. import fcntl
  203. locked_file_descriptor = open(*args, **kwargs)
  204. fcntl.lockf(locked_file_descriptor, fcntl.LOCK_EX)
  205. return locked_file_descriptor