/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
0.64.1 by Ian Clatworthy
1st cut: gfi parser + --info processing method
1
# Copyright (C) 2008 Canonical Ltd
2
#
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
7
#
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
12
#
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
17
"""Import processor that supports all Bazaar repository formats."""
18
19
0.64.17 by Ian Clatworthy
escape commit messages, diff author to committer and cache fixes
20
import re
0.64.6 by Ian Clatworthy
generic processing method working for one revision in one branch
21
import time
0.64.5 by Ian Clatworthy
first cut at generic processing method
22
from bzrlib import (
0.64.37 by Ian Clatworthy
create branches as required
23
    builtins,
24
    bzrdir,
0.64.67 by James Westby
Add support for -Dfast-import.
25
    debug,
0.64.6 by Ian Clatworthy
generic processing method working for one revision in one branch
26
    delta,
0.64.5 by Ian Clatworthy
first cut at generic processing method
27
    errors,
28
    generate_ids,
29
    inventory,
30
    lru_cache,
31
    osutils,
0.64.26 by Ian Clatworthy
more progress reporting tweaks
32
    progress,
0.64.5 by Ian Clatworthy
first cut at generic processing method
33
    revision,
34
    revisiontree,
0.64.37 by Ian Clatworthy
create branches as required
35
    transport,
0.64.5 by Ian Clatworthy
first cut at generic processing method
36
    )
0.64.51 by Ian Clatworthy
disable autopacking
37
from bzrlib.repofmt import pack_repo
0.64.1 by Ian Clatworthy
1st cut: gfi parser + --info processing method
38
from bzrlib.trace import (
0.64.67 by James Westby
Add support for -Dfast-import.
39
    error,
40
    mutter,
0.64.1 by Ian Clatworthy
1st cut: gfi parser + --info processing method
41
    note,
42
    warning,
43
    )
0.64.24 by Ian Clatworthy
smart blob caching using analysis done by --info
44
import bzrlib.util.configobj.configobj as configobj
0.64.5 by Ian Clatworthy
first cut at generic processing method
45
from bzrlib.plugins.fastimport import (
0.64.50 by Ian Clatworthy
cleanly restart after an interruption - basic mirroring
46
    errors as plugin_errors,
0.64.31 by Ian Clatworthy
fix branch updating for the single branch case
47
    helpers,
0.64.50 by Ian Clatworthy
cleanly restart after an interruption - basic mirroring
48
    idmapfile,
0.64.5 by Ian Clatworthy
first cut at generic processing method
49
    processor,
50
    revisionloader,
51
    )
0.64.1 by Ian Clatworthy
1st cut: gfi parser + --info processing method
52
53
0.64.41 by Ian Clatworthy
update multiple working trees if requested
54
# How many commits before automatically reporting progress
55
_DEFAULT_AUTO_PROGRESS = 1000
56
0.64.28 by Ian Clatworthy
checkpoint and count params to generic processor
57
# How many commits before automatically checkpointing
58
_DEFAULT_AUTO_CHECKPOINT = 10000
59
0.64.77 by Ian Clatworthy
add inv-fulltext option and improve speed
60
# How many commits before each inventory fulltext
61
_DEFAULT_INV_FULLTEXT = 200
62
0.64.44 by Ian Clatworthy
smart caching of serialised inventories
63
# How many inventories to cache
64
_DEFAULT_INV_CACHE_SIZE = 10
65
0.64.41 by Ian Clatworthy
update multiple working trees if requested
66
0.64.1 by Ian Clatworthy
1st cut: gfi parser + --info processing method
67
class GenericProcessor(processor.ImportProcessor):
68
    """An import processor that handles basic imports.
69
70
    Current features supported:
71
0.64.16 by Ian Clatworthy
safe processing tweaks
72
    * blobs are cached in memory
0.64.28 by Ian Clatworthy
checkpoint and count params to generic processor
73
    * files and symlinks commits are supported
74
    * checkpoints automatically happen at a configurable frequency
75
      over and above the stream requested checkpoints
76
    * timestamped progress reporting, both automatic and stream requested
0.64.41 by Ian Clatworthy
update multiple working trees if requested
77
    * LATER: reset support, tags for each branch
0.64.1 by Ian Clatworthy
1st cut: gfi parser + --info processing method
78
    * some basic statistics are dumped on completion.
0.64.24 by Ian Clatworthy
smart blob caching using analysis done by --info
79
0.64.50 by Ian Clatworthy
cleanly restart after an interruption - basic mirroring
80
    At checkpoints and on completion, the commit-id -> revision-id map is
81
    saved to a file called 'fastimport-id-map'. If the import crashes
82
    or is interrupted, it can be started again and this file will be
83
    used to skip over already loaded revisions. The format of each line
84
    is "commit-id revision-id" so commit-ids cannot include spaces.
85
0.64.24 by Ian Clatworthy
smart blob caching using analysis done by --info
86
    Here are the supported parameters:
87
0.64.38 by Ian Clatworthy
clean-up doc ready for initial release
88
    * info - name of a hints file holding the analysis generated
89
      by running the fast-import-info processor in verbose mode. When
0.64.33 by Ian Clatworthy
make tree updating optional and minor UI improvements
90
      importing large repositories, this parameter is needed so
91
      that the importer knows what blobs to intelligently cache.
92
0.64.41 by Ian Clatworthy
update multiple working trees if requested
93
    * trees - update the working trees before completing.
0.64.33 by Ian Clatworthy
make tree updating optional and minor UI improvements
94
      By default, the importer updates the repository
95
      and branches and the user needs to run 'bzr update' for the
0.64.41 by Ian Clatworthy
update multiple working trees if requested
96
      branches of interest afterwards.
0.64.28 by Ian Clatworthy
checkpoint and count params to generic processor
97
98
    * checkpoint - automatically checkpoint every n commits over and
99
      above any checkpoints contained in the import stream.
100
      The default is 10000.
101
0.64.44 by Ian Clatworthy
smart caching of serialised inventories
102
    * count - only import this many commits then exit. If not set
103
      or negative, all commits are imported.
104
    
0.64.77 by Ian Clatworthy
add inv-fulltext option and improve speed
105
    * inv-fulltext - create an inventory fulltext every n commits.
106
      The default is 200.
107
0.64.44 by Ian Clatworthy
smart caching of serialised inventories
108
    * inv-cache - number of inventories to cache.
109
      If not set, the default is 10.
0.64.47 by Ian Clatworthy
add option for enabling experimental stuff
110
111
    * experimental - enable experimental mode, i.e. use features
112
      not yet fully tested.
0.64.82 by Ian Clatworthy
Merge Pieter de Bie's export-fixes branch
113
114
    * import-marks - name of file to read to load mark information from
115
116
    * export-marks - name of file to write to save mark information to
0.64.1 by Ian Clatworthy
1st cut: gfi parser + --info processing method
117
    """
118
0.64.47 by Ian Clatworthy
add option for enabling experimental stuff
119
    known_params = [
120
        'info',
121
        'trees',
122
        'checkpoint',
123
        'count',
124
        'inv-cache',
0.64.77 by Ian Clatworthy
add inv-fulltext option and improve speed
125
        'inv-fulltext',
0.64.47 by Ian Clatworthy
add option for enabling experimental stuff
126
        'experimental',
0.68.7 by Pieter de Bie
Add importing and exporting of marks to bzr-fastimport
127
        'import-marks',
128
        'export-marks',
0.64.47 by Ian Clatworthy
add option for enabling experimental stuff
129
        ]
0.64.33 by Ian Clatworthy
make tree updating optional and minor UI improvements
130
131
    def note(self, msg, *args):
132
        """Output a note but timestamp it."""
133
        msg = "%s %s" % (self._time_of_day(), msg)
134
        note(msg, *args)
135
136
    def warning(self, msg, *args):
137
        """Output a warning but timestamp it."""
0.64.34 by Ian Clatworthy
report lost branches
138
        msg = "%s WARNING: %s" % (self._time_of_day(), msg)
0.64.33 by Ian Clatworthy
make tree updating optional and minor UI improvements
139
        warning(msg, *args)
140
0.64.67 by James Westby
Add support for -Dfast-import.
141
    def debug(self, mgs, *args):
142
        """Output a debug message if the appropriate -D option was given."""
143
        if "fast-import" in debug.debug_flags:
144
            msg = "%s DEBUG: %s" % (self._time_of_day(), msg)
145
            mutter(msg, *args)
146
0.64.33 by Ian Clatworthy
make tree updating optional and minor UI improvements
147
    def _time_of_day(self):
148
        """Time of day as a string."""
149
        # Note: this is a separate method so tests can patch in a fixed value
150
        return time.strftime("%H:%M:%S")
0.68.7 by Pieter de Bie
Add importing and exporting of marks to bzr-fastimport
151
152
    def _import_marks(self, filename):
153
        try:
154
            f = file(filename)
155
        except IOError:
