Remove an unnecessary parameter to make_patch_name
[stgit] / stgit / utils.py
1 """Common utility functions
2 """
3
4 import errno, os, os.path, re, sys
5 from stgit.config import config
6
7 __copyright__ = """
8 Copyright (C) 2005, Catalin Marinas <catalin.marinas@gmail.com>
9
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.
13
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.
18
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 """
23
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)
29
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
40
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()
50
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()
58
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()
65
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()
75
76 def create_empty_file(name):
77 """Creates an empty file
78 """
79 mkdir_file(name, 'w+').close()
80
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
92
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
106
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):]
112
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)]
118
119 def remove_file_and_dirs(basedir, file):
120 """Remove join(basedir, file), and then remove the directory it
121 was in if empty, and try the same with its parent, until we find a
122 nonempty directory or reach basedir."""
123 os.remove(os.path.join(basedir, file))
124 try:
125 os.removedirs(os.path.join(basedir, os.path.dirname(file)))
126 except OSError:
127 # file's parent dir may not be empty after removal
128 pass
129
130 def create_dirs(directory):
131 """Create the given directory, if the path doesn't already exist."""
132 if directory and not os.path.isdir(directory):
133 create_dirs(os.path.dirname(directory))
134 try:
135 os.mkdir(directory)
136 except OSError, e:
137 if e.errno != errno.EEXIST:
138 raise e
139
140 def rename(basedir, file1, file2):
141 """Rename join(basedir, file1) to join(basedir, file2), not
142 leaving any empty directories behind and creating any directories
143 necessary."""
144 full_file2 = os.path.join(basedir, file2)
145 create_dirs(os.path.dirname(full_file2))
146 os.rename(os.path.join(basedir, file1), full_file2)
147 try:
148 os.removedirs(os.path.join(basedir, os.path.dirname(file1)))
149 except OSError:
150 # file1's parent dir may not be empty after move
151 pass
152
153 class EditorException(Exception):
154 pass
155
156 def call_editor(filename):
157 """Run the editor on the specified filename."""
158
159 # the editor
160 editor = config.get('stgit.editor')
161 if editor:
162 pass
163 elif 'EDITOR' in os.environ:
164 editor = os.environ['EDITOR']
165 else:
166 editor = 'vi'
167 editor += ' %s' % filename
168
169 print 'Invoking the editor: "%s"...' % editor,
170 sys.stdout.flush()
171 err = os.system(editor)
172 if err:
173 raise EditorException, 'editor failed, exit code: %d' % err
174 print 'done'
175
176 def patch_name_from_msg(msg):
177 """Return a string to be used as a patch name. This is generated
178 from the top line of the string passed as argument, and is at most
179 30 characters long."""
180 if not msg:
181 return None
182
183 subject_line = msg.split('\n', 1)[0].lstrip().lower()
184 return re.sub('[\W]+', '-', subject_line).strip('-')[:30]
185
186 def make_patch_name(msg, unacceptable, default_name = 'patch'):
187 """Return a patch name generated from the given commit message,
188 guaranteed to make unacceptable(name) be false. If the commit
189 message is empty, base the name on default_name instead."""
190 patchname = patch_name_from_msg(msg)
191 if not patchname:
192 patchname = default_name
193 if unacceptable(patchname):
194 suffix = 0
195 while unacceptable('%s-%d' % (patchname, suffix)):
196 suffix += 1
197 patchname = '%s-%d' % (patchname, suffix)
198 return patchname