<s> import os <EOL> from robot . errors import DataError <EOL> from robot . utils import binary_file_writer , file_writer , PY2 <EOL> from . filewriters import FileWriter <EOL> class DataFileWriter ( object ) : <EOL> """<STR_LIT>""" <EOL> def __init__ ( self , ** options ) : <EOL> """<STR_LIT>""" <EOL> self . _options = options <EOL> def write ( self , datafile ) : <EOL> """<STR_LIT>""" <EOL> with WritingContext ( datafile , ** self . _options ) as ctx : <EOL> FileWriter ( ctx ) . write ( datafile ) <EOL> class WritingContext ( object ) : <EOL> """<STR_LIT>""" <EOL> txt_format = '<STR_LIT>' <EOL> html_format = '<STR_LIT:html>' <EOL> tsv_format = '<STR_LIT>' <EOL> robot_format = '<STR_LIT>' <EOL> txt_column_count = <NUM_LIT:8> <EOL> html_column_count = <NUM_LIT:5> <EOL> tsv_column_count = <NUM_LIT:8> <EOL> _formats = [ txt_format , html_format , tsv_format , robot_format ] <EOL> def __init__ ( self , datafile , format = '<STR_LIT>' , output = None , pipe_separated = False , <EOL> txt_separating_spaces = <NUM_LIT:4> , line_separator = '<STR_LIT:\n>' ) : <EOL> """<STR_LIT>""" <EOL> self . datafile = datafile <EOL> self . pipe_separated = pipe_separated <EOL> self . line_separator = line_separator <EOL> self . _given_output = output <EOL> self . format = self . _validate_format ( format ) or self . _format_from_file ( ) <EOL> self . txt_separating_spaces = txt_separating_spaces <EOL> self . output = output <EOL> def __enter__ ( self ) : <EOL> if not self . output : <EOL> path = self . _output_path ( ) <EOL> if PY2 and self . format == self . tsv_format : <EOL> self . output = binary_file_writer ( path ) <EOL> else : <EOL> self . output = file_writer ( path , newline = self . line_separator ) <EOL> return self <EOL> def __exit__ ( self , * exc_info ) : <EOL> if self . _given_output is None : <EOL> self . output . close ( ) <EOL> def _validate_format ( self , format ) : <EOL> format = format . lower ( ) if format else '<STR_LIT>' <EOL> if format and format not in self . _formats : <EOL> raise DataError ( '<STR_LIT>' % format ) <EOL> return format <EOL> def _format_from_file ( self ) : <EOL> return self . _format_from_extension ( self . _source_from_file ( ) ) <EOL> def _format_from_extension ( self , path ) : <EOL> return os . path . splitext ( path ) [ <NUM_LIT:1> ] [ <NUM_LIT:1> : ] . lower ( ) <EOL> def _output_path ( self ) : <EOL> return '<STR_LIT>' % ( self . _base_name ( ) , self . format ) <EOL> def _base_name ( self ) : <EOL> return os . path . splitext ( self . _source_from_file ( ) ) [ <NUM_LIT:0> ] <EOL> def _source_from_file ( self ) : <EOL> return getattr ( self . datafile , '<STR_LIT>' , self . datafile . source ) </s>
