Mercurial > treepkg > treepkg
comparison 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 |
comparison
equal
deleted
inserted
replaced
-1:000000000000 | 0:f78a02e79c84 |
---|---|
1 # Copyright (C) 2007 by Intevation GmbH | |
2 # Authors: | |
3 # Bernhard Herzog <bh@intevation.de> | |
4 # | |
5 # This program is free software under the GPL (>=v2) | |
6 # Read the file COPYING coming with the software for details. | |
7 | |
8 """Collection of functions that didn't fit elsewhere""" | |
9 | |
10 import os | |
11 import tempfile | |
12 | |
13 import run | |
14 | |
15 | |
16 def extract_value_for_key(lines, key): | |
17 """Parses a sequence of strings for a key and returns the associated value | |
18 | |
19 The function determines the first string in lines that starts with | |
20 key. It returns the rest of the lines stripped of leading and | |
21 trailing whitespace. | |
22 """ | |
23 for line in lines: | |
24 if line.startswith(key): | |
25 return line[len(key):].strip() | |
26 | |
27 def extract_lsm_version(lsm_file): | |
28 return extract_value_for_key(open(lsm_file), "Version:") | |
29 | |
30 def debian_changelog_version(changelog): | |
31 """Returns the newest version in a debian changelog.""" | |
32 output = run.capture_output(["dpkg-parsechangelog", "-l" + changelog]) | |
33 return extract_value_for_key(output.splitlines(), "Version:") | |
34 | |
35 | |
36 def ensure_directory(directory): | |
37 """Creates directory and all its parents. | |
38 | |
39 Unlike os.makedirs, this function doesn't throw an exception | |
40 """ | |
41 if not os.path.isdir(directory): | |
42 os.makedirs(directory) | |
43 | |
44 | |
45 def writefile(filename, contents): | |
46 """Write contents to filename in an atomic way. | |
47 | |
48 The contents are first written to a temporary file in the same | |
49 directory as filename. Once the contents are written, the temporary | |
50 file is closed and renamed to filename. | |
51 """ | |
52 dirname, basename = os.path.split(filename) | |
53 fileno, tempname = tempfile.mkstemp("", basename, dirname) | |
54 try: | |
55 os.write(fileno, contents) | |
56 if not contents.endswith("\n"): | |
57 os.write(fileno, "\n") | |
58 os.close(fileno) | |
59 os.rename(tempname, filename) | |
60 finally: | |
61 if os.path.exists(tempname): | |
62 os.remove(tempname) | |
63 | |
64 | |
65 class StatusFile(object): | |
66 | |
67 def __init__(self, filename): | |
68 assert os.path.isabs(filename) | |
69 self.filename = filename | |
70 | |
71 def set(self, status, extra=""): | |
72 ensure_directory(os.path.dirname(self.filename)) | |
73 writefile(self.filename, status + "\n" + extra) |