summaryrefslogtreecommitdiffstats
path: root/lib/utils.py
blob: b9343adbf302942ce6090655ed2acab0177489b8 (plain)
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import io
import os
import json
import shutil
from myconfig import MyConfig


config = MyConfig()


#Exceptions
class EpochError(Exception):
    def __init__(self, value):
        self.value = value

    def __str__(self):
        return repr(self.value)

#Utils


#File Load/Store/Length
def read_file(infile):
    with open(infile, 'r') as f:
        data = ''.join(f.readlines())
    return data


def write_file(outfile, data):
    with open(outfile, 'w') as f:
        f.writelines([data])
    return


def get_file_length(infile):
    f = open(infile, 'r')
    f.seek(0, io.SEEK_END)
    length = f.tell()
    f.close()
    return length

def copyfile(src, dst):
    print('copying from ' + src + ' to ' + dst)
    shutil.copyfile(src, dst)


#JSON Load/Store
def load_status(infile):
    data = '{}'
    if os.access(infile, os.R_OK):
        data = read_file(infile)

    return json.loads(data)


def store_status(outfile, obj):
    write_file(outfile, json.dumps(obj))
    return


def check_epoch(obj, passname):
    epochname = passname + 'Epoch'
    if not epochname in obj:
        return False
    object_epoch = int(obj[epochname])
    config_epoch = int(config.getEpochs()[epochname])
    if object_epoch > config_epoch:
        raise EpochError('Un-excepted larger epoch en-countered.\n' + \
                             'Please increace the epoch in myconfig.py\n')

    if object_epoch < config_epoch:
        return False
    if object_epoch == config_epoch:
        return True
    return None


def sign_epoch(obj, passname):
    epochname = passname + 'Epoch'
    obj[epochname] = config.getEpochs()[epochname]

#test case
if __name__ == '__main__':
    obj = load_status('/tmp/test.status')
    print(obj)
    store_status('/tmp/test.status', obj)