csv.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. #
  2. # SPDX-License-Identifier: Apache-2.0
  3. r"""
  4. =============
  5. CSV Formatter
  6. =============
  7. This formatter outputs the issues in a comma separated values format.
  8. :Example:
  9. .. code-block:: none
  10. filename,test_name,test_id,issue_severity,issue_confidence,issue_cwe,
  11. issue_text,line_number,line_range,more_info
  12. examples/yaml_load.py,blacklist_calls,B301,MEDIUM,HIGH,
  13. https://cwe.mitre.org/data/definitions/20.html,"Use of unsafe yaml
  14. load. Allows instantiation of arbitrary objects. Consider yaml.safe_load().
  15. ",5,[5],https://bandit.readthedocs.io/en/latest/
  16. .. versionadded:: 0.11.0
  17. .. versionchanged:: 1.5.0
  18. New field `more_info` added to output
  19. .. versionchanged:: 1.7.3
  20. New field `CWE` added to output
  21. """
  22. # Necessary for this formatter to work when imported on Python 2. Importing
  23. # the standard library's csv module conflicts with the name of this module.
  24. import csv
  25. import logging
  26. import sys
  27. from bandit.core import docs_utils
  28. LOG = logging.getLogger(__name__)
  29. def report(manager, fileobj, sev_level, conf_level, lines=-1):
  30. """Prints issues in CSV format
  31. :param manager: the bandit manager object
  32. :param fileobj: The output file object, which may be sys.stdout
  33. :param sev_level: Filtering severity level
  34. :param conf_level: Filtering confidence level
  35. :param lines: Number of lines to report, -1 for all
  36. """
  37. results = manager.get_issue_list(
  38. sev_level=sev_level, conf_level=conf_level
  39. )
  40. with fileobj:
  41. fieldnames = [
  42. "filename",
  43. "test_name",
  44. "test_id",
  45. "issue_severity",
  46. "issue_confidence",
  47. "issue_cwe",
  48. "issue_text",
  49. "line_number",
  50. "col_offset",
  51. "end_col_offset",
  52. "line_range",
  53. "more_info",
  54. ]
  55. writer = csv.DictWriter(
  56. fileobj, fieldnames=fieldnames, extrasaction="ignore"
  57. )
  58. writer.writeheader()
  59. for result in results:
  60. r = result.as_dict(with_code=False)
  61. r["issue_cwe"] = r["issue_cwe"]["link"]
  62. r["more_info"] = docs_utils.get_url(r["test_id"])
  63. writer.writerow(r)
  64. if fileobj.name != sys.stdout.name:
  65. LOG.info("CSV output written to file: %s", fileobj.name)