Remove unneeded import
[stgit] / stgit / commands / common.py
1 """Function/variables common to all the commands
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 import sys, os, os.path, re
22 from stgit.exception import *
23 from stgit.utils import *
24 from stgit.out import *
25 from stgit.run import *
26 from stgit import stack, git, basedir
27 from stgit.config import config, file_extensions
28 from stgit.lib import stack as libstack
29 from stgit.lib import git as libgit
30
31 # Command exception class
32 class CmdException(StgException):
33 pass
34
35 # Utility functions
36 def parse_rev(rev):
37 """Parse a revision specification into its branch:patch parts.
38 """
39 try:
40 branch, patch = rev.split(':', 1)
41 except ValueError:
42 branch = None
43 patch = rev
44
45 return (branch, patch)
46
47 def git_id(crt_series, rev):
48 """Return the GIT id
49 """
50 # TODO: remove this function once all the occurrences were converted
51 # to git_commit()
52 repository = libstack.Repository.default()
53 return git_commit(rev, repository, crt_series.get_name()).sha1
54
55 def git_commit(name, repository, branch_name = None):
56 """Return the a Commit object if 'name' is a patch name or Git commit.
57 The patch names allowed are in the form '<branch>:<patch>' and can
58 be followed by standard symbols used by git rev-parse. If <patch>
59 is '{base}', it represents the bottom of the stack.
60 """
61 # Try a [branch:]patch name first
62 branch, patch = parse_rev(name)
63 if not branch:
64 branch = branch_name or repository.current_branch_name
65
66 # The stack base
67 if patch.startswith('{base}'):
68 base_id = repository.get_stack(branch).base.sha1
69 return repository.rev_parse(base_id +
70 strip_prefix('{base}', patch))
71
72 # Other combination of branch and patch
73 try:
74 return repository.rev_parse('patches/%s/%s' % (branch, patch),
75 discard_stderr = True)
76 except libgit.RepositoryException:
77 pass
78
79 # Try a Git commit
80 try:
81 return repository.rev_parse(name, discard_stderr = True)
82 except libgit.RepositoryException:
83 raise CmdException('%s: Unknown patch or revision name' % name)
84
85 def check_local_changes():
86 if git.local_changes():
87 raise CmdException('local changes in the tree. Use "refresh" or'
88 ' "status --reset"')
89
90 def check_head_top_equal(crt_series):
91 if not crt_series.head_top_equal():
92 raise CmdException('HEAD and top are not the same. This can happen'
93 ' if you modify a branch with git. "stg repair'
94 ' --help" explains more about what to do next.')
95
96 def check_conflicts():
97 if git.get_conflicts():
98 raise CmdException('Unsolved conflicts. Please resolve them first'
99 ' or revert the changes with "status --reset"')
100
101 def print_crt_patch(crt_series, branch = None):
102 if not branch:
103 patch = crt_series.get_current()
104 else:
105 patch = stack.Series(branch).get_current()
106
107 if patch:
108 out.info('Now at patch "%s"' % patch)
109 else:
110 out.info('No patches applied')
111
112 def resolved_all(reset = None):
113 conflicts = git.get_conflicts()
114 git.resolved(conflicts, reset)
115
116 def push_patches(crt_series, patches, check_merged = False):
117 """Push multiple patches onto the stack. This function is shared
118 between the push and pull commands
119 """
120 forwarded = crt_series.forward_patches(patches)
121 if forwarded > 1:
122 out.info('Fast-forwarded patches "%s" - "%s"'
123 % (patches[0], patches[forwarded - 1]))
124 elif forwarded == 1:
125 out.info('Fast-forwarded patch "%s"' % patches[0])
126
127 names = patches[forwarded:]
128
129 # check for patches merged upstream
130 if names and check_merged:
131 out.start('Checking for patches merged upstream')
132
133 merged = crt_series.merged_patches(names)
134
135 out.done('%d found' % len(merged))
136 else:
137 merged = []
138
139 for p in names:
140 out.start('Pushing patch "%s"' % p)
141
142 if p in merged:
143 crt_series.push_empty_patch(p)
144 out.done('merged upstream')
145 else:
146 modified = crt_series.push_patch(p)
147
148 if crt_series.empty_patch(p):
149 out.done('empty patch')
150 elif modified:
151 out.done('modified')
152 else:
153 out.done()
154
155 def pop_patches(crt_series, patches, keep = False):
156 """Pop the patches in the list from the stack. It is assumed that
157 the patches are listed in the stack reverse order.
158 """
159 if len(patches) == 0:
160 out.info('Nothing to push/pop')
161 else:
162 p = patches[-1]
163 if len(patches) == 1:
164 out.start('Popping patch "%s"' % p)
165 else:
166 out.start('Popping patches "%s" - "%s"' % (patches[0], p))
167 crt_series.pop_patch(p, keep)
168 out.done()
169
170 def parse_patches(patch_args, patch_list, boundary = 0, ordered = False):
171 """Parse patch_args list for patch names in patch_list and return
172 a list. The names can be individual patches and/or in the
173 patch1..patch2 format.
174 """
175 # in case it receives a tuple
176 patch_list = list(patch_list)
177 patches = []
178
179 for name in patch_args:
180 pair = name.split('..')
181 for p in pair:
182 if p and not p in patch_list:
183 raise CmdException, 'Unknown patch name: %s' % p
184
185 if len(pair) == 1:
186 # single patch name
187 pl = pair
188 elif len(pair) == 2:
189 # patch range [p1]..[p2]
190 # inclusive boundary
191 if pair[0]:
192 first = patch_list.index(pair[0])
193 else:
194 first = -1
195 # exclusive boundary
196 if pair[1]:
197 last = patch_list.index(pair[1]) + 1
198 else:
199 last = -1
200
201 # only cross the boundary if explicitly asked
202 if not boundary:
203 boundary = len(patch_list)
204 if first < 0:
205 if last <= boundary:
206 first = 0
207 else:
208 first = boundary
209 if last < 0:
210 if first < boundary:
211 last = boundary
212 else:
213 last = len(patch_list)
214
215 if last > first:
216 pl = patch_list[first:last]
217 else:
218 pl = patch_list[(last - 1):(first + 1)]
219 pl.reverse()
220 else:
221 raise CmdException, 'Malformed patch name: %s' % name
222
223 for p in pl:
224 if p in patches:
225 raise CmdException, 'Duplicate patch name: %s' % p
226
227 patches += pl
228
229 if ordered:
230 patches = [p for p in patch_list if p in patches]
231
232 return patches
233
234 def name_email(address):
235 p = parse_name_email(address)
236 if p:
237 return p
238 else:
239 raise CmdException('Incorrect "name <email>"/"email (name)" string: %s'
240 % address)
241
242 def name_email_date(address):
243 p = parse_name_email_date(address)
244 if p:
245 return p
246 else:
247 raise CmdException('Incorrect "name <email> date" string: %s' % address)
248
249 def address_or_alias(addr_str):
250 """Return the address if it contains an e-mail address or look up
251 the aliases in the config files.
252 """
253 def __address_or_alias(addr):
254 if not addr:
255 return None
256 if addr.find('@') >= 0:
257 # it's an e-mail address
258 return addr
259 alias = config.get('mail.alias.'+addr)
260 if alias:
261 # it's an alias
262 return alias
263 raise CmdException, 'unknown e-mail alias: %s' % addr
264
265 addr_list = [__address_or_alias(addr.strip())
266 for addr in addr_str.split(',')]
267 return ', '.join([addr for addr in addr_list if addr])
268
269 def prepare_rebase(crt_series):
270 # pop all patches
271 applied = crt_series.get_applied()
272 if len(applied) > 0:
273 out.start('Popping all applied patches')
274 crt_series.pop_patch(applied[0])
275 out.done()
276 return applied
277
278 def rebase(crt_series, target):
279 try:
280 tree_id = git_id(crt_series, target)
281 except:
282 # it might be that we use a custom rebase command with its own
283 # target type
284 tree_id = target
285 if tree_id == git.get_head():
286 out.info('Already at "%s", no need for rebasing.' % target)
287 return
288 if target:
289 out.start('Rebasing to "%s"' % target)
290 else:
291 out.start('Rebasing to the default target')
292 git.rebase(tree_id = tree_id)
293 out.done()
294
295 def post_rebase(crt_series, applied, nopush, merged):
296 # memorize that we rebased to here
297 crt_series._set_field('orig-base', git.get_head())
298 # push the patches back
299 if not nopush:
300 push_patches(crt_series, applied, merged)
301
302 #
303 # Patch description/e-mail/diff parsing
304 #
305 def __end_descr(line):
306 return re.match('---\s*$', line) or re.match('diff -', line) or \
307 re.match('Index: ', line)
308
309 def __split_descr_diff(string):
310 """Return the description and the diff from the given string
311 """
312 descr = diff = ''
313 top = True
314
315 for line in string.split('\n'):
316 if top:
317 if not __end_descr(line):
318 descr += line + '\n'
319 continue
320 else:
321 top = False
322 diff += line + '\n'
323
324 return (descr.rstrip(), diff)
325
326 def __parse_description(descr):
327 """Parse the patch description and return the new description and
328 author information (if any).
329 """
330 subject = body = ''
331 authname = authemail = authdate = None
332
333 descr_lines = [line.rstrip() for line in descr.split('\n')]
334 if not descr_lines:
335 raise CmdException, "Empty patch description"
336
337 lasthdr = 0
338 end = len(descr_lines)
339
340 # Parse the patch header
341 for pos in range(0, end):
342 if not descr_lines[pos]:
343 continue
344 # check for a "From|Author:" line
345 if re.match('\s*(?:from|author):\s+', descr_lines[pos], re.I):
346 auth = re.findall('^.*?:\s+(.*)$', descr_lines[pos])[0]
347 authname, authemail = name_email(auth)
348 lasthdr = pos + 1
349 continue
350 # check for a "Date:" line
351 if re.match('\s*date:\s+', descr_lines[pos], re.I):
352 authdate = re.findall('^.*?:\s+(.*)$', descr_lines[pos])[0]
353 lasthdr = pos + 1
354 continue
355 if subject:
356 break
357 # get the subject
358 subject = descr_lines[pos]
359 lasthdr = pos + 1
360
361 # get the body
362 if lasthdr < end:
363 body = reduce(lambda x, y: x + '\n' + y, descr_lines[lasthdr:], '')
364
365 return (subject + body, authname, authemail, authdate)
366
367 def parse_mail(msg):
368 """Parse the message object and return (description, authname,
369 authemail, authdate, diff)
370 """
371 from email.Header import decode_header, make_header
372
373 def __decode_header(header):
374 """Decode a qp-encoded e-mail header as per rfc2047"""
375 try:
376 words_enc = decode_header(header)
377 hobj = make_header(words_enc)
378 except Exception, ex:
379 raise CmdException, 'header decoding error: %s' % str(ex)
380 return unicode(hobj).encode('utf-8')
381
382 # parse the headers
383 if msg.has_key('from'):
384 authname, authemail = name_email(__decode_header(msg['from']))
385 else:
386 authname = authemail = None
387
388 # '\n\t' can be found on multi-line headers
389 descr = __decode_header(msg['subject']).replace('\n\t', ' ')
390 authdate = msg['date']
391
392 # remove the '[*PATCH*]' expression in the subject
393 if descr:
394 descr = re.findall('^(\[.*?[Pp][Aa][Tt][Cc][Hh].*?\])?\s*(.*)$',
395 descr)[0][1]
396 else:
397 raise CmdException, 'Subject: line not found'
398
399 # the rest of the message
400 msg_text = ''
401 for part in msg.walk():
402 if part.get_content_type() == 'text/plain':
403 msg_text += part.get_payload(decode = True)
404
405 rem_descr, diff = __split_descr_diff(msg_text)
406 if rem_descr:
407 descr += '\n\n' + rem_descr
408
409 # parse the description for author information
410 descr, descr_authname, descr_authemail, descr_authdate = \
411 __parse_description(descr)
412 if descr_authname:
413 authname = descr_authname
414 if descr_authemail:
415 authemail = descr_authemail
416 if descr_authdate:
417 authdate = descr_authdate
418
419 return (descr, authname, authemail, authdate, diff)
420
421 def parse_patch(text):
422 """Parse the input text and return (description, authname,
423 authemail, authdate, diff)
424 """
425 descr, diff = __split_descr_diff(text)
426 descr, authname, authemail, authdate = __parse_description(descr)
427
428 # we don't yet have an agreed place for the creation date.
429 # Just return None
430 return (descr, authname, authemail, authdate, diff)
431
432 def readonly_constant_property(f):
433 """Decorator that converts a function that computes a value to an
434 attribute that returns the value. The value is computed only once,
435 the first time it is accessed."""
436 def new_f(self):
437 n = '__' + f.__name__
438 if not hasattr(self, n):
439 setattr(self, n, f(self))
440 return getattr(self, n)
441 return property(new_f)
442
443 class DirectoryException(StgException):
444 pass
445
446 class _Directory(object):
447 def __init__(self, needs_current_series = True):
448 self.needs_current_series = needs_current_series
449 @readonly_constant_property
450 def git_dir(self):
451 try:
452 return Run('git', 'rev-parse', '--git-dir'
453 ).discard_stderr().output_one_line()
454 except RunException:
455 raise DirectoryException('No git repository found')
456 @readonly_constant_property
457 def __topdir_path(self):
458 try:
459 lines = Run('git', 'rev-parse', '--show-cdup'
460 ).discard_stderr().output_lines()
461 if len(lines) == 0:
462 return '.'
463 elif len(lines) == 1:
464 return lines[0]
465 else:
466 raise RunException('Too much output')
467 except RunException:
468 raise DirectoryException('No git repository found')
469 @readonly_constant_property
470 def is_inside_git_dir(self):
471 return { 'true': True, 'false': False
472 }[Run('git', 'rev-parse', '--is-inside-git-dir'
473 ).output_one_line()]
474 @readonly_constant_property
475 def is_inside_worktree(self):
476 return { 'true': True, 'false': False
477 }[Run('git', 'rev-parse', '--is-inside-work-tree'
478 ).output_one_line()]
479 def cd_to_topdir(self):
480 os.chdir(self.__topdir_path)
481
482 class DirectoryAnywhere(_Directory):
483 def setup(self):
484 pass
485
486 class DirectoryHasRepository(_Directory):
487 def setup(self):
488 self.git_dir # might throw an exception
489
490 class DirectoryInWorktree(DirectoryHasRepository):
491 def setup(self):
492 DirectoryHasRepository.setup(self)
493 if not self.is_inside_worktree:
494 raise DirectoryException('Not inside a git worktree')
495
496 class DirectoryGotoToplevel(DirectoryInWorktree):
497 def setup(self):
498 DirectoryInWorktree.setup(self)
499 self.cd_to_topdir()
500
501 class DirectoryHasRepositoryLib(_Directory):
502 """For commands that use the new infrastructure in stgit.lib.*."""
503 def __init__(self):
504 self.needs_current_series = False
505 def setup(self):
506 # This will throw an exception if we don't have a repository.
507 self.repository = libstack.Repository.default()