~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/upgrade.py

Merge bzr.dev, update to use new hooks.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2008, 2009, 2010 Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2008-2011 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
17
17
"""bzr upgrade logic."""
18
18
 
19
19
 
20
 
from bzrlib.bzrdir import BzrDir, format_registry
21
 
import bzrlib.errors as errors
 
20
from bzrlib import (
 
21
    errors,
 
22
    trace,
 
23
    ui,
 
24
    urlutils,
 
25
    )
 
26
from bzrlib.controldir import (
 
27
    ControlDir,
 
28
    format_registry,
 
29
    )
 
30
from bzrlib.i18n import gettext
22
31
from bzrlib.remote import RemoteBzrDir
23
 
import bzrlib.ui as ui
24
32
 
25
33
 
26
34
class Convert(object):
27
35
 
28
 
    def __init__(self, url, format=None):
 
36
    def __init__(self, url=None, format=None, control_dir=None):
 
37
        """Convert a Bazaar control directory to a given format.
 
38
 
 
39
        Either the url or control_dir parameter must be given.
 
40
 
 
41
        :param url: the URL of the control directory or None if the
 
42
          control_dir is explicitly given instead
 
43
        :param format: the format to convert to or None for the default
 
44
        :param control_dir: the control directory or None if it is
 
45
          specified via the URL parameter instead
 
46
        """
29
47
        self.format = format
30
 
        self.bzrdir = BzrDir.open_unsupported(url)
31
48
        # XXX: Change to cleanup
32
49
        warning_id = 'cross_format_fetch'
33
50
        saved_warning = warning_id in ui.ui_factory.suppressed_warnings
 
51
        if url is None and control_dir is None:
 
52
            raise AssertionError(
 
53
                "either the url or control_dir parameter must be set.")
 
54
        if control_dir is not None:
 
55
            self.bzrdir = control_dir
 
56
        else:
 
57
            self.bzrdir = ControlDir.open_unsupported(url)
34
58
        if isinstance(self.bzrdir, RemoteBzrDir):
35
59
            self.bzrdir._ensure_real()
36
60
            self.bzrdir = self.bzrdir._real_bzrdir
48
72
        try:
49
73
            branch = self.bzrdir.open_branch()
50
74
            if branch.user_url != self.bzrdir.user_url:
51
 
                ui.ui_factory.note("This is a checkout. The branch (%s) needs to be "
52
 
                             "upgraded separately." %
53
 
                             branch.user_url)
 
75
                ui.ui_factory.note(gettext(
 
76
                    'This is a checkout. The branch (%s) needs to be upgraded'
 
77
                    ' separately.') % (urlutils.unescape_for_display(
 
78
                        branch.user_url, 'utf-8')))
54
79
            del branch
55
80
        except (errors.NotBranchError, errors.IncompatibleRepositories):
56
81
            # might not be a format we can open without upgrading; see e.g.
71
96
        if not self.bzrdir.needs_format_conversion(format):
72
97
            raise errors.UpToDateFormat(self.bzrdir._format)
73
98
        if not self.bzrdir.can_convert_format():
