/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 breezy/upgrade.py

  • Committer: Gustav Hartvigsson
  • Date: 2021-01-09 21:36:27 UTC
  • Revision ID: gustav.hartvigsson@gmail.com-20210109213627-h1xwcutzy9m7a99b
Added 'Case Preserving Working Tree Use Cases' from Canonical Wiki

* Addod a page from the Canonical Bazaar wiki
  with information on the scmeatics of case
  perserving filesystems an a case insensitive
  filesystem works.
  
  * Needs re-work, but this will do as it is the
    same inforamoton as what was on the linked
    page in the currint documentation.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
#! /usr/bin/python
2
 
 
3
 
# Copyright (C) 2005 Canonical Ltd
4
 
 
 
1
# Copyright (C) 2005, 2006, 2008-2011 Canonical Ltd
 
2
#
5
3
# This program is free software; you can redistribute it and/or modify
6
4
# it under the terms of the GNU General Public License as published by
7
5
# the Free Software Foundation; either version 2 of the License, or
8
6
# (at your option) any later version.
9
 
 
 
7
#
10
8
# This program is distributed in the hope that it will be useful,
11
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
12
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
11
# GNU General Public License for more details.
14
 
 
 
12
#
15
13
# You should have received a copy of the GNU General Public License
16
14
# along with this program; if not, write to the Free Software
17
 
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18
 
 
19
 
"""Experiment in converting existing bzr branches to weaves."""
20
 
 
21
 
try:
22
 
    import psyco
23
 
    psyco.full()
24
 
except ImportError:
25
 
    pass
26
 
 
27
 
 
28
 
import logging
29
 
 
30
 
import bzrlib.branch
31
 
from bzrlib.revfile import Revfile
32
 
from bzrlib.weave import Weave
33
 
from bzrlib.weavefile import read_weave, write_weave
34
 
from bzrlib.progress import ProgressBar
35
 
from bzrlib.atomicfile import AtomicFile
36
 
import bzrlib.trace
37
 
import tempfile
38
 
import hotshot, hotshot.stats
39
 
import sys
40
 
 
41
 
def convert():
42
 
    bzrlib.trace.enable_default_logging()
43
 
 
44
 
    pb = ProgressBar()
45
 
 
46
 
    inv_weave = Weave()
47
 
 
48
 
    last_text_sha = {}
49
 
 
50
 
    # holds in-memory weaves for all files
51
 
    text_weaves = {}
52
 
 
53
 
    b = bzrlib.branch.find_branch('.')
54
 
 
55
 
    revno = 1
56
 
    rev_history = b.revision_history()
57
 
    last_idx = None
58
 
    inv_parents = []
59
 
    text_count = 0
60
 
    
61
 
    for rev_id in rev_history:
62
 
        pb.update('converting revision', revno, len(rev_history))
63
 
        
64
 
        inv_xml = b.get_inventory_xml(rev_id).readlines()
65
 
 
66
 
        new_idx = inv_weave.add(rev_id, inv_parents, inv_xml)
67
 
        inv_parents = [new_idx]
68
 
 
69
 
        tree = b.revision_tree(rev_id)
70
 
        inv = tree.inventory
71
 
 
72
 
        # for each file in the inventory, put it into its own revfile
73
 
        for file_id in inv:
74
 
            ie = inv[file_id]
75
 
            if ie.kind != 'file':
76
 
                continue
77
 
            if last_text_sha.get(file_id) == ie.text_sha1:
78
 
                # same as last time
79
 
                continue
80
 
            last_text_sha[file_id] = ie.text_sha1
81
 
 
82
 
            # new text (though possibly already stored); need to store it
83
 
            text_lines = tree.get_file(file_id).readlines()
84
 
 
85
 
            # if the file's created for the first time in this
86
 
            # revision then make a new weave; else find the old one
87
 
            if file_id not in text_weaves:
88
 
                text_weaves[file_id] = Weave()
