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
|
#
# main.py - main function for sponsor-patch script
#
# Copyright (C) 2010, Benjamin Drung <bdrung@ubuntu.com>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
from __future__ import print_function
import os
import pwd
import shutil
import sys
from distro_info import UbuntuDistroInfo
from launchpadlib.launchpad import Launchpad
from ubuntutools import subprocess
from ubuntutools.logger import Logger
from ubuntutools.update_maintainer import (update_maintainer,
MaintainerUpdateException)
from ubuntutools.question import input_number
from ubuntutools.sponsor_patch.bugtask import BugTask, is_sync
from ubuntutools.sponsor_patch.patch import Patch
from ubuntutools.sponsor_patch.question import ask_for_manual_fixing
from ubuntutools.sponsor_patch.source_package import SourcePackage
if sys.version_info[0] < 3:
range = xrange # noqa, pylint: disable=redefined-builtin,undefined-variable
def is_command_available(command, check_sbin=False):
"Is command in $PATH?"
path = os.environ.get('PATH', '/usr/bin:/bin').split(':')
if check_sbin:
path += [directory[:-3] + 'sbin'
for directory in path if directory.endswith('/bin')]
return any(os.access(os.path.join(directory, command), os.X_OK)
for directory in path)
def check_dependencies():
"Do we have all the commands we need for full functionality?"
missing = []
for cmd in ('patch', 'bzr', 'quilt', 'dput', 'lintian'):
if not is_command_available(cmd):
missing.append(cmd)
if not is_command_available('bzr-buildpackage'):
missing.append('bzr-builddeb')
if not any(is_command_available(cmd, check_sbin=True)
for cmd in ('pbuilder', 'sbuild', 'cowbuilder')):
missing.append('pbuilder/cowbuilder/sbuild')
if missing:
Logger.warn("sponsor-patch requires %s to be installed for full "
"functionality", ', '.join(missing))
def get_source_package_name(bug_task):
package = None
if bug_task.bug_target_name != "ubuntu":
assert bug_task.bug_target_name.endswith("(Ubuntu)")
package = bug_task.bug_target_name.split(" ")[0]
return package
def get_user_shell():
try:
shell = os.environ["SHELL"]
except KeyError:
shell = pwd.getpwuid(os.getuid())[6]
return shell
def edit_source():
# Spawn shell to allow modifications
cmd = [get_user_shell()]
Logger.command(cmd)
print("""An interactive shell was launched in
file://%s
Edit your files. When you are done, exit the shell. If you wish to abort the
process, exit the shell such that it returns an exit code other than zero.
""" % (os.getcwd()), end=' ')
returncode = subprocess.call(cmd)
if returncode != 0:
Logger.error("Shell exited with exit value %i." % (returncode))
sys.exit(1)
def ask_for_patch_or_branch(bug, attached_patches, linked_branches):
patch = None
branch = None
if len(attached_patches) == 0:
msg = "https://launchpad.net/bugs/%i has %i branches linked:" % \
(bug.id, len(linked_branches))
elif len(linked_branches) == 0:
msg = "https://launchpad.net/bugs/%i has %i patches attached:" % \
(bug.id, len(attached_patches))
else:
branches = "%i branch" % len(linked_branches)
if len(linked_branches) > 1:
branches += "es"
patches = "%i patch" % len(attached_patches)
if len(attached_patches) > 1:
patches += "es"
msg = "https://launchpad.net/bugs/%i has %s linked and %s attached:" % \
(bug.id, branches, patches)
Logger.normal(msg)
i = 0
for linked_branch in linked_branches:
i += 1
print("%i) %s" % (i, linked_branch.display_name))
for attached_patch in attached_patches:
i += 1
print("%i) %s" % (i, attached_patch.title))
selected = input_number("Which branch or patch do you want to download",
1, i, i)
if selected <= len(linked_branches):
branch = linked_branches[selected - 1].bzr_identity
else:
patch = Patch(attached_patches[selected - len(linked_branches) - 1])
return (patch, branch)
def get_patch_or_branch(bug):
patch = None
branch = None
if not is_sync(bug):
attached_patches = [a for a in bug.attachments if a.type == "Patch"]
linked_branches = [b.branch for b in bug.linked_branches]
if len(attached_patches) == 0 and len(linked_branches) == 0:
if len(bug.attachments) == 0:
Logger.error("No attachment and no linked branch found on "
"bug #%i. Add the tag sync to the bug if it is "
"a sync request.", bug.id)
else:
Logger.error("No attached patch and no linked branch found. "
"Go to https://launchpad.net/bugs/%i and mark an "
"attachment as patch.", bug.id)
sys.exit(1)
elif len(attached_patches) == 1 and len(linked_branches) == 0:
patch = Patch(attached_patches[0])
elif len(attached_patches) == 0 and len(linked_branches) == 1:
branch = linked_branches[0].bzr_identity
else:
patch, branch = ask_for_patch_or_branch(bug, attached_patches,
linked_branches)
return (patch, branch)
def download_branch(branch):
dir_name = os.path.basename(branch)
if os.path.isdir(dir_name):
shutil.rmtree(dir_name)
cmd = ["bzr", "branch", branch]
Logger.command(cmd)
if subprocess.call(cmd) != 0:
Logger.error("Failed to download branch %s." % (branch))
sys.exit(1)
return dir_name
def merge_branch(branch):
edit = False
cmd = ["bzr", "merge", branch]
Logger.command(cmd)
if subprocess.call(cmd) != 0:
Logger.error("Failed to merge branch %s." % (branch))
ask_for_manual_fixing()
edit = True
return edit
def extract_source(dsc_file, verbose=False):
cmd = ["dpkg-source", "--no-preparation", "-x", dsc_file]
if not verbose:
cmd.insert(1, "-q")
Logger.command(cmd)
if subprocess.call(cmd) != 0:
Logger.error("Extraction of %s failed." % (os.path.basename(dsc_file)))
sys.exit(1)
def get_open_ubuntu_bug_task(launchpad, bug, branch=None):
"""Returns an open Ubuntu bug task for a given Launchpad bug.
The bug task needs to be open (not complete) and target Ubuntu. The user
will be ask to select one if multiple open Ubuntu bug task exits for the
bug.
"""
bug_tasks = [BugTask(x, launchpad) for x in bug.bug_tasks]
ubuntu_tasks = [x for x in bug_tasks if x.is_ubuntu_task()]
bug_id = bug.id
if branch:
branch = branch.split('/')
# Non-production LP?
if len(branch) > 5:
branch = branch[3:]
if len(ubuntu_tasks) == 0:
Logger.error("No Ubuntu bug task found on bug #%i." % (bug_id))
sys.exit(1)
elif len(ubuntu_tasks) == 1:
task = ubuntu_tasks[0]
if len(ubuntu_tasks) > 1 and branch and branch[1] == 'ubuntu':
tasks = [t for t in ubuntu_tasks if
t.get_series() == branch[2] and t.package == branch[3]]
if len(tasks) > 1:
# A bug targeted to the development series?
tasks = [t for t in tasks if t.series is not None]
assert len(tasks) == 1
task = tasks[0]
elif len(ubuntu_tasks) > 1:
task_list = [t.get_short_info() for t in ubuntu_tasks]
Logger.info("%i Ubuntu tasks exist for bug #%i.\n%s", len(ubuntu_tasks),
bug_id, "\n".join(task_list))
open_ubuntu_tasks = [x for x in ubuntu_tasks if not x.is_complete()]
if len(open_ubuntu_tasks) == 1:
task = open_ubuntu_tasks[0]
else:
Logger.normal("https://launchpad.net/bugs/%i has %i Ubuntu tasks:" %
(bug_id, len(ubuntu_tasks)))
for i in range(len(ubuntu_tasks)):
print("%i) %s" % (i + 1,
ubuntu_tasks[i].get_package_and_series()))
selected = input_number("To which Ubuntu task does the patch belong",
1, len(ubuntu_tasks))
task = ubuntu_tasks[selected - 1]
Logger.info("Selected Ubuntu task: %s" % (task.get_short_info()))
return task
def _create_and_change_into(workdir):
"""Create (if it does not exits) and change into given working directory."""
if not os.path.isdir(workdir):
try:
os.makedirs(workdir)
except os.error as error:
Logger.error("Failed to create the working directory %s [Errno %i]: %s." %
(workdir, error.errno, error.strerror))
sys.exit(1)
if workdir != os.getcwd():
Logger.command(["cd", workdir])
os.chdir(workdir)
def _update_maintainer_field():
"""Update the Maintainer field in debian/control."""
Logger.command(["update-maintainer"])
try:
update_maintainer("debian", Logger.verbose)
except MaintainerUpdateException as e:
Logger.error("update-maintainer failed: %s", str(e))
sys.exit(1)
def _update_timestamp():
"""Run dch to update the timestamp of debian/changelog."""
cmd = ["dch", "--maintmaint", "--release", ""]
Logger.command(cmd)
if subprocess.call(cmd) != 0:
Logger.info("Failed to update timestamp in debian/changelog.")
def _download_and_change_into(task, dsc_file, patch, branch):
"""Downloads the patch and branch and changes into the source directory."""
if branch:
branch_dir = download_branch(task.get_branch_link())
# change directory
Logger.command(["cd", branch_dir])
os.chdir(branch_dir)
else:
if patch:
patch.download()
Logger.info("Ubuntu package: %s" % (task.package))
if task.is_merge():
Logger.info("The task is a merge request.")
if task.is_sync():
Logger.info("The task is a sync request.")
extract_source(dsc_file, Logger.verbose)
# change directory
directory = task.package + '-' + task.get_version().upstream_version
Logger.command(["cd", directory])
os.chdir(directory)
def sponsor_patch(bug_number, build, builder, edit, keyid, lpinstance, update,
upload, workdir):
workdir = os.path.realpath(os.path.expanduser(workdir))
_create_and_change_into(workdir)
launchpad = Launchpad.login_with("sponsor-patch", lpinstance)
bug = launchpad.bugs[bug_number]
(patch, branch) = get_patch_or_branch(bug)
task = get_open_ubuntu_bug_task(launchpad, bug, branch)
dsc_file = task.download_source()
_download_and_change_into(task, dsc_file, patch, branch)
source_package = SourcePackage(task.package, builder, workdir, branch)
if is_sync(bug) and not edit:
successful = source_package.reload_changelog()
if successful:
source_package.check_sync_request_version(bug_number, task)
previous_version = task.get_previous_version()
successful = source_package.check_version(previous_version)
if successful:
if build:
dist = UbuntuDistroInfo().devel()
successful = source_package.build(update, dist)
update = False
else:
# We are going to run lintian, so we need a source package
successful = source_package.build_source(None, upload,
previous_version)
if successful:
series = task.get_debian_source_series()
if source_package.sync(upload, series, bug_number, bug.owner.name):
return
else:
edit = True
else:
edit = True
if patch:
edit |= patch.apply(task)
elif branch:
edit |= merge_branch(branch)
while True:
if edit:
edit_source()
# All following loop executions require manual editing.
edit = True
_update_maintainer_field()
if not source_package.reload_changelog():
continue
if not source_package.check_version(task.get_version()):
continue
_update_timestamp()
if not source_package.build_source(keyid, upload,
task.get_previous_version()):
continue
source_package.generate_debdiff(dsc_file)
# Make sure that the Launchpad bug will be closed
if not source_package.is_fixed(bug):
continue
if not source_package.check_target(upload, launchpad):
continue
if build:
successful_built = source_package.build(update)
update = False
if not successful_built:
continue
if not source_package.ask_and_upload(upload):
continue
# Leave while loop if everything worked
break
|