0.64.82 by Ian Clatworthy
Merge Pieter de Bie's export-fixes branch
156
            self.warning(
157
                "Could not open import-marks file, not importing marks")
0.68.7 by Pieter de Bie
Add importing and exporting of marks to bzr-fastimport
158
            return
159
160
        firstline = f.readline()
161
        match = re.match(r'^format=(\d+)$', firstline)
162
        if not match:
0.64.82 by Ian Clatworthy
Merge Pieter de Bie's export-fixes branch
163
            print >>sys.stderr, "%r doesn't look like a mark file" % \
164
                (filename,)
0.68.7 by Pieter de Bie
Add importing and exporting of marks to bzr-fastimport
165
            sys.exit(1)
166
        elif match.group(1) != '1':
167
            print >>sys.stderr, 'format version in mark file not supported'
168
            sys.exit(1)
169
170
        for string in f.readline().rstrip('\n').split('\0'):
171
            if not string:
172
                continue
173
            name, integer = string.rsplit('.', 1)
174
            # We really can't do anything with the branch information, so we
175
            # just skip it
176
            
177
        self.cache_mgr.revision_ids = {}
178
        for line in f:
179
            line = line.rstrip('\n')
180
            mark, revid = line.split(' ', 1)
181
            self.cache_mgr.revision_ids[mark] = revid
0.64.82 by Ian Clatworthy
Merge Pieter de Bie's export-fixes branch
182
        f.close()
0.64.67 by James Westby
Add support for -Dfast-import.
183
    
0.68.7 by Pieter de Bie
Add importing and exporting of marks to bzr-fastimport
184
    def export_marks(self, filename):
0.64.82 by Ian Clatworthy
Merge Pieter de Bie's export-fixes branch
185
        try:
186
            f = file(filename, 'w')
187
        except IOError:
188
            self.warning(
189
                "Could not open export-marks file, not exporting marks")
190
            return
0.68.7 by Pieter de Bie
Add importing and exporting of marks to bzr-fastimport
191
        f.write('format=1\n')
192
        f.write('\0tmp.0\n')
193
        for mark, revid in self.cache_mgr.revision_ids.iteritems():
194
            f.write('%s %s\n' % (mark, revid))
195
        f.close()
196
        
0.64.1 by Ian Clatworthy
1st cut: gfi parser + --info processing method
197
    def pre_process(self):
0.64.26 by Ian Clatworthy
more progress reporting tweaks
198
        self._start_time = time.time()
0.64.28 by Ian Clatworthy
checkpoint and count params to generic processor
199
        self._load_info_and_params()
0.64.44 by Ian Clatworthy
smart caching of serialised inventories
200
        self.cache_mgr = GenericCacheManager(self.info, self.verbose,
201
            self.inventory_cache_size)
0.68.7 by Pieter de Bie
Add importing and exporting of marks to bzr-fastimport
202
        
0.64.82 by Ian Clatworthy
Merge Pieter de Bie's export-fixes branch
203
        if self.params.get("import-marks") is not None:
0.68.7 by Pieter de Bie
Add importing and exporting of marks to bzr-fastimport
204
            self._import_marks(self.params.get("import-marks"))
205
            self.skip_total = False
206
            self.first_incremental_commit = True
207
        else:
208
            self.first_incremental_commit = False
209
            self.skip_total = self._init_id_map()
210
            if self.skip_total:
211
                self.note("Found %d commits already loaded - "
212
                    "skipping over these ...", self.skip_total)
0.64.50 by Ian Clatworthy
cleanly restart after an interruption - basic mirroring
213
        self._revision_count = 0
214
215
        # mapping of tag name to revision_id
216
        self.tags = {}
217
218
        # Create the revision loader needed for committing
0.64.79 by Ian Clatworthy
support new Repository API
219
        new_repo_api = hasattr(self.repo, 'revisions')
0.64.49 by Ian Clatworthy
skip check re fulltext storage better than delta for inventories when in experimental mode
220
        if self._experimental:
0.64.77 by Ian Clatworthy
add inv-fulltext option and improve speed
221
            def fulltext_when(count):
222
                total = self.total_commits
223
                if total is not None and count == total:
224
                    fulltext = True
225
                else:
226
                    fulltext = count % self.inv_fulltext_every == 0
227
                if fulltext:
228
                    self.note("%d commits - storing inventory as full-text",
229
                        count)
230
                return fulltext
231
0.64.79 by Ian Clatworthy
support new Repository API
232
            if new_repo_api:
233
                self.loader = revisionloader.ImportRevisionLoader2(
234
                    self.repo, self.inventory_cache_size,
235
                    fulltext_when=fulltext_when)
236
            else:
237
                self.loader = revisionloader.ImportRevisionLoader1(
238
                    self.repo, self.inventory_cache_size,
239
                    fulltext_when=fulltext_when)
0.64.49 by Ian Clatworthy
skip check re fulltext storage better than delta for inventories when in experimental mode
240
        else:
0.64.79 by Ian Clatworthy
support new Repository API
241
            if new_repo_api:
242
                self.loader = revisionloader.RevisionLoader2(self.repo)
243
            else:
244
                self.loader = revisionloader.RevisionLoader1(self.repo)
0.64.28 by Ian Clatworthy
checkpoint and count params to generic processor
245
0.64.51 by Ian Clatworthy
disable autopacking
246
        # Disable autopacking if the repo format supports it.
247
        # THIS IS A HACK - there is no sanctioned way of doing this yet.
248
        if isinstance(self.repo, pack_repo.KnitPackRepository):
249
            self._original_max_pack_count = \
250
                self.repo._pack_collection._max_pack_count
251
            def _max_pack_count_for_import(total_revisions):
252
                return total_revisions + 1
253
            self.repo._pack_collection._max_pack_count = \
254
                _max_pack_count_for_import
255
        else:
256
            self._original_max_pack_count = None
257
            
0.64.28 by Ian Clatworthy
checkpoint and count params to generic processor
258
        # Create a write group. This is committed at the end of the import.
259
        # Checkpointing closes the current one and starts a new one.
260
        self.repo.start_write_group()
261
262
    def _load_info_and_params(self):
0.64.52 by Ian Clatworthy
switch on experimental mode by default
263
        self._experimental = bool(self.params.get('experimental', False))
0.64.47 by Ian Clatworthy
add option for enabling experimental stuff
264
0.64.50 by Ian Clatworthy
cleanly restart after an interruption - basic mirroring
265
        # This is currently hard-coded but might be configurable via
266
        # parameters one day if that's needed
267
        repo_transport = self.repo.control_files._transport
268
        self.id_map_path = repo_transport.local_abspath("fastimport-id-map")
269
0.64.24 by Ian Clatworthy
smart blob caching using analysis done by --info
270
        # Load the info file, if any
271
        info_path = self.params.get('info')
272
        if info_path is not None:
273
            self.info = configobj.ConfigObj(info_path)
274
        else:
275
            self.info = None
276
0.64.41 by Ian Clatworthy
update multiple working trees if requested
277
        # Decide how often to automatically report progress
278
        # (not a parameter yet)
279
        self.progress_every = _DEFAULT_AUTO_PROGRESS
280
        if self.verbose:
281
            self.progress_every = self.progress_every / 10
282
0.64.28 by Ian Clatworthy
checkpoint and count params to generic processor
283
        # Decide how often to automatically checkpoint
284
        self.checkpoint_every = int(self.params.get('checkpoint',
285
            _DEFAULT_AUTO_CHECKPOINT))
0.64.6 by Ian Clatworthy
generic processing method working for one revision in one branch
286
0.64.77 by Ian Clatworthy
add inv-fulltext option and improve speed
287
        # Decide how often to fulltext the inventory
288
        self.inv_fulltext_every = int(self.params.get('inv-fulltext',
289
            _DEFAULT_INV_FULLTEXT))
290
0.64.44 by Ian Clatworthy
smart caching of serialised inventories
291
        # Decide how big to make the inventory cache
292
        self.inventory_cache_size = int(self.params.get('inv-cache',
293
            _DEFAULT_INV_CACHE_SIZE))
294
0.64.28 by Ian Clatworthy
checkpoint and count params to generic processor
295
        # Find the maximum number of commits to import (None means all)
296
        # and prepare progress reporting. Just in case the info file
297
        # has an outdated count of commits, we store the max counts
298
        # at which we need to terminate separately to the total used
299
        # for progress tracking.
300
        try:
301
            self.max_commits = int(self.params['count'])
0.64.38 by Ian Clatworthy
clean-up doc ready for initial release
302
            if self.max_commits < 0:
303
                self.max_commits = None
0.64.28 by Ian Clatworthy
checkpoint and count params to generic processor
304
        except KeyError:
305
            self.max_commits = None
0.64.25 by Ian Clatworthy
slightly better progress reporting
306
        if self.info is not None:
307
            self.total_commits = int(self.info['Command counts']['commit'])
