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.
 
 
 
 
 
 

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