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