0.64.28 by Ian Clatworthy
checkpoint and count params to generic processor
308
            if (self.max_commits is not None and
309
                self.total_commits > self.max_commits):
310
                self.total_commits = self.max_commits
0.64.25 by Ian Clatworthy
slightly better progress reporting
311
        else:
0.64.28 by Ian Clatworthy
checkpoint and count params to generic processor
312
            self.total_commits = self.max_commits
0.64.25 by Ian Clatworthy
slightly better progress reporting
313
0.64.27 by Ian Clatworthy
1st cut at performance tuning
314
    def _process(self, command_iter):
315
        # if anything goes wrong, abort the write group if any
316
        try:
317
            processor.ImportProcessor._process(self, command_iter)
318
        except:
319
            if self.repo is not None and self.repo.is_in_write_group():
320
                self.repo.abort_write_group()
321
            raise
322
0.64.6 by Ian Clatworthy
generic processing method working for one revision in one branch
323
    def post_process(self):
0.64.50 by Ian Clatworthy
cleanly restart after an interruption - basic mirroring
324
        # Commit the current write group and checkpoint the id map
0.64.27 by Ian Clatworthy
1st cut at performance tuning
325
        self.repo.commit_write_group()
0.64.50 by Ian Clatworthy
cleanly restart after an interruption - basic mirroring
326
        self._save_id_map()
0.64.27 by Ian Clatworthy
1st cut at performance tuning
327
0.64.82 by Ian Clatworthy
Merge Pieter de Bie's export-fixes branch
328
        if self.params.get("export-marks") is not None:
0.68.7 by Pieter de Bie
Add importing and exporting of marks to bzr-fastimport
329
            self.export_marks(self.params.get("export-marks"))
330
0.64.31 by Ian Clatworthy
fix branch updating for the single branch case
331
        # Update the branches
332
        self.note("Updating branch information ...")
0.64.37 by Ian Clatworthy
create branches as required
333
        updater = GenericBranchUpdater(self.repo, self.branch, self.cache_mgr,
0.75.1 by Brian de Alwis
Add support for multiple branches by supporting the 'reset' command.
334
            helpers.invert_dictset(self.cache_mgr.heads),
0.64.64 by Ian Clatworthy
save tags known about in each branch
335
            self.cache_mgr.last_ref, self.tags)
0.64.34 by Ian Clatworthy
report lost branches
336
        branches_updated, branches_lost = updater.update()
337
        self._branch_count = len(branches_updated)
338
339
        # Tell the user about branches that were not created
340
        if branches_lost:
0.64.37 by Ian Clatworthy
create branches as required
341
            if not self.repo.is_shared():
342
                self.warning("Cannot import multiple branches into "
343
                    "an unshared repository")
344
            self.warning("Not creating branches for these head revisions:")
0.64.34 by Ian Clatworthy
report lost branches
345
            for lost_info in branches_lost:
346
                head_revision = lost_info[1]
347
                branch_name = lost_info[0]
0.64.67 by James Westby
Add support for -Dfast-import.
348
                self.note("\t %s = %s", head_revision, branch_name)
0.64.34 by Ian Clatworthy
report lost branches
349
350
        # Update the working trees as requested and dump stats
0.64.33 by Ian Clatworthy
make tree updating optional and minor UI improvements
351
        self._tree_count = 0
0.64.34 by Ian Clatworthy
report lost branches
352
        remind_about_update = True
0.64.54 by Ian Clatworthy
handle existing branches and only count the branches really updated
353
        if self._branch_count == 0:
354
            self.note("no branches to update")
355
            self.note("no working trees to update")
356
            remind_about_update = False
357
        elif self.params.get('trees', False):
0.64.41 by Ian Clatworthy
update multiple working trees if requested
358
            trees = self._get_working_trees(branches_updated)
359
            if trees:
360
                self.note("Updating the working trees ...")
0.64.33 by Ian Clatworthy
make tree updating optional and minor UI improvements
361
                if self.verbose:
362
                    report = delta._ChangeReporter()
363
                else:
364
                    reporter = None
0.64.41 by Ian Clatworthy
update multiple working trees if requested
365
                for wt in trees:
366
                    wt.update(reporter)
367
                    self._tree_count += 1
0.64.34 by Ian Clatworthy
report lost branches
368
                remind_about_update = False
0.64.41 by Ian Clatworthy
update multiple working trees if requested
369
            else:
370
                self.warning("No working trees available to update")
0.64.31 by Ian Clatworthy
fix branch updating for the single branch case
371
        self.dump_stats()
0.64.51 by Ian Clatworthy
disable autopacking
372
373
        # Finish up by telling the user what to do next.
374
        if self._original_max_pack_count:
375
            # We earlier disabled autopacking, creating one pack every
0.64.75 by Ian Clatworthy
if checkpointed, pack repository and delete obsolete_packs
376
            # checkpoint instead. We now pack the repository to optimise
377
            # how data is stored.
378
            if self._revision_count > self.checkpoint_every:
379
                self.note("Packing repository ...")
380
                self.repo.pack()
381
                # To be conservative, packing puts the old packs and
382
                # indices in obsolete_packs. We err on the side of
383
                # optimism and clear out that directory to save space.
384
                self.note("Removing obsolete packs ...")
385
                # TODO: Use a public API for this once one exists
386
                repo_transport = self.repo._pack_collection.transport
387
                repo_transport.clone('obsolete_packs').delete_multi(
388
                    repo_transport.list_dir('obsolete_packs'))
0.64.34 by Ian Clatworthy
report lost branches
389
        if remind_about_update:
0.64.75 by Ian Clatworthy
if checkpointed, pack repository and delete obsolete_packs
390
            # This message is explicitly not timestamped.
0.64.51 by Ian Clatworthy
disable autopacking
391
            note("To refresh the working tree for a branch, "
392
                "use 'bzr update'.")
0.64.41 by Ian Clatworthy
update multiple working trees if requested
393
394
    def _get_working_trees(self, branches):
395
        """Get the working trees for branches in the repository."""
396
        result = []
397
        wt_expected = self.repo.make_working_trees()
398
        for br in branches:
399
            if br == self.branch and br is not None:
400
                wt = self.working_tree
401
            elif wt_expected:
402
                try:
403
                    wt = br.bzrdir.open_workingtree()
404
                except errors.NoWorkingTree:
405
                    self.warning("No working tree for branch %s", br)
406
                    continue
407
            else:
408
                continue
409
            result.append(wt)
410
        return result
0.64.6 by Ian Clatworthy
generic processing method working for one revision in one branch
411
412
    def dump_stats(self):
0.64.33 by Ian Clatworthy
make tree updating optional and minor UI improvements
413
        time_required = progress.str_tdelta(time.time() - self._start_time)
0.64.50 by Ian Clatworthy
cleanly restart after an interruption - basic mirroring
414
        rc = self._revision_count - self.skip_total
0.64.6 by Ian Clatworthy
generic processing method working for one revision in one branch
415
        bc = self._branch_count
0.64.33 by Ian Clatworthy
make tree updating optional and minor UI improvements
416
        wtc = self._tree_count
417
        self.note("Imported %d %s, updating %d %s and %d %s in %s",
0.64.32 by Ian Clatworthy
move single_plural into helpers
418
            rc, helpers.single_plural(rc, "revision", "revisions"),
419
            bc, helpers.single_plural(bc, "branch", "branches"),
0.64.33 by Ian Clatworthy
make tree updating optional and minor UI improvements
420
            wtc, helpers.single_plural(wtc, "tree", "trees"),
421
            time_required)
0.64.28 by Ian Clatworthy
checkpoint and count params to generic processor
422
0.64.50 by Ian Clatworthy
cleanly restart after an interruption - basic mirroring
423
    def _init_id_map(self):
424
        """Load the id-map and check it matches the repository.
425
        
426
        :return: the number of entries in the map
427
        """
428
        # Currently, we just check the size. In the future, we might
429
        # decide to be more paranoid and check that the revision-ids
430
        # are identical as well.
431
        self.cache_mgr.revision_ids, known = idmapfile.load_id_map(
432
            self.id_map_path)
433
        existing_count = len(self.repo.all_revision_ids())
434
        if existing_count != known:
435
            raise plugin_errors.BadRepositorySize(known, existing_count)
436
        return known
437
438
    def _save_id_map(self):
439
        """Save the id-map."""
440
        # Save the whole lot every time. If this proves a problem, we can
441
        # change to 'append just the new ones' at a later time.
442
        idmapfile.save_id_map(self.id_map_path, self.cache_mgr.revision_ids)
443
0.64.5 by Ian Clatworthy
first cut at generic processing method
444
    def blob_handler(self, cmd):
445
        """Process a BlobCommand."""
446
        if cmd.mark is not None:
0.64.36 by Ian Clatworthy
fix head tracking when unmarked commits used
447
            dataref = cmd.id
0.64.5 by Ian Clatworthy
first cut at generic processing method
448
        else:
449
            dataref = osutils.sha_strings(cmd.data)
