Mercurial > treepkg > treepkg
view treepkg/util.py @ 83:83e48a76f759
Document what extract_value_for_key returns when the key is not found
author | Bernhard Herzog <bh@intevation.de> |
---|---|
date | Fri, 31 Aug 2007 17:07:18 +0000 |
parents | d0d08c7e7d37 |
children | 3ae54f99db26 |
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 shutil import run def import_dotted_name(dotted_name): module = __import__(dotted_name) for name in dotted_name.split(".")[1:]: module = getattr(module, name) return module 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. If the key is not found in lines, the function returns None. """ 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 copytree(src, dst, symlinks=False): """Recursively copy a directory tree using copy2(). This version is basically the same as the one in the shutil module in the python standard library, however, it's OK if the destination directory already exists. If the optional symlinks flag is true, symbolic links in the source tree result in symbolic links in the destination tree; if it is false, the contents of the files pointed to by symbolic links are copied. """ names = os.listdir(src) ensure_directory(dst) errors = [] for name in names: srcname = os.path.join(src, name) dstname = os.path.join(dst, name) try: if symlinks and os.path.islink(srcname): linkto = os.readlink(srcname) os.symlink(linkto, dstname) elif os.path.isdir(srcname): copytree(srcname, dstname, symlinks) else: shutil.copy2(srcname, dstname) # XXX What about devices, sockets etc.? except (IOError, os.error), why: errors.append((srcname, dstname, why)) if errors: raise Error, errors def writefile(filename, contents, permissions=None): """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. The optional parameter permissions, if given, are the permissions for the new file. By default, or if the parameter is None, the default permissions set by the tempfile.mkstemp are used which means that the file is only readable for the user that created the file. The permissions value is used as the second parameter to os.chmod. """ 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) if permissions is not None: os.chmod(tempname, permissions) 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 read(self): f = open(self.filename) try: self.status = f.read() finally: f.close() def set(self, status, extra=""): ensure_directory(os.path.dirname(self.filename)) writefile(self.filename, status + "\n" + extra) def get(self): self.read() return self.status.strip()