89
 
                
90
 
            w = text_weaves[file_id]
91
 
 
92
 
            # base the new text version off whatever was last
93
 
            # (actually it'd be better to track this, to allow for
94
 
            # files that are deleted and then reappear)
95
 
            last = len(w)
96
 
            if last == 0:
97
 
                parents = []
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
 
 
17
"""brz upgrade logic."""
 
18
 
 
19
from . import (
 
20
    errors,
 
21
    trace,
 
22
    ui,
 
23
    urlutils,
 
24
    )
 
25
from .controldir import (
 
26
    ControlDir,
 
27
    format_registry,
 
28
    )
 
29
from .i18n import gettext
 
30
from .bzr.remote import RemoteBzrDir
 
31
 
 
32
 
 
33
class Convert(object):
 
34
 
 
35
    def __init__(self, url=None, format=None, control_dir=None):
 
36
        """Convert a Bazaar control directory to a given format.
 
37
 
 
38
        Either the url or control_dir parameter must be given.
 
39
 
 
40
        :param url: the URL of the control directory or None if the
 
41
          control_dir is explicitly given instead
 
42
        :param format: the format to convert to or None for the default
 
43
        :param control_dir: the control directory or None if it is
 
44
          specified via the URL parameter instead
 
45
        """
 
46
        self.format = format
 
47
        # XXX: Change to cleanup
 
48
        warning_id = 'cross_format_fetch'
 
49
        saved_warning = warning_id in ui.ui_factory.suppressed_warnings
 
50
        if url is None and control_dir is None:
 
51
            raise AssertionError(
 
52
                "either the url or control_dir parameter must be set.")
 
53
        if control_dir is not None:
 
54
            self.controldir = control_dir
 
55
        else:
 
56
            self.controldir = ControlDir.open_unsupported(url)
 
57
        if isinstance(self.controldir, RemoteBzrDir):
 
58
            self.controldir._ensure_real()
 
59
            self.controldir = self.controldir._real_bzrdir
 
60
        if self.controldir.root_transport.is_readonly():
 
61
            raise errors.UpgradeReadonly
 
62
        self.transport = self.controldir.root_transport
 
63
        ui.ui_factory.suppressed_warnings.add(warning_id)
 
64
        try:
 
65
            self.convert()
 
66
        finally:
 
67
            if not saved_warning:
 
68
                ui.ui_factory.suppressed_warnings.remove(warning_id)
 
69
 
 
70
    def convert(self):
 
71
        try:
 
72
            branch = self.controldir.open_branch()
 
73
            if branch.user_url != self.controldir.user_url:
 
74
                ui.ui_factory.note(gettext(
 
75
                    'This is a checkout. The branch (%s) needs to be upgraded'
 
76
                    ' separately.') % (urlutils.unescape_for_display(
 
77
                        branch.user_url, 'utf-8')))
 
78
            del branch
 
79
        except (errors.NotBranchError, errors.IncompatibleRepositories):
 
80
            # might not be a format we can open without upgrading; see e.g.
 
81
            # https://bugs.launchpad.net/bzr/+bug/253891
 
82
            pass
 
83
        if self.format is None:
 
84
            try:
 
85
                rich_root = self.controldir.find_repository()._format.rich_root_data
 
86
            except errors.NoRepositoryPresent:
 
87
                rich_root = False  # assume no rich roots
 
88
            if rich_root:
 
89
                format_name = "default-rich-root"
98
90
            else:
99
 
                parents = [last-1]
100
 
 
101
 
            w.add(rev_id, parents, text_lines)
102
 
            text_count += 1
103
 
 
104
 
        revno += 1
105
 
 
106
 
    pb.clear()
107
 
    print '%6d revisions and inventories' % revno
108
 
    print '%6d texts' % text_count
109
 
 
110
 
    i = 0
111
 
    # TODO: commit them all atomically at the end, not one by one
112
 
    write_atomic_weave(inv_weave, 'weaves/inventory.weave')