0.64.24 by Ian Clatworthy
smart blob caching using analysis done by --info
450
        self.cache_mgr.store_blob(dataref, cmd.data)
0.64.5 by Ian Clatworthy
first cut at generic processing method
451
452
    def checkpoint_handler(self, cmd):
453
        """Process a CheckpointCommand."""
0.64.27 by Ian Clatworthy
1st cut at performance tuning
454
        # Commit the current write group and start a new one
455
        self.repo.commit_write_group()
0.64.50 by Ian Clatworthy
cleanly restart after an interruption - basic mirroring
456
        self._save_id_map()
0.64.27 by Ian Clatworthy
1st cut at performance tuning
457
        self.repo.start_write_group()
0.64.5 by Ian Clatworthy
first cut at generic processing method
458
459
    def commit_handler(self, cmd):
460
        """Process a CommitCommand."""
0.64.50 by Ian Clatworthy
cleanly restart after an interruption - basic mirroring
461
        if self.skip_total and self._revision_count < self.skip_total:
462
            _track_heads(cmd, self.cache_mgr)
463
            # Check that we really do know about this commit-id
464
            if not self.cache_mgr.revision_ids.has_key(cmd.id):
465
                raise plugin_errors.BadRestart(cmd.id)
466
            # Consume the file commands and free any non-sticky blobs
467
            for fc in cmd.file_iter():
468
                pass
469
            self.cache_mgr._blobs = {}
470
            self._revision_count += 1
471
            # If we're finished getting back to where we were,
472
            # load the file-ids cache
473
            if self._revision_count == self.skip_total:
474
                self._gen_file_ids_cache()
475
                self.note("Generated the file-ids cache - %d entries",
476
                    len(self.cache_mgr.file_ids.keys()))
477
            return
0.68.7 by Pieter de Bie
Add importing and exporting of marks to bzr-fastimport
478
        if self.first_incremental_commit:
479
            self.first_incremental_commit = None
480
            parents = _track_heads(cmd, self.cache_mgr)
481
            self._gen_file_ids_cache(parents)
0.64.50 by Ian Clatworthy
cleanly restart after an interruption - basic mirroring
482
483
        # 'Commit' the revision and report progress
0.64.7 by Ian Clatworthy
start of multiple commit handling
484
        handler = GenericCommitHandler(cmd, self.repo, self.cache_mgr,
0.64.48 by Ian Clatworthy
one revision loader instance
485
            self.loader, self.verbose, self._experimental)
0.64.27 by Ian Clatworthy
1st cut at performance tuning
486
        handler.process()
0.64.36 by Ian Clatworthy
fix head tracking when unmarked commits used
487
        self.cache_mgr.revision_ids[cmd.id] = handler.revision_id
0.64.27 by Ian Clatworthy
1st cut at performance tuning
488
        self._revision_count += 1
0.64.36 by Ian Clatworthy
fix head tracking when unmarked commits used
489
        self.report_progress("(%s)" % cmd.id)
0.64.31 by Ian Clatworthy
fix branch updating for the single branch case
490
491
        # Check if we should finish up or automatically checkpoint
0.64.28 by Ian Clatworthy
checkpoint and count params to generic processor
492
        if (self.max_commits is not None and
493
            self._revision_count >= self.max_commits):
0.64.50 by Ian Clatworthy
cleanly restart after an interruption - basic mirroring
494
            self.note("Stopping after reaching requested count of commits")
0.64.28 by Ian Clatworthy
checkpoint and count params to generic processor
495
            self.finished = True
496
        elif self._revision_count % self.checkpoint_every == 0:
497
            self.note("%d commits - automatic checkpoint triggered",
498
                self._revision_count)
499
            self.checkpoint_handler(None)
0.64.1 by Ian Clatworthy
1st cut: gfi parser + --info processing method
500
0.64.82 by Ian Clatworthy
Merge Pieter de Bie's export-fixes branch
501
    def _gen_file_ids_cache(self, revs=False):
0.64.50 by Ian Clatworthy
cleanly restart after an interruption - basic mirroring
502
        """Generate the file-id cache by searching repository inventories.
503
        """
504
        # Get the interesting revisions - the heads
0.68.7 by Pieter de Bie
Add importing and exporting of marks to bzr-fastimport
505
        if revs:
506
            head_ids = revs
507
        else:
508
            head_ids = self.cache_mgr.heads.keys()
0.64.50 by Ian Clatworthy
cleanly restart after an interruption - basic mirroring
509
        revision_ids = [self.cache_mgr.revision_ids[h] for h in head_ids]
510
511
        # Update the fileid cache
512
        file_ids = {}
513
        for revision_id in revision_ids:
514
            inv = self.repo.revision_tree(revision_id).inventory
515
            # Cache the inventoires while we're at it
516
            self.cache_mgr.inventories[revision_id] = inv
517
            for path, ie in inv.iter_entries():
518
                file_ids[path] = ie.file_id
519
        self.cache_mgr.file_ids = file_ids
520
0.64.25 by Ian Clatworthy
slightly better progress reporting
521
    def report_progress(self, details=''):
522
        # TODO: use a progress bar with ETA enabled
0.64.41 by Ian Clatworthy
update multiple working trees if requested
523
        if self._revision_count % self.progress_every == 0:
0.64.26 by Ian Clatworthy
more progress reporting tweaks
524
            if self.total_commits is not None:
525
                counts = "%d/%d" % (self._revision_count, self.total_commits)
526
                eta = progress.get_eta(self._start_time, self._revision_count,
527
                    self.total_commits)
0.64.33 by Ian Clatworthy
make tree updating optional and minor UI improvements
528
                eta_str = progress.str_tdelta(eta)
529
                if eta_str.endswith('--'):
530
                    eta_str = ''
531
                else:
532
                    eta_str = '[%s] ' % eta_str
0.64.26 by Ian Clatworthy
more progress reporting tweaks
533
            else:
534
                counts = "%d" % (self._revision_count,)
535
                eta_str = ''
0.64.28 by Ian Clatworthy
checkpoint and count params to generic processor
536
            self.note("%s commits processed %s%s" % (counts, eta_str, details))
0.64.25 by Ian Clatworthy
slightly better progress reporting
537
0.64.1 by Ian Clatworthy
1st cut: gfi parser + --info processing method
538
    def progress_handler(self, cmd):
539
        """Process a ProgressCommand."""
0.64.34 by Ian Clatworthy
report lost branches
540
        # We could use a progress bar here instead
0.64.28 by Ian Clatworthy
checkpoint and count params to generic processor
541
        self.note("progress %s" % (cmd.message,))
0.64.5 by Ian Clatworthy
first cut at generic processing method
542
543
    def reset_handler(self, cmd):
544
        """Process a ResetCommand."""
0.64.12 by Ian Clatworthy
lightweight tags, filter processor and param validation
545
        if cmd.ref.startswith('refs/tags/'):
546
            self._set_tag(cmd.ref[len('refs/tags/'):], cmd.from_)
0.75.1 by Brian de Alwis
Add support for multiple branches by supporting the 'reset' command.
547
	    return
548
0.75.2 by Brian de Alwis
Reset takes a <commitsh> and not just a revid; added note to
549
	# FIXME: cmd.from_ is a committish and thus could reference
550
	# another branch.  Create a method for resolving commitsh's.
0.75.1 by Brian de Alwis
Add support for multiple branches by supporting the 'reset' command.
551
        if cmd.from_ is not None:
552
            self.cache_mgr.last_ref = cmd.ref
553
            self.cache_mgr.heads.setdefault(cmd.from_, set()).add(cmd.ref)
554
            self.cache_mgr.last_ids[cmd.ref] = cmd.from_
555
556
            updater = GenericBranchUpdater(self.repo, self.branch, self.cache_mgr,
557
                helpers.invert_dictset(self.cache_mgr.heads),
558
                self.cache_mgr.last_ref, self.tags)
559
            updater.update()
0.64.5 by Ian Clatworthy
first cut at generic processing method
560
561
    def tag_handler(self, cmd):
562
        """Process a TagCommand."""
0.64.12 by Ian Clatworthy
lightweight tags, filter processor and param validation
563
        self._set_tag(cmd.id, cmd.from_)
564
565
    def _set_tag(self, name, from_):
566
        """Define a tag given a name an import 'from' reference."""
567
        bzr_tag_name = name.decode('utf-8', 'replace')
568
        bzr_rev_id = self.cache_mgr.revision_ids[from_]
0.64.11 by Ian Clatworthy
tag support
569
        self.tags[bzr_tag_name] = bzr_rev_id
0.64.5 by Ian Clatworthy
first cut at generic processing method
570
571
0.64.6 by Ian Clatworthy
generic processing method working for one revision in one branch
572
class GenericCacheManager(object):
573
    """A manager of caches for the GenericProcessor."""
574
0.64.24 by Ian Clatworthy
smart blob caching using analysis done by --info
575
    def __init__(self, info, verbose=False, inventory_cache_size=10):
