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