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.
 
 
 
 
 
 

492 lines
17 KiB

  1. """
  2. :synopsis: Contains a singleton GitIndexer class, which clones and indexes git
  3. repositories.
  4. """
  5. 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. import bs4
  15. from ..database import Database
  16. from ..parser import parse, UnsupportedFileError
  17. from ..languages import LANGS
  18. from ..codelet import Codelet
  19. GIT_CLONE_DIR = "/tmp/bitshift"
  20. THREAD_QUEUE_SLEEP = 0.5
  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 dirname: (str) The repository's on-disk directory name.
  31. """
  32. def __init__(self, url, name, framework_name, rank):
  33. """
  34. Create a GitRepository instance.
  35. :param url: see :attr:`GitRepository.url`
  36. :param name: see :attr:`GitRepository.name`
  37. :param framework_name: see :attr:`GitRepository.framework_name`
  38. :param rank: see :attr:`GitRepository.rank`
  39. :type url: str
  40. :type name: str
  41. :type framework_name: str
  42. :type rank: float
  43. """
  44. self.url = url
  45. self.name = name
  46. self.framework_name = framework_name
  47. self.rank = rank
  48. self.dirname = name.replace("-", "--").replace("/", "-")
  49. class GitIndexer(threading.Thread):
  50. """
  51. A singleton Git repository indexer.
  52. :class:`GitIndexer` indexes the repositories cloned by the
  53. :class:`_GitCloner` singleton.
  54. :ivar index_queue: (:class:`Queue.Queue`) A queue containing
  55. :class:`GitRepository` objects for every new repository succesfully
  56. cloned by :class:`_GitCloner`, which are to be indexed.
  57. :ivar git_cloner: (:class:`_GitCloner`) The corresponding repository cloner,
  58. which feeds :class:`GitIndexer`.
  59. :ivar _logger: (:class:`logging.Logger`) A class-specific logger object.
  60. """
  61. def __init__(self, clone_queue, run_event):
  62. """
  63. Create an instance of the singleton `GitIndexer`.
  64. :param clone_queue: see :attr:`self.index_queue`
  65. :type index_queue: see :attr:`self.index_queue`
  66. """
  67. MAX_INDEX_QUEUE_SIZE = 10
  68. self.index_queue = Queue.Queue(maxsize=MAX_INDEX_QUEUE_SIZE)
  69. self.run_event = run_event
  70. self.git_cloner = _GitCloner(clone_queue, self.index_queue, run_event)
  71. self.git_cloner.start()
  72. self.database = Database()
  73. self._logger = logging.getLogger("%s.%s" %
  74. (__name__, self.__class__.__name__))
  75. self._logger.info("Starting.")
  76. if not os.path.exists(GIT_CLONE_DIR):
  77. os.makedirs(GIT_CLONE_DIR)
  78. super(GitIndexer, self).__init__(name=self.__class__.__name__)
  79. def run(self):
  80. """
  81. Retrieve metadata about newly cloned repositories and index them.
  82. Blocks until new repositories appear in :attr:`self.index_queue`, then
  83. retrieves one, and attempts indexing it. Should any errors occur, the
  84. new repository will be discarded and the indexer will index the next in
  85. the queue.
  86. """
  87. while self.run_event.is_set():
  88. while self.index_queue.empty():
  89. time.sleep(THREAD_QUEUE_SLEEP)
  90. repo = self.index_queue.get()
  91. self.index_queue.task_done()
  92. self._index_repository(repo)
  93. def _index_repository(self, repo):
  94. """
  95. Clone and index (create and insert Codeletes for) a Git repository.
  96. `git clone` the Git repository located at **repo.url**, call
  97. `_insert_repository_codelets()`, then remove said repository.
  98. :param repo_url: The metadata of the repository to be indexed.
  99. :type repo_url: :class:`GitRepository`
  100. """
  101. self._logger.info(u"Indexing repo: %s", repo.name)
  102. with _ChangeDir("%s/%s" % (GIT_CLONE_DIR, repo.dirname)):
  103. try:
  104. self._insert_repository_codelets(repo)
  105. except Exception:
  106. self._logger.exception("Exception raised while indexing:")
  107. finally:
  108. if os.path.isdir("%s/%s" % (GIT_CLONE_DIR, repo.dirname)):
  109. shutil.rmtree("%s/%s" % (GIT_CLONE_DIR, repo.dirname))
  110. def _insert_repository_codelets(self, repo):
  111. """
  112. Create and insert a Codelet for the files inside a Git repository.
  113. Create a new Codelet, and insert it into the Database singleton, for
  114. every file inside the current working directory's default branch
  115. (usually *master*).
  116. :param repo_url: The metadata of the repository to be indexed.
  117. :type repo_url: :class:`GitRepository`
  118. """
  119. commits_meta = self._get_commits_metadata()
  120. if commits_meta is None:
  121. return
  122. for filename in commits_meta.keys():
  123. try:
  124. with open(filename) as source_file:
  125. source = self._decode(source_file.read())
  126. if source is None:
  127. continue
  128. except IOError:
  129. continue
  130. authors = [(self._decode(author), None) for author in
  131. commits_meta[filename]["authors"]]
  132. url = self._generate_file_url(filename, repo.url, repo.framework_name)
  133. codelet = Codelet("%s: %s" % (repo.name, filename), source,
  134. filename, None, authors, url,
  135. commits_meta[filename]["time_created"],
  136. commits_meta[filename]["time_last_modified"],
  137. repo.rank)
  138. self._logger.debug("Indexing file: %s", codelet.name)
  139. try:
  140. parse(codelet)
  141. except UnsupportedFileError:
  142. continue
  143. self.database.insert(codelet)
  144. def _generate_file_url(self, filename, repo_url, framework_name):
  145. """
  146. Return a url for a filename from a Git wrapper framework.
  147. :param filename: The path of the file.
  148. :param repo_url: The url of the file's parent repository.
  149. :param framework_name: The name of the framework the repository is from.
  150. :type filename: str
  151. :type repo_url: str
  152. :type framework_name: str
  153. :return: The file's full url on the given framework, if successfully
  154. derived.
  155. :rtype: str, or None
  156. .. warning::
  157. Various Git subprocesses will occasionally fail, and, seeing as the
  158. information they provide is a crucial component of some repository
  159. file urls, None may be returned.
  160. """
  161. try:
  162. if framework_name == "GitHub":
  163. default_branch = subprocess.check_output("git branch"
  164. " --no-color", shell=True)[2:-1]
  165. parts = [repo_url, "blob", default_branch, filename]
  166. elif framework_name == "Bitbucket":
  167. commit_hash = subprocess.check_output("git rev-parse HEAD",
  168. shell=True).replace("\n", "")
  169. parts = [repo_url, "src", commit_hash, filename]
  170. return "/".join(s.strip("/") for s in parts)
  171. except subprocess.CalledProcessError:
  172. return None
  173. def _get_git_commits(self):
  174. """
  175. Return the current working directory's formatted commit data.
  176. Uses `git log` to generate metadata about every single file in the
  177. repository's commit history.
  178. :return: The author, timestamp, and names of all modified files of every
  179. commit.
  180. .. code-block:: python
  181. sample_returned_array = [
  182. {
  183. "author" : (str) "author"
  184. "timestamp" : (`datetime.datetime`) <object>,
  185. "filenames" : (str array) ["file1", "file2"]
  186. }
  187. ]
  188. :rtype: array of dictionaries
  189. """
  190. git_log = subprocess.check_output(("git --no-pager log --name-only"
  191. " --pretty=format:'%n%n%an%n%at' -z"), shell=True)
  192. commits = []
  193. for commit in git_log.split("\n\n"):
  194. fields = commit.split("\n")
  195. if len(fields) > 2:
  196. commits.append({
  197. "author" : fields[0],
  198. "timestamp" : datetime.datetime.fromtimestamp(int(fields[1])),
  199. "filenames" : fields[2].split("\x00")[:-2]
  200. })
  201. return commits
  202. def _get_tracked_files(self):
  203. """
  204. Return a list of the filenames of all valuable files in the Git repository.
  205. Get a list of the filenames of the non-binary (Perl heuristics used for
  206. filetype identification) files currently inside the current working
  207. directory's Git repository. Then, weed out any boilerplate/non-code files
  208. that match the regex rules in GIT_IGNORE_FILES.
  209. :return: The filenames of all index-worthy non-binary files.
  210. :rtype: str array
  211. """
  212. files = []
  213. for dirname, subdir_names, filenames in os.walk("."):
  214. for filename in filenames:
  215. path = os.path.join(dirname, filename)
  216. if self._is_ascii(path):
  217. files.append(path[2:])
  218. return files
  219. def _get_commits_metadata(self):
  220. """
  221. Return a dictionary containing every valuable tracked file's metadata.
  222. :return: A dictionary with author names, time of creation, and time of last
  223. modification for every filename key.
  224. .. code-block:: python
  225. sample_returned_dict = {
  226. "my_file" : {
  227. "authors" : (str array) ["author1", "author2"],
  228. "time_created" : (`datetime.datetime`) <object>,
  229. "time_last_modified" : (`datetime.datetime`) <object>
  230. }
  231. }
  232. :rtype: dictionary of dictionaries
  233. """
  234. commits = self._get_git_commits()
  235. tracked_files = self._get_tracked_files()
  236. files_meta = {}
  237. for commit in commits:
  238. for filename in commit["filenames"]:
  239. if filename not in tracked_files:
  240. continue
  241. if filename not in files_meta.keys():
  242. files_meta[filename] = {
  243. "authors" : [commit["author"]],
  244. "time_last_modified" : commit["timestamp"],
  245. "time_created" : commit["timestamp"]
  246. }
  247. else:
  248. if commit["author"] not in files_meta[filename]["authors"]:
  249. files_meta[filename]["authors"].append(commit["author"])
  250. files_meta[filename]["time_created"] = commit["timestamp"]
  251. return files_meta
  252. def _decode(self, raw):
  253. """
  254. Return a decoded a raw string.
  255. :param raw: The string to string.
  256. :type raw: (str)
  257. :return: If the original encoding is successfully inferenced, return the
  258. decoded string.
  259. :rtype: str, or None
  260. .. warning::
  261. The raw string's original encoding is identified by heuristics which
  262. can, and occasionally will, fail. Decoding will then fail, and None
  263. will be returned.
  264. """
  265. try:
  266. encoding = bs4.BeautifulSoup(raw).original_encoding
  267. return raw.decode(encoding) if encoding is not None else None
  268. except (LookupError, UnicodeDecodeError, UserWarning) as exception:
  269. return None
  270. def _is_ascii(self, filename):
  271. """
  272. Heuristically determine whether a file is ASCII text or binary.
  273. If a portion of the file contains null bytes, or the percentage of bytes
  274. that aren't ASCII is greater than 30%, then the file is concluded to be
  275. binary. This heuristic is used by the `file` utility, Perl's inbuilt `-T`
  276. operator, and is the de-facto method for in : passdetermining whether a
  277. file is ASCII.
  278. :param filename: The path of the file to test.
  279. :type filename: str
  280. :return: Whether the file is probably ASCII.
  281. :rtype: Boolean
  282. """
  283. try:
  284. with open(filename) as source:
  285. file_snippet = source.read(512)
  286. if not file_snippet:
  287. return True
  288. ascii_characters = "".join(map(chr, range(32, 127)) +
  289. list("\n\r\t\b"))
  290. null_trans = string.maketrans("", "")
  291. if "\0" in file_snippet:
  292. return False
  293. non_ascii = file_snippet.translate(null_trans, ascii_characters)
  294. return not float(len(non_ascii)) / len(file_snippet) > 0.30
  295. except IOError:
  296. return False
  297. class _GitCloner(threading.Thread):
  298. """
  299. A singleton Git repository cloner.
  300. Clones the repositories crawled by :class:`crawler.GitHubCrawler` for
  301. :class:`GitIndexer` to index.
  302. :ivar clone_queue: (:class:`Queue.Queue`) see
  303. :attr:`crawler.GitHubCrawler.clone_queue`.
  304. :ivar index_queue: (:class:`Queue.Queue`) see
  305. :attr:`GitIndexer.index_queue`.
  306. :ivar _logger: (:class:`logging.Logger`) A class-specific logger object.
  307. """
  308. def __init__(self, clone_queue, index_queue, run_event):
  309. """
  310. Create an instance of the singleton :class:`_GitCloner`.
  311. :param clone_queue: see :attr:`self.clone_queue`
  312. :param index_queue: see :attr:`self.index_queue`
  313. :type clone_queue: see :attr:`self.clone_queue`
  314. :type index_queue: see :attr:`self.index_queue`
  315. """
  316. self.clone_queue = clone_queue
  317. self.index_queue = index_queue
  318. self.run_event = run_event
  319. self._logger = logging.getLogger("%s.%s" %
  320. (__name__, self.__class__.__name__))
  321. self._logger.info("Starting.")
  322. super(_GitCloner, self).__init__(name=self.__class__.__name__)
  323. def run(self):
  324. """
  325. Retrieve metadata about newly crawled repositories and clone them.
  326. Blocks until new :class:`GitRepository` appear in
  327. :attr:`self.clone_queue`, then attempts cloning them. If
  328. succcessful, the cloned repository is added to :attr:`self.index_queue`
  329. for the `GitIndexer` to clone; otherwise, it is discarded.
  330. """
  331. while self.run_event.is_set():
  332. while self.clone_queue.empty():
  333. time.sleep(THREAD_QUEUE_SLEEP)
  334. repo = self.clone_queue.get()
  335. self.clone_queue.task_done()
  336. try:
  337. self._clone_repository(repo)
  338. except Exception:
  339. pass
  340. def _clone_repository(self, repo):
  341. """
  342. Attempt cloning a Git repository.
  343. :param repo: Metadata about the repository to clone.
  344. :type repo: :class:`GitRepository`
  345. """
  346. GIT_CLONE_TIMEOUT = 500
  347. queue_percent_full = (float(self.index_queue.qsize()) /
  348. self.index_queue.maxsize) * 100
  349. command = ["perl", "-e", "alarm shift @ARGV; exec @ARGV",
  350. str(GIT_CLONE_TIMEOUT), "git", "clone", "--single-branch",
  351. repo.url, GIT_CLONE_DIR + "/" + repo.dirname]
  352. if subprocess.call(command) != 0:
  353. subprocess.call(["pkill", "-f", "git"]) # This makes Ben K upset
  354. if os.path.isdir("%s/%s" % (GIT_CLONE_DIR, repo.dirname)):
  355. shutil.rmtree("%s/%s" % (GIT_CLONE_DIR, repo.dirname))
  356. return
  357. while self.index_queue.full():
  358. time.sleep(THREAD_QUEUE_SLEEP)
  359. self.index_queue.put(repo)
  360. class _ChangeDir(object):
  361. """
  362. A wrapper class for os.chdir(), to map onto `with` and handle exceptions.
  363. :ivar new_path: (str) The path to change the current directory to.
  364. :ivar old_path: (str) The path of the directory to return to.
  365. """
  366. def __init__(self, new_path):
  367. """
  368. Create a _ChangeDir instance.
  369. :param new_path: The directory to enter.
  370. :type new_path: str
  371. """
  372. self.new_path = new_path
  373. def __enter__(self):
  374. """
  375. Change the current working-directory to **new_path**.
  376. """
  377. self.old_path = os.getcwd()
  378. os.chdir(self.new_path)
  379. def __exit__(self, *exception):
  380. """
  381. Change the current working-directory to **old_path**.
  382. :param exception: Various exception arguments passed by `with`.
  383. :type exception: varargs
  384. """
  385. os.chdir(self.old_path)