Blame lib/dbtexmf/dblatex/grubber/util.py.enable-python3

Packit 5164a5
# This file is part of Rubber and thus covered by the GPL
Packit 5164a5
# (c) Emmanuel Beffara, 2002--2006
Packit 5164a5
"""
Packit 5164a5
This module contains utility functions and classes used by the main system and
Packit 5164a5
by the modules for various tasks.
Packit 5164a5
"""
Packit 5164a5
Packit 5164a5
try:
Packit 5164a5
    import hashlib
Packit 5164a5
except ImportError:
Packit 5164a5
    # Fallback for python 2.4:
Packit 5164a5
    import md5 as hashlib
Packit 5164a5
import os
Packit 5164a5
from msg import _, msg
Packit 5164a5
Packit 5164a5
Packit 5164a5
def md5_file(fname):
Packit 5164a5
    """
Packit 5164a5
    Compute the MD5 sum of a given file.
Packit 5164a5
    """
Packit 5164a5
    m = hashlib.md5()
Packit 5164a5
    file = open(fname)
Packit 5164a5
    for line in file.readlines():
Packit 5164a5
        m.update(line)
Packit 5164a5
    file.close()
Packit 5164a5
    return m.digest()
Packit 5164a5
Packit 5164a5
Packit 5164a5
class Watcher:
Packit 5164a5
    """
Packit 5164a5
    Watch for any changes of the files to survey, by checking the file MD5 sums.
Packit 5164a5
    """
Packit 5164a5
    def __init__(self):
Packit 5164a5
        self.files = {}
Packit 5164a5
Packit 5164a5
    def watch(self, file):
Packit 5164a5
        if os.path.exists(file):
Packit 5164a5
            self.files[file] = md5_file(file)
Packit 5164a5
        else:
Packit 5164a5
            self.files[file] = None
Packit 5164a5
Packit 5164a5
    def update(self):
Packit 5164a5
        """
Packit 5164a5
        Update the MD5 sums of all files watched, and return the name of one
Packit 5164a5
        of the files that changed, or None of they didn't change.
Packit 5164a5
        """
Packit 5164a5
        changed = []
Packit 5164a5
        for file in self.files.keys():
Packit 5164a5
            if os.path.exists(file):
Packit 5164a5
                new = md5_file(file)
Packit 5164a5
                if self.files[file] != new:
Packit 5164a5
                    msg.debug(_("%s MD5 checksum changed") % \
Packit 5164a5
                              os.path.basename(file))
Packit 5164a5
                    changed.append(file)
Packit 5164a5
                self.files[file] = new
Packit 5164a5
        return changed
Packit 5164a5