576
        """Create a manager of caches.
577
578
        :param info: a ConfigObj holding the output from
579
            the --info processor, or None if no hints are available
580
        """
581
        self.verbose = verbose
582
0.64.6 by Ian Clatworthy
generic processing method working for one revision in one branch
583
        # dataref -> data. datref is either :mark or the sha-1.
0.64.24 by Ian Clatworthy
smart blob caching using analysis done by --info
584
        # Sticky blobs aren't removed after being referenced.
585
        self._blobs = {}
586
        self._sticky_blobs = {}
0.64.6 by Ian Clatworthy
generic processing method working for one revision in one branch
587
588
        # revision-id -> Inventory cache
589
        # these are large and we probably don't need too many as
590
        # most parents are recent in history
591
        self.inventories = lru_cache.LRUCache(inventory_cache_size)
592
0.64.50 by Ian Clatworthy
cleanly restart after an interruption - basic mirroring
593
        # import commmit-ids -> revision-id lookup table
0.64.6 by Ian Clatworthy
generic processing method working for one revision in one branch
594
        # we need to keep all of these but they are small
595
        self.revision_ids = {}
596
0.64.22 by Ian Clatworthy
fix more inventory lookup bugs
597
        # path -> file-ids - as generated
0.64.14 by Ian Clatworthy
commit of modified files working
598
        self.file_ids = {}
0.64.6 by Ian Clatworthy
generic processing method working for one revision in one branch
599
0.75.1 by Brian de Alwis
Add support for multiple branches by supporting the 'reset' command.
600
        # Head tracking: last ref, last id per ref & map of commit ids to ref*s*
0.64.36 by Ian Clatworthy
fix head tracking when unmarked commits used
601
        self.last_ref = None
602
        self.last_ids = {}
603
        self.heads = {}
604
0.64.24 by Ian Clatworthy
smart blob caching using analysis done by --info
605
        # Work out the blobs to make sticky - None means all
0.64.25 by Ian Clatworthy
slightly better progress reporting
606
        self._blobs_to_keep = None
607
        if info is not None:
608
            try:
609
                self._blobs_to_keep = info['Blob usage tracking']['multi']
610
            except KeyError:
611
                # info not in file - possible when no blobs used
612
                pass
0.64.24 by Ian Clatworthy
smart blob caching using analysis done by --info
613
614
    def store_blob(self, id, data):
615
        """Store a blob of data."""
616
        if (self._blobs_to_keep is None or data == '' or
617
            id in self._blobs_to_keep):
618
            self._sticky_blobs[id] = data
619
        else:
620
            self._blobs[id] = data
621
622
    def fetch_blob(self, id):
623
        """Fetch a blob of data."""
624
        try:
625
            return self._sticky_blobs[id]
626
        except KeyError:
627
            return self._blobs.pop(id)
628
0.64.16 by Ian Clatworthy
safe processing tweaks
629
    def _delete_path(self, path):
630
        """Remove a path from caches."""
0.64.22 by Ian Clatworthy
fix more inventory lookup bugs
631
        # we actually want to remember what file-id we gave a path,
632
        # even when that file is deleted, so doing nothing is correct
633
        pass
0.64.16 by Ian Clatworthy
safe processing tweaks
634
635
    def _rename_path(self, old_path, new_path):
636
        """Rename a path in the caches."""
0.64.66 by Ian Clatworthy
fix a duplicate file-id after rename bug
637
        # In this case, we need to forget the file-id we gave a path,
638
        # otherwise, we'll get duplicate file-ids in the repository.
0.64.16 by Ian Clatworthy
safe processing tweaks
639
        self.file_ids[new_path] = self.file_ids[old_path]
0.64.66 by Ian Clatworthy
fix a duplicate file-id after rename bug
640
        del self.file_ids[old_path]
0.64.16 by Ian Clatworthy
safe processing tweaks
641
642
0.64.50 by Ian Clatworthy
cleanly restart after an interruption - basic mirroring
643
def _track_heads(cmd, cache_mgr):
644
    """Track the repository heads given a CommitCommand.
645
    
646
    :return: the list of parents in terms of commit-ids
647
    """
648
    # Get the true set of parents
0.64.60 by Ian Clatworthy
support merges when from clause implicit
649
    if cmd.from_ is not None:
650
        parents = [cmd.from_]
0.64.55 by Ian Clatworthy
fix head tracking when from clause implied
651
    else:
0.64.50 by Ian Clatworthy
cleanly restart after an interruption - basic mirroring
652
        last_id = cache_mgr.last_ids.get(cmd.ref)
653
        if last_id is not None:
654
            parents = [last_id]
655
        else:
656
            parents = []
0.64.60 by Ian Clatworthy
support merges when from clause implicit
657
    parents.extend(cmd.merges)
0.64.50 by Ian Clatworthy
cleanly restart after an interruption - basic mirroring
658
    # Track the heads
659
    for parent in parents:
660
        try:
0.75.1 by Brian de Alwis
Add support for multiple branches by supporting the 'reset' command.
661
            del cache_mgr.heads[parent] # FIXME?
0.64.50 by Ian Clatworthy
cleanly restart after an interruption - basic mirroring
662
        except KeyError:
663
            # it's ok if the parent isn't there - another
664
            # commit may have already removed it
665
            pass
0.75.1 by Brian de Alwis
Add support for multiple branches by supporting the 'reset' command.
666
    cache_mgr.heads.setdefault(cmd.id, set()).add(cmd.ref)
0.64.50 by Ian Clatworthy
cleanly restart after an interruption - basic mirroring
667
    cache_mgr.last_ids[cmd.ref] = cmd.id
668
    cache_mgr.last_ref = cmd.ref
669
    return parents
670
671
0.64.5 by Ian Clatworthy
first cut at generic processing method
672
class GenericCommitHandler(processor.CommitHandler):
673
0.64.48 by Ian Clatworthy
one revision loader instance
674
    def __init__(self, command, repo, cache_mgr, loader, verbose=False,
0.64.47 by Ian Clatworthy
add option for enabling experimental stuff
675
        _experimental=False):
0.64.5 by Ian Clatworthy
first cut at generic processing method
676
        processor.CommitHandler.__init__(self, command)
677
        self.repo = repo
0.64.6 by Ian Clatworthy
generic processing method working for one revision in one branch
678
        self.cache_mgr = cache_mgr
0.64.48 by Ian Clatworthy
one revision loader instance
679
        self.loader = loader
0.64.14 by Ian Clatworthy
commit of modified files working
680
        self.verbose = verbose
0.64.47 by Ian Clatworthy
add option for enabling experimental stuff
681
        self._experimental = _experimental
0.64.5 by Ian Clatworthy
first cut at generic processing method
682
0.64.43 by Ian Clatworthy
verbose mode cleanup
683
    def note(self, msg, *args):
684
        """Output a note but add context."""
685
        msg = "%s (%s)" % (msg, self.command.id)
686
        note(msg, *args)
687
688
    def warning(self, msg, *args):
689
        """Output a warning but add context."""
690
        msg = "WARNING: %s (%s)" % (msg, self.command.id)
691
        warning(msg, *args)
692
0.64.67 by James Westby
Add support for -Dfast-import.
693
    def debug(self, msg, *args):
694
        """Output a mutter if the appropriate -D option was given."""
695
        if "fast-import" in debug.debug_flags:
696
            msg = "%s (%s)" % (msg, self.command.id)
697
            mutter(msg, *args)
698
0.64.5 by Ian Clatworthy
first cut at generic processing method
699
    def pre_process_files(self):
700
        """Prepare for committing."""
701
        self.revision_id = self.gen_revision_id()
702
        # cache of texts for this commit, indexed by file-id
0.64.6 by Ian Clatworthy
generic processing method working for one revision in one branch
703
        self.lines_for_commit = {}
0.64.5 by Ian Clatworthy
first cut at generic processing method
704
0.64.50 by Ian Clatworthy
cleanly restart after an interruption - basic mirroring
705
        # Track the heads and get the real parent list
706
        parents = _track_heads(self.command, self.cache_mgr)
0.64.36 by Ian Clatworthy
fix head tracking when unmarked commits used
707
0.64.14 by Ian Clatworthy
commit of modified files working
708
        # Get the parent inventories
0.64.36 by Ian Clatworthy
fix head tracking when unmarked commits used
709
        if parents:
0.64.31 by Ian Clatworthy
fix branch updating for the single branch case
710
            self.parents = [self.cache_mgr.revision_ids[p]
0.64.36 by Ian Clatworthy
fix head tracking when unmarked commits used
711
                for p in parents]
0.64.7 by Ian Clatworthy
start of multiple commit handling
712
        else:
0.64.31 by Ian Clatworthy
fix branch updating for the single branch case
713
            self.parents = []
0.64.67 by James Westby
Add support for -Dfast-import.
714
        self.debug("revision parents are %s", str(self.parents))
