A semantic search engine for source code https://bitshift.benkurtovic.com/
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.
 
 
 
 
 
 

349 lines
12 KiB

  1. """
  2. :synopsis: Contains a singleton GitIndexer class, which clones and indexes git
  3. repositories.
  4. """
  5. from datetime import datetime
  6. import logging
  7. import os
  8. import Queue
  9. import shutil
  10. import string
  11. import time
  12. import threading
  13. from bs4 import UnicodeDammit
  14. import git
  15. from ..database import Database
  16. from ..parser import parse, UnsupportedFileError
  17. from ..codelet import Codelet
  18. GIT_CLONE_DIR = "/tmp/bitshift"
  19. THREAD_QUEUE_SLEEP = 0.5
  20. MAX_INDEX_QUEUE_SIZE = 10
  21. class GitRepository(object):
  22. """
  23. A representation of a Git repository's metadata.
  24. :ivar url: (str) The repository's url.
  25. :ivar name: (str) The name of the repository.
  26. :ivar framework_name: (str) The name of the online Git framework that the
  27. repository belongs to (eg, GitHub, BitBucket).
  28. :ivar rank: (float) The rank of the repository, as assigned by
  29. :class:`crawler.GitHubCrawler`.
  30. :ivar path: (str) The repository's on-disk directory path.
  31. :ivar repo: (git.Repo) A git.Repo representation of the repository.
  32. """
  33. def __init__(self, url, name, framework_name, rank):
  34. """
  35. Create a GitRepository instance.
  36. :param url: see :attr:`GitRepository.url`
  37. :param name: see :attr:`GitRepository.name`
  38. :param framework_name: see :attr:`GitRepository.framework_name`
  39. :param rank: see :attr:`GitRepository.rank`
  40. :type url: str
  41. :type name: str
  42. :type framework_name: str
  43. :type rank: float
  44. """
  45. self.url = url
  46. self.name = name
  47. self.framework_name = framework_name
  48. self.rank = rank
  49. dirname = name.replace("/", "-") + "-" + str(int(time.time()))
  50. self.path = os.path.join(GIT_CLONE_DIR, dirname)
  51. self.repo = None
  52. class GitIndexer(threading.Thread):
  53. """
  54. A singleton Git repository indexer.
  55. :class:`GitIndexer` indexes the repositories cloned by the
  56. :class:`_GitCloner` singleton.
  57. :ivar index_queue: (:class:`Queue.Queue`) A queue containing
  58. :class:`GitRepository` objects for every new repository succesfully
  59. cloned by :class:`_GitCloner`, which are to be indexed.
  60. :ivar git_cloner: (:class:`_GitCloner`) The corresponding repository
  61. cloner, which feeds :class:`GitIndexer`.
  62. :ivar _logger: (:class:`logging.Logger`) A class-specific logger object.
  63. """
  64. def __init__(self, clone_queue, run_event):
  65. """
  66. Create an instance of the singleton `GitIndexer`.
  67. :param clone_queue: see :attr:`self.index_queue`
  68. :type index_queue: see :attr:`self.index_queue`
  69. """
  70. self.index_queue = Queue.Queue(maxsize=MAX_INDEX_QUEUE_SIZE)
  71. self.run_event = run_event
  72. self.git_cloner = _GitCloner(clone_queue, self.index_queue, run_event)
  73. self.git_cloner.start()
  74. self.database = Database()
  75. self._logger = logging.getLogger("%s.%s" %
  76. (__name__, self.__class__.__name__))
  77. self._logger.info("Starting.")
  78. if not os.path.exists(GIT_CLONE_DIR):
  79. os.makedirs(GIT_CLONE_DIR)
  80. super(GitIndexer, self).__init__(name=self.__class__.__name__)
  81. def run(self):
  82. """
  83. Retrieve metadata about newly cloned repositories and index them.
  84. Blocks until new repositories appear in :attr:`self.index_queue`, then
  85. retrieves one, and attempts indexing it. Should any errors occur, the
  86. new repository will be discarded and the indexer will index the next in
  87. the queue.
  88. """
  89. while True:
  90. while self.index_queue.empty() and self.run_event.is_set():
  91. time.sleep(THREAD_QUEUE_SLEEP)
  92. if not self.run_event.is_set():
  93. break
  94. repo = self.index_queue.get()
  95. self.index_queue.task_done()
  96. self._index_repository(repo)
  97. def _index_repository(self, repo):
  98. """
  99. Clone and index (create and insert Codeletes for) a Git repository.
  100. `git clone` the Git repository located at **repo.url**, call
  101. `_insert_repository_codelets()`, then remove said repository.
  102. :param repo: The metadata of the repository to be indexed.
  103. :type repo: :class:`GitRepository`
  104. """
  105. self._logger.info(u"Indexing repo: %s", repo.name)
  106. try:
  107. self._insert_repository_codelets(repo)
  108. except Exception:
  109. self._logger.exception("Exception raised while indexing:")
  110. finally:
  111. if os.path.isdir(repo.path):
  112. shutil.rmtree(repo.path)
  113. def _insert_repository_codelets(self, repo):
  114. """
  115. Create and insert a Codelet for the files inside a Git repository.
  116. Create a new Codelet, and insert it into the Database singleton, for
  117. every file inside the current working directory's default branch
  118. (usually *master*).
  119. :param repo_url: The metadata of the repository to be indexed.
  120. :type repo_url: :class:`GitRepository`
  121. """
  122. file_meta = self._get_file_metadata(repo.repo)
  123. if file_meta is None:
  124. return
  125. for filename, data in file_meta.iteritems():
  126. name = ("%s: %s" % (repo.name, filename)).encode("utf8")
  127. authors = [(author, None) for author in data["authors"]]
  128. encoded_source = data["blob"].data_stream.read()
  129. source = UnicodeDammit(encoded_source).unicode_markup
  130. url = self._generate_file_url(filename, repo)
  131. codelet = Codelet(name, source, filename, None, authors, url,
  132. data["time_created"], data["time_last_modified"],
  133. repo.rank)
  134. self._logger.debug("Indexing file: %s", codelet.name)
  135. try:
  136. parse(codelet)
  137. except UnsupportedFileError:
  138. continue
  139. except Exception:
  140. self._logger.exception("Exception raised while parsing:")
  141. self.database.insert(codelet)
  142. def _generate_file_url(self, filename, repo):
  143. """
  144. Return a url for a filename from a Git wrapper framework.
  145. :param filename: The path of the file.
  146. :param repo: The git repo.
  147. :type filename: str
  148. :type repo: :class:`GitRepository`
  149. :return: The file's full url on the given framework, if successfully
  150. derived.
  151. :rtype: str, or None
  152. """
  153. if repo.framework_name == "GitHub":
  154. default_branch = repo.repo.active_branch.name
  155. parts = [repo.url, "blob", default_branch, filename]
  156. elif repo.framework_name == "Bitbucket":
  157. try:
  158. commit_hash = repo.repo.head.commit.hexsha
  159. except ValueError: # No commits
  160. return None
  161. parts = [repo.url, "src", commit_hash, filename]
  162. return "/".join(s.strip("/") for s in parts)
  163. def _get_file_metadata(self, repo):
  164. """
  165. Return a dictionary containing every valuable tracked file's metadata.
  166. :return: A dictionary with author names, time of creation, and time of
  167. last modification for every filename key.
  168. .. code-block:: python
  169. sample_returned_dict = {
  170. "my_file" : {
  171. "blob": (GitPython Blob) <object>,
  172. "authors" : (str list) ["author1", "author2"],
  173. "time_created" : (`datetime.datetime`) <object>,
  174. "time_last_modified" : (`datetime.datetime`) <object>
  175. }
  176. }
  177. :rtype: dictionary of dictionaries
  178. """
  179. try:
  180. tree = repo.head.commit.tree
  181. except ValueError: # No commits
  182. return {}
  183. files = {}
  184. self._logger.debug("Building file metadata")
  185. for item in tree.traverse():
  186. if item.type != "blob" or not self._is_ascii(item.data_stream):
  187. continue
  188. log = repo.git.log("--follow", '--format=%an %ct', "--", item.path)
  189. lines = log.splitlines()
  190. authors = {line.rsplit(" ", 1)[0].decode("utf8") for line in lines}
  191. last_mod = int(lines[0].rsplit(" ", 1)[1])
  192. created = int(lines[-1].rsplit(" ", 1)[1])
  193. files[item.path] = {
  194. "blob": item,
  195. "authors" : authors,
  196. "time_last_modified": datetime.fromtimestamp(last_mod),
  197. "time_created": datetime.fromtimestamp(created)
  198. }
  199. return files
  200. def _is_ascii(self, source):
  201. """
  202. Heuristically determine whether a file is ASCII text or binary.
  203. If a portion of the file contains null bytes, or the percentage of bytes
  204. that aren't ASCII is greater than 30%, then the file is concluded to be
  205. binary. This heuristic is used by the `file` utility, Perl's inbuilt `-T`
  206. operator, and is the de-facto method for in : passdetermining whether a
  207. file is ASCII.
  208. :param source: The file object to test.
  209. :type source: `file`
  210. :return: Whether the file is probably ASCII.
  211. :rtype: Boolean
  212. """
  213. file_snippet = source.read(512)
  214. if not file_snippet:
  215. return True
  216. ascii_characters = "".join(map(chr, range(32, 127)) +
  217. list("\n\r\t\b"))
  218. null_trans = string.maketrans("", "")
  219. if "\0" in file_snippet:
  220. return False
  221. non_ascii = file_snippet.translate(null_trans, ascii_characters)
  222. return not float(len(non_ascii)) / len(file_snippet) > 0.30
  223. class _GitCloner(threading.Thread):
  224. """
  225. A singleton Git repository cloner.
  226. Clones the repositories crawled by :class:`crawler.GitHubCrawler` for
  227. :class:`GitIndexer` to index.
  228. :ivar clone_queue: (:class:`Queue.Queue`) see
  229. :attr:`crawler.GitHubCrawler.clone_queue`.
  230. :ivar index_queue: (:class:`Queue.Queue`) see
  231. :attr:`GitIndexer.index_queue`.
  232. :ivar _logger: (:class:`logging.Logger`) A class-specific logger object.
  233. """
  234. def __init__(self, clone_queue, index_queue, run_event):
  235. """
  236. Create an instance of the singleton :class:`_GitCloner`.
  237. :param clone_queue: see :attr:`self.clone_queue`
  238. :param index_queue: see :attr:`self.index_queue`
  239. :type clone_queue: see :attr:`self.clone_queue`
  240. :type index_queue: see :attr:`self.index_queue`
  241. """
  242. self.clone_queue = clone_queue
  243. self.index_queue = index_queue
  244. self.run_event = run_event
  245. self._logger = logging.getLogger("%s.%s" %
  246. (__name__, self.__class__.__name__))
  247. self._logger.info("Starting.")
  248. super(_GitCloner, self).__init__(name=self.__class__.__name__)
  249. def run(self):
  250. """
  251. Retrieve metadata about newly crawled repositories and clone them.
  252. Blocks until new :class:`GitRepository` appear in
  253. :attr:`self.clone_queue`, then attempts cloning them. If
  254. succcessful, the cloned repository is added to :attr:`self.index_queue`
  255. for the `GitIndexer` to clone; otherwise, it is discarded.
  256. """
  257. while True:
  258. while self.clone_queue.empty() and self.run_event.is_set():
  259. time.sleep(THREAD_QUEUE_SLEEP)
  260. if not self.run_event.is_set():
  261. break
  262. repo = self.clone_queue.get()
  263. self.clone_queue.task_done()
  264. try:
  265. self._clone_repository(repo)
  266. except Exception:
  267. self._logger.exception("Exception raised while cloning:")
  268. def _clone_repository(self, repo):
  269. """
  270. Attempt cloning a Git repository.
  271. :param repo: Metadata about the repository to clone.
  272. :type repo: :class:`GitRepository`
  273. """
  274. self._logger.info("Cloning repo: %s", repo.url)
  275. repo.repo = git.Repo.clone_from(repo.url, to_path=repo.path, bare=True,
  276. single_branch=True)
  277. while self.index_queue.full() and self.run_event.is_set():
  278. time.sleep(THREAD_QUEUE_SLEEP)
  279. if self.run_event.is_set():
  280. self.index_queue.put(repo)