Skip to content
database.py 2.42 KiB
Newer Older
Seblu's avatar
Seblu committed
# coding: utf-8

# archversion - Archlinux Version Controller
# Copyright © 2012 Sébastien Luttringer
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

'''Database Module'''

Seblu's avatar
Seblu committed
from archversion import XDG_DIRECTORY
Seblu's avatar
Seblu committed
from archversion.error import BaseError
Seblu's avatar
Seblu committed
from os.path import join
from xdg.BaseDirectory import save_cache_path
Seblu's avatar
Seblu committed
import json
import logging
Seblu's avatar
Seblu committed

Seblu's avatar
Seblu committed

class JsonDatabase(dict):
    '''Json database'''

    _path = None

    def __del__(self):
        if self._path is not None:
            self.save()

Seblu's avatar
Seblu committed
    def load(self, filename):
Seblu's avatar
Seblu committed
        '''Load registered version database into this database'''
Seblu's avatar
Seblu committed
        assert(filename is not None)
        path = join(save_cache_path(XDG_DIRECTORY), filename)
        try:
            open(path, "a")
        except (IOError, OSError) as exp:
            raise BaseError("Create database filename failed; %s" % exp)
        logging.debug("Loading database %s" % path)
        try:
            fileobj = open(path, "r")
            dico = json.load(fileobj)
            self.update(dico)
        except Exception as exp:
            logging.error("Unable to load database %s: %s" % (path, exp))
        # because we use self._path is __del__, this should be done when
        # we are sure that db is loaded
        self._path = path
Seblu's avatar
Seblu committed

    def save(self, save_empty=False):
Seblu's avatar
Seblu committed
        '''Save current version database into a file'''
        if not save_empty and len(self) == 0:
            logging.debug("Not saved. Database is empty")
            return
        if self._path is not None:
            logging.debug("Saving database %s" % self._path)
Seblu's avatar
Seblu committed
            try:
                fileobj = open(self._path, "w")
Seblu's avatar
Seblu committed
                json.dump(self, fileobj)
            except Exception as exp:
                logging.error("Unable to save database %s: %s" % (self._path, exp))