/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/upgrade.py

  • Committer: Marius Kruger
  • Date: 2010-07-10 21:28:56 UTC
  • mto: (5384.1.1 integration)
  • mto: This revision was merged to the branch mainline in revision 5385.
  • Revision ID: marius.kruger@enerweb.co.za-20100710212856-uq4ji3go0u5se7hx
* Update documentation
* add 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
14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
 
"""brz upgrade logic."""
18
 
 
19
 
from __future__ import absolute_import
20
 
 
21
 
from . import (
22
 
    errors,
23
 
    trace,
24
 
    ui,
25
 
    urlutils,
26
 
    )
27
 
from .controldir import (
28
 
    ControlDir,
29
 
    format_registry,
30
 
    )
31
 
from .i18n import gettext
32
 
from .bzr.remote import RemoteBzrDir
 
17
"""bzr upgrade logic."""
 
18
 
 
19
 
 
20
from bzrlib.bzrdir import BzrDir, format_registry
 
21
import bzrlib.errors as errors
 
22
from bzrlib.remote import RemoteBzrDir
 
23
import bzrlib.ui as ui
33
24
 
34
25
 
35
26
class Convert(object):
36
27
 
37
 
    def __init__(self, url=None, format=None, control_dir=None):
38
 
        """Convert a Bazaar control directory to a given format.
39
 
 
40
 
        Either the url or control_dir parameter must be given.
41
 
 
42
 
        :param url: the URL of the control directory or None if the
43
 
          control_dir is explicitly given instead
44
 
        :param format: the format to convert to or None for the default
45
 
        :param control_dir: the control directory or None if it is
46
 
          specified via the URL parameter instead
47
 
        """
 
28
    def __init__(self, url, format=None):
48
29
        self.format = format
 
30
        self.bzrdir = BzrDir.open_unsupported(url)
49
31
        # XXX: Change to cleanup
50
32
        warning_id = 'cross_format_fetch'
51
33
        saved_warning = warning_id in ui.ui_factory.suppressed_warnings
52
 
        if url is None and control_dir is None:
53
 
            raise AssertionError(
54
 
                "either the url or control_dir parameter must be set.")
55
 
        if control_dir is not None:
56
 
            self.controldir = control_dir
57
 
        else:
58
 
            self.controldir = ControlDir.open_unsupported(url)
59
 
        if isinstance(self.controldir, RemoteBzrDir):
60
 
            self.controldir._ensure_real()
61
 
            self.controldir = self.controldir._real_bzrdir
62
 
        if self.controldir.root_transport.is_readonly():
 
34
        if isinstance(self.bzrdir, RemoteBzrDir):
 
35
            self.bzrdir._ensure_real()
 
36
            self.bzrdir = self.bzrdir._real_bzrdir
 
37
        if self.bzrdir.root_transport.is_readonly():
63
38
            raise errors.UpgradeReadonly
64
 
        self.transport = self.controldir.root_transport
 
39
        self.transport = self.bzrdir.root_transport
65
40
        ui.ui_factory.suppressed_warnings.add(warning_id)
66
41
        try:
67
42
            self.convert()
71
46
 
72
47
    def convert(self):
73
48
        try:
74
 
            branch = self.controldir.open_branch()
75
 
            if branch.user_url != self.controldir.user_url:
76
 
                ui.ui_factory.note(gettext(
77
 
                    'This is a checkout. The branch (%s) needs to be upgraded'
78
 
                    ' separately.') % (urlutils.unescape_for_display(
79
 
                        branch.user_url, 'utf-8')))
 
49
            branch = self.bzrdir.open_branch()
 
50
            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)
80
54
            del branch
81
55
        except (errors.NotBranchError, errors.IncompatibleRepositories):
82
56
            # might not be a format we can open without upgrading; see e.g.
84
58
            pass
85
59
        if self.format is None:
86
60
            try:
87
 
                rich_root = self.controldir.find_repository()._format.rich_root_data
 
61
                rich_root = self.bzrdir.find_repository()._format.rich_root_data
88
62
            except errors.NoRepositoryPresent:
89
 
                rich_root = False  # assume no rich roots
 
63
                rich_root = False # assume no rich roots
90
64
            if rich_root:
91
65
                format_name = "default-rich-root"
92
66
            else:
93
67
                format_name = "default"
