utils.py 892 B

1234567891011121314151617181920212223
  1. # Copyright (c) 2016 Rackspace, Inc.
  2. #
  3. # SPDX-License-Identifier: Apache-2.0
  4. """Utility functions for formatting plugins for Bandit."""
  5. import io
  6. def wrap_file_object(fileobj):
  7. """Handle differences in Python 2 and 3 around writing bytes."""
  8. # If it's not an instance of IOBase, we're probably using Python 2 and
  9. # that is less finnicky about writing text versus bytes to a file.
  10. if not isinstance(fileobj, io.IOBase):
  11. return fileobj
  12. # At this point we're using Python 3 and that will mangle text written to
  13. # a file written in bytes mode. So, let's check if the file can handle
  14. # text as opposed to bytes.
  15. if isinstance(fileobj, io.TextIOBase):
  16. return fileobj
  17. # Finally, we've determined that the fileobj passed in cannot handle text,
  18. # so we use TextIOWrapper to handle the conversion for us.
  19. return io.TextIOWrapper(fileobj)