113
 
    for file_id, file_weave in text_weaves.items():
114
 
        pb.update('writing weave', i, len(text_weaves))
115
 
        write_atomic_weave(file_weave, 'weaves/%s.weave' % file_id)
116
 
        i += 1
117
 
 
118
 
    pb.clear()
119
 
 
120
 
 
121
 
def write_atomic_weave(weave, filename):
122
 
    inv_wf = AtomicFile(filename)
123
 
    try:
124
 
        write_weave(weave, inv_wf)
125
 
        inv_wf.commit()
126
 
    finally:
127
 
        inv_wf.close()
128
 
 
129
 
    
130
 
 
131
 
 
132
 
def profile_convert(): 
133
 
    prof_f = tempfile.NamedTemporaryFile()
134
 
 
135
 
    prof = hotshot.Profile(prof_f.name)
136
 
 
137
 
    prof.runcall(convert) 
138
 
    prof.close()
139
 
 
140
 
    stats = hotshot.stats.load(prof_f.name)
141
 
    #stats.strip_dirs()
142
 
    stats.sort_stats('time')
143
 
    ## XXX: Might like to write to stderr or the trace file instead but
144
 
    ## print_stats seems hardcoded to stdout
145
 
    stats.print_stats(20)
146
 
            
147
 
 
148
 
if '-p' in sys.argv[1:]:
149
 
    profile_convert()
150
 
else:
151
 
    convert()
152
 
    
 
91
                format_name = "default"
 
92
            format = format_registry.make_controldir(format_name)
 
93
        else:
 
94
            format = self.format
 
95
        if not self.controldir.needs_format_conversion(format):
 
96
            raise errors.UpToDateFormat(self.controldir._format)
 
97
        if not self.controldir.can_convert_format():
 
98
            raise errors.BzrError(gettext("cannot upgrade from bzrdir format %s") %
 
99
                                  self.controldir._format)
 
100
        self.controldir.check_conversion_target(format)
 
101
        ui.ui_factory.note(gettext('starting upgrade of %s') %
 
102
                           urlutils.unescape_for_display(self.transport.base, 'utf-8'))
 
103
 
 
104
        self.backup_oldpath, self.backup_newpath = self.controldir.backup_bzrdir()
 
105
        while self.controldir.needs_format_conversion(format):
 
106
            converter = self.controldir._format.get_converter(format)
 
107
            self.controldir = converter.convert(self.controldir, None)
 
108
        ui.ui_factory.note(gettext('finished'))
 
109
 
 
110
    def clean_up(self):
 
111
        """Clean-up after a conversion.
 
112
 
 
113
        This removes the backup.bzr directory.
 
114
        """
 
115
        transport = self.transport
 
116
        backup_relpath = transport.relpath(self.backup_newpath)
 
117
        with ui.ui_factory.nested_progress_bar() as child_pb:
 
118
            child_pb.update(gettext('Deleting backup.bzr'))
 
119
            transport.delete_tree(backup_relpath)
 
120
 
 
121
 
 
122
def upgrade(url, format=None, clean_up=False, dry_run=False):
 
123
    """Upgrade locations to format.
 
124
 
 
125
    This routine wraps the smart_upgrade() routine with a nicer UI.
 
126
    In particular, it ensures all URLs can be opened before starting
 
127
    and reports a summary at the end if more than one upgrade was attempted.
 
128
    This routine is useful for command line tools. Other breezy clients
 
129
    probably ought to use smart_upgrade() instead.
 
130
 
 
131
    :param url: a URL of the locations to upgrade.
 
132
    :param format: the format to convert to or None for the best default
 
133
    :param clean-up: if True, the backup.bzr directory is removed if the
 
134
      upgrade succeeded for a given repo/branch/tree
 
135
    :param dry_run: show what would happen but don't actually do any upgrades
 
136
    :return: the list of exceptions encountered
 
137
    """
 
