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