0.64.7 by Ian Clatworthy
start of multiple commit handling
715
0.64.14 by Ian Clatworthy
commit of modified files working
716
        # Seed the inventory from the previous one
717
        if len(self.parents) == 0:
718
            self.inventory = self.gen_initial_inventory()
0.64.5 by Ian Clatworthy
first cut at generic processing method
719
        else:
720
            # use the bzr_revision_id to lookup the inv cache
0.64.47 by Ian Clatworthy
add option for enabling experimental stuff
721
            inv = self.get_inventory(self.parents[0])
722
            # TODO: Shallow copy - deep inventory copying is expensive
723
            self.inventory = inv.copy()
0.64.13 by Ian Clatworthy
commit of new files working
724
        if not self.repo.supports_rich_root():
725
            # In this repository, root entries have no knit or weave. When
726
            # serializing out to disk and back in, root.revision is always
727
            # the new revision_id.
0.64.14 by Ian Clatworthy
commit of modified files working
728
            self.inventory.root.revision = self.revision_id
0.64.5 by Ian Clatworthy
first cut at generic processing method
729
0.64.22 by Ian Clatworthy
fix more inventory lookup bugs
730
        # directory-path -> inventory-entry for current inventory
731
        self.directory_entries = dict(self.inventory.directories())
732
0.64.14 by Ian Clatworthy
commit of modified files working
733
    def post_process_files(self):
734
        """Save the revision."""
0.64.17 by Ian Clatworthy
escape commit messages, diff author to committer and cache fixes
735
        self.cache_mgr.inventories[self.revision_id] = self.inventory
0.64.5 by Ian Clatworthy
first cut at generic processing method
736
0.64.6 by Ian Clatworthy
generic processing method working for one revision in one branch
737
        # Load the revision into the repository
0.64.17 by Ian Clatworthy
escape commit messages, diff author to committer and cache fixes
738
        rev_props = {}
0.64.6 by Ian Clatworthy
generic processing method working for one revision in one branch
739
        committer = self.command.committer
740
        who = "%s <%s>" % (committer[0],committer[1])
0.64.17 by Ian Clatworthy
escape commit messages, diff author to committer and cache fixes
741
        author = self.command.author
742
        if author is not None:
743
            author_id = "%s <%s>" % (author[0],author[1])
744
            if author_id != who:
745
                rev_props['author'] = author_id
0.64.6 by Ian Clatworthy
generic processing method working for one revision in one branch
746
        rev = revision.Revision(
747
           timestamp=committer[2],
748
           timezone=committer[3],
749
           committer=who,
0.64.17 by Ian Clatworthy
escape commit messages, diff author to committer and cache fixes
750
           message=self._escape_commit_message(self.command.message),
751
           revision_id=self.revision_id,
752
           properties=rev_props,
753
           parent_ids=self.parents)
0.64.14 by Ian Clatworthy
commit of modified files working
754
        self.loader.load(rev, self.inventory, None,
0.64.48 by Ian Clatworthy
one revision loader instance
755
            lambda file_id: self._get_lines(file_id),
756
            lambda revision_ids: self._get_inventories(revision_ids))
0.64.6 by Ian Clatworthy
generic processing method working for one revision in one branch
757
0.64.17 by Ian Clatworthy
escape commit messages, diff author to committer and cache fixes
758
    def _escape_commit_message(self, message):
759
        """Replace xml-incompatible control characters."""
0.64.6 by Ian Clatworthy
generic processing method working for one revision in one branch
760
        # It's crap that we need to do this at this level (but we do)
0.64.17 by Ian Clatworthy
escape commit messages, diff author to committer and cache fixes
761
        # Code copied from bzrlib.commit.
762
        
763
        # Python strings can include characters that can't be
764
        # represented in well-formed XML; escape characters that
765
        # aren't listed in the XML specification
766
        # (http://www.w3.org/TR/REC-xml/#NT-Char).
767
        message, _ = re.subn(
768
            u'[^\x09\x0A\x0D\u0020-\uD7FF\uE000-\uFFFD]+',
769
            lambda match: match.group(0).encode('unicode_escape'),
770
            message)
771
        return message
0.64.5 by Ian Clatworthy
first cut at generic processing method
772
773
    def modify_handler(self, filecmd):
774
        if filecmd.dataref is not None:
0.64.24 by Ian Clatworthy
smart blob caching using analysis done by --info
775
            data = self.cache_mgr.fetch_blob(filecmd.dataref)
0.64.5 by Ian Clatworthy
first cut at generic processing method
776
        else:
777
            data = filecmd.data
0.64.67 by James Westby
Add support for -Dfast-import.
778
        self.debug("modifying %s", filecmd.path)
0.64.5 by Ian Clatworthy
first cut at generic processing method
779
        self._modify_inventory(filecmd.path, filecmd.kind,
780
            filecmd.is_executable, data)
781
782
    def delete_handler(self, filecmd):
783
        path = filecmd.path
0.64.67 by James Westby
Add support for -Dfast-import.
784
        self.debug("deleting %s", path)
0.64.63 by Ian Clatworthy
remove warning about delete iff file is in a merge parent
785
        fileid = self.bzr_file_id(path)
0.64.21 by Ian Clatworthy
fix one inventory lookup bug
786
        try:
0.64.63 by Ian Clatworthy
remove warning about delete iff file is in a merge parent
787
            del self.inventory[fileid]
0.64.47 by Ian Clatworthy
add option for enabling experimental stuff
788
        except KeyError:
0.64.63 by Ian Clatworthy
remove warning about delete iff file is in a merge parent
789
            self._warn_unless_in_merges(fileid, path)
0.64.21 by Ian Clatworthy
fix one inventory lookup bug
790
        except errors.NoSuchId:
0.64.63 by Ian Clatworthy
remove warning about delete iff file is in a merge parent
791
            self._warn_unless_in_merges(fileid, path)
0.64.45 by Ian Clatworthy
fix compatibility with Python 2.4
792
        try:
793
            self.cache_mgr._delete_path(path)
794
        except KeyError:
795
            pass
0.64.5 by Ian Clatworthy
first cut at generic processing method
796
0.64.63 by Ian Clatworthy
remove warning about delete iff file is in a merge parent
797
    def _warn_unless_in_merges(self, fileid, path):
798
        if len(self.parents) <= 1:
799
            return
800
        for parent in self.parents[1:]:
801
            if fileid in self.get_inventory(parent):
802
                return
803
        self.warning("ignoring delete of %s as not in parent inventories", path)
804
0.64.5 by Ian Clatworthy
first cut at generic processing method
805
    def copy_handler(self, filecmd):
806
        raise NotImplementedError(self.copy_handler)
807
808
    def rename_handler(self, filecmd):
0.64.16 by Ian Clatworthy
safe processing tweaks
809
        old_path = filecmd.old_path
810
        new_path = filecmd.new_path
0.64.67 by James Westby
Add support for -Dfast-import.
811
        self.debug("renaming %s to %s", old_path, new_path)
0.64.16 by Ian Clatworthy
safe processing tweaks
812
        file_id = self.bzr_file_id(old_path)
0.65.4 by James Westby
Make the rename handling more robust.
813
        basename, new_parent_ie = self._ensure_directory(new_path)
814
        new_parent_id = new_parent_ie.file_id
0.64.67 by James Westby
Add support for -Dfast-import.
815
        existing_id = self.inventory.path2id(new_path)
816
        if existing_id is not None:
817
            self.inventory.remove_recursive_id(existing_id)
0.74.1 by John Arbash Meinel
Change the rename code to create a new text entry.
818
        ie = self.inventory[file_id]
819
        lines = self.loader._get_lines(file_id, ie.revision)
820
        self.lines_for_commit[file_id] = lines
0.65.4 by James Westby
Make the rename handling more robust.
821
        self.inventory.rename(file_id, new_parent_id, basename)
0.64.16 by Ian Clatworthy
safe processing tweaks
822
        self.cache_mgr._rename_path(old_path, new_path)
0.74.1 by John Arbash Meinel
Change the rename code to create a new text entry.
823
        self.inventory[file_id].revision = self.revision_id
0.64.5 by Ian Clatworthy
first cut at generic processing method
824
825
    def deleteall_handler(self, filecmd):
0.73.1 by Miklos Vajna
Implement the 'deleteall' command.
826
        self.debug("deleting all files (and also all directories)")
827
        for path, fileid in self.cache_mgr.file_ids.items():
828
            del self.inventory[fileid]
829
            self.cache_mgr._delete_path(path)
0.64.5 by Ian Clatworthy
first cut at generic processing method
830
0.64.16 by Ian Clatworthy
safe processing tweaks
831
    def bzr_file_id_and_new(self, path):
832
        """Get a Bazaar file identifier and new flag for a path.
833
        
0.64.17 by Ian Clatworthy
escape commit messages, diff author to committer and cache fixes
834
        :return: file_id, is_new where
835
          is_new = True if the file_id is newly created
0.64.16 by Ian Clatworthy
safe processing tweaks
836
        """