138
    control_dirs = [ControlDir.open_unsupported(url)]
 
139
    attempted, succeeded, exceptions = smart_upgrade(control_dirs,
 
140
                                                     format, clean_up=clean_up, dry_run=dry_run)
 
141
    if len(attempted) > 1:
 
142
        attempted_count = len(attempted)
 
143
        succeeded_count = len(succeeded)
 
144
        failed_count = attempted_count - succeeded_count
 
145
        ui.ui_factory.note(
 
146
            gettext('\nSUMMARY: {0} upgrades attempted, {1} succeeded,'
 
147
                    ' {2} failed').format(
 
148
                attempted_count, succeeded_count, failed_count))
 
149
    return exceptions
 
150
 
 
151
 
 
152
def smart_upgrade(control_dirs, format, clean_up=False,
 
153
                  dry_run=False):
 
154
    """Convert control directories to a new format intelligently.
 
155
 
 
156
    If the control directory is a shared repository, dependent branches
 
157
    are also converted provided the repository converted successfully.
 
158
    If the conversion of a branch fails, remaining branches are still tried.
 
159
 
 
160
    :param control_dirs: the BzrDirs to upgrade
 
161
    :param format: the format to convert to or None for the best default
 
162
    :param clean_up: if True, the backup.bzr directory is removed if the
 
163
      upgrade succeeded for a given repo/branch/tree
 
164
    :param dry_run: show what would happen but don't actually do any upgrades
 
165
    :return: attempted-control-dirs, succeeded-control-dirs, exceptions
 
166
    """
 
167
    all_attempted = []
 
168
    all_succeeded = []
 
169
    all_exceptions = []
 
170
    for control_dir in control_dirs:
 
171
        attempted, succeeded, exceptions = _smart_upgrade_one(control_dir,
 
172
                                                              format, clean_up=clean_up, dry_run=dry_run)
 
173
        all_attempted.extend(attempted)
 
174
        all_succeeded.extend(succeeded)
 
175
        all_exceptions.extend(exceptions)
 
176
    return all_attempted, all_succeeded, all_exceptions
 
177
 
 
178
 
 
179
def _smart_upgrade_one(control_dir, format, clean_up=False,
 
180
                       dry_run=False):
 
181
    """Convert a control directory to a new format intelligently.
 
182
 
 
183
    See smart_upgrade for parameter details.
 
184
    """
 
185
    # If the URL is a shared repository, find the dependent branches
 
186
    dependents = None
 
187
    try:
 
188
        repo = control_dir.open_repository()
 
189
    except errors.NoRepositoryPresent:
 
190
        # A branch or checkout using a shared repository higher up
 
191
        pass
 
192
    else:
 
193
        # The URL is a repository. If it successfully upgrades,
 
194
        # then upgrade the dependent branches as well.
 
195
        if repo.is_shared():
 
196
            dependents = list(repo.find_branches(using=True))
 
197
 
 
198
    # Do the conversions
 
199
    attempted = [control_dir]
 
200
    succeeded, exceptions = _convert_items([control_dir], format, clean_up,
 
201
                                           dry_run)
 
202
    if succeeded and dependents:
 
203
        ui.ui_factory.note(gettext('Found %d dependent branches - upgrading ...')
 
204
                           % (len(dependents),))
 
205
        # Convert dependent branches
 
206
        branch_cdirs = [b.controldir for b in dependents]
 
207
        successes, problems = _convert_items(branch_cdirs, format, clean_up,
 
208
                                             dry_run, label="branch")
 
209
        attempted.extend(branch_cdirs)
 
210
        succeeded.extend(successes)
 
211
        exceptions.extend(problems)
 
212
 
 
213
    # Return the result
 
214
    return attempted, succeeded, exceptions
 
215
 
 
216
# FIXME: There are several problems below:
 
217
# - RemoteRepository doesn't support _unsupported (really ?)
 
