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 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
|
#
# Copyright 2010 Martin Owens
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>
#
"""
Some simple gtk bzr processes.
"""
import sys
import os
import time
import logging
import shutil
import urllib
from GroundControl.gtkcommon import StatusApp
from bzrlib.config import GlobalConfig
from bzrlib.branch import Branch
from bzrlib import ui, urlutils, add
from bzrlib.workingtree import WorkingTree
from bzrlib.transport import get_transport
from bzrlib.plugin import load_plugins
from bzrlib import builtins, errors
class BzrBranch(object):
"""More friendly reprisentation of a bzr branch"""
def __init__(self, location):
self.location = location
self._transport = None
self._url = None
self._branch = None
self._config = None
@property
def transport(self):
"""Return this branch's transport object"""
if not self._transport:
logging.debug("Transporting from '%s'" % self.location)
self._transport = get_transport(self.location)
return self._transport
@property
def url(self):
"""Return the branch's transport external url"""
if not self._url:
self._url = self.transport.external_url()
return self._url
@property
def external_url(self):
"""Always return the external url of the branch"""
if self.path:
return self._branch.get_push_location()
return self.url
@property
def path(self):
"""Return a path only if the branch is local"""
url = urllib.unquote(self.url)
if url[:7] == 'file://':
return url[7:]
@property
def branch(self):
"""Return the bzrlib Branch object"""
if not self._branch:
self._branch = Branch.open_from_transport(self.transport)
return self._branch
@property
def suffix(self):
"""Return the derived results, which normal is the working name"""
return urlutils.derive_to_location(self.location)
@property
def config(self):
"""Returns the branch configuration object"""
if not self._config:
self._config = self.branch.get_config()
return self._config
def get_workingtree(self):
"""Working tree, includes everything but news files"""
(wtr, path) = WorkingTree.open_containing(self.path)
return wtr
def get_oldtree(self):
"""Return the old tree (for comparison"""
return self.branch.repository.revision_tree(self.branch.last_revision())
def get_changes(self):
"""Return a list of changes"""
try:
return self.get_workingtree().changes_from(
self.get_oldtree(), want_unversioned=True)
except AssertionError, message:
logging.error("Couldn't update view, %s" % message)
def push_revno(self, set_to=None):
"""The revision number of the last push."""
return self._config_revno('push_revno', set_to)
def pull_revno(self, set_to=None):
"""The revision number the code was pulled at."""
return self._config_revno('pull_revno', set_to)
def commit_revno(self, set_to=None):
"""The revision number of the last commit."""
return self._config_revno('commit_revno', set_to)
def merge_revno(self, set_to=None):
"""The revision number of the merge request."""
return self._config_revno('merge_revno', set_to)
def _config_revno(self, name, set_to=None):
"""Handle any configuration held revision number."""
if set_to:
if set_to == True:
set_to = self.branch.revno()
self.config.set_user_option(name, str(set_to))
else:
result = self.config.get_user_option(name)
if result:
return int(result)
def has_changes(self):
"""Return true if there are changes"""
return self.get_workingtree().has_changes(self.get_oldtree())
def has_newfiles(self):
"""Return true if there are new unrevisioned files"""
for file in self.get_workingtree().unknowns():
return True
def has_branching(self):
"""Doth return true if branch options file exists"""
loc = self.location
loc = os.path.join(loc, '.bzr', 'branch', 'branch.conf')
return os.path.exists(loc)
def has_commits(self):
"""Doth return True should there be local commits not pushed"""
push_rev = self.push_revno()
commit_rev = self.commit_revno()
pull_rev = self.pull_revno()
local_rev = self.branch.revno()
if not pull_rev:
# This might not be the best way of doing this as there is
# A lot of scope for errors and mis-reading.
logging.debug("The Pull revision wasn't set, so we get it:")
pull_rev = self.get_parent_branch().branch.revno()
self.pull_revno(pull_rev)
if local_rev != commit_rev:
# Don't trust local data if it's different and update it.
push_rev = None
self.commit_revno(True)
commit_rev = local_rev
if not push_rev:
# Then we have a missing or untrusted push revision.
logging.debug("The Push revision wasn't set, so we get it:")
push_rev = self._get_push_rev()
self.push_revno(push_rev)
logging.debug("Commit/Push (%s/%s)." % (
str(commit_rev), str(push_rev)))
return commit_rev > push_rev
def is_child(self):
"""Doth return true should thy parent be pressent and the not same
as the push location, to prevent merge requests for trunks"""
return self.branch.get_parent() != self.branch.get_push_location()
def is_locked(self):
"""Doth return true should the branch be locked"""
return self.branch.get_physical_lock_status()
def has_pushes(self):
"""Doth return True should thy last push revision be
greater than the original pull revision."""
return self.push_revno() > self.pull_revno()
def _get_push_rev(self):
"""Gets the revision of the remote branch"""
remote = self.get_push_branch(check_exists=True)
if not remote:
# We use the parent branch if the push branch doesn't exist
# This is because we assume it's not been pushed yet.
remote = self.get_parent_branch()
return remote.branch.revno()
def get_push_branch(self, check_exists=True):
"""Returns the branch object for the push target as configured"""
try:
result = BzrBranch(self.branch.get_push_location())
if check_exists:
result.branch
return result
except errors.NotBranchError:
logging.debug("Push location not created yet.")
return None
def get_parent_branch(self):
"""Returns the branches original parent remote brance"""
return BzrBranch(self.branch.get_parent())
def get_launchpad_name(self):
"""Return the simple launchpad for of this branch"""
url = self.branch.get_parent()
return 'lp:' + '/'.join(url.split('/')[-4:-1])
def do_delete(self, *args, **kwargs):
"""Delete local branch based on url, but not remote branches."""
path = self.path
if path:
shutil.rmtree(path)
else:
logging.error(_("Unable to remove branch at '%s'") % path)
class GtkUIFactory(ui.UIFactory):
"""Simple Example UI Class"""
def __init__(self, app):
super(GtkUIFactory, self).__init__()
self._total_byte_count = 0
self._bytes_since_update = 0
self._last_task = None
self._transport_update_time = None
self.status_app = app
self.status_app.update(0, _("Please Wait..."))
def report_transport_activity(self, transport, byte_count, direction):
"""Called by transports as they do IO. Update a progress."""
self._total_byte_count += byte_count
self._bytes_since_update += byte_count
if self._last_task:
trans_msg = 'Connecting...'
task_msg = self._format_task(self._last_task)
fraction = self._last_task._overall_completion_fraction()
now = time.time()
if self._transport_update_time is None:
self._transport_update_time = now
elif now >= (self._transport_update_time + 0.5):
# guard against clock stepping backwards, don't update too ofen
rate = self._bytes_since_update / (
now - self._transport_update_time)
trans_msg = ("%6dKB %5dKB/s" %
(self._total_byte_count>>10, int(rate)>>10,))
self.status_app.update(fraction, task_msg, trans_msg)
def _format_task(self, task):
if not task.show_count:
s = ''
elif task.current_cnt is not None and task.total_cnt is not None:
s = ' %d/%d' % (task.current_cnt, task.total_cnt)
elif task.current_cnt is not None:
s = ' %d' % (task.current_cnt)
else:
s = ''
# compose all the parent messages
t = task
m = task.msg
while t._parent_task:
t = t._parent_task
if t.msg:
m = t.msg + ':' + m
return m + s
def _progress_updated(self, task):
"""Called by the task object when it has changed.
:param task: The top task object; its parents are also included
by following links.
"""
must_update = task is not self._last_task
self._last_task = task
self._last_task = task
self.status_app.update()
# See /usr/lib/python2.6/dist-packages/bzrlib/ui/text.py
# See ~/Projects/research/qbzr/lib/uifactory.py
def get_password(self, prompt='', **kwargs):
"""Request a password from the UI"""
pass
def get_username(self, prompt='', **kwargs):
"""Request a username from the UI"""
pass
def get_boolean(self, prompt):
"""Ask the user to choose yes or no to a question"""
# We really ort to be showing a prompt, but can't figure
# It out right now.
#prompt = self.status_app.load_window('prompt',
# _('Bazaar Prompt'), prompt)
return True #prompt.hold()
def clear_term(self):
"""Get ready for a text message output. (clear terminal)"""
pass
class BazaarStatusApp(StatusApp):
"""Add some extra methods in for bazaar actions"""
def load_vars(self, args, kwargs):
"""Strip out the branch variable"""
self.encoding = 'utf-8'
branch = kwargs.pop('branch', None)
if branch and type(branch) is not BzrBranch:
branch = BzrBranch(branch)
self.branch = branch
def do_work(self):
"""Pass on the action"""
ui.ui_factory = GtkUIFactory(self)
load_plugins()
try:
self.do_action()
except errors.BzrError, error:
message = self.translate_error(error)
self.pop_error(_("Bazaar Error"), message)
except IOError, error:
message = _("Not Online")
self.pop_error(_("Bazaar Error"), message)
def translate_error(self, error):
"""Return a useful error message from a bzr error"""
if type(error) == errors.FileExists:
return _("Bazaar directory already exists, can't proceed.")
else:
return str(error)
def do_command(self, command, **kwargs):
"""Generic method for calling builtin bzr methods"""
cmd = getattr(builtins, 'cmd_' + command)()
logging.debug("Running bzr %s on %s" % (command, self.branch.location))
cmd.outf = self
# We have to do it this way because not all
# commands accept a directory input for some reason.
if kwargs.has_key('directory') and not kwargs['directory']:
kwargs['directory'] = self.branch.location
cmd.run( **kwargs )
# Make sure to clean up
cmd.cleanup_now()
def write(self, content):
"""Being used as a file handle, write out"""
self.update( 0.5, content, "Processing..." )
def do_action(self):
"""Replace with sub class method"""
raise NotImplementedError("do_action method for a Bazaar status class.")
class BranchStatusApp(BazaarStatusApp):
"""Perform a bazaar branch action with GUI"""
task_name = _("Retrieving Data")
def load_vars(self, args, kwargs):
"""Load all the branching variables from inputs"""
self.dest = kwargs.pop('path')
self.workname = kwargs.pop('workname')
super(BranchStatusApp, self).load_vars(args, kwargs)
def do_action(self):
"""Actually do the bzr branch action"""
# The workname can contain a full push location, but may not always.
push_lp = self.workname
if 'lp:' not in push_lp:
# We're going to use the user, project name and workname to make
# A preconfigured push location.
config = GlobalConfig()
user = config.get_user_option('launchpad_username')
project = self.branch.url.split('/')[-3]
push_lp = 'lp:~%s/%s/%s' % (user, project, self.workname)
dest_dir = os.path.join(self.dest, self.workname)
else:
dest_dir = os.path.join(self.dest, self.workname.split('/')[-1])
logging.debug("Saving to '%s'" % dest_dir)
# Save the branch contents (creates a new branch)
branched = self.branch.branch.bzrdir.sprout(dest_dir).open_branch()
# Push this through our transport (which includes the plugins)
remote_transport = get_transport(push_lp)
# And set our push directory to this new url
branched.set_push_location(remote_transport.external_url())
# Make a note of the revisions we pulled at.
local_branch = BzrBranch(dest_dir)
local_branch.pull_revno(True)
local_branch.commit_revno(True)
local_branch.push_revno(True)
logging.debug("Branching Complete")
class CheckoutStatusApp(BazaarStatusApp):
"""Perform a bazaar checkout action with GUI"""
task_name = _("Retrieving Data")
def load_vars(self, args, kwargs):
"""Load the checkout variables"""
self.dest = kwargs.pop('path')
super(CheckoutStatusApp, self).load_vars(args, kwargs)
def do_action(self):
"""Do a checkout instead of a branch"""
dest_dir = os.path.join(self.dest, self.branch.suffix)
self.branch.branch.create_checkout(dest_dir, lightweight=True)
class CommitStatusApp(BazaarStatusApp):
"""Perform a self assuming commit with GUI"""
task_name = _("Committing Changes")
def load_vars(self, args, kwargs):
"""Load the Commit GUI"""
self.message = kwargs.pop('message')
self.ignore = kwargs.pop('ignore', False)
self.fixes = kwargs.pop('fixes', [])
self.flist = kwargs.pop('file_list', None)
super(CommitStatusApp, self).load_vars(args, kwargs)
def do_action(self):
"""Do a real commit"""
worktree = self.branch.get_workingtree()
if not self.ignore:
# First lets add all the files to the repositary
action = add.AddAction(to_file=sys.stderr, should_print=True)
file_list = self.generate_list(worktree)
if len(file_list):
worktree.smart_add(file_list, action=action, save=True)
# Next commit the changes, not a very complex one right now
# But at this point we might want to call cmd_commit instead.
#rev = worktree.commit(message_callback=self.get_message)
self.do_command('commit',
selected_list=[ self.branch.location ],
message=self.message,
fixes=self.fixes)
# Update the commited branch revision config
self.branch.commit_revno(True)
def generate_list(self, wtr):
"""List files to add"""
result = []
for file in wtr.unknowns():
res = os.path.join(self.branch.path, file)
logging.debug("Added new file '%s'" % res)
result.append(res)
return result
class PushStatusApp(BazaarStatusApp):
"""Push tot he default push target"""
task_name = _("Uploading Data")
def do_action(self):
"""Do a real push to default target"""
this_br = self.branch.branch
self.do_command('push', directory=None,
location=this_br.get_push_location())
# Update the pushed revision config
self.branch.push_revno(True)
class PullStatusApp(BazaarStatusApp):
"""Pull or Merge from the parent branch"""
task_name = _("Synchronising Data")
def do_action(self):
"""Do a pull from parent branch"""
if self.branch.has_branching():
location = self.branch.branch.get_parent()
# Allow pulling in the merge if no commits
self.do_command('merge', pull=True,
directory=self.branch.location,
location=self.branch.branch.get_parent())
# Update the pushed revision config
self.branch.pull_revno(True)
else:
self.do_command('update', dir=self.branch.location)
class RevertStatusApp(BazaarStatusApp):
"""Revert any changes to the branch"""
task_name = _("Reverting Branch")
def do_action(self):
"""Do a pull from parent branch"""
from bzrlib.clean_tree import clean_tree
loc = self.branch.location
clean_tree(loc, unknown=True, ignored=False, detritus=True,
dry_run=False, no_prompt=True)
self.do_command('revert', file_list=[ loc ])
class MergeStatusApp(BazaarStatusApp):
"""Revert any changes to the branch"""
task_name = _("Merging Branch")
def load_vars(self, args, kwargs):
"""Load the Commit GUI"""
self.source = kwargs.pop('source')
super(MergeStatusApp, self).load_vars(args, kwargs)
def do_action(self):
"""Do a pull from parent branch"""
loc = self.branch.location
logging.debug("Merging in branch %s" % self.source)
self.do_command('merge', location=self.source, directory=loc)
class UnlockStatusApp(BazaarStatusApp):
"""Revert any changes to the branch"""
task_name = _("Unlocking Branch")
def do_action(self):
"""Do a pull from parent branch"""
loc = self.branch.location
self.do_command('break_lock', location=loc)
|