94
 
            format = format_registry.make_controldir(format_name)
 
68
            format = format_registry.make_bzrdir(format_name)
95
69
        else:
96
70
            format = self.format
97
 
        if not self.controldir.needs_format_conversion(format):
98
 
            raise errors.UpToDateFormat(self.controldir._format)
99
 
        if not self.controldir.can_convert_format():
100
 
            raise errors.BzrError(gettext("cannot upgrade from bzrdir format %s") %
101
 
                                  self.controldir._format)
102
 
        self.controldir.check_conversion_target(format)
103
 
        ui.ui_factory.note(gettext('starting upgrade of %s') %
104
 
                           urlutils.unescape_for_display(self.transport.base, 'utf-8'))
105
 
 
106
 
        self.backup_oldpath, self.backup_newpath = self.controldir.backup_bzrdir()
107
 
        while self.controldir.needs_format_conversion(format):
108
 
            converter = self.controldir._format.get_converter(format)
109
 
            self.controldir = converter.convert(self.controldir, None)
110
 
        ui.ui_factory.note(gettext('finished'))
111
 
 
112
 
    def clean_up(self):
113
 
        """Clean-up after a conversion.
114
 
 
115
 
        This removes the backup.bzr directory.
116
 
        """
117
 
        transport = self.transport
118
 
        backup_relpath = transport.relpath(self.backup_newpath)
119
 
        with ui.ui_factory.nested_progress_bar() as child_pb:
120
 
            child_pb.update(gettext('Deleting backup.bzr'))
121
 
            transport.delete_tree(backup_relpath)
122
 
 
123
 
 
124
 
def upgrade(url, format=None, clean_up=False, dry_run=False):
125
 
    """Upgrade locations to format.
126
 
 
127
 
    This routine wraps the smart_upgrade() routine with a nicer UI.
128
 
    In particular, it ensures all URLs can be opened before starting
129
 
    and reports a summary at the end if more than one upgrade was attempted.
130
 
    This routine is useful for command line tools. Other breezy clients
131
 
    probably ought to use smart_upgrade() instead.
132
 
 
133
 
    :param url: a URL of the locations to upgrade.
134
 
    :param format: the format to convert to or None for the best default
135
 
    :param clean-up: if True, the backup.bzr directory is removed if the
136
 
      upgrade succeeded for a given repo/branch/tree
137
 
    :param dry_run: show what would happen but don't actually do any upgrades
138
 
    :return: the list of exceptions encountered
139
 
    """
140
 
    control_dirs = [ControlDir.open_unsupported(url)]
141
 
    attempted, succeeded, exceptions = smart_upgrade(control_dirs,
142
 
                                                     format, clean_up=clean_up, dry_run=dry_run)
143
 
    if len(attempted) > 1:
144
 
        attempted_count = len(attempted)
145
 
        succeeded_count = len(succeeded)
146
 
        failed_count = attempted_count - succeeded_count
147
 
        ui.ui_factory.note(
148
 
            gettext('\nSUMMARY: {0} upgrades attempted, {1} succeeded,'
149
 
                    ' {2} failed').format(
150
 
                attempted_count, succeeded_count, failed_count))
151
 
    return exceptions
152
 
 
153
 
 
154
 
def smart_upgrade(control_dirs, format, clean_up=False,
155
 
                  dry_run=False):
156
 
    """Convert control directories to a new format intelligently.
157
 
 
158
 
    If the control directory is a shared repository, dependent branches
159
 
    are also converted provided the repository converted successfully.
160
 
    If the conversion of a branch fails, remaining branches are still tried.
161
 
 
162
 
    :param control_dirs: the BzrDirs to upgrade
163
 
    :param format: the format to convert to or None for the best default
164
 
    :param clean_up: if True, the backup.bzr directory is removed if the
165
 
      upgrade succeeded for a given repo/branch/tree
166
 
    :param dry_run: show what would happen but don't actually do any upgrades
167
 
    :return: attempted-control-dirs, succeeded-control-dirs, exceptions
168
 
    """
169
 
    all_attempted = []
170
 
    all_succeeded = []
171
 
    all_exceptions = []
172
 
    for control_dir in control_dirs:
173
 
        attempted, succeeded, exceptions = _smart_upgrade_one(control_dir,
174
 
                                                              format, clean_up=clean_up, dry_run=dry_run)