837
        try:
0.64.67 by James Westby
Add support for -Dfast-import.
838
            id = self.cache_mgr.file_ids[path]
839
            return id, False
0.64.16 by Ian Clatworthy
safe processing tweaks
840
        except KeyError:
841
            id = generate_ids.gen_file_id(path)
842
            self.cache_mgr.file_ids[path] = id
0.64.67 by James Westby
Add support for -Dfast-import.
843
            self.debug("Generated new file id %s for '%s'", id, path)
0.64.16 by Ian Clatworthy
safe processing tweaks
844
            return id, True
845
0.64.5 by Ian Clatworthy
first cut at generic processing method
846
    def bzr_file_id(self, path):
0.64.14 by Ian Clatworthy
commit of modified files working
847
        """Get a Bazaar file identifier for a path."""
0.64.16 by Ian Clatworthy
safe processing tweaks
848
        return self.bzr_file_id_and_new(path)[0]
0.64.5 by Ian Clatworthy
first cut at generic processing method
849
0.64.6 by Ian Clatworthy
generic processing method working for one revision in one branch
850
    def gen_initial_inventory(self):
851
        """Generate an inventory for a parentless revision."""
852
        inv = inventory.Inventory(revision_id=self.revision_id)
853
        return inv
854
0.64.5 by Ian Clatworthy
first cut at generic processing method
855
    def gen_revision_id(self):
856
        """Generate a revision id.
857
858
        Subclasses may override this to produce deterministic ids say.
859
        """
860
        committer = self.command.committer
0.64.16 by Ian Clatworthy
safe processing tweaks
861
        # Perhaps 'who' being the person running the import is ok? If so,
862
        # it might be a bit quicker and give slightly better compression?
0.64.5 by Ian Clatworthy
first cut at generic processing method
863
        who = "%s <%s>" % (committer[0],committer[1])
864
        timestamp = committer[2]
865
        return generate_ids.gen_revision_id(who, timestamp)
866
0.64.7 by Ian Clatworthy
start of multiple commit handling
867
    def get_inventory(self, revision_id):
868
        """Get the inventory for a revision id."""
869
        try:
870
            inv = self.cache_mgr.inventories[revision_id]
871
        except KeyError:
0.64.43 by Ian Clatworthy
verbose mode cleanup
872
            if self.verbose:
873
                self.note("get_inventory cache miss for %s", revision_id)
0.64.7 by Ian Clatworthy
start of multiple commit handling
874
            # Not cached so reconstruct from repository
875
            inv = self.repo.revision_tree(revision_id).inventory
876
            self.cache_mgr.inventories[revision_id] = inv
877
        return inv
878
0.64.5 by Ian Clatworthy
first cut at generic processing method
879
    def _get_inventories(self, revision_ids):
880
        """Get the inventories for revision-ids.
881
        
882
        This is a callback used by the RepositoryLoader to
883
        speed up inventory reconstruction."""
884
        present = []
885
        inventories = []
0.64.6 by Ian Clatworthy
generic processing method working for one revision in one branch
886
        # If an inventory is in the cache, we assume it was
0.64.5 by Ian Clatworthy
first cut at generic processing method
887
        # successfully loaded into the repsoitory
888
        for revision_id in revision_ids:
889
            try:
0.64.6 by Ian Clatworthy
generic processing method working for one revision in one branch
890
                inv = self.cache_mgr.inventories[revision_id]
0.64.5 by Ian Clatworthy
first cut at generic processing method
891
                present.append(revision_id)
892
            except KeyError:
0.64.43 by Ian Clatworthy
verbose mode cleanup
893
                if self.verbose:
894
                    self.note("get_inventories cache miss for %s", revision_id)
0.64.5 by Ian Clatworthy
first cut at generic processing method
895
                # Not cached so reconstruct from repository
896
                if self.repo.has_revision(revision_id):
897
                    rev_tree = self.repo.revision_tree(revision_id)
898
                    present.append(revision_id)
899
                else:
900
                    rev_tree = self.repo.revision_tree(None)
901
                inv = rev_tree.inventory
0.64.6 by Ian Clatworthy
generic processing method working for one revision in one branch
902
                self.cache_mgr.inventories[revision_id] = inv
903
            inventories.append(inv)
0.64.5 by Ian Clatworthy
first cut at generic processing method
904
        return present, inventories
905
0.64.6 by Ian Clatworthy
generic processing method working for one revision in one branch
906
    def _get_lines(self, file_id):
907
        """Get the lines for a file-id."""
908
        return self.lines_for_commit[file_id]
0.64.5 by Ian Clatworthy
first cut at generic processing method
909
910
    def _modify_inventory(self, path, kind, is_executable, data):
911
        """Add to or change an item in the inventory."""
912
        # Create the new InventoryEntry
913
        basename, parent_ie = self._ensure_directory(path)
0.64.22 by Ian Clatworthy
fix more inventory lookup bugs
914
        file_id = self.bzr_file_id(path)
0.64.16 by Ian Clatworthy
safe processing tweaks
915
        ie = inventory.make_entry(kind, basename, parent_ie.file_id, file_id)
0.64.6 by Ian Clatworthy
generic processing method working for one revision in one branch
916
        ie.revision = self.revision_id
0.64.5 by Ian Clatworthy
first cut at generic processing method
917
        if isinstance(ie, inventory.InventoryFile):
918
            ie.executable = is_executable
0.64.13 by Ian Clatworthy
commit of new files working
919
            lines = osutils.split_lines(data)
920
            ie.text_sha1 = osutils.sha_strings(lines)
921
            ie.text_size = sum(map(len, lines))
0.64.6 by Ian Clatworthy
generic processing method working for one revision in one branch
922
            self.lines_for_commit[file_id] = lines
0.64.73 by James Westby
Correct typo: InventoryLnk -> InventoryLink
923
        elif isinstance(ie, inventory.InventoryLink):
0.64.74 by Ian Clatworthy
fix symlink importing
924
            ie.symlink_target = data.encode('utf8')
925
            # There are no lines stored for a symlink so
926
            # make sure the cache used by get_lines knows that
927
            self.lines_for_commit[file_id] = []
0.64.5 by Ian Clatworthy
first cut at generic processing method
928
        else:
929
            raise errors.BzrError("Cannot import items of kind '%s' yet" %
930
                (kind,))
931
0.64.16 by Ian Clatworthy
safe processing tweaks
932
        # Record this new inventory entry
0.64.22 by Ian Clatworthy
fix more inventory lookup bugs
933
        if file_id in self.inventory:
0.64.21 by Ian Clatworthy
fix one inventory lookup bug
934
            # HACK: no API for this (del+add does more than it needs to)
935
            self.inventory._byid[file_id] = ie
0.64.61 by Ian Clatworthy
fix missing revisions bug
936
            parent_ie.children[basename] = ie
0.64.22 by Ian Clatworthy
fix more inventory lookup bugs
937
        else:
938
            self.inventory.add(ie)
0.64.5 by Ian Clatworthy
first cut at generic processing method
939
940
    def _ensure_directory(self, path):
941
        """Ensure that the containing directory exists for 'path'"""
942
        dirname, basename = osutils.split(path)
943
        if dirname == '':
944
            # the root node doesn't get updated
0.64.16 by Ian Clatworthy
safe processing tweaks
945
            return basename, self.inventory.root
0.64.5 by Ian Clatworthy
first cut at generic processing method
946
        try:
0.64.22 by Ian Clatworthy
fix more inventory lookup bugs
947
            ie = self.directory_entries[dirname]
0.64.5 by Ian Clatworthy
first cut at generic processing method
948
        except KeyError:
949
            # We will create this entry, since it doesn't exist
950
            pass
951
        else:
952
            return basename, ie
953
954
        # No directory existed, we will just create one, first, make sure
955
        # the parent exists
956
        dir_basename, parent_ie = self._ensure_directory(dirname)
957
        dir_file_id = self.bzr_file_id(dirname)
958
        ie = inventory.entry_factory['directory'](dir_file_id,
959
                                                  dir_basename,
960
                                                  parent_ie.file_id)
961
        ie.revision = self.revision_id
0.64.22 by Ian Clatworthy
fix more inventory lookup bugs
962
        self.directory_entries[dirname] = ie
0.64.16 by Ian Clatworthy
safe processing tweaks
963
        # There are no lines stored for a directory so
964
        # make sure the cache used by get_lines knows that
965
        self.lines_for_commit[dir_file_id] = []
0.64.47 by Ian Clatworthy
add option for enabling experimental stuff
966
        #print "adding dir for %s" % path
0.64.16 by Ian Clatworthy
safe processing tweaks
967
        self.inventory.add(ie)
0.64.5 by Ian Clatworthy
first cut at generic processing method
968
        return basename, ie
