~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/upgrade.py

  • Committer: Martin Pool
  • Date: 2010-02-25 06:17:27 UTC
  • mfrom: (5055 +trunk)
  • mto: This revision was merged to the branch mainline in revision 5057.
  • Revision ID: mbp@sourcefrog.net-20100225061727-4sd9lt0qmdc6087t
merge news

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2008-2011 Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2008, 2009, 2010 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 import (
21
 
    errors,
22
 
    trace,
23
 
    ui,
24
 
    urlutils,
25
 
    )
26
 
from bzrlib.bzrdir import (
27
 
    BzrDir,
28
 
    format_registry,
29
 
    )
30
 
from bzrlib.i18n import gettext
 
20
from bzrlib.bzrdir import BzrDir, format_registry
 
21
import bzrlib.errors as errors
31
22
from bzrlib.remote import RemoteBzrDir
 
23
import bzrlib.ui as ui
32
24
 
33
25
 
34
26
class Convert(object):
35
27
 
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
 
        """
 
28
    def __init__(self, url, format=None):
47
29
        self.format = format
48
 
        # XXX: Change to cleanup
49
 
        warning_id = 'cross_format_fetch'
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 = BzrDir.open_unsupported(url)
 
30
        self.bzrdir = BzrDir.open_unsupported(url)
58
31
        if isinstance(self.bzrdir, RemoteBzrDir):
59
32
            self.bzrdir._ensure_real()
60
33
            self.bzrdir = self.bzrdir._real_bzrdir
61
34
        if self.bzrdir.root_transport.is_readonly():
62
35
            raise errors.UpgradeReadonly
63
36
        self.transport = self.bzrdir.root_transport
64
 
        ui.ui_factory.suppressed_warnings.add(warning_id)
65
 
        try:
66
 
            self.convert()
67
 
        finally:
68
 
            if not saved_warning:
69
 
                ui.ui_factory.suppressed_warnings.remove(warning_id)
 
37
        self.convert()
70
38
 
71
39
    def convert(self):
72
40
        try:
73
41
            branch = self.bzrdir.open_branch()
74
 
            if branch.user_url != self.bzrdir.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')))
 
42
            if branch.bzrdir.root_transport.base != \
 
43
                self.bzrdir.root_transport.base:
 
44
                ui.ui_factory.note("This is a checkout. The branch (%s) needs to be "
 
45
                             "upgraded separately." %
 
46
                             branch.bzrdir.root_transport.base)
79
47
            del branch
80
48
        except (errors.NotBranchError, errors.IncompatibleRepositories):
81
49
            # might not be a format we can open without upgrading; see e.g.
96
64
        if not self.bzrdir.needs_format_conversion(format):
97
65
            raise errors.UpToDateFormat(self.bzrdir._format)
98
66
        if not self.bzrdir.can_convert_format():
99
 
            raise errors.BzrError(gettext("cannot upgrade from bzrdir format %s") %
 
67
            raise errors.BzrError("cannot upgrade from bzrdir format %s" %
100
68
                           self.bzrdir._format)
101
69
        self.bzrdir.check_conversion_target(format)
102
 
        ui.ui_factory.note(gettext('starting upgrade of %s') % 
103
 
            urlutils.unescape_for_display(self.transport.base, 'utf-8'))
 
70
        ui.ui_factory.note('starting upgrade of %s' % self.transport.base)
104
71
 
105
 
        self.backup_oldpath, self.backup_newpath = self.bzrdir.backup_bzrdir()
 
72
        self.bzrdir.backup_bzrdir()
106
73
        while self.bzrdir.needs_format_conversion(format):
107
74
            converter = self.bzrdir._format.get_converter(format)
108
75
            self.bzrdir = converter.convert(self.bzrdir, None)
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 = [BzrDir.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 Exception, ex:
288
 
            trace.warning('conversion error: %s' % ex)
289
 
            exceptions.append(ex)
290
 
            continue
291
 
 
292
 
        # Do any required post processing
293
 
        succeeded.append(control_dir)
294
 
        if clean_up:
295
 
            try:
296
 
                ui.ui_factory.note(gettext('Removing backup ...'))
297
 
                if not dry_run:
298
 
                    cv.clean_up()
299
 
            except Exception, ex:
300
 
                trace.warning(gettext('failed to clean-up {0}: {1}') % (location, ex))
301
 
                exceptions.append(ex)
302
 
 
303
 
    child_pb.finished()
304
 
 
305
 
    # Return the result
306
 
    return succeeded, exceptions
 
76
        ui.ui_factory.note("finished")
 
77
 
 
78
 
 
79
def upgrade(url, format=None):
 
80
    """Upgrade to format, or the default bzrdir format if not supplied."""
 
81
    Convert(url, format)