Source

mdhub / mdhub / commands / __init__.py

Full commit
# -*- coding: utf-8 -*-

"""
Commands/Transformations implementation.
"""

import logging
import copy
import pymarc
from mdhub import util

FORMAT = '%(asctime)s %(name)-12s %(levelname)-8s %(funcName)-10s %(message)s'
log = logging.getLogger('mdhub.commands')
logging.basicConfig(level=logging.INFO,
    format=FORMAT, datefmt='%m-%d %H:%M')

COMMAND_MAP = {} # forward declaration

def command_factory(name, **kwargs):
    """
    Lookup and create the appropriate command object.
    All available commands should be listed in ``COMMAND_MAP``.
    """
    command_object = COMMAND_MAP[name](name, **kwargs)
    return command_object

class Command(object):
    """
    Command superclass.
    """
    def __init__(self, name, **kwargs):
        self.name = name
        self.argmap = kwargs

    def __repr__(self):
        return u'<{0} {1}>'.format(self.name, self.argmap.items())

    def execute(self, bag):
        """
        Stub implementation of execute()
        """
        log.debug("Executing {0} on bag: {1}".format(self.name, bag))
        return bag

class Noop(Command):
    """
    An example noop command. Just some kind of identity function.
    """
    pass

class Copyall(Command):
    """
    Copy all tags/field into our own MARC record.
    """
    def execute(self, bag):
        if bag['type'] == 'marc':
            bag['marc'] = copy.deepcopy(bag['original'])
            log.debug("Created deep copy of original MARC record.")
        else:
            log.error("Don't know how to copyall on non-MARC input.")
            raise NotImplementedError
        return bag

class Copy(Command):
    """
    Copy a ``src`` field value into a ``dst`` field value.
    """
    def execute(self, bag):
        if bag['type'] == 'marc':
            src, dst = self.argmap['src'], self.argmap['dst']
            fields = copy.deepcopy(bag['original'].get_fields(src))
            for field in fields:
                field.tag = dst
            bag['marc'].add_field(fields)
        else:
            log.error(
                "Don't know how to map non-MARC field to MARC fields yet.")
            raise NotImplementedError
        return bag

class GetFincID(Command):
    """
    Get a finc id. Either a FINC ID identified by source and record id is
    already in our DB or it isn't.
    """
    def execute(self, bag):
        store = bag['store']
        if bag['type'] == 'marc':
            finc_id = util.encode_fincid(bag.get_original_marc_value('001'),
                source_id=bag['source_id'])
            record = store.get_record(finc_id)
            if record == None:
                store.set_record(finc_id, 'dummy')
                log.debug("Stored raw FINC record: {0}".format(finc_id))
            else:
                log.debug("We already got FINC id: {0}".format(finc_id))
            bag['finc_id'] = finc_id

COMMAND_MAP = {
    'noop' : Noop,
    'copyall' : Copyall,
    'copy' : Copy,
    'get_finc_id' : GetFincID,
}

if __name__ == '__main__':
    pass