1 """Common utility functions
4 import errno, optparse, os, os.path, re, sys
5 from stgit.exception import *
6 from stgit.config import config
7 from stgit.out import *
10 Copyright (C) 2005, Catalin Marinas <catalin.marinas@gmail.com>
12 This program is free software; you can redistribute it and/or modify
13 it under the terms of the GNU General Public License version 2 as
14 published by the Free Software Foundation.
16 This program is distributed in the hope that it will be useful,
17 but WITHOUT ANY WARRANTY; without even the implied warranty of
18 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 GNU General Public License for more details.
21 You should have received a copy of the GNU General Public License
22 along with this program; if not, write to the Free Software
23 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
26 def mkdir_file(filename, mode):
27 """Opens filename with the given mode, creating the directory it's
28 in if it doesn't already exist."""
29 create_dirs(os.path.dirname(filename))
30 return file(filename, mode)
32 def read_strings(filename):
33 """Reads the lines from a file
35 f = file(filename, 'r')
36 lines = [line.strip() for line in f.readlines()]
40 def read_string(filename, multiline = False):
41 """Reads the first line from a file
43 f = file(filename, 'r')
47 result = f.readline().strip()
51 def write_strings(filename, lines):
52 """Write 'lines' sequence to file
54 f = file(filename, 'w+')
55 f.writelines([line + '\n' for line in lines])
58 def write_string(filename, line, multiline = False):
59 """Writes 'line' to file and truncates it
61 f = mkdir_file(filename, 'w+')
68 def append_strings(filename, lines):
69 """Appends 'lines' sequence to file
71 f = mkdir_file(filename, 'a+')
76 def append_string(filename, line):
77 """Appends 'line' to file
79 f = mkdir_file(filename, 'a+')
83 def insert_string(filename, line):
84 """Inserts 'line' at the beginning of the file
86 f = mkdir_file(filename, 'r+')
88 f.seek(0); f.truncate()
93 def create_empty_file(name):
94 """Creates an empty file
96 mkdir_file(name, 'w+').close()
98 def list_files_and_dirs(path):
99 """Return the sets of filenames and directory names in a
102 for fd in os.listdir(path):
103 full_fd = os.path.join(path, fd)
104 if os.path.isfile(full_fd):
106 elif os.path.isdir(full_fd):
110 def walk_tree(basedir):
111 """Starting in the given directory, iterate through all its
112 subdirectories. For each subdirectory, yield the name of the
113 subdirectory (relative to the base directory), the list of
114 filenames in the subdirectory, and the list of directory names in
118 subdir = subdirs.pop()
119 files, dirs = list_files_and_dirs(os.path.join(basedir, subdir))
121 subdirs.append(os.path.join(subdir, d))
122 yield subdir, files, dirs
124 def strip_prefix(prefix, string):
125 """Return string, without the prefix. Blow up if string doesn't
126 start with prefix."""
127 assert string.startswith(prefix)
128 return string[len(prefix):]
130 def strip_suffix(suffix, string):
131 """Return string, without the suffix. Blow up if string doesn't
133 assert string.endswith(suffix)
134 return string[:-len(suffix)]
136 def remove_file_and_dirs(basedir, file):
137 """Remove join(basedir, file), and then remove the directory it
138 was in if empty, and try the same with its parent, until we find a
139 nonempty directory or reach basedir."""
140 os.remove(os.path.join(basedir, file))
142 os.removedirs(os.path.join(basedir, os.path.dirname(file)))
144 # file's parent dir may not be empty after removal
147 def create_dirs(directory):
148 """Create the given directory, if the path doesn't already exist."""
149 if directory and not os.path.isdir(directory):
150 create_dirs(os.path.dirname(directory))
154 if e.errno != errno.EEXIST:
157 def rename(basedir, file1, file2):
158 """Rename join(basedir, file1) to join(basedir, file2), not
159 leaving any empty directories behind and creating any directories
161 full_file2 = os.path.join(basedir, file2)
162 create_dirs(os.path.dirname(full_file2))
163 os.rename(os.path.join(basedir, file1), full_file2)
165 os.removedirs(os.path.join(basedir, os.path.dirname(file1)))
167 # file1's parent dir may not be empty after move
170 class EditorException(StgException):
173 def call_editor(filename):
174 """Run the editor on the specified filename."""
177 editor = config.get('stgit.editor')
180 elif 'EDITOR' in os.environ:
181 editor = os.environ['EDITOR']
184 editor += ' %s' % filename
186 out.start('Invoking the editor: "%s"' % editor)
187 err = os.system(editor)
189 raise EditorException, 'editor failed, exit code: %d' % err
192 def edit_string(s, filename):
193 f = file(filename, 'w')
196 call_editor(filename)
203 def patch_name_from_msg(msg):
204 """Return a string to be used as a patch name. This is generated
205 from the top line of the string passed as argument."""
209 name_len = config.get('stgit.namelength')
213 subject_line = msg.split('\n', 1)[0].lstrip().lower()
214 return re.sub('[\W]+', '-', subject_line).strip('-')[:name_len]
216 def make_patch_name(msg, unacceptable, default_name = 'patch'):
217 """Return a patch name generated from the given commit message,
218 guaranteed to make unacceptable(name) be false. If the commit
219 message is empty, base the name on default_name instead."""
220 patchname = patch_name_from_msg(msg)
222 patchname = default_name
223 if unacceptable(patchname):
225 while unacceptable('%s-%d' % (patchname, suffix)):
227 patchname = '%s-%d' % (patchname, suffix)
230 # any and all functions are builtin in Python 2.5 and higher, but not
232 if not 'any' in dir(__builtins__):
238 if not 'all' in dir(__builtins__):
245 def make_sign_options():
246 def callback(option, opt_str, value, parser, sign_str):
247 if parser.values.sign_str not in [None, sign_str]:
248 raise optparse.OptionValueError(
249 '--ack and --sign were both specified')
250 parser.values.sign_str = sign_str
251 return [optparse.make_option('--sign', action = 'callback',
252 callback = callback, dest = 'sign_str',
253 callback_args = ('Signed-off-by',),
254 help = 'add Signed-off-by line'),
255 optparse.make_option('--ack', action = 'callback',
256 callback = callback, dest = 'sign_str',
257 callback_args = ('Acked-by',),
258 help = 'add Acked-by line')]
260 def add_sign_line(desc, sign_str, name, email):
263 sign_str = '%s: %s <%s>' % (sign_str, name, email)
267 if not any(s in desc for s in ['\nSigned-off-by:', '\nAcked-by:']):
269 return '%s\n%s\n' % (desc, sign_str)
271 def make_message_options():
273 if parser.values.message != None:
274 raise optparse.OptionValueError(
275 'Cannot give more than one --message or --file')
276 def no_combine(parser):
277 if (parser.values.message != None
278 and parser.values.save_template != None):
279 raise optparse.OptionValueError(
280 'Cannot give both --message/--file and --save-template')
281 def msg_callback(option, opt_str, value, parser):
283 parser.values.message = value
285 def file_callback(option, opt_str, value, parser):
288 parser.values.message = sys.stdin.read()
291 parser.values.message = f.read()
294 def templ_callback(option, opt_str, value, parser):
300 f = file(value, 'w+')
303 parser.values.save_template = w
305 m = optparse.make_option
306 return [m('-m', '--message', action = 'callback', callback = msg_callback,
307 dest = 'message', type = 'string',
308 help = 'use MESSAGE instead of invoking the editor'),
309 m('-f', '--file', action = 'callback', callback = file_callback,
310 dest = 'message', type = 'string', metavar = 'FILE',
311 help = 'use FILE instead of invoking the editor'),
312 m('--save-template', action = 'callback', callback = templ_callback,
313 metavar = 'FILE', dest = 'save_template', type = 'string',
314 help = 'save the message template to FILE and exit')]
317 STGIT_SUCCESS = 0 # everything's OK
318 STGIT_GENERAL_ERROR = 1 # seems to be non-command-specific error
319 STGIT_COMMAND_ERROR = 2 # seems to be a command that failed
321 def strip_leading(prefix, s):
322 """Strip leading prefix from a string. Blow up if the prefix isn't
324 assert s.startswith(prefix)
325 return s[len(prefix):]
327 def add_dict(d1, d2):
328 """Return a new dict with the contents of both d1 and d2. In case of
329 conflicting mappings, d2 takes precedence."""