footprints.py 2.51 KB
# -*- coding: utf-8 -*-
import os
import copy

# from dfs.utils import check_hexsum as check_sum

def getmtime(path):
    return round(os.path.getmtime(path))

from utils import all_files

class FootPrints:

    """Class for footprints file manipulation."""

    def __init__(self, prints_path, dir_path, exts):
        self.prints_path = prints_path
        self.dir_path = dir_path
        self.exts = exts
        if not os.path.exists(prints_path):
            with open(prints_path, "w") as f: pass
        self.prints = self.read()
        self.backup = copy.deepcopy(self.prints)

    def modified(self, name):
        try:
            # (mtime, csum) = self.get_print(name)
            mtime = self.get_print(name)
        except KeyError:
            return False

        path = os.path.join(self.dir_path, name)
        if mtime != self.print_now(path):
            return True
        return False

    """ sprawdza czy nie pojawily sie jakies nowe pliki, ewentualnie dodajac dla nich wpisy """
    def refresh(self):
        old_prints = self.prints
        new_prints = {}
        for name in all_files(self.dir_path, self.exts):
            if old_prints.has_key(name):
                new_prints[name] = old_prints[name]
            else:
                path = os.path.join(self.dir_path, name)
                new_prints[name] = self.print_now(path)
        self.prints = new_prints

    def renew(self, name):
        path = os.path.join(self.dir_path, name)
        try:
            self.prints[name] = self.print_now(path)
        except:
            del self.prints[name]
            print "Footprints: "+ path + " file not found."
                
    def renew_all(self):
        for key in self.prints.keys():
            self.renew(key)

    def get_print(self, name):
        path = os.path.join(self.dir_path, name)
        return self.prints[name]

    def print_now(self, path):        
        return max(getmtime(path + ext) for ext in self.exts)

    def read(self):
        prints = {}
        with open(self.prints_path) as f:
            for line in f:
                key, mtime = line.split()
                prints[key] = float(mtime)
        return prints

    def write(self):
        with open(self.prints_path, "w") as f:
            # for key, (mtime, csum) in sorted(self.prints.items()):
            #     print >> f, key, "=", mtime, csum
            for key, mtime in sorted(self.prints.items()):
                print >> f, key, mtime

    def save(self):
        if self.prints != self.backup:
            self.write()