~osomon/phatch/extract-all-metadata

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import glob, os, pprint
import actions, ct

def importActions():
    #actions=result
    result = {}
    for filename in glob.glob(os.path.join(ct.ACTIONS_PATH,'*.py')):
        basename= os.path.basename(os.path.splitext(filename)[0])
        module  = getattr(__import__('actions.'+basename),basename)
        for attr in dir(module):
            if attr[:7] == ct.ACTION_PREFIX or attr == 'Action':
                cl                  = getattr(module,attr)
                result[cl.label]    = cl
    #labels
    labels                          = result.keys()
    labels.sort()
    #fields
    fields = {}
    for label in result:
        fields[label]  = result[label]()._fields
        #return
    return result, labels, fields


ACTIONS, ACTION_LABELS, ACTION_FIELDS = importActions()

def saveData(filename,data):
    """data = {'actions':...}"""
    #check filename
    if os.path.splitext(filename)[1].lower() != '.py':
        filename    += '.py'
    #prepare data
    data['actions'] = [action.dump() for action in data['actions']]
    #backup previous
    if os.path.isfile(filename):
        os.rename(filename,filename+'~')
    #write it
    f       = open(filename,'wb')
    f.write(pprint.pformat(data))
    f.close()

def openData(filename):
    #read source
    f       = open(filename,'rb')
    source  = f.read()
    f.close()
    #load data
    data        = eval(source)
    result      = []
    for action in data['actions']:
        actionLabel     = action['label']
        actionFields   = action['fields']
        newAction       = ACTIONS[actionLabel]()
        newAction.load(actionFields)
        result.append(newAction)
    data['actions'] = result
    return data