searchcode_code.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """Searchcode (IT)
  3. """
  4. from json import loads
  5. from urllib.parse import urlencode
  6. # about
  7. about = {
  8. "website": 'https://searchcode.com/',
  9. "wikidata_id": None,
  10. "official_api_documentation": 'https://searchcode.com/api/',
  11. "use_official_api": True,
  12. "require_api_key": False,
  13. "results": 'JSON',
  14. }
  15. # engine dependent config
  16. categories = ['it']
  17. search_api = 'https://searchcode.com/api/codesearch_I/?'
  18. # special code-endings which are not recognised by the file ending
  19. code_endings = {'cs': 'c#', 'h': 'c', 'hpp': 'cpp', 'cxx': 'cpp'}
  20. # paging is broken in searchcode.com's API .. not sure it will ever been fixed
  21. # paging = True
  22. def request(query, params):
  23. args = urlencode(
  24. {
  25. 'q': query,
  26. # paging is broken in searchcode.com's API
  27. # 'p': params['pageno'] - 1,
  28. # 'per_page': 10,
  29. }
  30. )
  31. params['url'] = search_api + args
  32. logger.debug("query_url --> %s", params['url'])
  33. return params
  34. def response(resp):
  35. results = []
  36. search_results = loads(resp.text)
  37. # parse results
  38. for result in search_results.get('results', []):
  39. href = result['url']
  40. title = "" + result['name'] + " - " + result['filename']
  41. repo = result['repo']
  42. lines = {}
  43. for line, code in result['lines'].items():
  44. lines[int(line)] = code
  45. code_language = code_endings.get(
  46. result['filename'].split('.')[-1].lower(), result['filename'].split('.')[-1].lower()
  47. )
  48. # append result
  49. results.append(
  50. {
  51. 'url': href,
  52. 'title': title,
  53. 'content': '',
  54. 'repository': repo,
  55. 'codelines': sorted(lines.items()),
  56. 'code_language': code_language,
  57. 'template': 'code.html',
  58. }
  59. )
  60. # return results
  61. return results