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