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.

69 lines
1.8 KiB

  1. import search
  2. import fmt.comments
  3. def postprocess(answer, keyword, options, request_options=None):
  4. answer = _answer_add_comments(answer, request_options=request_options)
  5. answer = _answer_filter_by_keyword(
  6. answer, keyword, options, request_options=request_options
  7. )
  8. return answer
  9. def _answer_add_comments(answer, request_options=None):
  10. if answer["format"] != "text+code":
  11. return answer
  12. topic = answer["topic"]
  13. if "filetype" in answer:
  14. filetype = answer["filetype"]
  15. else:
  16. filetype = "bash"
  17. if "/" in topic:
  18. filetype = topic.split("/", 1)[0]
  19. if filetype.startswith("q:"):
  20. filetype = filetype[2:]
  21. answer["answer"] = fmt.comments.beautify(
  22. answer["answer"], filetype, request_options
  23. )
  24. answer["format"] = "code"
  25. answer["filetype"] = filetype
  26. return answer
  27. def _answer_filter_by_keyword(answer, keyword, options, request_options=None):
  28. answer["answer"] = _filter_by_keyword(answer["answer"], keyword, options)
  29. return answer
  30. def _filter_by_keyword(answer, keyword, options):
  31. def _join_paragraphs(paragraphs):
  32. answer = "\n".join(paragraphs)
  33. return answer
  34. def _split_paragraphs(text):
  35. answer = []
  36. paragraph = ""
  37. if isinstance(text, bytes):
  38. text = text.decode("utf-8")
  39. for line in text.splitlines():
  40. if line == "":
  41. answer.append(paragraph)
  42. paragraph = ""
  43. else:
  44. paragraph += line + "\n"
  45. answer.append(paragraph)
  46. return answer
  47. paragraphs = [
  48. p
  49. for p in _split_paragraphs(answer)
  50. if search.match(p, keyword, options=options)
  51. ]
  52. if not paragraphs:
  53. return ""
  54. return _join_paragraphs(paragraphs)