5749b3bd8476df9e2808a3723e23d7acd4e4c71d
[stgit] / stgit / utils.py
1 """Common utility functions
2 """
3
4 __copyright__ = """
5 Copyright (C) 2005, Catalin Marinas <catalin.marinas@gmail.com>
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License version 2 as
9 published by the Free Software Foundation.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, write to the Free Software
18 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 """
20
21 def read_string(filename, multiline = False):
22 """Reads the first line from a file
23 """
24 f = file(filename, 'r')
25 if multiline:
26 result = f.read()
27 else:
28 result = f.readline().strip()
29 f.close()
30 return result
31
32 def write_string(filename, line, multiline = False):
33 """Writes 'line' to file and truncates it
34 """
35 f = file(filename, 'w+')
36 if multiline:
37 f.write(line)
38 else:
39 print >> f, line
40 f.close()
41
42 def append_strings(filename, lines):
43 """Appends 'lines' sequence to file
44 """
45 f = file(filename, 'a+')
46 for line in lines:
47 print >> f, line
48 f.close()
49
50 def append_string(filename, line):
51 """Appends 'line' to file
52 """
53 f = file(filename, 'a+')
54 print >> f, line
55 f.close()
56
57 def insert_string(filename, line):
58 """Inserts 'line' at the beginning of the file
59 """
60 f = file(filename, 'r+')
61 lines = f.readlines()
62 f.seek(0); f.truncate()
63 print >> f, line
64 f.writelines(lines)
65 f.close()
66
67 def create_empty_file(name):
68 """Creates an empty file
69 """
70 file(name, 'w+').close()