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.
 
 
 
 
 
 

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