0.64.31 by Ian Clatworthy
fix branch updating for the single branch case
969
970
0.64.34 by Ian Clatworthy
report lost branches
971
class GenericBranchUpdater(object):
0.64.31 by Ian Clatworthy
fix branch updating for the single branch case
972
0.64.64 by Ian Clatworthy
save tags known about in each branch
973
    def __init__(self, repo, branch, cache_mgr, heads_by_ref, last_ref, tags):
0.64.31 by Ian Clatworthy
fix branch updating for the single branch case
974
        """Create an object responsible for updating branches.
975
976
        :param heads_by_ref: a dictionary where
977
          names are git-style references like refs/heads/master;
978
          values are one item lists of commits marks.
979
        """
0.64.37 by Ian Clatworthy
create branches as required
980
        self.repo = repo
0.64.31 by Ian Clatworthy
fix branch updating for the single branch case
981
        self.branch = branch
982
        self.cache_mgr = cache_mgr
983
        self.heads_by_ref = heads_by_ref
984
        self.last_ref = last_ref
0.64.64 by Ian Clatworthy
save tags known about in each branch
985
        self.tags = tags
0.64.31 by Ian Clatworthy
fix branch updating for the single branch case
986
987
    def update(self):
988
        """Update the Bazaar branches and tips matching the heads.
989
990
        If the repository is shared, this routine creates branches
991
        as required. If it isn't, warnings are produced about the
992
        lost of information.
0.64.33 by Ian Clatworthy
make tree updating optional and minor UI improvements
993
0.64.34 by Ian Clatworthy
report lost branches
994
        :return: updated, lost_heads where
995
          updated = the list of branches updated
996
          lost_heads = a list of (bazaar-name,revision) for branches that
997
            would have been created had the repository been shared
0.64.31 by Ian Clatworthy
fix branch updating for the single branch case
998
        """
0.64.33 by Ian Clatworthy
make tree updating optional and minor UI improvements
999
        updated = []
0.64.37 by Ian Clatworthy
create branches as required
1000
        branch_tips, lost_heads = self._get_matching_branches()
0.64.31 by Ian Clatworthy
fix branch updating for the single branch case
1001
        for br, tip in branch_tips:
0.64.54 by Ian Clatworthy
handle existing branches and only count the branches really updated
1002
            if self._update_branch(br, tip):
1003
                updated.append(br)
0.64.34 by Ian Clatworthy
report lost branches
1004
        return updated, lost_heads
0.64.31 by Ian Clatworthy
fix branch updating for the single branch case
1005
1006
    def _get_matching_branches(self):
1007
        """Get the Bazaar branches.
1008
0.64.34 by Ian Clatworthy
report lost branches
1009
        :return: default_tip, branch_tips, lost_tips where
0.64.31 by Ian Clatworthy
fix branch updating for the single branch case
1010
          default_tip = the last commit mark for the default branch
1011
          branch_tips = a list of (branch,tip) tuples for other branches.
0.64.34 by Ian Clatworthy
report lost branches
1012
          lost_heads = a list of (bazaar-name,revision) for branches that
0.64.37 by Ian Clatworthy
create branches as required
1013
            would have been created had the repository been shared and
1014
            everything succeeded
0.64.31 by Ian Clatworthy
fix branch updating for the single branch case
1015
        """
0.64.37 by Ian Clatworthy
create branches as required
1016
        branch_tips = []
1017
        lost_heads = []
1018
        ref_names = self.heads_by_ref.keys()
1019
        if self.branch is not None:
0.64.40 by Ian Clatworthy
always use heads/master as the trunk if it is present
1020
            trunk = self.select_trunk(ref_names)
1021
            default_tip = self.heads_by_ref[trunk][0]
0.64.37 by Ian Clatworthy
create branches as required
1022
            branch_tips.append((self.branch, default_tip))
0.64.40 by Ian Clatworthy
always use heads/master as the trunk if it is present
1023
            ref_names.remove(trunk)
0.64.34 by Ian Clatworthy
report lost branches
1024
1025
        # Convert the reference names into Bazaar speak
1026
        bzr_names = self._get_bzr_names_from_ref_names(ref_names)
1027
0.64.37 by Ian Clatworthy
create branches as required
1028
        # Policy for locating branches
1029
        def dir_under_current(name, ref_name):
1030
            # Using the Bazaar name, get a directory under the current one
1031
            return name
1032
        def dir_sister_branch(name, ref_name):
1033
            # Using the Bazaar name, get a sister directory to the branch
1034
            return osutils.pathjoin(self.branch.base, "..", name)
1035
        if self.branch is not None:
1036
            dir_policy = dir_sister_branch
1037
        else:
1038
            dir_policy = dir_under_current
1039
0.64.34 by Ian Clatworthy
report lost branches
1040
        # Create/track missing branches
1041
        shared_repo = self.repo.is_shared()
1042
        for name in sorted(bzr_names.keys()):
1043
            ref_name = bzr_names[name]
1044
            tip = self.heads_by_ref[ref_name][0]
1045
            if shared_repo:
0.64.37 by Ian Clatworthy
create branches as required
1046
                location = dir_policy(name, ref_name)
1047
                try:
1048
                    br = self.make_branch(location)
1049
                    branch_tips.append((br,tip))
1050
                    continue
1051
                except errors.BzrError, ex:
1052
                    error("ERROR: failed to create branch %s: %s",
1053
                        location, ex)
1054
            lost_head = self.cache_mgr.revision_ids[tip]
1055
            lost_info = (name, lost_head)
1056
            lost_heads.append(lost_info)
1057
        return branch_tips, lost_heads
1058
0.64.40 by Ian Clatworthy
always use heads/master as the trunk if it is present
1059
    def select_trunk(self, ref_names):
1060
        """Given a set of ref names, choose one as the trunk."""
1061
        for candidate in ['refs/heads/master']:
1062
            if candidate in ref_names:
1063
                return candidate
1064
        # Use the last reference in the import stream
1065
        return self.last_ref
1066
0.64.37 by Ian Clatworthy
create branches as required
1067
    def make_branch(self, location):
0.64.54 by Ian Clatworthy
handle existing branches and only count the branches really updated
1068
        """Make a branch in the repository if not already there."""
1069
        try:
1070
            return bzrdir.BzrDir.open(location).open_branch()
1071
        except errors.NotBranchError, ex:
1072
            return bzrdir.BzrDir.create_branch_convenience(location)
0.64.34 by Ian Clatworthy
report lost branches
1073
1074
    def _get_bzr_names_from_ref_names(self, ref_names):
0.64.37 by Ian Clatworthy
create branches as required
1075
        """Generate Bazaar branch names from import ref names.
1076
        
1077
        :return: a dictionary with Bazaar names as keys and
1078
          the original reference names as values.
1079
        """
0.64.34 by Ian Clatworthy
report lost branches
1080
        bazaar_names = {}
1081
        for ref_name in sorted(ref_names):
1082
            parts = ref_name.split('/')
1083
            if parts[0] == 'refs':
1084
                parts.pop(0)
1085
            full_name = "--".join(parts)
1086
            bazaar_name = parts[-1]
1087
            if bazaar_name in bazaar_names:
1088
                bazaar_name = full_name
1089
            bazaar_names[bazaar_name] = ref_name
1090
        return bazaar_names
0.64.31 by Ian Clatworthy
fix branch updating for the single branch case
1091
1092
    def _update_branch(self, br, last_mark):
0.64.54 by Ian Clatworthy
handle existing branches and only count the branches really updated
1093
        """Update a branch with last revision and tag information.
1094
        
1095
        :return: whether the branch was changed or not
1096
        """
0.64.31 by Ian Clatworthy
fix branch updating for the single branch case
1097
        last_rev_id = self.cache_mgr.revision_ids[last_mark]
0.64.64 by Ian Clatworthy
save tags known about in each branch
1098
        revs = list(self.repo.iter_reverse_revision_history(last_rev_id))
1099
        revno = len(revs)
0.64.54 by Ian Clatworthy
handle existing branches and only count the branches really updated
1100
        existing_revno, existing_last_rev_id = br.last_revision_info()
1101
        changed = False
1102
        if revno != existing_revno or last_rev_id != existing_last_rev_id:
1103
            br.set_last_revision_info(revno, last_rev_id)
1104
            changed = True
0.64.64 by Ian Clatworthy
save tags known about in each branch
1105
        # apply tags known in this branch
1106
        my_tags = {}
1107
        if self.tags:
1108
            for tag,rev in self.tags.items():
1109
                if rev in revs:
1110
                    my_tags[tag] = rev
1111
            if my_tags:
1112
                br.tags._set_tag_dict(my_tags)
1113
                changed = True
1114
        if changed:
1115
            tagno = len(my_tags)
1116
            note("\t branch %s now has %d %s and %d %s", br.nick,
1117
                revno, helpers.single_plural(revno, "revision", "revisions"),
1118
                tagno, helpers.single_plural(tagno, "tag", "tags"))
0.64.54 by Ian Clatworthy
handle existing branches and only count the branches really updated
1119
        return changed