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