175
 
        all_attempted.extend(attempted)
176
 
        all_succeeded.extend(succeeded)
177
 
        all_exceptions.extend(exceptions)
178
 
    return all_attempted, all_succeeded, all_exceptions
179
 
 
180
 
 
181
 
def _smart_upgrade_one(control_dir, format, clean_up=False,
182
 
                       dry_run=False):
183
 
    """Convert a control directory to a new format intelligently.
184
 
 
185
 
    See smart_upgrade for parameter details.
186
 
    """
187
 
    # If the URL is a shared repository, find the dependent branches
188
 
    dependents = None
189
 
    try:
190
 
        repo = control_dir.open_repository()
191
 
    except errors.NoRepositoryPresent:
192
 
        # A branch or checkout using a shared repository higher up
193
 
        pass
194
 
    else:
195
 
        # The URL is a repository. If it successfully upgrades,
196
 
        # then upgrade the dependent branches as well.
197
 
        if repo.is_shared():
198
 
            dependents = list(repo.find_branches(using=True))
199
 
 
200
 
    # Do the conversions
201
 
    attempted = [control_dir]
202
 
    succeeded, exceptions = _convert_items([control_dir], format, clean_up,
203
 
                                           dry_run)
204
 
    if succeeded and dependents:
205
 
        ui.ui_factory.note(gettext('Found %d dependent branches - upgrading ...')
206
 
                           % (len(dependents),))
207
 
        # Convert dependent branches
208
 
        branch_cdirs = [b.controldir for b in dependents]
209
 
        successes, problems = _convert_items(branch_cdirs, format, clean_up,
210
 
                                             dry_run, label="branch")
211
 
        attempted.extend(branch_cdirs)
212
 
        succeeded.extend(successes)
213
 
        exceptions.extend(problems)
214
 
 
215
 
    # Return the result
216
 
    return attempted, succeeded, exceptions
217
 
 
218
 
# FIXME: There are several problems below:
219
 
# - RemoteRepository doesn't support _unsupported (really ?)
220
 
# - raising AssertionError is rude and may not be necessary
221
 
# - no tests
222
 
# - the only caller uses only the label
223
 
 
224
 
 
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
 
    with ui.ui_factory.nested_progress_bar() as child_pb:
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") %
282
 
                            (type_label), i + 1, len(items))
283
 
            ui.ui_factory.note(gettext('Upgrading {0} {1} ...').format(type_label,
284
 
                                                                       urlutils.unescape_for_display(location, 'utf-8'),))
285
 
            try:
286
 
                if not dry_run:
287
 
                    cv = Convert(control_dir=control_dir, format=format)
288
 
            except errors.UpToDateFormat as ex:
289
 
                ui.ui_factory.note(str(ex))
290
 
                succeeded.append(control_dir)
291
 
                continue
292
 
            except Exception as ex:
293
 
                trace.warning('conversion error: %s' % ex)
294
 
                exceptions.append(ex)
295
 
                continue
296
 
 
297
 
            # Do any required post processing
298
 
            succeeded.append(control_dir)
299
 
            if clean_up:
300
 
                try:
301
 
                    ui.ui_factory.note(gettext('Removing backup ...'))
302
 
                    if not dry_run:
303
 
                        cv.clean_up()
304
 
                except Exception as ex:
305
 
                    trace.warning(
306
 
                        gettext('failed to clean-up {0}: {1}') % (location, ex))
307
 
                    exceptions.append(ex)
308
 
 
309
 
    # Return the result
310
 
    return succeeded, exceptions
 
71
        if not self.bzrdir.needs_format_conversion(format):
 
72
            raise errors.UpToDateFormat(self.bzrdir._format)
 
73
        if not self.bzrdir.can_convert_format():
 
74
            raise errors.BzrError("cannot upgrade from bzrdir format %s" %
 
75
                           self.bzrdir._format)
 
76
        self.bzrdir.check_conversion_target(format)
 
77
        ui.ui_factory.note('starting upgrade of %s' % self.transport.base)
 
78
 
 
79
        self.bzrdir.backup_bzrdir()
 
80
        while self.bzrdir.needs_format_conversion(format):
 
81
            converter = self.bzrdir._format.get_converter(format)
 
82
            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)