searchcode_code.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. """
  2. Searchcode (It)
  3. @website https://searchcode.com/
  4. @provide-api yes (https://searchcode.com/api/)
  5. @using-api yes
  6. @results JSON
  7. @stable yes
  8. @parse url, title, content
  9. """
  10. from urllib import urlencode
  11. from json import loads
  12. # engine dependent config
  13. categories = ['it']
  14. paging = True
  15. # search-url
  16. url = 'https://searchcode.com/'
  17. search_url = url + 'api/codesearch_I/?{query}&p={pageno}'
  18. # special code-endings which are not recognised by the file ending
  19. code_endings = {'cs': 'c#',
  20. 'h': 'c',
  21. 'hpp': 'cpp',
  22. 'cxx': 'cpp'}
  23. # do search-request
  24. def request(query, params):
  25. params['url'] = search_url.format(query=urlencode({'q': query}),
  26. pageno=params['pageno'] - 1)
  27. # Disable SSL verification
  28. # error: (60) SSL certificate problem: unable to get local issuer
  29. # certificate
  30. params['verify'] = False
  31. return params
  32. # get response from search-request
  33. def response(resp):
  34. results = []
  35. search_results = loads(resp.text)
  36. # parse results
  37. for result in search_results.get('results', []):
  38. href = result['url']
  39. title = "" + result['name'] + " - " + result['filename']
  40. repo = result['repo']
  41. lines = dict()
  42. for line, code in result['lines'].items():
  43. lines[int(line)] = code
  44. code_language = code_endings.get(
  45. result['filename'].split('.')[-1].lower(),
  46. result['filename'].split('.')[-1].lower())
  47. # append result
  48. results.append({'url': href,
  49. 'title': title,
  50. 'content': '',
  51. 'repository': repo,
  52. 'codelines': sorted(lines.items()),
  53. 'code_language': code_language,
  54. 'template': 'code.html'})
  55. # return results
  56. return results