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.
 
 
 
 
 
 

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