Beispiel #1
0
class FileNameDecoder(Decoder):
    """
    Parses a CWR filename to create a FileTag instance. It is meant to take
    care of the old and the new naming conventions, and so it will require one
    grammar rule for each.

    If the filename does not conform any of the two conventions, then an empty
    FileTag will be returned.
    """

    def __init__(self, grammar_old, grammar_new):
        super(FileNameDecoder, self).__init__()

        self._filename_decoder_old = GrammarDecoder(grammar_old)
        self._filename_decoder_new = GrammarDecoder(grammar_new)

    def decode(self, file_name):
        """
        Parses the filename, creating a FileTag from it.

        It will try both the old and the new conventions, if the filename does
        not conform any of them, then an empty FileTag will be returned.

        :param file_name: filename to parse
        :return: a FileTag instance
        """
        try:
            file_tag = self._filename_decoder_new.decode(file_name)
        except:
            try:
                file_tag = self._filename_decoder_old.decode(file_name)
            except:
                file_tag = FileTag(0, 0, '', '', '')

        return file_tag
Beispiel #2
0
class FileDecoder(Decoder):
    """
    Parses a CWR file, both its contents and the file name, to create a CWRFile
     instance.

    As the CWRFile contains a FileTag, this decoder will also try to decode the
    file's name.

    For this it will use a second decoder, which will take care of the filename.
    """

    def __init__(self, grammar, filename_decoder):
        super(FileDecoder, self).__init__()

        # Logger
        self._logger = logging.getLogger(__name__)

        self._filename_decoder = filename_decoder
        self._file_decoder = GrammarDecoder(grammar)

    def decode(self, data):
        """
        Parses the file, creating a CWRFile from it.

        It requires a dictionary with two values:
        - filename, containing the filename
        - contents, containing the file contents

        :param data: dictionary with the data to parse
        :return: a CWRFile instance
        """
        file_name = self._filename_decoder.decode(data['filename'])

        file_data = data['contents']
        i = 0
        max_size = len(file_data)
        while file_data[i:i + 1] != 'H' and i < max_size:
            i += 1
        if i > 0:
            data['contents'] = file_data[i:]

        transmission = self._file_decoder.decode(data['contents'])[0]

        return CWRFile(file_name, transmission)