1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
|
import argparse
import logging
import os
from pygit2 import Commit
import shutil
import subprocess
import sys
import tempfile
import textwrap
from gitubuntu.git_repository import GitUbuntuRepository, git_dep14_tag
from gitubuntu.run import decode_binary, run
from gitubuntu.source_information import GitUbuntuSourceInformation
from gitubuntu.versioning import version_compare
class TagException(Exception):
pass
class ReconstructException(Exception):
pass
def parse_args(subparsers=None, base_subparsers=None):
kwargs = dict(description='Given a %(prog)s import\'d tree, assist with an Ubuntu merge',
formatter_class=argparse.RawTextHelpFormatter,
epilog='Creates old/ubuntu, old/debian and new/debian '
'tags for the specified Ubuntu merge.\n'
'Breaks the specified Ubuntu merge '
'into a sequence of non-git-merge-commits '
'suitable for rebasing.\n'
'Working tree must be clean.'
)
if base_subparsers:
kwargs['parents'] = base_subparsers
if subparsers:
parser = subparsers.add_parser('merge', **kwargs)
parser.set_defaults(func=cli_main)
else:
parser = argparse.ArgumentParser(**kwargs)
parser.add_argument('subsubcommand',
help='start - Breakup Ubuntu delta into individual commits\n'
'finish - Construct d/changelog suitable for uploading. '
'`%(prog)s merge start` must have been run first.',
metavar='start|finish',
choices=['start', 'finish'])
width, _ = shutil.get_terminal_size()
subhelp_width = width - 30
subhelp_text = '\n'.join(textwrap.wrap(
'A reference to a commit whose corresponding ' +
'version is to be merged.',
subhelp_width
)
)
parser.add_argument('commitish',
type=str,
help=subhelp_text
)
subhelp_text = '\n'.join(textwrap.wrap(
'A reference to a commit whose corresponding ' +
'version to prepare to merge with. If not ' +
'specified, debian/sid is used. ' +
'If <onto> does not already exist as a ' +
'local branch, it will be created and track ' +
'pkg/<onto>.',
subhelp_width
)
)
parser.add_argument('onto',
help=subhelp_text,
type=str,
default='debian/sid',
nargs='?'
)
parser.add_argument('--bug',
help='Launchpad bug to close with this merge.',
type=str)
parser.add_argument('--release', type=str,
help='Ubuntu release to target with merge. If not '
'specified, the current development release from '
'Launchpad is used.')
parser.add_argument('-d', '--directory', type=str,
help='Use git repository at specified location.',
default=os.path.abspath(os.getcwd())
)
parser.add_argument('-f', '--force',
help='Overwrite existing tags and branches, where '
'applicable.',
action='store_true'
)
parser.add_argument('--tag-only',
help='When rebasing a previous merge, only '
'tag old/ubuntu, old/debian and new/debian.',
action='store_true'
)
if not subparsers:
return parser.parse_args()
return 'merge - %s' % kwargs['description']
def cli_main(args):
return main(
directory=args.directory,
commitish=args.commitish,
onto=args.onto,
force=args.force,
tag_only=args.tag_only,
bug=args.bug,
release=args.release,
subcommand=args.subsubcommand,
)
def do_tag(repo, tag_prefix, commitish, merge_base_commit_hash, onto, force):
errors = False
try:
repo.tag('%sold/ubuntu' % tag_prefix, commitish, force)
except:
errors = True
try:
repo.tag('%sold/debian' % tag_prefix, merge_base_commit_hash, force)
except:
errors = True
try:
repo.tag('%snew/debian' % tag_prefix, onto, force)
except:
errors = True
if errors:
raise TagException('Failed to tag commits.')
def do_reconstruct(repo, tag_prefix, commitish, merge_base_commit_hash, force):
versions=()
repo.checkout_commitish(merge_base_commit_hash)
stdout, _ = repo.git_run(
[
'rev-list',
'--ancestry-path',
'--reverse',
'%s..%s' % (merge_base_commit_hash, commitish),
],
decode=False,
)
for commit in stdout.split(b'\n'):
commit = decode_binary(commit).strip()
# empty newline
if len(commit) == 0:
continue
obj = repo.get_commitish(commit)
args = [
'cherry-pick',
'--allow-empty',
'--keep-redundant-commits',
]
if len(obj.peel(Commit).parents) > 1:
args += ['-m', '2']
args += [str(obj.id)]
repo.git_run(args)
try:
repo.git_run(['diff', '--exit-code', commitish])
except:
logging.error(
"Resulting cleaned-up commit is not "
"source-identical to %s",
commitish
)
raise ReconstructException("Failed to reconstruct commit.")
old_head_version, _ = repo.get_changelog_versions_from_treeish(commitish)
repo.tag(
'%sreconstruct/%s' % (tag_prefix, git_dep14_tag(old_head_version)),
str(repo.get_commitish('HEAD').id),
force,
)
def do_start(repo, tag_prefix, commitish, merge_base_commit_hash, onto, force, tag_only):
try:
do_tag(repo, tag_prefix, commitish, merge_base_commit_hash, onto, force)
if not tag_only:
do_reconstruct(repo, tag_prefix, commitish, merge_base_commit_hash, force)
return 0
except (TagException, ReconstructException):
return 1
def do_merge_changelogs(repo, commitish, merge_base_commit_hash, onto):
# save merge_base_commit_hash:debian/changelog to tmp file
old_debian_changelog = repo.extract_file_from_treeish(
merge_base_commit_hash,
'debian/changelog',
)
old_ubuntu_changelog = repo.extract_file_from_treeish(
commitish,
'debian/changelog',
)
new_debian_changelog = repo.extract_file_from_treeish(
onto,
'debian/changelog',
)
run(
[
'dpkg-mergechangelogs',
old_debian_changelog.name,
old_ubuntu_changelog.name,
new_debian_changelog.name,
'debian/changelog',
]
)
# handle conflicts
repo.git_run(['commit', '-m', 'merge-changelogs', 'debian/changelog'])
old_debian_changelog.close()
old_ubuntu_changelog.close()
new_debian_changelog.close()
def do_reconstruct_changelog(repo, onto, release, bug):
# XXX: extract release from launchpad, add flag
distribution = release
if not distribution:
# Don't need most arguments here as we're only grabbing some
# data from launchpad about the active series
ubuntu_source_information = GitUbuntuSourceInformation(
'ubuntu',
None
)
distribution = ubuntu_source_information.active_series_name_list[0]
run(
[
'dch',
'--force-distribution',
'--distribution',
distribution,
'PLACEHOLDER',
]
)
with tempfile.NamedTemporaryFile(mode='w+t', delete=False) as fp:
with open('debian/changelog', 'r+t') as dch:
for line in dch:
if 'PLACEHOLDER' in line:
fp.write(' * Merge with Debian unstable')
if bug:
fp.write(' (LP: #%s)' % bug)
fp.write('. Remaining changes:\n')
# merge-changelogs is HEAD
stdout, _ = repo.git_run(
['rev-list', '--reverse', '%s..HEAD^' % onto,]
)
for rev in stdout.splitlines():
out, _ = repo.git_run(
['log', '--pretty=%B', '-n', '1', rev,]
)
look_for_marker = False
if '--CL--' in out:
look_for_marker = True
# None implies changelog entry not yet seen
top_level_changelog = None
message = ''
for s in out.splitlines():
# Skip blanklines
if not s:
continue
if look_for_marker:
if '--CL--' in s:
look_for_marker = False
else:
if '--CL--' in s:
break
if top_level_changelog is None:
top_level_changelog = False
if s.strip().startswith('*'):
top_level_changelog = True
# Don't close old bugs, but close new bugs
if top_level_changelog is False:
s = s.replace('LP:', 'LP')
message += s + '\n'
fp.write(message)
else:
fp.write(line)
fp.flush()
shutil.move(fp.name, dch.name)
dch.flush()
repo.git_run(['commit', '-m', 'reconstruct-changelog', 'debian/changelog'])
def do_update_maintainer(repo):
run(['update-maintainer'])
paths = []
for path in ['debian/control', 'debian/control.in']:
if os.path.exists(path):
paths.append(path)
cmd = ['commit', '-m', 'update-maintainer']
cmd.extend(paths)
repo.git_run(cmd)
def do_finish(repo, tag_prefix, commitish, merge_base_commit_hash, onto, release, bug, force):
# 0) check is either new/debian or lp#/new/debian is an ancestor
# of HEAD
ancestor_check = False
ancestors_checked = set()
# if --bug was not passed, merge-base will fail because it
# can't find the bug-specific tag
try:
ancestors_checked.add('%snew/debian' % tag_prefix)
repo.git_run(
[
'merge-base',
'--is-ancestor',
'%snew/debian' % tag_prefix,
'HEAD',
],
verbose_on_failure=False,
)
ancestor_check = True
except subprocess.CalledProcessError as e:
try:
ancestors_checked.add('new/debian')
repo.git_run(
['merge-base', '--is-ancestor', 'new/debian', 'HEAD'],
verbose_on_failure=False,
)
ancestor_check = True
except subprocess.CalledProcessError as e:
pass
if not ancestor_check:
if len(ancestors_checked) > 1:
msg = ' and '.join(ancestors_checked) + ' are not ancestors'
else:
msg = '%s is not an ancestor' % ancestors_checked.pop()
if force:
logging.error("%s of the HEAD commit, but --force passed.", msg)
else:
logging.error(
"%s of the HEAD commit. Did you run `git-ubuntu merge "
"start` first? (Pass -f to force the merge).",
msg
)
return 1
# 1) git merge-changelogs old/ubuntu old/debian new/debian
do_merge_changelogs(repo, commitish, merge_base_commit_hash, onto)
# 2) git reconstruct-changelog <onto>
do_reconstruct_changelog(repo, onto, release, bug)
# TODO elide from each entry any lines outside of changelog-markers
# (add flag to specify it?)
# 3) update-maintainer
do_update_maintainer(repo)
return 0
def main(
directory,
commitish,
onto,
force,
tag_only,
bug,
release,
subcommand,
):
"""Entry point to merge
Arguments:
@directory: string path to directory containing local repository
@commitish: string commitish to merge
@onto: string commitish to merge to
@force: if True, overwrite objects in the repository rather than
erroring
@tag_only: if True, only create tags in the local repository
@bug: string bug number closed by this merge
@release: string Ubuntu release to target this merge to
@subcommand: string merge stage to run, one of 'start' or 'finish'
Returns 0 if the subcommand completes successfully; 1 otherwise.
"""
repo = GitUbuntuRepository(directory)
tag_prefix = ''
if bug:
tag_prefix = 'lp%s/' % bug
try:
commitish_obj = repo.get_commitish(commitish)
except KeyError:
logging.error(
"%s is not a defined object in this git repository.",
commitish
)
return 1
commitish_version, _ = repo.get_changelog_versions_from_treeish(
str(commitish_obj.id),
)
try:
onto_obj = repo.get_commitish(onto)
onto_version, _ = repo.get_changelog_versions_from_treeish(onto)
if version_compare(commitish_version, onto_version) >= 0:
if force:
logging.info(
"%s version (%s) is after %s version (%s), "
"but --force passed.",
commitish,
commitish_version,
onto,
onto_version,
)
else:
logging.error(
"%s version (%s) is after %s version (%s). "
"Are you sure you want to merge? "
"(Pass -f to force the merge).",
commitish,
commitish_version,
onto,
onto_version,
)
return 1
except KeyError:
logging.info("%s is not a defined object in this git repository.", onto)
logging.info(
"Creating a local branch named %s tracking pkg/%s.",
onto,
onto,
)
try:
branch = repo.create_tracking_branch(
onto,
'pkg/%s' % onto,
force=force,
)
except:
logging.error(
"Failed to create local branch (%s). "
"Does it already exist (pass -f)?",
onto,
)
return 1
onto_obj = repo.get_commitish(onto)
stdout, _ = run(['git', 'status', '--porcelain'])
if len(stdout) > 0:
logging.error('Working tree must be clean to continue:')
logging.error(stdout)
return 1
merge_base_commit_hash = repo.find_ubuntu_merge_base(commitish)
if not merge_base_commit_hash:
logging.error(
"Unable to find a common ancestor for %s and %s.",
onto,
commitish,
)
return 1
if merge_base_commit_hash == str(onto_obj.id):
logging.error(
"The common ancestor of %s and %s is "
"identical to %s. No merge is necessary.",
onto,
commitish,
onto,
)
return 1
merge_base_version, _ = repo.get_changelog_versions_from_treeish(
merge_base_commit_hash,
)
if subcommand == 'start':
return do_start(
repo,
tag_prefix,
commitish,
merge_base_commit_hash,
onto,
force,
tag_only,
)
elif subcommand == 'finish':
return do_finish(
repo,
tag_prefix,
commitish,
merge_base_commit_hash,
onto,
release,
bug,
force,
)
|