chiark / gitweb /
ed6e43c2c9282ee87333317d02f73c14eb616c1d
[stgit] / stgit / utils.py
1 """Common utility functions
2 """
3
4 import errno, os, os.path
5
6 __copyright__ = """
7 Copyright (C) 2005, Catalin Marinas <catalin.marinas@gmail.com>
8
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License version 2 as
11 published by the Free Software Foundation.
12
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with this program; if not, write to the Free Software
20 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 """
22
23 def mkdir_file(filename, mode):
24     """Opens filename with the given mode, creating the directory it's
25     in if it doesn't already exist."""
26     create_dirs(os.path.dirname(filename))
27     return file(filename, mode)
28
29 def read_string(filename, multiline = False):
30     """Reads the first line from a file
31     """
32     f = file(filename, 'r')
33     if multiline:
34         result = f.read()
35     else:
36         result = f.readline().strip()
37     f.close()
38     return result
39
40 def write_string(filename, line, multiline = False):
41     """Writes 'line' to file and truncates it
42     """
43     f = mkdir_file(filename, 'w+')
44     if multiline:
45         f.write(line)
46     else:
47         print >> f, line
48     f.close()
49
50 def append_strings(filename, lines):
51     """Appends 'lines' sequence to file
52     """
53     f = mkdir_file(filename, 'a+')
54     for line in lines:
55         print >> f, line
56     f.close()
57
58 def append_string(filename, line):
59     """Appends 'line' to file
60     """
61     f = mkdir_file(filename, 'a+')
62     print >> f, line
63     f.close()
64
65 def insert_string(filename, line):
66     """Inserts 'line' at the beginning of the file
67     """
68     f = mkdir_file(filename, 'r+')
69     lines = f.readlines()
70     f.seek(0); f.truncate()
71     print >> f, line
72     f.writelines(lines)
73     f.close()
74
75 def create_empty_file(name):
76     """Creates an empty file
77     """
78     mkdir_file(name, 'w+').close()
79
80 def list_files_and_dirs(path):
81     """Return the sets of filenames and directory names in a
82     directory."""
83     files, dirs = [], []
84     for fd in os.listdir(path):
85         full_fd = os.path.join(path, fd)
86         if os.path.isfile(full_fd):
87             files.append(fd)
88         elif os.path.isdir(full_fd):
89             dirs.append(fd)
90     return files, dirs
91
92 def walk_tree(basedir):
93     """Starting in the given directory, iterate through all its
94     subdirectories. For each subdirectory, yield the name of the
95     subdirectory (relative to the base directory), the list of
96     filenames in the subdirectory, and the list of directory names in
97     the subdirectory."""
98     subdirs = ['']
99     while subdirs:
100         subdir = subdirs.pop()
101         files, dirs = list_files_and_dirs(os.path.join(basedir, subdir))
102         for d in dirs:
103             subdirs.append(os.path.join(subdir, d))
104         yield subdir, files, dirs
105
106 def strip_prefix(prefix, string):
107     """Return string, without the prefix. Blow up if string doesn't
108     start with prefix."""
109     assert string.startswith(prefix)
110     return string[len(prefix):]
111
112 def remove_dirs(basedir, dirs):
113     """Starting at join(basedir, dirs), remove the directory if empty,
114     and try the same with its parent, until we find a nonempty
115     directory or reach basedir."""
116     path = dirs
117     while path:
118         try:
119             os.rmdir(os.path.join(basedir, path))
120         except OSError:
121             return # can't remove nonempty directory
122         path = os.path.dirname(path)
123
124 def remove_file_and_dirs(basedir, file):
125     """Remove join(basedir, file), and then remove the directory it
126     was in if empty, and try the same with its parent, until we find a
127     nonempty directory or reach basedir."""
128     os.remove(os.path.join(basedir, file))
129     remove_dirs(basedir, os.path.dirname(file))
130
131 def create_dirs(directory):
132     """Create the given directory, if the path doesn't already exist."""
133     if directory and not os.path.isdir(directory):
134         create_dirs(os.path.dirname(directory))
135         try:
136             os.mkdir(directory)
137         except OSError, e:
138             if e.errno != errno.EEXIST:
139                 raise e
140
141 def rename(basedir, file1, file2):
142     """Rename join(basedir, file1) to join(basedir, file2), not
143     leaving any empty directories behind and creating any directories
144     necessary."""
145     full_file2 = os.path.join(basedir, file2)
146     create_dirs(os.path.dirname(full_file2))
147     os.rename(os.path.join(basedir, file1), full_file2)
148     remove_dirs(basedir, os.path.dirname(file1))