14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
from __future__ import absolute_import
18
from StringIO import StringIO
22
from . import lazy_import
23
lazy_import.lazy_import(globals(), """
25
22
branch as _mod_branch,
32
28
revision as _mod_revision,
37
from breezy.bzr import (
40
from breezy.bzr.bundle import (
34
from bzrlib.bundle import (
41
35
serializer as bundle_serializer,
37
from bzrlib.email_message import EmailMessage
52
40
class MergeRequestBodyParams(object):
68
56
"""Hooks for MergeDirective classes."""
70
58
def __init__(self):
71
hooks.Hooks.__init__(self, "breezy.merge_directive",
72
"BaseMergeDirective.hooks")
59
hooks.Hooks.__init__(self)
60
self.create_hook(hooks.HookPoint('merge_request_body',
75
61
"Called with a MergeRequestBodyParams when a body is needed for"
76
62
" a merge request. Callbacks must return a body. If more"
77
63
" than one callback is registered, the output of one callback is"
78
" provided to the next.", (1, 15, 0))
64
" provided to the next.", (1, 15, 0), False))
81
67
class BaseMergeDirective(object):
82
68
"""A request to perform a merge into a branch.
84
This is the base class that all merge directive implementations
70
This is the base class that all merge directive implementations
85
71
should derive from.
87
:cvar multiple_output_files: Whether or not this merge directive
73
:cvar multiple_output_files: Whether or not this merge directive
88
74
stores a set of revisions in more than one file
93
79
multiple_output_files = False
95
81
def __init__(self, revision_id, testament_sha1, time, timezone,
96
target_branch, patch=None, source_branch=None,
97
message=None, bundle=None):
82
target_branch, patch=None, source_branch=None, message=None,
100
86
:param revision_id: The revision to merge
103
89
:param time: The current POSIX timestamp time
104
90
:param timezone: The timezone offset
105
:param target_branch: Location of branch to apply the merge to
91
:param target_branch: The branch to apply the merge to
106
92
:param patch: The text of a diff or bundle
107
93
:param source_branch: A public location to merge the revision from
108
94
:param message: The message to use when committing this merge
151
137
stanza.add(key, self.__dict__[key])
152
138
if base_revision:
153
139
stanza.add('base_revision_id', self.base_revision_id)
154
lines = [b'# ' + self._format_string + b'\n']
140
lines = ['# ' + self._format_string + '\n']
155
141
lines.extend(rio.to_patch_lines(stanza))
156
lines.append(b'# \n')
159
145
def write_to_directory(self, path):
167
153
def from_objects(klass, repository, revision_id, time, timezone,
168
target_branch, patch_type='bundle',
169
local_target_branch=None, public_branch=None, message=None):
154
target_branch, patch_type='bundle',
155
local_target_branch=None, public_branch=None, message=None):
170
156
"""Generate a merge directive from various objects
172
158
:param repository: The repository containing the revision
176
162
:param target_branch: The url of the branch to merge into
177
163
:param patch_type: 'bundle', 'diff' or None, depending on the type of
179
:param local_target_branch: the submit branch, either itself or a local copy
180
:param public_branch: location of a public branch containing
165
:param local_target_branch: a local copy of the target branch
166
:param public_branch: location of a public branch containing the target
182
168
:param message: Message to use when committing the merge
183
169
:return: The merge directive
192
178
if revision_id == _mod_revision.NULL_REVISION:
193
179
t_revision_id = None
194
180
t = testament.StrictTestament3.from_revision(repository, t_revision_id)
195
if local_target_branch is None:
196
submit_branch = _mod_branch.Branch.open(target_branch)
198
submit_branch = local_target_branch
181
submit_branch = _mod_branch.Branch.open(target_branch)
199
182
if submit_branch.get_public_branch() is not None:
200
183
target_branch = submit_branch.get_public_branch()
201
184
if patch_type is None:
209
192
submit_revision_id)
210
193
type_handler = {'bundle': klass._generate_bundle,
211
194
'diff': klass._generate_diff,
212
None: lambda x, y, z: None}
195
None: lambda x, y, z: None }
213
196
patch = type_handler[patch_type](repository, revision_id,
222
205
return klass(revision_id, t.as_sha1(), time, timezone, target_branch,
223
patch, patch_type, public_branch, message)
206
patch, patch_type, public_branch, message)
225
208
def get_disk_name(self, branch):
226
209
"""Generate a suitable basename for storing this directive on disk
232
215
if self.revision_id == revision_id:
236
revno = branch.revision_id_to_dotted_revno(self.revision_id)
237
except errors.NoSuchRevision:
239
nick = re.sub('(\\W+)', '-', branch.nick).strip('-')
218
revno = branch.get_revision_id_to_revno_map().get(self.revision_id,
220
nick = re.sub('(\W+)', '-', branch.nick).strip('-')
240
221
return '%s-%s' % (nick, '.'.join(str(n) for n in revno))
243
224
def _generate_diff(repository, revision_id, ancestor_id):
244
225
tree_1 = repository.revision_tree(ancestor_id)
245
226
tree_2 = repository.revision_tree(revision_id)
247
228
diff.show_diff_trees(tree_1, tree_2, s, old_label='', new_label='')
248
229
return s.getvalue()
251
232
def _generate_bundle(repository, revision_id, ancestor_id):
253
234
bundle_serializer.write_bundle(repository, revision_id,
255
236
return s.getvalue()
260
241
:param branch: The source branch, to get the signing strategy
261
242
:return: a string
263
my_gpg = gpg.GPGStrategy(branch.get_config_stack())
264
return my_gpg.sign(b''.join(self.to_lines()), gpg.MODE_CLEAR)
244
my_gpg = gpg.GPGStrategy(branch.get_config())
245
return my_gpg.sign(''.join(self.to_lines()))
266
247
def to_email(self, mail_to, branch, sign=False):
267
248
"""Serialize as an email message.
282
263
body = self.to_signed(branch)
284
body = b''.join(self.to_lines())
285
message = email_message.EmailMessage(mail_from, mail_to, subject,
265
body = ''.join(self.to_lines())
266
message = EmailMessage(mail_from, mail_to, subject, body)
289
269
def install_revisions(self, target_repo):
291
271
if not target_repo.has_revision(self.revision_id):
292
272
if self.patch_type == 'bundle':
293
273
info = bundle_serializer.read_bundle(
294
BytesIO(self.get_raw_bundle()))
274
StringIO(self.get_raw_bundle()))
295
275
# We don't use the bundle's target revision, because
296
276
# MergeDirective.revision_id is authoritative.
309
289
info.real_revisions)
310
290
for revision in info.real_revisions:
311
291
for parent_id in revision.parent_ids:
312
if (parent_id not in bundle_revisions
313
and not target_repo.has_revision(parent_id)):
292
if (parent_id not in bundle_revisions and
293
not target_repo.has_revision(parent_id)):
314
294
missing_revisions.append(parent_id)
315
295
# reverse missing revisions to try to get heads first
316
296
unique_missing = []
355
335
elif len(self.hooks['merge_request_body']) > 0:
356
336
trace.warning('Cannot run merge_request_body hooks because mail'
357
337
' client %s does not support message bodies.',
358
mail_client.__class__.__name__)
338
mail_client.__class__.__name__)
359
339
mail_client.compose_merge_request(to, subject,
360
b''.join(self.to_lines()),
340
''.join(self.to_lines()),
377
357
directly using the standard patch program.
380
_format_string = b'Bazaar merge directive format 1'
360
_format_string = 'Bazaar merge directive format 1'
382
362
def __init__(self, revision_id, testament_sha1, time, timezone,
383
363
target_branch, patch=None, patch_type=None,
390
370
:param time: The current POSIX timestamp time
391
371
:param timezone: The timezone offset
392
:param target_branch: Location of the branch to apply the merge to
372
:param target_branch: The branch to apply the merge to
393
373
:param patch: The text of a diff or bundle
394
374
:param patch_type: None, "diff" or "bundle", depending on the contents
397
377
:param message: The message to use when committing this merge
399
379
BaseMergeDirective.__init__(self, revision_id, testament_sha1, time,
400
timezone, target_branch, patch, source_branch, message)
380
timezone, target_branch, patch, source_branch, message)
401
381
if patch_type not in (None, 'diff', 'bundle'):
402
382
raise ValueError(patch_type)
403
383
if patch_type != 'bundle' and source_branch is None:
464
444
kwargs['revision_id'] = kwargs['revision_id'].encode('utf-8')
465
if 'testament_sha1' in kwargs:
466
kwargs['testament_sha1'] = kwargs['testament_sha1'].encode('ascii')
467
445
return MergeDirective(time=time, timezone=timezone,
468
446
patch_type=patch_type, patch=patch, **kwargs)
491
469
class MergeDirective2(BaseMergeDirective):
493
_format_string = b'Bazaar merge directive format 2 (Bazaar 0.90)'
471
_format_string = 'Bazaar merge directive format 2 (Bazaar 0.90)'
495
473
def __init__(self, revision_id, testament_sha1, time, timezone,
496
474
target_branch, patch=None, source_branch=None, message=None,
498
476
if source_branch is None and bundle is None:
499
477
raise errors.NoMergeSource()
500
478
BaseMergeDirective.__init__(self, revision_id, testament_sha1, time,
501
timezone, target_branch, patch, source_branch, message)
479
timezone, target_branch, patch, source_branch, message)
502
480
self.bundle = bundle
503
481
self.base_revision_id = base_revision_id
531
start = next(line_iter)
509
start = line_iter.next()
532
510
except StopIteration:
535
if start.startswith(b'# Begin patch'):
513
if start.startswith('# Begin patch'):
537
515
for line in line_iter:
538
if line.startswith(b'# Begin bundle'):
516
if line.startswith('# Begin bundle'):
541
519
patch_lines.append(line)
544
patch = b''.join(patch_lines)
522
patch = ''.join(patch_lines)
545
523
if start is not None:
546
if start.startswith(b'# Begin bundle'):
547
bundle = b''.join(line_iter)
524
if start.startswith('# Begin bundle'):
525
bundle = ''.join(line_iter)
549
527
raise errors.IllegalMergeDirectivePayload(start)
550
528
time, timezone = timestamp.parse_patch_date(stanza.get('timestamp'))
558
536
kwargs['revision_id'] = kwargs['revision_id'].encode('utf-8')
559
537
kwargs['base_revision_id'] =\
560
538
kwargs['base_revision_id'].encode('utf-8')
561
if 'testament_sha1' in kwargs:
562
kwargs['testament_sha1'] = kwargs['testament_sha1'].encode('ascii')
563
539
return klass(time=time, timezone=timezone, patch=patch, bundle=bundle,
566
542
def to_lines(self):
567
543
lines = self._to_lines(base_revision=True)
568
544
if self.patch is not None:
569
lines.append(b'# Begin patch\n')
545
lines.append('# Begin patch\n')
570
546
lines.extend(self.patch.splitlines(True))
571
547
if self.bundle is not None:
572
lines.append(b'# Begin bundle\n')
548
lines.append('# Begin bundle\n')
573
549
lines.extend(self.bundle.splitlines(True))
577
553
def from_objects(klass, repository, revision_id, time, timezone,
578
target_branch, include_patch=True, include_bundle=True,
579
local_target_branch=None, public_branch=None, message=None,
580
base_revision_id=None):
554
target_branch, include_patch=True, include_bundle=True,
555
local_target_branch=None, public_branch=None, message=None,
556
base_revision_id=None):
581
557
"""Generate a merge directive from various objects
583
559
:param repository: The repository containing the revision
587
563
:param target_branch: The url of the branch to merge into
588
564
:param include_patch: If true, include a preview patch
589
565
:param include_bundle: If true, include a bundle
590
:param local_target_branch: the target branch, either itself or a local copy
591
:param public_branch: location of a public branch containing
566
:param local_target_branch: a local copy of the target branch
567
:param public_branch: location of a public branch containing the target
593
569
:param message: Message to use when committing the merge
594
570
:return: The merge directive
599
575
If the message is not supplied, the message from revision_id will be
600
576
used for the commit.
602
with cleanup.ExitStack() as exit_stack:
603
exit_stack.enter_context(repository.lock_write())
580
repository.lock_write()
581
locked.append(repository)
604
582
t_revision_id = revision_id
605
if revision_id == b'null:':
583
if revision_id == 'null:':
606
584
t_revision_id = None
607
585
t = testament.StrictTestament3.from_revision(repository,
609
if local_target_branch is None:
610
submit_branch = _mod_branch.Branch.open(target_branch)
612
submit_branch = local_target_branch
613
exit_stack.enter_context(submit_branch.lock_read())
587
submit_branch = _mod_branch.Branch.open(target_branch)
588
submit_branch.lock_read()
589
locked.append(submit_branch)
614
590
if submit_branch.get_public_branch() is not None:
615
591
target_branch = submit_branch.get_public_branch()
616
592
submit_revision_id = submit_branch.last_revision()
631
607
if include_bundle:
632
bundle = base64.b64encode(klass._generate_bundle(repository, revision_id,
608
bundle = klass._generate_bundle(repository, revision_id,
609
ancestor_id).encode('base-64')
637
613
if public_branch is not None and not include_bundle:
638
614
public_branch_obj = _mod_branch.Branch.open(public_branch)
639
exit_stack.enter_context(public_branch_obj.lock_read())
615
public_branch_obj.lock_read()
616
locked.append(public_branch_obj)
640
617
if not public_branch_obj.repository.has_revision(
642
619
raise errors.PublicBranchOutOfDate(public_branch,
644
621
testament_sha1 = t.as_sha1()
623
for entry in reversed(locked):
645
625
return klass(revision_id, testament_sha1, time, timezone,
646
target_branch, patch, public_branch, message, bundle,
626
target_branch, patch, public_branch, message, bundle,
649
629
def _verify_patch(self, repository):
650
630
calculated_patch = self._generate_diff(repository, self.revision_id,
651
631
self.base_revision_id)
652
632
# Convert line-endings to UNIX
653
stored_patch = re.sub(b'\r\n?', b'\n', self.patch)
654
calculated_patch = re.sub(b'\r\n?', b'\n', calculated_patch)
633
stored_patch = re.sub('\r\n?', '\n', self.patch)
634
calculated_patch = re.sub('\r\n?', '\n', calculated_patch)
655
635
# Strip trailing whitespace
656
calculated_patch = re.sub(b' *\n', b'\n', calculated_patch)
657
stored_patch = re.sub(b' *\n', b'\n', stored_patch)
636
calculated_patch = re.sub(' *\n', '\n', calculated_patch)
637
stored_patch = re.sub(' *\n', '\n', stored_patch)
658
638
return (calculated_patch == stored_patch)
660
640
def get_merge_request(self, repository):