aboutsummaryrefslogtreecommitdiff
blob: cc4e234e512f2a6525736322e66472551dcde485 (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
# -*- coding: utf-8 -*-

"""
    revisions.py
    ~~~~~~~~~~~~

    This module implements a Python object with the revisions for each
    package fetched from the octave-forge SVN.

    :copyright: (c) 2010 by Rafael Goncalves Martins
    :license: GPL-2, see LICENSE for more details.
"""

import json

class Revisions(object):
    
    def __init__(self, json_file):
        self._file = json_file
    
    def _load_json(self):
        revisions = {}
        try:
            with open(self._file) as fp:
                revisions = json.load(fp)
        except:
            return {}
        return revisions
    
    def _dump_json(self, revisions):
        try:
            with open(self._file, 'w') as fp:
                json.dump(revisions, fp)
        except:
            return False
        return True
            
    def get(self, category=None, package=None):
        revisions = self._load_json()
        if category is None:
            return revisions        
        if category in revisions:
            if package is None:
                return revisions[category]
            if package in revisions[category]:
                return revisions[category][package]
        return None
    
    def set(self, category, package, value):
        revisions = self._load_json()
        if category not in revisions:
            revisions[category] = {}
        revisions[category][package] = value
        if not self._dump_json(revisions):
            raise RuntimeError('Failed to save JSON file.')
        

if __name__ == '__main__':
    a = Revisions('/tmp/file.json')
    a.set('main', 'fuuuu', 1234)
    print a.get()