Exemplo n.º 1
0
def ReadFile(filename, logger=None):
    """Read the contents of the file.

  An optional logger can be specified to emit messages to your favorite logging
  stream. If specified, then no exception is raised. This is external so that it
  can be used by third-party applications.

  Arguments:
    filename: (unicode) The name of the file.
    logger: (function) A function or lambda that takes a string and emits it.

  Returns:
    The contents of filename.

  Raises:
    IOError: raised if there was an error reading the file.
  """
    try:
        encoding = file_resources.FileEncoding(filename)

        # Preserves line endings.
        with py3compat.open_with_encoding(filename,
                                          mode='r',
                                          encoding=encoding,
                                          newline='') as fd:
            lines = fd.readlines()

        line_ending = file_resources.LineEnding(lines)
        source = '\n'.join(line.rstrip('\r\n') for line in lines) + '\n'
        return source, line_ending, encoding
    except IOError as err:  # pragma: no cover
        if logger:
            logger(err)
        raise
Exemplo n.º 2
0
 def test_line_ending_weighted(self):
   lines = [
       'spam\n',
       'spam\n',
       'spam\r',
       'spam\r\n',
   ]
   actual = file_resources.LineEnding(lines)
   self.assertEqual(actual, '\n')
Exemplo n.º 3
0
 def test_line_ending_combo(self):
   lines = ['spam\r\n', 'spam\r\n']
   actual = file_resources.LineEnding(lines)
   self.assertEqual(actual, '\r\n')
Exemplo n.º 4
0
 def test_line_ending_carriage_return(self):
   lines = ['spam\r', 'spam\r']
   actual = file_resources.LineEnding(lines)
   self.assertEqual(actual, '\r')