view treepkg/util.py @ 0:f78a02e79c84

initial checkin
author Bernhard Herzog <bh@intevation.de>
date Tue, 06 Mar 2007 17:37:32 +0100
parents
children fee641fec94e
line wrap: on
line source
# Copyright (C) 2007 by Intevation GmbH
# Authors:
# Bernhard Herzog <bh@intevation.de>
#
# This program is free software under the GPL (>=v2)
# Read the file COPYING coming with the software for details.

"""Collection of functions that didn't fit elsewhere"""

import os
import tempfile

import run


def extract_value_for_key(lines, key):
    """Parses a sequence of strings for a key and returns the associated value

    The function determines the first string in lines that starts with
    key.  It returns the rest of the lines stripped of leading and
    trailing whitespace.
    """
    for line in lines:
        if line.startswith(key):
            return line[len(key):].strip()

def extract_lsm_version(lsm_file):
    return extract_value_for_key(open(lsm_file), "Version:")

def debian_changelog_version(changelog):
    """Returns the newest version in a debian changelog."""
    output = run.capture_output(["dpkg-parsechangelog",  "-l" + changelog])
    return extract_value_for_key(output.splitlines(), "Version:")


def ensure_directory(directory):
    """Creates directory and all its parents.

    Unlike os.makedirs, this function doesn't throw an exception
    """
    if not os.path.isdir(directory):
        os.makedirs(directory)


def writefile(filename, contents):
    """Write contents to filename in an atomic way.

    The contents are first written to a temporary file in the same
    directory as filename.  Once the contents are written, the temporary
    file is closed and renamed to filename.
    """
    dirname, basename = os.path.split(filename)
    fileno, tempname = tempfile.mkstemp("", basename, dirname)
    try:
        os.write(fileno, contents)
        if not contents.endswith("\n"):
            os.write(fileno, "\n")
        os.close(fileno)
        os.rename(tempname, filename)
    finally:
        if os.path.exists(tempname):
            os.remove(tempname)


class StatusFile(object):

    def __init__(self, filename):
        assert os.path.isabs(filename)
        self.filename = filename

    def set(self, status, extra=""):
        ensure_directory(os.path.dirname(self.filename))
        writefile(self.filename, status + "\n" + extra)
This site is hosted by Intevation GmbH (Datenschutzerklärung und Impressum | Privacy Policy and Imprint)