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.
 
 
 
 
 
 

499 lines
17 KiB

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