PageRenderTime 23ms CodeModel.GetById 32ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/git/util.py

https://github.com/nowells/GitPython
Python | 345 lines | 329 code | 5 blank | 11 comment | 5 complexity | c1ba12b0b75617ee7e8cc17a9a6ed7b6 MD5 | raw file
  1. # utils.py
  2. # Copyright (C) 2008, 2009 Michael Trier (mtrier@gmail.com) and contributors
  3. #
  4. # This module is part of GitPython and is released under
  5. # the BSD License: http://www.opensource.org/licenses/bsd-license.php
  6. import os
  7. import sys
  8. import time
  9. import tempfile
  10. from gitdb.util import (
  11. make_sha,
  12. LockedFD,
  13. file_contents_ro,
  14. LazyMixin,
  15. to_hex_sha,
  16. to_bin_sha
  17. )
  18. __all__ = ( "stream_copy", "join_path", "to_native_path_windows", "to_native_path_linux",
  19. "join_path_native", "Stats", "IndexFileSHA1Writer", "Iterable", "IterableList",
  20. "BlockingLockFile", "LockFile" )
  21. def stream_copy(source, destination, chunk_size=512*1024):
  22. """Copy all data from the source stream into the destination stream in chunks
  23. of size chunk_size
  24. :return: amount of bytes written"""
  25. br = 0
  26. while True:
  27. chunk = source.read(chunk_size)
  28. destination.write(chunk)
  29. br += len(chunk)
  30. if len(chunk) < chunk_size:
  31. break
  32. # END reading output stream
  33. return br
  34. def join_path(a, *p):
  35. """Join path tokens together similar to os.path.join, but always use
  36. '/' instead of possibly '\' on windows."""
  37. path = a
  38. for b in p:
  39. if b.startswith('/'):
  40. path += b[1:]
  41. elif path == '' or path.endswith('/'):
  42. path += b
  43. else:
  44. path += '/' + b
  45. return path
  46. def to_native_path_windows(path):
  47. return path.replace('/','\\')
  48. def to_native_path_linux(path):
  49. return path.replace('\\','/')
  50. if sys.platform.startswith('win'):
  51. to_native_path = to_native_path_windows
  52. else:
  53. # no need for any work on linux
  54. def to_native_path_linux(path):
  55. return path
  56. to_native_path = to_native_path_linux
  57. def join_path_native(a, *p):
  58. """As join path, but makes sure an OS native path is returned. This is only
  59. needed to play it safe on my dear windows and to assure nice paths that only
  60. use '\'"""
  61. return to_native_path(join_path(a, *p))
  62. class Stats(object):
  63. """
  64. Represents stat information as presented by git at the end of a merge. It is
  65. created from the output of a diff operation.
  66. ``Example``::
  67. c = Commit( sha1 )
  68. s = c.stats
  69. s.total # full-stat-dict
  70. s.files # dict( filepath : stat-dict )
  71. ``stat-dict``
  72. A dictionary with the following keys and values::
  73. deletions = number of deleted lines as int
  74. insertions = number of inserted lines as int
  75. lines = total number of lines changed as int, or deletions + insertions
  76. ``full-stat-dict``
  77. In addition to the items in the stat-dict, it features additional information::
  78. files = number of changed files as int"""
  79. __slots__ = ("total", "files")
  80. def __init__(self, total, files):
  81. self.total = total
  82. self.files = files
  83. @classmethod
  84. def _list_from_string(cls, repo, text):
  85. """Create a Stat object from output retrieved by git-diff.
  86. :return: git.Stat"""
  87. hsh = {'total': {'insertions': 0, 'deletions': 0, 'lines': 0, 'files': 0}, 'files': dict()}
  88. for line in text.splitlines():
  89. (raw_insertions, raw_deletions, filename) = line.split("\t")
  90. insertions = raw_insertions != '-' and int(raw_insertions) or 0
  91. deletions = raw_deletions != '-' and int(raw_deletions) or 0
  92. hsh['total']['insertions'] += insertions
  93. hsh['total']['deletions'] += deletions
  94. hsh['total']['lines'] += insertions + deletions
  95. hsh['total']['files'] += 1
  96. hsh['files'][filename.strip()] = {'insertions': insertions,
  97. 'deletions': deletions,
  98. 'lines': insertions + deletions}
  99. return Stats(hsh['total'], hsh['files'])
  100. class IndexFileSHA1Writer(object):
  101. """Wrapper around a file-like object that remembers the SHA1 of
  102. the data written to it. It will write a sha when the stream is closed
  103. or if the asked for explicitly usign write_sha.
  104. Only useful to the indexfile
  105. :note: Based on the dulwich project"""
  106. __slots__ = ("f", "sha1")
  107. def __init__(self, f):
  108. self.f = f
  109. self.sha1 = make_sha("")
  110. def write(self, data):
  111. self.sha1.update(data)
  112. return self.f.write(data)
  113. def write_sha(self):
  114. sha = self.sha1.digest()
  115. self.f.write(sha)
  116. return sha
  117. def close(self):
  118. sha = self.write_sha()
  119. self.f.close()
  120. return sha
  121. def tell(self):
  122. return self.f.tell()
  123. class LockFile(object):
  124. """Provides methods to obtain, check for, and release a file based lock which
  125. should be used to handle concurrent access to the same file.
  126. As we are a utility class to be derived from, we only use protected methods.
  127. Locks will automatically be released on destruction"""
  128. __slots__ = ("_file_path", "_owns_lock")
  129. def __init__(self, file_path):
  130. self._file_path = file_path
  131. self._owns_lock = False
  132. def __del__(self):
  133. self._release_lock()
  134. def _lock_file_path(self):
  135. """:return: Path to lockfile"""
  136. return "%s.lock" % (self._file_path)
  137. def _has_lock(self):
  138. """:return: True if we have a lock and if the lockfile still exists
  139. :raise AssertionError: if our lock-file does not exist"""
  140. if not self._owns_lock:
  141. return False
  142. return True
  143. def _obtain_lock_or_raise(self):
  144. """Create a lock file as flag for other instances, mark our instance as lock-holder
  145. :raise IOError: if a lock was already present or a lock file could not be written"""
  146. if self._has_lock():
  147. return
  148. lock_file = self._lock_file_path()
  149. if os.path.isfile(lock_file):
  150. raise IOError("Lock for file %r did already exist, delete %r in case the lock is illegal" % (self._file_path, lock_file))
  151. try:
  152. fd = os.open(lock_file, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0)
  153. os.close(fd)
  154. except OSError,e:
  155. raise IOError(str(e))
  156. self._owns_lock = True
  157. def _obtain_lock(self):
  158. """The default implementation will raise if a lock cannot be obtained.
  159. Subclasses may override this method to provide a different implementation"""
  160. return self._obtain_lock_or_raise()
  161. def _release_lock(self):
  162. """Release our lock if we have one"""
  163. if not self._has_lock():
  164. return
  165. # if someone removed our file beforhand, lets just flag this issue
  166. # instead of failing, to make it more usable.
  167. lfp = self._lock_file_path()
  168. try:
  169. # on bloody windows, the file needs write permissions to be removable.
  170. # Why ...
  171. if os.name == 'nt':
  172. os.chmod(lfp, 0777)
  173. # END handle win32
  174. os.remove(lfp)
  175. except OSError:
  176. pass
  177. self._owns_lock = False
  178. class BlockingLockFile(LockFile):
  179. """The lock file will block until a lock could be obtained, or fail after
  180. a specified timeout.
  181. :note: If the directory containing the lock was removed, an exception will
  182. be raised during the blocking period, preventing hangs as the lock
  183. can never be obtained."""
  184. __slots__ = ("_check_interval", "_max_block_time")
  185. def __init__(self, file_path, check_interval_s=0.3, max_block_time_s=sys.maxint):
  186. """Configure the instance
  187. :parm check_interval_s:
  188. Period of time to sleep until the lock is checked the next time.
  189. By default, it waits a nearly unlimited time
  190. :parm max_block_time_s: Maximum amount of seconds we may lock"""
  191. super(BlockingLockFile, self).__init__(file_path)
  192. self._check_interval = check_interval_s
  193. self._max_block_time = max_block_time_s
  194. def _obtain_lock(self):
  195. """This method blocks until it obtained the lock, or raises IOError if
  196. it ran out of time or if the parent directory was not available anymore.
  197. If this method returns, you are guranteed to own the lock"""
  198. starttime = time.time()
  199. maxtime = starttime + float(self._max_block_time)
  200. while True:
  201. try:
  202. super(BlockingLockFile, self)._obtain_lock()
  203. except IOError:
  204. # synity check: if the directory leading to the lockfile is not
  205. # readable anymore, raise an execption
  206. curtime = time.time()
  207. if not os.path.isdir(os.path.dirname(self._lock_file_path())):
  208. msg = "Directory containing the lockfile %r was not readable anymore after waiting %g seconds" % (self._lock_file_path(), curtime - starttime)
  209. raise IOError(msg)
  210. # END handle missing directory
  211. if curtime >= maxtime:
  212. msg = "Waited %g seconds for lock at %r" % ( maxtime - starttime, self._lock_file_path())
  213. raise IOError(msg)
  214. # END abort if we wait too long
  215. time.sleep(self._check_interval)
  216. else:
  217. break
  218. # END endless loop
  219. class IterableList(list):
  220. """
  221. List of iterable objects allowing to query an object by id or by named index::
  222. heads = repo.heads
  223. heads.master
  224. heads['master']
  225. heads[0]
  226. It requires an id_attribute name to be set which will be queried from its
  227. contained items to have a means for comparison.
  228. A prefix can be specified which is to be used in case the id returned by the
  229. items always contains a prefix that does not matter to the user, so it
  230. can be left out."""
  231. __slots__ = ('_id_attr', '_prefix')
  232. def __new__(cls, id_attr, prefix=''):
  233. return super(IterableList,cls).__new__(cls)
  234. def __init__(self, id_attr, prefix=''):
  235. self._id_attr = id_attr
  236. self._prefix = prefix
  237. def __getattr__(self, attr):
  238. attr = self._prefix + attr
  239. for item in self:
  240. if getattr(item, self._id_attr) == attr:
  241. return item
  242. # END for each item
  243. return list.__getattribute__(self, attr)
  244. def __getitem__(self, index):
  245. if isinstance(index, int):
  246. return list.__getitem__(self,index)
  247. try:
  248. return getattr(self, index)
  249. except AttributeError:
  250. raise IndexError( "No item found with id %r" % (self._prefix + index) )
  251. class Iterable(object):
  252. """Defines an interface for iterable items which is to assure a uniform
  253. way to retrieve and iterate items within the git repository"""
  254. __slots__ = tuple()
  255. _id_attribute_ = "attribute that most suitably identifies your instance"
  256. @classmethod
  257. def list_items(cls, repo, *args, **kwargs):
  258. """
  259. Find all items of this type - subclasses can specify args and kwargs differently.
  260. If no args are given, subclasses are obliged to return all items if no additional
  261. arguments arg given.
  262. :note: Favor the iter_items method as it will
  263. :return:list(Item,...) list of item instances"""
  264. out_list = IterableList( cls._id_attribute_ )
  265. out_list.extend(cls.iter_items(repo, *args, **kwargs))
  266. return out_list
  267. @classmethod
  268. def iter_items(cls, repo, *args, **kwargs):
  269. """For more information about the arguments, see list_items
  270. :return: iterator yielding Items"""
  271. raise NotImplementedError("To be implemented by Subclass")