74
 
            raise errors.BzrError("cannot upgrade from bzrdir format %s" %
 
99
            raise errors.BzrError(gettext("cannot upgrade from bzrdir format %s") %
75
100
                           self.bzrdir._format)
76
101
        self.bzrdir.check_conversion_target(format)
77
 
        ui.ui_factory.note('starting upgrade of %s' % self.transport.base)
 
102
        ui.ui_factory.note(gettext('starting upgrade of %s') % 
 
103
            urlutils.unescape_for_display(self.transport.base, 'utf-8'))
78
104
 
79
 
        self.bzrdir.backup_bzrdir()
 
105
        self.backup_oldpath, self.backup_newpath = self.bzrdir.backup_bzrdir()
80
106
        while self.bzrdir.needs_format_conversion(format):
81
107
            converter = self.bzrdir._format.get_converter(format)
82
108
            self.bzrdir = converter.convert(self.bzrdir, None)
83
 
        ui.ui_factory.note("finished")
84
 
 
85
 
 
86
 
def upgrade(url, format=None):
87
 
    """Upgrade to format, or the default bzrdir format if not supplied."""
88
 
    Convert(url, format)
 
109
        ui.ui_factory.note(gettext('finished'))
 
110
 
 
111
    def clean_up(self):
 
112
        """Clean-up after a conversion.
 
113
 
 
114
        This removes the backup.bzr directory.
 
115
        """
 
116
        transport = self.transport
 
117
        backup_relpath = transport.relpath(self.backup_newpath)
 
118
        child_pb = ui.ui_factory.nested_progress_bar()
 
119
        child_pb.update(gettext('Deleting backup.bzr'))
 
120
        try:
 
121
            transport.delete_tree(backup_relpath)
 
122
        finally:
 
123
            child_pb.finished()
 
124
 
 
125
 
 
126
def upgrade(url, format=None, clean_up=False, dry_run=False):
 
127
    """Upgrade locations to format.
 
128
 
 
129
    This routine wraps the smart_upgrade() routine with a nicer UI.
 
130
    In particular, it ensures all URLs can be opened before starting
 
131
    and reports a summary at the end if more than one upgrade was attempted.
 
132
    This routine is useful for command line tools. Other bzrlib clients
 
133
    probably ought to use smart_upgrade() instead.
 
134
 
 
135
    :param url: a URL of the locations to upgrade.
 
136
    :param format: the format to convert to or None for the best default
 
137
    :param clean-up: if True, the backup.bzr directory is removed if the
 
138
      upgrade succeeded for a given repo/branch/tree
 
139
    :param dry_run: show what would happen but don't actually do any upgrades
 
140
    :return: the list of exceptions encountered
 
141
    """
 
142
    control_dirs = [ControlDir.open_unsupported(url)]
 
143
    attempted, succeeded, exceptions = smart_upgrade(control_dirs,
 
144
        format, clean_up=clean_up, dry_run=dry_run)
 
145
    if len(attempted) > 1:
 
146
        attempted_count = len(attempted)
 
147
        succeeded_count = len(succeeded)
 
148
        failed_count = attempted_count - succeeded_count
 
149
        ui.ui_factory.note(
 
150
            gettext('\nSUMMARY: {0} upgrades attempted, {1} succeeded,'\
 
151
                    ' {2} failed').format(
 
152
                     attempted_count, succeeded_count, failed_count))
 
153
    return exceptions
 
154
 
 
155
 
 
156
def smart_upgrade(control_dirs, format, clean_up=False,
 
157
    dry_run=False):
 
158
    """Convert control directories to a new format intelligently.
 
159
 
 
160
    If the control directory is a shared repository, dependent branches
 
161
    are also converted provided the repository converted successfully.
 
162
    If the conversion of a branch fails, remaining branches are still tried.
 
163
 
 
164
    :param control_dirs: the BzrDirs to upgrade
 
165
    :param format: the format to convert to or None for the best default
 
166
    :param clean_up: if True, the backup.bzr directory is removed if the
 
167
      upgrade succeeded for a given repo/branch/tree
 
168
    :param dry_run: show what would happen but don't actually do any upgrades
 
169
    :return: attempted-control-dirs, succeeded-control-dirs, exceptions
 
170
    """
 
171
    all_attempted = []
 
172
    all_succeeded = []
 
173
    all_exceptions = []
 
174
    for control_dir in control_dirs:
 
175
        attempted, succeeded, exceptions = _smart_upgrade_one(control_dir,
 
176
            format, clean_up=clean_up, dry_run=dry_run)
 
177
        all_attempted.extend(attempted)
 
178
        all_succeeded.extend(succeeded)
 
179
        all_exceptions.extend(exceptions)
 
180
    return all_attempted, all_succeeded, all_exceptions
 
181
 
 
182
 
 
183
def _smart_upgrade_one(control_dir, format, clean_up=False,
 
184
    dry_run=False):
 
185
    """Convert a control directory to a new format intelligently.
 
186
 
 
187
    See smart_upgrade for parameter details.
 
188
    """
 
189
    # If the URL is a shared repository, find the dependent branches
 
190
    dependents = None
 
191
    try:
 
192
        repo = control_dir.open_repository()
 
193
    except errors.NoRepositoryPresent:
 
194
        # A branch or checkout using a shared repository higher up
 
195
        pass
 
196
    else:
 
197
        # The URL is a repository. If it successfully upgrades,
 
198
        # then upgrade the dependent branches as well.
 
199
        if repo.is_shared():
 
200
            dependents = repo.find_branches(using=True)
 
201
 
 
202
    # Do the conversions
 
203
    attempted = [control_dir]
 
204
    succeeded, exceptions = _convert_items([control_dir], format, clean_up,
 
205
                                           dry_run)
 
206
    if succeeded and dependents:
 
207
        ui.ui_factory.note(gettext('Found %d dependent branches - upgrading ...')
 
208
                           % (len(dependents),))
 
209
        # Convert dependent branches
 
210
        branch_cdirs = [b.bzrdir for b in dependents]
 
211
        successes, problems = _convert_items(branch_cdirs, format, clean_up,
 
212
            dry_run, label="branch")
 
213
        attempted.extend(branch_cdirs)
 
214
        succeeded.extend(successes)
 
215
        exceptions.extend(problems)
 
216
 
 
217
    # Return the result
 
218
    return attempted, succeeded, exceptions
 
219
 
 
220
# FIXME: There are several problems below:
 
221
# - RemoteRepository doesn't support _unsupported (really ?)
 
222
# - raising AssertionError is rude and may not be necessary
 
223
# - no tests
 
224
# - the only caller uses only the label
 
225
def _get_object_and_label(control_dir):
 
226
    """Return the primary object and type label for a control directory.
 
227
 
 
228
    :return: object, label where:
 
229
      * object is a Branch, Repository or WorkingTree and
 
230
      * label is one of:
 
231
        * branch            - a branch
 
232
        * repository        - a repository
 
233
        * tree              - a lightweight checkout
 
234
    """
 
235
    try:
 
236
        try:
 
237
            br = control_dir.open_branch(unsupported=True,
 
238
                                         ignore_fallbacks=True)
 
239
        except NotImplementedError:
 
240
            # RemoteRepository doesn't support the unsupported parameter
 
241
            br = control_dir.open_branch(ignore_fallbacks=True)
 
242
    except errors.NotBranchError:
 
243
        pass
 
244
    else:
 
245
        return br, "branch"
 
246
    try:
 
247
        repo = control_dir.open_repository()
 
248
    except errors.NoRepositoryPresent:
 
249
        pass
 
250
    else:
 
251
        return repo, "repository"
 
252
    try:
 
253
        wt = control_dir.open_workingtree()
 
254
    except (errors.NoWorkingTree, errors.NotLocalUrl):
 
255
        pass
 
256
    else:
 
257
        return wt, "tree"
 
258
    raise AssertionError("unknown type of control directory %s", control_dir)
 
259
 
 
260
 
 
261
def _convert_items(items, format, clean_up, dry_run, label=None):
 
262
    """Convert a sequence of control directories to the given format.
 
263
 
 
264
    :param items: the control directories to upgrade
 
265
    :param format: the format to convert to or None for the best default
 
266
    :param clean-up: if True, the backup.bzr directory is removed if the
 
267
      upgrade succeeded for a given repo/branch/tree
 
268
    :param dry_run: show what would happen but don't actually do any upgrades
 
269
    :param label: the label for these items or None to calculate one
 
270
    :return: items successfully upgraded, exceptions
 
271
    """
 
272
    succeeded = []
 
273
    exceptions = []
 
274
    child_pb = ui.ui_factory.nested_progress_bar()
 
275
    child_pb.update(gettext('Upgrading bzrdirs'), 0, len(items))
 
276
    for i, control_dir in enumerate(items):
 
277
        # Do the conversion
 
278
        location = control_dir.root_transport.base
 
279
        bzr_object, bzr_label = _get_object_and_label(control_dir)
 
280
        type_label = label or bzr_label
 
281
        child_pb.update(gettext("Upgrading %s") % (type_label), i+1, len(items))
 
282
        ui.ui_factory.note(gettext('Upgrading {0} {1} ...').format(type_label, 
 
283
            urlutils.unescape_for_display(location, 'utf-8'),))
 
284
        try:
 
285
            if not dry_run:
 
286
                cv = Convert(control_dir=control_dir, format=format)
 
287
        except errors.UpToDateFormat, ex:
 
288
            ui.ui_factory.note(str(ex))
 
289
            succeeded.append(control_dir)
 
290
            continue
 
291
        except Exception, ex:
 
292
            trace.warning('conversion error: %s' % ex)
 
293
            exceptions.append(ex)
 
294
            continue
 
295
 
 
296
        # Do any required post processing
 
297
        succeeded.append(control_dir)
 
298
        if clean_up:
 
299
            try:
 
300
                ui.ui_factory.note(gettext('Removing backup ...'))
 
301
                if not dry_run:
 
302
                    cv.clean_up()
 
303
            except Exception, ex:
 
304
                trace.warning(gettext('failed to clean-up {0}: {1}') % (location, ex))
 
305
                exceptions.append(ex)
 
306
 
 
307
    child_pb.finished()
 
308
 
 
309
    # Return the result
 
310
    return succeeded, exceptions