218
# - raising AssertionError is rude and may not be necessary
 
219
# - no tests
 
220
# - the only caller uses only the label
 
221
 
 
222
 
 
223
def _get_object_and_label(control_dir):
 
224
    """Return the primary object and type label for a control directory.
 
225
 
 
226
    :return: object, label where:
 
227
      * object is a Branch, Repository or WorkingTree and
 
228
      * label is one of:
 
229
        * branch            - a branch
 
230
        * repository        - a repository
 
231
        * tree              - a lightweight checkout
 
232
    """
 
233
    try:
 
234
        try:
 
235
            br = control_dir.open_branch(unsupported=True,
 
236
                                         ignore_fallbacks=True)
 
237
        except NotImplementedError:
 
238
            # RemoteRepository doesn't support the unsupported parameter
 
239
            br = control_dir.open_branch(ignore_fallbacks=True)
 
240
    except errors.NotBranchError:
 
241
        pass
 
242
    else:
 
243
        return br, "branch"
 
244
    try:
 
245
        repo = control_dir.open_repository()
 
246
    except errors.NoRepositoryPresent:
 
247
        pass
 
248
    else:
 
249
        return repo, "repository"
 
250
    try:
 
251
        wt = control_dir.open_workingtree()
 
252
    except (errors.NoWorkingTree, errors.NotLocalUrl):
 
253
        pass
 
254
    else:
 
255
        return wt, "tree"
 
256
    raise AssertionError("unknown type of control directory %s", control_dir)
 
257
 
 
258
 
 
259
def _convert_items(items, format, clean_up, dry_run, label=None):
 
260
    """Convert a sequence of control directories to the given format.
 
261
 
 
262
    :param items: the control directories to upgrade
 
263
    :param format: the format to convert to or None for the best default
 
264
    :param clean-up: if True, the backup.bzr directory is removed if the
 
265
      upgrade succeeded for a given repo/branch/tree
 
266
    :param dry_run: show what would happen but don't actually do any upgrades
 
267
    :param label: the label for these items or None to calculate one
 
268
    :return: items successfully upgraded, exceptions
 
269
    """
 
270
    succeeded = []
 
271
    exceptions = []
 
272
    with ui.ui_factory.nested_progress_bar() as child_pb:
 
273
        child_pb.update(gettext('Upgrading bzrdirs'), 0, len(items))
 
274
        for i, control_dir in enumerate(items):
 
275
            # Do the conversion
 
276
            location = control_dir.root_transport.base
 
277
            bzr_object, bzr_label = _get_object_and_label(control_dir)
 
278
            type_label = label or bzr_label
 
279
            child_pb.update(gettext("Upgrading %s") %
 
280
                            (type_label), i + 1, len(items))
 
281
            ui.ui_factory.note(gettext('Upgrading {0} {1} ...').format(type_label,
 
282
                                                                       urlutils.unescape_for_display(location, 'utf-8'),))
 
283
            try:
 
284
                if not dry_run:
 
285
                    cv = Convert(control_dir=control_dir, format=format)
 
286
            except errors.UpToDateFormat as ex:
 
287
                ui.ui_factory.note(str(ex))
 
288
                succeeded.append(control_dir)
 
289
                continue
 
290
            except Exception as ex:
 
291
                trace.warning('conversion error: %s' % ex)
 
292
                exceptions.append(ex)
 
293
                continue
 
294
 
 
295
            # Do any required post processing
 
296
            succeeded.append(control_dir)
 
297
            if clean_up:
 
298
                try:
 
299
                    ui.ui_factory.note(gettext('Removing backup ...'))
 
300
                    if not dry_run:
 
301
                        cv.clean_up()
 
302
                except Exception as ex:
 
303
                    trace.warning(
 
304
                        gettext('failed to clean-up {0}: {1}') % (location, ex))
 
305
                    exceptions.append(ex)
 
306
 
 
307
    # Return the result
 
308
    return succeeded, exceptions