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