chiark / gitweb /
780ff51c8cf19dd3f1c70865de77d0c273383873
[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 optparse import OptionParser, make_option
23
24 from stgit.exception import *
25 from stgit.utils import *
26 from stgit.out import *
27 from stgit.run import *
28 from stgit import stack, git, basedir
29 from stgit.config import config, file_extensions
30 from stgit.lib import stack as libstack
31 from stgit.lib import git as libgit
32
33 # Command exception class
34 class CmdException(StgException):
35     pass
36
37 # Utility functions
38 def parse_rev(rev):
39     """Parse a revision specification into its branch:patch parts.
40     """
41     try:
42         branch, patch = rev.split(':', 1)
43     except ValueError:
44         branch = None
45         patch = rev
46
47     return (branch, patch)
48
49 def git_id(crt_series, rev):
50     """Return the GIT id
51     """
52     # TODO: remove this function once all the occurrences were converted
53     # to git_commit()
54     repository = libstack.Repository.default()
55     return git_commit(rev, repository, crt_series.get_name()).sha1
56
57 def git_commit(name, repository, branch_name = None):
58     """Return the a Commit object if 'name' is a patch name or Git commit.
59     The patch names allowed are in the form '<branch>:<patch>' and can
60     be followed by standard symbols used by git-rev-parse. If <patch>
61     is '{base}', it represents the bottom of the stack.
62     """
63     # Try a [branch:]patch name first
64     branch, patch = parse_rev(name)
65     if not branch:
66         branch = branch_name or repository.current_branch_name
67
68     # The stack base
69     if patch.startswith('{base}'):
70         base_id = repository.get_stack(branch).base.sha1
71         return repository.rev_parse(base_id +
72                                     strip_prefix('{base}', patch))
73
74     # Other combination of branch and patch
75     try:
76         return repository.rev_parse('patches/%s/%s' % (branch, patch),
77                                     discard_stderr = True)
78     except libgit.RepositoryException:
79         pass
80
81     # Try a Git commit
82     try:
83         return repository.rev_parse(name, discard_stderr = True)
84     except libgit.RepositoryException:
85         raise CmdException('%s: Unknown patch or revision name' % name)
86
87 def check_local_changes():
88     if git.local_changes():
89         raise CmdException('local changes in the tree. Use "refresh" or'
90                            ' "status --reset"')
91
92 def check_head_top_equal(crt_series):
93     if not crt_series.head_top_equal():
94         raise CmdException('HEAD and top are not the same. This can happen'
95                            ' if you modify a branch with git. "stg repair'
96                            ' --help" explains more about what to do next.')
97
98 def check_conflicts():
99     if git.get_conflicts():
100         raise CmdException('Unsolved conflicts. Please resolve them first'
101                            ' or revert the 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 = parse_name_email(address)
238     if p:
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_str):
252     """Return the address if it contains an e-mail address or look up
253     the aliases in the config files.
254     """
255     def __address_or_alias(addr):
256         if not addr:
257             return None
258         if addr.find('@') >= 0:
259             # it's an e-mail address
260             return addr
261         alias = config.get('mail.alias.'+addr)
262         if alias:
263             # it's an alias
264             return alias
265         raise CmdException, 'unknown e-mail alias: %s' % addr
266
267     addr_list = [__address_or_alias(addr.strip())
268                  for addr in addr_str.split(',')]
269     return ', '.join([addr for addr in addr_list if addr])
270
271 def prepare_rebase(crt_series):
272     # pop all patches
273     applied = crt_series.get_applied()
274     if len(applied) > 0:
275         out.start('Popping all applied patches')
276         crt_series.pop_patch(applied[0])
277         out.done()
278     return applied
279
280 def rebase(crt_series, target):
281     try:
282         tree_id = git_id(crt_series, target)
283     except:
284         # it might be that we use a custom rebase command with its own
285         # target type
286         tree_id = target
287     if tree_id == git.get_head():
288         out.info('Already at "%s", no need for rebasing.' % target)
289         return
290     if target:
291         out.start('Rebasing to "%s"' % target)
292     else:
293         out.start('Rebasing to the default target')
294     git.rebase(tree_id = tree_id)
295     out.done()
296
297 def post_rebase(crt_series, applied, nopush, merged):
298     # memorize that we rebased to here
299     crt_series._set_field('orig-base', git.get_head())
300     # push the patches back
301     if not nopush:
302         push_patches(crt_series, applied, merged)
303
304 #
305 # Patch description/e-mail/diff parsing
306 #
307 def __end_descr(line):
308     return re.match('---\s*$', line) or re.match('diff -', line) or \
309             re.match('Index: ', line)
310
311 def __split_descr_diff(string):
312     """Return the description and the diff from the given string
313     """
314     descr = diff = ''
315     top = True
316
317     for line in string.split('\n'):
318         if top:
319             if not __end_descr(line):
320                 descr += line + '\n'
321                 continue
322             else:
323                 top = False
324         diff += line + '\n'
325
326     return (descr.rstrip(), diff)
327
328 def __parse_description(descr):
329     """Parse the patch description and return the new description and
330     author information (if any).
331     """
332     subject = body = ''
333     authname = authemail = authdate = None
334
335     descr_lines = [line.rstrip() for line in  descr.split('\n')]
336     if not descr_lines:
337         raise CmdException, "Empty patch description"
338
339     lasthdr = 0
340     end = len(descr_lines)
341
342     # Parse the patch header
343     for pos in range(0, end):
344         if not descr_lines[pos]:
345            continue
346         # check for a "From|Author:" line
347         if re.match('\s*(?:from|author):\s+', descr_lines[pos], re.I):
348             auth = re.findall('^.*?:\s+(.*)$', descr_lines[pos])[0]
349             authname, authemail = name_email(auth)
350             lasthdr = pos + 1
351             continue
352         # check for a "Date:" line
353         if re.match('\s*date:\s+', descr_lines[pos], re.I):
354             authdate = re.findall('^.*?:\s+(.*)$', descr_lines[pos])[0]
355             lasthdr = pos + 1
356             continue
357         if subject:
358             break
359         # get the subject
360         subject = descr_lines[pos]
361         lasthdr = pos + 1
362
363     # get the body
364     if lasthdr < end:
365         body = reduce(lambda x, y: x + '\n' + y, descr_lines[lasthdr:], '')
366
367     return (subject + body, authname, authemail, authdate)
368
369 def parse_mail(msg):
370     """Parse the message object and return (description, authname,
371     authemail, authdate, diff)
372     """
373     from email.Header import decode_header, make_header
374
375     def __decode_header(header):
376         """Decode a qp-encoded e-mail header as per rfc2047"""
377         try:
378             words_enc = decode_header(header)
379             hobj = make_header(words_enc)
380         except Exception, ex:
381             raise CmdException, 'header decoding error: %s' % str(ex)
382         return unicode(hobj).encode('utf-8')
383
384     # parse the headers
385     if msg.has_key('from'):
386         authname, authemail = name_email(__decode_header(msg['from']))
387     else:
388         authname = authemail = None
389
390     # '\n\t' can be found on multi-line headers
391     descr = __decode_header(msg['subject']).replace('\n\t', ' ')
392     authdate = msg['date']
393
394     # remove the '[*PATCH*]' expression in the subject
395     if descr:
396         descr = re.findall('^(\[.*?[Pp][Aa][Tt][Cc][Hh].*?\])?\s*(.*)$',
397                            descr)[0][1]
398     else:
399         raise CmdException, 'Subject: line not found'
400
401     # the rest of the message
402     msg_text = ''
403     for part in msg.walk():
404         if part.get_content_type() == 'text/plain':
405             msg_text += part.get_payload(decode = True)
406
407     rem_descr, diff = __split_descr_diff(msg_text)
408     if rem_descr:
409         descr += '\n\n' + rem_descr
410
411     # parse the description for author information
412     descr, descr_authname, descr_authemail, descr_authdate = \
413            __parse_description(descr)
414     if descr_authname:
415         authname = descr_authname
416     if descr_authemail:
417         authemail = descr_authemail
418     if descr_authdate:
419        authdate = descr_authdate
420
421     return (descr, authname, authemail, authdate, diff)
422
423 def parse_patch(text):
424     """Parse the input text and return (description, authname,
425     authemail, authdate, diff)
426     """
427     descr, diff = __split_descr_diff(text)
428     descr, authname, authemail, authdate = __parse_description(descr)
429
430     # we don't yet have an agreed place for the creation date.
431     # Just return None
432     return (descr, authname, authemail, authdate, diff)
433
434 def readonly_constant_property(f):
435     """Decorator that converts a function that computes a value to an
436     attribute that returns the value. The value is computed only once,
437     the first time it is accessed."""
438     def new_f(self):
439         n = '__' + f.__name__
440         if not hasattr(self, n):
441             setattr(self, n, f(self))
442         return getattr(self, n)
443     return property(new_f)
444
445 class DirectoryException(StgException):
446     pass
447
448 class _Directory(object):
449     def __init__(self, needs_current_series = True):
450         self.needs_current_series =  needs_current_series
451     @readonly_constant_property
452     def git_dir(self):
453         try:
454             return Run('git', 'rev-parse', '--git-dir'
455                        ).discard_stderr().output_one_line()
456         except RunException:
457             raise DirectoryException('No git repository found')
458     @readonly_constant_property
459     def __topdir_path(self):
460         try:
461             lines = Run('git', 'rev-parse', '--show-cdup'
462                         ).discard_stderr().output_lines()
463             if len(lines) == 0:
464                 return '.'
465             elif len(lines) == 1:
466                 return lines[0]
467             else:
468                 raise RunException('Too much output')
469         except RunException:
470             raise DirectoryException('No git repository found')
471     @readonly_constant_property
472     def is_inside_git_dir(self):
473         return { 'true': True, 'false': False
474                  }[Run('git', 'rev-parse', '--is-inside-git-dir'
475                        ).output_one_line()]
476     @readonly_constant_property
477     def is_inside_worktree(self):
478         return { 'true': True, 'false': False
479                  }[Run('git', 'rev-parse', '--is-inside-work-tree'
480                        ).output_one_line()]
481     def cd_to_topdir(self):
482         os.chdir(self.__topdir_path)
483
484 class DirectoryAnywhere(_Directory):
485     def setup(self):
486         pass
487
488 class DirectoryHasRepository(_Directory):
489     def setup(self):
490         self.git_dir # might throw an exception
491
492 class DirectoryInWorktree(DirectoryHasRepository):
493     def setup(self):
494         DirectoryHasRepository.setup(self)
495         if not self.is_inside_worktree:
496             raise DirectoryException('Not inside a git worktree')
497
498 class DirectoryGotoToplevel(DirectoryInWorktree):
499     def setup(self):
500         DirectoryInWorktree.setup(self)
501         self.cd_to_topdir()
502
503 class DirectoryHasRepositoryLib(_Directory):
504     """For commands that use the new infrastructure in stgit.lib.*."""
505     def __init__(self):
506         self.needs_current_series = False
507     def setup(self):
508         # This will throw an exception if we don't have a repository.
509         self.repository = libstack.Repository.default()