/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
0.81.1 by Ian Clatworthy
move GenericCommitHandler into its own module in prep for a delta-based one
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
0.64.334 by Jelmer Vernooij
Remove old FSF address. Thanks Dan Callaghan.
14
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
0.81.1 by Ian Clatworthy
move GenericCommitHandler into its own module in prep for a delta-based one
15
16
"""CommitHandlers that build and save revisions & their inventories."""
17
6628.1.2 by Jelmer Vernooij
Fix imports, move exporter.py, drop explorer metadata.
18
from __future__ import absolute_import
0.81.1 by Ian Clatworthy
move GenericCommitHandler into its own module in prep for a delta-based one
19
6628.1.2 by Jelmer Vernooij
Fix imports, move exporter.py, drop explorer metadata.
20
from ... import (
0.123.9 by Jelmer Vernooij
Provide stubs for logging functions no longer provided by python-fastimport.
21
    debug,
0.81.1 by Ian Clatworthy
move GenericCommitHandler into its own module in prep for a delta-based one
22
    errors,
23
    generate_ids,
24
    osutils,
25
    revision,
26
    )
6670.4.3 by Jelmer Vernooij
Fix more imports.
27
from ...bzr import (
28
    inventory,
6670.4.10 by Jelmer Vernooij
Move serializer to bzr.
29
    serializer,
6670.4.3 by Jelmer Vernooij
Fix more imports.
30
    )
6628.1.2 by Jelmer Vernooij
Fix imports, move exporter.py, drop explorer metadata.
31
from ...trace import (
0.123.9 by Jelmer Vernooij
Provide stubs for logging functions no longer provided by python-fastimport.
32
    mutter,
33
    note,
34
    warning,
35
    )
0.123.2 by Jelmer Vernooij
Split out fastimport, import it from the system.
36
from fastimport import (
0.123.1 by Jelmer Vernooij
Move pure-fastimport code into its own directory, in preparation of splitting it into a separate package.
37
    helpers,
38
    processor,
39
    )
0.81.1 by Ian Clatworthy
move GenericCommitHandler into its own module in prep for a delta-based one
40
6628.1.2 by Jelmer Vernooij
Fix imports, move exporter.py, drop explorer metadata.
41
from .helpers import (
0.123.8 by Jelmer Vernooij
Use modes for FileModifyCommand.
42
    mode_to_kind,
43
    )
44
0.81.1 by Ian Clatworthy
move GenericCommitHandler into its own module in prep for a delta-based one
45
0.64.192 by Ian Clatworthy
delegate commit message escaping to the serializer if it's a modern one
46
_serializer_handles_escaping = hasattr(serializer.Serializer,
47
    'squashes_xml_invalid_characters')
48
0.64.318 by Jelmer Vernooij
Avoid Inventory.copy, which has disappeared in newer versions of Bazaar.
49
0.84.3 by Ian Clatworthy
fix inventory copying when using deltas
50
def copy_inventory(inv):
0.64.318 by Jelmer Vernooij
Avoid Inventory.copy, which has disappeared in newer versions of Bazaar.
51
    entries = inv.iter_entries_by_dir()
0.64.319 by Jelmer Vernooij
fix typo.
52
    inv = inventory.Inventory(None, inv.revision_id)
0.64.318 by Jelmer Vernooij
Avoid Inventory.copy, which has disappeared in newer versions of Bazaar.
53
    for path, inv_entry in entries:
54
        inv.add(inv_entry.copy())
55
    return inv
0.84.3 by Ian Clatworthy
fix inventory copying when using deltas
56
57
0.81.2 by Ian Clatworthy
refactor InventoryCommitHandler general stuff into parent class
58
class GenericCommitHandler(processor.CommitHandler):
59
    """Base class for Bazaar CommitHandlers."""
0.81.1 by Ian Clatworthy
move GenericCommitHandler into its own module in prep for a delta-based one
60
0.64.195 by Ian Clatworthy
prune directories that become empty after a delete or rename
61
    def __init__(self, command, cache_mgr, rev_store, verbose=False,
62
        prune_empty_dirs=True):
0.81.2 by Ian Clatworthy
refactor InventoryCommitHandler general stuff into parent class
63
        super(GenericCommitHandler, self).__init__(command)
0.81.1 by Ian Clatworthy
move GenericCommitHandler into its own module in prep for a delta-based one
64
        self.cache_mgr = cache_mgr
0.81.4 by Ian Clatworthy
generalise RevisionLoader to RevisionStore as a repo abstraction
65
        self.rev_store = rev_store
0.81.1 by Ian Clatworthy
move GenericCommitHandler into its own module in prep for a delta-based one
66
        self.verbose = verbose
0.64.159 by Ian Clatworthy
make the file-id cache optional and branch-ref aware
67
        self.branch_ref = command.ref
0.64.195 by Ian Clatworthy
prune directories that become empty after a delete or rename
68
        self.prune_empty_dirs = prune_empty_dirs
0.99.5 by Ian Clatworthy
handle adding the same file twice in the one commit
69
        # This tracks path->file-id for things we're creating this commit.
70
        # If the same path is created multiple times, we need to warn the
71
        # user and add it just once.
0.99.17 by Ian Clatworthy
Handle rename of a file/symlink modified already in this commit
72
        # If a path is added then renamed or copied, we need to handle that.
0.99.5 by Ian Clatworthy
handle adding the same file twice in the one commit
73
        self._new_file_ids = {}
0.99.17 by Ian Clatworthy
Handle rename of a file/symlink modified already in this commit
74
        # This tracks path->file-id for things we're modifying this commit.
75
        # If a path is modified then renamed or copied, we need the make
76
        # sure we grab the new content.
77
        self._modified_file_ids = {}
0.99.13 by Ian Clatworthy
Handle delete then add of a file/symlink in the one commit
78
        # This tracks the paths for things we're deleting this commit.
79
        # If the same path is added or the destination of a rename say,
80
        # then a fresh file-id is required.
81
        self._paths_deleted_this_commit = set()
0.81.1 by Ian Clatworthy
move GenericCommitHandler into its own module in prep for a delta-based one
82
0.123.9 by Jelmer Vernooij
Provide stubs for logging functions no longer provided by python-fastimport.
83
    def mutter(self, msg, *args):
84
        """Output a mutter but add context."""
85
        msg = "%s (%s)" % (msg, self.command.id)
86
        mutter(msg, *args)
87
88
    def debug(self, msg, *args):
89
        """Output a mutter if the appropriate -D option was given."""
90
        if "fast-import" in debug.debug_flags:
91
            msg = "%s (%s)" % (msg, self.command.id)
92
            mutter(msg, *args)
93
94
    def note(self, msg, *args):
95
        """Output a note but add context."""
96
        msg = "%s (%s)" % (msg, self.command.id)
97
        note(msg, *args)
98
99
    def warning(self, msg, *args):
100
        """Output a warning but add context."""
101
        msg = "%s (%s)" % (msg, self.command.id)
102
        warning(msg, *args)
103
0.81.1 by Ian Clatworthy
move GenericCommitHandler into its own module in prep for a delta-based one
104
    def pre_process_files(self):
105
        """Prepare for committing."""
106
        self.revision_id = self.gen_revision_id()
107
        # cache of texts for this commit, indexed by file-id
0.115.4 by John Arbash Meinel
(broken) Start working towards using CommitBuilder rather than using a custom implementation.
108
        self.data_for_commit = {}
0.64.171 by Ian Clatworthy
use inv deltas by default for all formats now: --classic to get old algorithm for packs
109
        #if self.rev_store.expects_rich_root():
0.115.4 by John Arbash Meinel
(broken) Start working towards using CommitBuilder rather than using a custom implementation.
110
        self.data_for_commit[inventory.ROOT_ID] = []
0.81.1 by Ian Clatworthy
move GenericCommitHandler into its own module in prep for a delta-based one
111
112
        # Track the heads and get the real parent list
0.123.6 by Jelmer Vernooij
Split out reftracker.
113
        parents = self.cache_mgr.reftracker.track_heads(self.command)
0.81.1 by Ian Clatworthy
move GenericCommitHandler into its own module in prep for a delta-based one
114
115
        # Convert the parent commit-ids to bzr revision-ids
116
        if parents:
0.129.2 by Jelmer Vernooij
Use lookup functions for committish.
117
            self.parents = [self.cache_mgr.lookup_committish(p)
0.81.1 by Ian Clatworthy
move GenericCommitHandler into its own module in prep for a delta-based one
118
                for p in parents]
119
        else:
120
            self.parents = []
121
        self.debug("%s id: %s, parents: %s", self.command.id,
122
            self.revision_id, str(self.parents))
123
0.85.2 by Ian Clatworthy
improve per-file graph generation
124
        # Tell the RevisionStore we're starting a new commit
125
        self.revision = self.build_revision()
0.99.1 by Ian Clatworthy
lookup file-ids in inventories instead of a cache
126
        self.parent_invs = [self.get_inventory(p) for p in self.parents]
0.85.2 by Ian Clatworthy
improve per-file graph generation
127
        self.rev_store.start_new_revision(self.revision, self.parents,
0.99.1 by Ian Clatworthy
lookup file-ids in inventories instead of a cache
128
            self.parent_invs)
0.85.2 by Ian Clatworthy
improve per-file graph generation
129
130
        # cache of per-file parents for this commit, indexed by file-id
131
        self.per_file_parents_for_commit = {}
132
        if self.rev_store.expects_rich_root():
0.64.160 by Ian Clatworthy
make per-file parents tuples and fix text loading in chk formats
133
            self.per_file_parents_for_commit[inventory.ROOT_ID] = ()
0.85.2 by Ian Clatworthy
improve per-file graph generation
134
0.81.5 by Ian Clatworthy
basic DeltaCommitHandler generating deltas
135
        # Keep the basis inventory. This needs to be treated as read-only.
136
        if len(self.parents) == 0:
0.84.4 by Ian Clatworthy
improved-but-not-yet-working CHKInventory support
137
            self.basis_inventory = self._init_inventory()
0.81.5 by Ian Clatworthy
basic DeltaCommitHandler generating deltas
138
        else:
139
            self.basis_inventory = self.get_inventory(self.parents[0])
0.84.5 by Ian Clatworthy
_ensure_directory to return parent_id, not parent_ie
140
        if hasattr(self.basis_inventory, "root_id"):
141
            self.inventory_root_id = self.basis_inventory.root_id
142
        else:
143
            self.inventory_root_id = self.basis_inventory.root.file_id
0.81.5 by Ian Clatworthy
basic DeltaCommitHandler generating deltas
144
145
        # directory-path -> inventory-entry for current inventory
0.84.12 by Ian Clatworthy
lookup directories on demand in CHKInventories, not all upfront
146
        self.directory_entries = {}
0.81.5 by Ian Clatworthy
basic DeltaCommitHandler generating deltas
147
0.84.4 by Ian Clatworthy
improved-but-not-yet-working CHKInventory support
148
    def _init_inventory(self):
149
        return self.rev_store.init_inventory(self.revision_id)
0.81.5 by Ian Clatworthy
basic DeltaCommitHandler generating deltas
150
151
    def get_inventory(self, revision_id):
152
        """Get the inventory for a revision id."""
153
        try:
154
            inv = self.cache_mgr.inventories[revision_id]
155
        except KeyError:
156
            if self.verbose:
0.64.148 by Ian Clatworthy
handle delete of unknown file in chk formats & reduce noise
157
                self.mutter("get_inventory cache miss for %s", revision_id)
0.81.5 by Ian Clatworthy
basic DeltaCommitHandler generating deltas
158
            # Not cached so reconstruct from the RevisionStore
159
            inv = self.rev_store.get_inventory(revision_id)
160
            self.cache_mgr.inventories[revision_id] = inv
161
        return inv
162
0.115.4 by John Arbash Meinel
(broken) Start working towards using CommitBuilder rather than using a custom implementation.
163
    def _get_data(self, file_id):
164
        """Get the data bytes for a file-id."""
165
        return self.data_for_commit[file_id]
166
0.81.10 by Ian Clatworthy
get DeltaCommitHandler passing all tests
167
    def _get_lines(self, file_id):
168
        """Get the lines for a file-id."""
0.115.4 by John Arbash Meinel
(broken) Start working towards using CommitBuilder rather than using a custom implementation.
169
        return osutils.split_lines(self._get_data(file_id))
0.81.10 by Ian Clatworthy
get DeltaCommitHandler passing all tests
170
0.85.2 by Ian Clatworthy
improve per-file graph generation
171
    def _get_per_file_parents(self, file_id):
172
        """Get the lines for a file-id."""
173
        return self.per_file_parents_for_commit[file_id]
174
0.81.10 by Ian Clatworthy
get DeltaCommitHandler passing all tests
175
    def _get_inventories(self, revision_ids):
176
        """Get the inventories for revision-ids.
177
        
178
        This is a callback used by the RepositoryStore to
179
        speed up inventory reconstruction.
180
        """
181
        present = []
182
        inventories = []
183
        # If an inventory is in the cache, we assume it was
184
        # successfully loaded into the revision store
185
        for revision_id in revision_ids:
186
            try:
187
                inv = self.cache_mgr.inventories[revision_id]
188
                present.append(revision_id)
189
            except KeyError:
190
                if self.verbose:
191
                    self.note("get_inventories cache miss for %s", revision_id)
192
                # Not cached so reconstruct from the revision store
193
                try:
194
                    inv = self.get_inventory(revision_id)
195
                    present.append(revision_id)
196
                except:
0.84.4 by Ian Clatworthy
improved-but-not-yet-working CHKInventory support
197
                    inv = self._init_inventory()
0.81.10 by Ian Clatworthy
get DeltaCommitHandler passing all tests
198
                self.cache_mgr.inventories[revision_id] = inv
199
            inventories.append(inv)
200
        return present, inventories
201
0.81.2 by Ian Clatworthy
refactor InventoryCommitHandler general stuff into parent class
202
    def bzr_file_id_and_new(self, path):
203
        """Get a Bazaar file identifier and new flag for a path.
204
        
205
        :return: file_id, is_new where
206
          is_new = True if the file_id is newly created
207
        """
0.99.13 by Ian Clatworthy
Handle delete then add of a file/symlink in the one commit
208
        if path not in self._paths_deleted_this_commit:
0.99.19 by Ian Clatworthy
Handle rename then modification of the new path
209
            # Try file-ids renamed in this commit
210
            id = self._modified_file_ids.get(path)
211
            if id is not None:
212
                return id, False
213
0.99.13 by Ian Clatworthy
Handle delete then add of a file/symlink in the one commit
214
            # Try the basis inventory
215
            id = self.basis_inventory.path2id(path)
216
            if id is not None:
217
                return id, False
218
            
219
            # Try the other inventories
220
            if len(self.parents) > 1:
221
                for inv in self.parent_invs[1:]:
222
                    id = self.basis_inventory.path2id(path)
223
                    if id is not None:
224
                        return id, False
0.99.1 by Ian Clatworthy
lookup file-ids in inventories instead of a cache
225
226
        # Doesn't exist yet so create it
0.64.247 by Ian Clatworthy
base file-ids on the basename, not path, as jam suggested. This improves the samba import from 565M to 353M.
227
        dirname, basename = osutils.split(path)
228
        id = generate_ids.gen_file_id(basename)
0.99.1 by Ian Clatworthy
lookup file-ids in inventories instead of a cache
229
        self.debug("Generated new file id %s for '%s' in revision-id '%s'",
230
            id, path, self.revision_id)
0.99.5 by Ian Clatworthy
handle adding the same file twice in the one commit
231
        self._new_file_ids[path] = id
0.99.1 by Ian Clatworthy
lookup file-ids in inventories instead of a cache
232
        return id, True
0.81.2 by Ian Clatworthy
refactor InventoryCommitHandler general stuff into parent class
233
234
    def bzr_file_id(self, path):
235
        """Get a Bazaar file identifier for a path."""
236
        return self.bzr_file_id_and_new(path)[0]
237
0.64.299 by Jelmer Vernooij
utf8 decode/encode paths and committer/author email/name, as python-fastimport no longer does so.
238
    def _utf8_decode(self, field, value):
239
        try:
0.64.332 by Jelmer Vernooij
Cope with non-utf8 characters in paths when importing.
240
            return value.decode('utf-8')
0.64.299 by Jelmer Vernooij
utf8 decode/encode paths and committer/author email/name, as python-fastimport no longer does so.
241
        except UnicodeDecodeError:
242
            # The spec says fields are *typically* utf8 encoded
243
            # but that isn't enforced by git-fast-export (at least)
244
            self.warning("%s not in utf8 - replacing unknown "
245
                "characters" % (field,))
0.64.332 by Jelmer Vernooij
Cope with non-utf8 characters in paths when importing.
246
            return value.decode('utf-8', 'replace')
247
248
    def _decode_path(self, path):
249
        try:
250
            return path.decode('utf-8')
251
        except UnicodeDecodeError:
252
            # The spec says fields are *typically* utf8 encoded
253
            # but that isn't enforced by git-fast-export (at least)
254
            self.warning("path %r not in utf8 - replacing unknown "
255
                "characters" % (path,))
256
            return path.decode('utf-8', 'replace')
0.64.299 by Jelmer Vernooij
utf8 decode/encode paths and committer/author email/name, as python-fastimport no longer does so.
257
258
    def _format_name_email(self, section, name, email):
0.64.177 by Ian Clatworthy
fix round-tripping of committer & author when name is an email
259
        """Format name & email as a string."""
0.64.299 by Jelmer Vernooij
utf8 decode/encode paths and committer/author email/name, as python-fastimport no longer does so.
260
        name = self._utf8_decode("%s name" % section, name)
261
        email = self._utf8_decode("%s email" % section, email)
262
0.64.177 by Ian Clatworthy
fix round-tripping of committer & author when name is an email
263
        if email:
264
            return "%s <%s>" % (name, email)
265
        else:
266
            return name
267
0.81.2 by Ian Clatworthy
refactor InventoryCommitHandler general stuff into parent class
268
    def gen_revision_id(self):
269
        """Generate a revision id.
270
271
        Subclasses may override this to produce deterministic ids say.
272
        """
273
        committer = self.command.committer
274
        # Perhaps 'who' being the person running the import is ok? If so,
275
        # it might be a bit quicker and give slightly better compression?
0.64.299 by Jelmer Vernooij
utf8 decode/encode paths and committer/author email/name, as python-fastimport no longer does so.
276
        who = self._format_name_email("committer", committer[0], committer[1])
0.81.2 by Ian Clatworthy
refactor InventoryCommitHandler general stuff into parent class
277
        timestamp = committer[2]
278
        return generate_ids.gen_revision_id(who, timestamp)
279
0.81.6 by Ian Clatworthy
basic DeltaCommitHandler mostly going bar rename
280
    def build_revision(self):
0.64.235 by Ian Clatworthy
Sanitize None revision properties to empty string
281
        rev_props = self._legal_revision_properties(self.command.properties)
0.112.5 by Max Bowsher
Default branch-nick to mapped git ref name.
282
        if 'branch-nick' not in rev_props:
283
            rev_props['branch-nick'] = self.cache_mgr.branch_mapper.git_to_bzr(
284
                    self.branch_ref)
0.102.10 by Ian Clatworthy
Store multiple authors and revision properties when defined
285
        self._save_author_info(rev_props)
0.81.6 by Ian Clatworthy
basic DeltaCommitHandler mostly going bar rename
286
        committer = self.command.committer
0.64.299 by Jelmer Vernooij
utf8 decode/encode paths and committer/author email/name, as python-fastimport no longer does so.
287
        who = self._format_name_email("committer", committer[0], committer[1])
0.64.298 by Jelmer Vernooij
Handle unicode decoding of commit messages in bzr-fastimport, python-fastimport no longer takes care of this.
288
        try:
289
            message = self.command.message.decode("utf-8")
0.64.303 by Jelmer Vernooij
Cope with non-utf8 characters in commit messages.
290
0.64.298 by Jelmer Vernooij
Handle unicode decoding of commit messages in bzr-fastimport, python-fastimport no longer takes care of this.
291
        except UnicodeDecodeError:
292
            self.warning(
293
                "commit message not in utf8 - replacing unknown characters")
0.64.303 by Jelmer Vernooij
Cope with non-utf8 characters in commit messages.
294
            message = self.command.message.decode('utf-8', 'replace')
0.64.192 by Ian Clatworthy
delegate commit message escaping to the serializer if it's a modern one
295
        if not _serializer_handles_escaping:
296
            # We need to assume the bad ol' days
297
            message = helpers.escape_commit_message(message)
0.81.6 by Ian Clatworthy
basic DeltaCommitHandler mostly going bar rename
298
        return revision.Revision(
299
           timestamp=committer[2],
300
           timezone=committer[3],
301
           committer=who,
0.64.192 by Ian Clatworthy
delegate commit message escaping to the serializer if it's a modern one
302
           message=message,
0.81.6 by Ian Clatworthy
basic DeltaCommitHandler mostly going bar rename
303
           revision_id=self.revision_id,
304
           properties=rev_props,
305
           parent_ids=self.parents)
0.81.2 by Ian Clatworthy
refactor InventoryCommitHandler general stuff into parent class
306
0.64.235 by Ian Clatworthy
Sanitize None revision properties to empty string
307
    def _legal_revision_properties(self, props):
308
        """Clean-up any revision properties we can't handle."""
309
        # For now, we just check for None because that's not allowed in 2.0rc1
310
        result = {}
311
        if props is not None:
312
            for name, value in props.items():
313
                if value is None:
314
                    self.warning(
315
                        "converting None to empty string for property %s"
316
                        % (name,))
317
                    result[name] = ''
318
                else:
319
                    result[name] = value
320
        return result
321
0.102.10 by Ian Clatworthy
Store multiple authors and revision properties when defined
322
    def _save_author_info(self, rev_props):
323
        author = self.command.author
324
        if author is None:
325
            return
326
        if self.command.more_authors:
327
            authors = [author] + self.command.more_authors
0.64.299 by Jelmer Vernooij
utf8 decode/encode paths and committer/author email/name, as python-fastimport no longer does so.
328
            author_ids = [self._format_name_email("author", a[0], a[1]) for a in authors]
0.102.10 by Ian Clatworthy
Store multiple authors and revision properties when defined
329
        elif author != self.command.committer:
0.64.299 by Jelmer Vernooij
utf8 decode/encode paths and committer/author email/name, as python-fastimport no longer does so.
330
            author_ids = [self._format_name_email("author", author[0], author[1])]
0.102.10 by Ian Clatworthy
Store multiple authors and revision properties when defined
331
        else:
332
            return
333
        # If we reach here, there are authors worth storing
334
        rev_props['authors'] = "\n".join(author_ids)
335
0.81.7 by Ian Clatworthy
merge import tests and tweaks to make them pass
336
    def _modify_item(self, path, kind, is_executable, data, inv):
0.81.5 by Ian Clatworthy
basic DeltaCommitHandler generating deltas
337
        """Add to or change an item in the inventory."""
0.99.5 by Ian Clatworthy
handle adding the same file twice in the one commit
338
        # If we've already added this, warn the user that we're ignoring it.
339
        # In the future, it might be nice to double check that the new data
340
        # is the same as the old but, frankly, exporters should be fixed
341
        # not to produce bad data streams in the first place ...
342
        existing = self._new_file_ids.get(path)
343
        if existing:
0.102.18 by Ian Clatworthy
Tweak some diagnostic messages
344
            # We don't warn about directories because it's fine for them
345
            # to be created already by a previous rename
346
            if kind != 'directory':
347
                self.warning("%s already added in this commit - ignoring" %
348
                    (path,))
0.99.5 by Ian Clatworthy
handle adding the same file twice in the one commit
349
            return
350
0.81.5 by Ian Clatworthy
basic DeltaCommitHandler generating deltas
351
        # Create the new InventoryEntry
0.84.5 by Ian Clatworthy
_ensure_directory to return parent_id, not parent_ie
352
        basename, parent_id = self._ensure_directory(path, inv)
0.81.5 by Ian Clatworthy
basic DeltaCommitHandler generating deltas
353
        file_id = self.bzr_file_id(path)
0.84.5 by Ian Clatworthy
_ensure_directory to return parent_id, not parent_ie
354
        ie = inventory.make_entry(kind, basename, parent_id, file_id)
0.81.5 by Ian Clatworthy
basic DeltaCommitHandler generating deltas
355
        ie.revision = self.revision_id
0.81.7 by Ian Clatworthy
merge import tests and tweaks to make them pass
356
        if kind == 'file':
0.81.5 by Ian Clatworthy
basic DeltaCommitHandler generating deltas
357
            ie.executable = is_executable
0.115.4 by John Arbash Meinel
(broken) Start working towards using CommitBuilder rather than using a custom implementation.
358
            # lines = osutils.split_lines(data)
359
            ie.text_sha1 = osutils.sha_string(data)
360
            ie.text_size = len(data)
361
            self.data_for_commit[file_id] = data
0.102.14 by Ian Clatworthy
export and import empty directories
362
        elif kind == 'directory':
363
            self.directory_entries[path] = ie
364
            # There are no lines stored for a directory so
365
            # make sure the cache used by get_lines knows that
0.115.4 by John Arbash Meinel
(broken) Start working towards using CommitBuilder rather than using a custom implementation.
366
            self.data_for_commit[file_id] = ''
0.81.7 by Ian Clatworthy
merge import tests and tweaks to make them pass
367
        elif kind == 'symlink':
0.64.332 by Jelmer Vernooij
Cope with non-utf8 characters in paths when importing.
368
            ie.symlink_target = self._decode_path(data)
0.81.5 by Ian Clatworthy
basic DeltaCommitHandler generating deltas
369
            # There are no lines stored for a symlink so
370
            # make sure the cache used by get_lines knows that
0.115.4 by John Arbash Meinel
(broken) Start working towards using CommitBuilder rather than using a custom implementation.
371
            self.data_for_commit[file_id] = ''
0.81.5 by Ian Clatworthy
basic DeltaCommitHandler generating deltas
372
        else:
0.64.229 by Ian Clatworthy
Handle git submodules in the stream by warning about + ignoring them
373
            self.warning("Cannot import items of kind '%s' yet - ignoring '%s'"
374
                % (kind, path))
375
            return
0.81.5 by Ian Clatworthy
basic DeltaCommitHandler generating deltas
376
        # Record it
0.64.323 by Jelmer Vernooij
Avoid deprecated Inventory.__contains__.
377
        if inv.has_id(file_id):
0.81.10 by Ian Clatworthy
get DeltaCommitHandler passing all tests
378
            old_ie = inv[file_id]
379
            if old_ie.kind == 'directory':
380
                self.record_delete(path, old_ie)
0.84.5 by Ian Clatworthy
_ensure_directory to return parent_id, not parent_ie
381
            self.record_changed(path, ie, parent_id)
0.81.5 by Ian Clatworthy
basic DeltaCommitHandler generating deltas
382
        else:
0.64.165 by Ian Clatworthy
handle adding a file to a dir deleted in the same commit
383
            try:
384
                self.record_new(path, ie)
385
            except:
0.64.167 by Ian Clatworthy
incremental packing for chk formats
386
                print "failed to add path '%s' with entry '%s' in command %s" \
387
                    % (path, ie, self.command.id)
388
                print "parent's children are:\n%r\n" % (ie.parent_id.children,)
0.64.165 by Ian Clatworthy
handle adding a file to a dir deleted in the same commit
389
                raise
0.81.5 by Ian Clatworthy
basic DeltaCommitHandler generating deltas
390
0.81.10 by Ian Clatworthy
get DeltaCommitHandler passing all tests
391
    def _ensure_directory(self, path, inv):
0.81.5 by Ian Clatworthy
basic DeltaCommitHandler generating deltas
392
        """Ensure that the containing directory exists for 'path'"""
393
        dirname, basename = osutils.split(path)
394
        if dirname == '':
395
            # the root node doesn't get updated
0.84.5 by Ian Clatworthy
_ensure_directory to return parent_id, not parent_ie
396
            return basename, self.inventory_root_id
0.81.5 by Ian Clatworthy
basic DeltaCommitHandler generating deltas
397
        try:
0.84.12 by Ian Clatworthy
lookup directories on demand in CHKInventories, not all upfront
398
            ie = self._get_directory_entry(inv, dirname)
0.81.5 by Ian Clatworthy
basic DeltaCommitHandler generating deltas
399
        except KeyError:
400
            # We will create this entry, since it doesn't exist
401
            pass
402
        else:
0.84.5 by Ian Clatworthy
_ensure_directory to return parent_id, not parent_ie
403
            return basename, ie.file_id
0.81.5 by Ian Clatworthy
basic DeltaCommitHandler generating deltas
404
405
        # No directory existed, we will just create one, first, make sure
406
        # the parent exists
0.84.5 by Ian Clatworthy
_ensure_directory to return parent_id, not parent_ie
407
        dir_basename, parent_id = self._ensure_directory(dirname, inv)
0.81.5 by Ian Clatworthy
basic DeltaCommitHandler generating deltas
408
        dir_file_id = self.bzr_file_id(dirname)
409
        ie = inventory.entry_factory['directory'](dir_file_id,
0.84.5 by Ian Clatworthy
_ensure_directory to return parent_id, not parent_ie
410
            dir_basename, parent_id)
0.81.5 by Ian Clatworthy
basic DeltaCommitHandler generating deltas
411
        ie.revision = self.revision_id
412
        self.directory_entries[dirname] = ie
413
        # There are no lines stored for a directory so
414
        # make sure the cache used by get_lines knows that
0.115.4 by John Arbash Meinel
(broken) Start working towards using CommitBuilder rather than using a custom implementation.
415
        self.data_for_commit[dir_file_id] = ''
0.81.10 by Ian Clatworthy
get DeltaCommitHandler passing all tests
416
417
        # It's possible that a file or symlink with that file-id
418
        # already exists. If it does, we need to delete it.
0.64.323 by Jelmer Vernooij
Avoid deprecated Inventory.__contains__.
419
        if inv.has_id(dir_file_id):
0.81.10 by Ian Clatworthy
get DeltaCommitHandler passing all tests
420
            self.record_delete(dirname, ie)
0.81.5 by Ian Clatworthy
basic DeltaCommitHandler generating deltas
421
        self.record_new(dirname, ie)
0.84.5 by Ian Clatworthy
_ensure_directory to return parent_id, not parent_ie
422
        return basename, ie.file_id
0.81.5 by Ian Clatworthy
basic DeltaCommitHandler generating deltas
423
0.84.12 by Ian Clatworthy
lookup directories on demand in CHKInventories, not all upfront
424
    def _get_directory_entry(self, inv, dirname):
425
        """Get the inventory entry for a directory.
426
        
427
        Raises KeyError if dirname is not a directory in inv.
428
        """
429
        result = self.directory_entries.get(dirname)
430
        if result is None:
0.99.21 by Ian Clatworthy
Handle deleting a directory then adding a file within it in the same commit
431
            if dirname in self._paths_deleted_this_commit:
432
                raise KeyError
0.64.146 by Ian Clatworthy
fix first file is in a subdirectory bug for chk formats
433
            try:
434
                file_id = inv.path2id(dirname)
435
            except errors.NoSuchId:
436
                # In a CHKInventory, this is raised if there's no root yet
437
                raise KeyError
0.84.12 by Ian Clatworthy
lookup directories on demand in CHKInventories, not all upfront
438
            if file_id is None:
439
                raise KeyError
440
            result = inv[file_id]
441
            # dirname must be a directory for us to return it
442
            if result.kind == 'directory':
443
                self.directory_entries[dirname] = result
444
            else:
445
                raise KeyError
446
        return result
447
0.81.6 by Ian Clatworthy
basic DeltaCommitHandler mostly going bar rename
448
    def _delete_item(self, path, inv):
0.99.7 by Ian Clatworthy
handle a delete of a newly added file
449
        newly_added = self._new_file_ids.get(path)
450
        if newly_added:
451
            # We've only just added this path earlier in this commit.
452
            file_id = newly_added
453
            # note: delta entries look like (old, new, file-id, ie)
454
            ie = self._delta_entries_by_fileid[file_id][3]
0.64.145 by Ian Clatworthy
handle delete of missing files for chk formats
455
        else:
0.99.7 by Ian Clatworthy
handle a delete of a newly added file
456
            file_id = inv.path2id(path)
457
            if file_id is None:
458
                self.mutter("ignoring delete of %s as not in inventory", path)
459
                return
460
            try:
461
                ie = inv[file_id]
462
            except errors.NoSuchId:
463
                self.mutter("ignoring delete of %s as not in inventory", path)
464
                return
465
        self.record_delete(path, ie)
0.81.6 by Ian Clatworthy
basic DeltaCommitHandler mostly going bar rename
466
467
    def _copy_item(self, src_path, dest_path, inv):
0.99.18 by Ian Clatworthy
Handle copy of a file/symlink already modified in this commit
468
        newly_changed = self._new_file_ids.get(src_path) or \
469
            self._modified_file_ids.get(src_path)
470
        if newly_changed:
471
            # We've only just added/changed this path earlier in this commit.
472
            file_id = newly_changed
0.99.8 by Ian Clatworthy
handle copy of a newly added file
473
            # note: delta entries look like (old, new, file-id, ie)
474
            ie = self._delta_entries_by_fileid[file_id][3]
475
        else:
476
            file_id = inv.path2id(src_path)
477
            if file_id is None:
478
                self.warning("ignoring copy of %s to %s - source does not exist",
479
                    src_path, dest_path)
480
                return
481
            ie = inv[file_id]
0.81.6 by Ian Clatworthy
basic DeltaCommitHandler mostly going bar rename
482
        kind = ie.kind
483
        if kind == 'file':
0.99.18 by Ian Clatworthy
Handle copy of a file/symlink already modified in this commit
484
            if newly_changed:
0.115.4 by John Arbash Meinel
(broken) Start working towards using CommitBuilder rather than using a custom implementation.
485
                content = self.data_for_commit[file_id]
0.99.8 by Ian Clatworthy
handle copy of a newly added file
486
            else:
487
                content = self.rev_store.get_file_text(self.parents[0], file_id)
0.81.7 by Ian Clatworthy
merge import tests and tweaks to make them pass
488
            self._modify_item(dest_path, kind, ie.executable, content, inv)
0.81.6 by Ian Clatworthy
basic DeltaCommitHandler mostly going bar rename
489
        elif kind == 'symlink':
0.64.332 by Jelmer Vernooij
Cope with non-utf8 characters in paths when importing.
490
            self._modify_item(dest_path, kind, False,
491
                ie.symlink_target.encode("utf-8"), inv)
0.81.6 by Ian Clatworthy
basic DeltaCommitHandler mostly going bar rename
492
        else:
493
            self.warning("ignoring copy of %s %s - feature not yet supported",
0.123.8 by Jelmer Vernooij
Use modes for FileModifyCommand.
494
                kind, dest_path)
0.81.6 by Ian Clatworthy
basic DeltaCommitHandler mostly going bar rename
495
496
    def _rename_item(self, old_path, new_path, inv):
0.99.17 by Ian Clatworthy
Handle rename of a file/symlink modified already in this commit
497
        existing = self._new_file_ids.get(old_path) or \
498
            self._modified_file_ids.get(old_path)
0.99.6 by Ian Clatworthy
Handle rename of a just added file
499
        if existing:
0.99.17 by Ian Clatworthy
Handle rename of a file/symlink modified already in this commit
500
            # We've only just added/modified this path earlier in this commit.
501
            # Change the add/modify of old_path to an add of new_path
502
            self._rename_pending_change(old_path, new_path, existing)
0.99.6 by Ian Clatworthy
Handle rename of a just added file
503
            return
504
0.81.8 by Ian Clatworthy
refactor rename_item
505
        file_id = inv.path2id(old_path)
0.64.167 by Ian Clatworthy
incremental packing for chk formats
506
        if file_id is None:
507
            self.warning(
508
                "ignoring rename of %s to %s - old path does not exist" %
509
                (old_path, new_path))
510
            return
0.81.8 by Ian Clatworthy
refactor rename_item
511
        ie = inv[file_id]
512
        rev_id = ie.revision
0.81.7 by Ian Clatworthy
merge import tests and tweaks to make them pass
513
        new_file_id = inv.path2id(new_path)
514
        if new_file_id is not None:
0.81.9 by Ian Clatworthy
refactor delete_item
515
            self.record_delete(new_path, inv[new_file_id])
0.81.8 by Ian Clatworthy
refactor rename_item
516
        self.record_rename(old_path, new_path, file_id, ie)
0.81.7 by Ian Clatworthy
merge import tests and tweaks to make them pass
517
0.81.8 by Ian Clatworthy
refactor rename_item
518
        # The revision-id for this entry will be/has been updated and
0.81.7 by Ian Clatworthy
merge import tests and tweaks to make them pass
519
        # that means the loader then needs to know what the "new" text is.
520
        # We therefore must go back to the revision store to get it.
0.81.8 by Ian Clatworthy
refactor rename_item
521
        lines = self.rev_store.get_file_lines(rev_id, file_id)
0.115.4 by John Arbash Meinel
(broken) Start working towards using CommitBuilder rather than using a custom implementation.
522
        self.data_for_commit[file_id] = ''.join(lines)
0.81.6 by Ian Clatworthy
basic DeltaCommitHandler mostly going bar rename
523
524
    def _delete_all_items(self, inv):
0.64.320 by Jelmer Vernooij
Fix deleteall handler.
525
        if len(inv) == 0:
526
            return
527
        for path, ie in inv.iter_entries_by_dir():
528
            if path != "":
529
                self.record_delete(path, ie)
0.81.6 by Ian Clatworthy
basic DeltaCommitHandler mostly going bar rename
530
0.64.145 by Ian Clatworthy
handle delete of missing files for chk formats
531
    def _warn_unless_in_merges(self, fileid, path):
532
        if len(self.parents) <= 1:
533
            return
534
        for parent in self.parents[1:]:
535
            if fileid in self.get_inventory(parent):
536
                return
537
        self.warning("ignoring delete of %s as not in parent inventories", path)
538
0.81.2 by Ian Clatworthy
refactor InventoryCommitHandler general stuff into parent class
539
540
class InventoryCommitHandler(GenericCommitHandler):
0.84.7 by Ian Clatworthy
CHKInventory support for non rich-root repos working, for simple imports at least
541
    """A CommitHandler that builds and saves Inventory objects."""
0.81.2 by Ian Clatworthy
refactor InventoryCommitHandler general stuff into parent class
542
543
    def pre_process_files(self):
544
        super(InventoryCommitHandler, self).pre_process_files()
545
0.64.159 by Ian Clatworthy
make the file-id cache optional and branch-ref aware
546
        # Seed the inventory from the previous one. Note that
547
        # the parent class version of pre_process_files() has
548
        # already set the right basis_inventory for this branch
549
        # but we need to copy it in order to mutate it safely
550
        # without corrupting the cached inventory value.
0.81.1 by Ian Clatworthy
move GenericCommitHandler into its own module in prep for a delta-based one
551
        if len(self.parents) == 0:
0.81.5 by Ian Clatworthy
basic DeltaCommitHandler generating deltas
552
            self.inventory = self.basis_inventory
0.81.1 by Ian Clatworthy
move GenericCommitHandler into its own module in prep for a delta-based one
553
        else:
0.84.3 by Ian Clatworthy
fix inventory copying when using deltas
554
            self.inventory = copy_inventory(self.basis_inventory)
0.81.5 by Ian Clatworthy
basic DeltaCommitHandler generating deltas
555
        self.inventory_root = self.inventory.root
556
0.81.7 by Ian Clatworthy
merge import tests and tweaks to make them pass
557
        # directory-path -> inventory-entry for current inventory
558
        self.directory_entries = dict(self.inventory.directories())
559
0.81.5 by Ian Clatworthy
basic DeltaCommitHandler generating deltas
560
        # Initialise the inventory revision info as required
0.81.4 by Ian Clatworthy
generalise RevisionLoader to RevisionStore as a repo abstraction
561
        if self.rev_store.expects_rich_root():
0.81.1 by Ian Clatworthy
move GenericCommitHandler into its own module in prep for a delta-based one
562
            self.inventory.revision_id = self.revision_id
563
        else:
0.81.4 by Ian Clatworthy
generalise RevisionLoader to RevisionStore as a repo abstraction
564
            # In this revision store, root entries have no knit or weave.
565
            # When serializing out to disk and back in, root.revision is
566
            # always the new revision_id.
0.81.1 by Ian Clatworthy
move GenericCommitHandler into its own module in prep for a delta-based one
567
            self.inventory.root.revision = self.revision_id
568
569
    def post_process_files(self):
570
        """Save the revision."""
571
        self.cache_mgr.inventories[self.revision_id] = self.inventory
0.85.2 by Ian Clatworthy
improve per-file graph generation
572
        self.rev_store.load(self.revision, self.inventory, None,
0.115.4 by John Arbash Meinel
(broken) Start working towards using CommitBuilder rather than using a custom implementation.
573
            lambda file_id: self._get_data(file_id),
0.85.2 by Ian Clatworthy
improve per-file graph generation
574
            lambda file_id: self._get_per_file_parents(file_id),
0.81.1 by Ian Clatworthy
move GenericCommitHandler into its own module in prep for a delta-based one
575
            lambda revision_ids: self._get_inventories(revision_ids))
576
0.81.6 by Ian Clatworthy
basic DeltaCommitHandler mostly going bar rename
577
    def record_new(self, path, ie):
0.81.7 by Ian Clatworthy
merge import tests and tweaks to make them pass
578
        try:
0.64.161 by Ian Clatworthy
fix per-graph parent handling for adds and renames
579
            # If this is a merge, the file was most likely added already.
580
            # The per-file parent(s) must therefore be calculated and
581
            # we can't assume there are none.
582
            per_file_parents, ie.revision = \
583
                self.rev_store.get_parents_and_revision_for_entry(ie)
584
            self.per_file_parents_for_commit[ie.file_id] = per_file_parents
0.81.7 by Ian Clatworthy
merge import tests and tweaks to make them pass
585
            self.inventory.add(ie)
586
        except errors.DuplicateFileId:
587
            # Directory already exists as a file or symlink
588
            del self.inventory[ie.file_id]
589
            # Try again
590
            self.inventory.add(ie)
0.81.6 by Ian Clatworthy
basic DeltaCommitHandler mostly going bar rename
591
0.84.5 by Ian Clatworthy
_ensure_directory to return parent_id, not parent_ie
592
    def record_changed(self, path, ie, parent_id):
0.81.6 by Ian Clatworthy
basic DeltaCommitHandler mostly going bar rename
593
        # HACK: no API for this (del+add does more than it needs to)
0.85.2 by Ian Clatworthy
improve per-file graph generation
594
        per_file_parents, ie.revision = \
595
            self.rev_store.get_parents_and_revision_for_entry(ie)
596
        self.per_file_parents_for_commit[ie.file_id] = per_file_parents
0.81.6 by Ian Clatworthy
basic DeltaCommitHandler mostly going bar rename
597
        self.inventory._byid[ie.file_id] = ie
0.84.5 by Ian Clatworthy
_ensure_directory to return parent_id, not parent_ie
598
        parent_ie = self.inventory._byid[parent_id]
0.81.6 by Ian Clatworthy
basic DeltaCommitHandler mostly going bar rename
599
        parent_ie.children[ie.name] = ie
600
0.81.9 by Ian Clatworthy
refactor delete_item
601
    def record_delete(self, path, ie):
602
        self.inventory.remove_recursive_id(ie.file_id)
0.81.8 by Ian Clatworthy
refactor rename_item
603
604
    def record_rename(self, old_path, new_path, file_id, ie):
0.64.161 by Ian Clatworthy
fix per-graph parent handling for adds and renames
605
        # For a rename, the revision-id is always the new one so
606
        # no need to change/set it here
607
        ie.revision = self.revision_id
608
        per_file_parents, _ = \
609
            self.rev_store.get_parents_and_revision_for_entry(ie)
610
        self.per_file_parents_for_commit[file_id] = per_file_parents
0.84.5 by Ian Clatworthy
_ensure_directory to return parent_id, not parent_ie
611
        new_basename, new_parent_id = self._ensure_directory(new_path,
0.81.10 by Ian Clatworthy
get DeltaCommitHandler passing all tests
612
            self.inventory)
0.81.8 by Ian Clatworthy
refactor rename_item
613
        self.inventory.rename(file_id, new_parent_id, new_basename)
614
0.81.6 by Ian Clatworthy
basic DeltaCommitHandler mostly going bar rename
615
    def modify_handler(self, filecmd):
616
        if filecmd.dataref is not None:
617
            data = self.cache_mgr.fetch_blob(filecmd.dataref)
618
        else:
619
            data = filecmd.data
620
        self.debug("modifying %s", filecmd.path)
0.123.8 by Jelmer Vernooij
Use modes for FileModifyCommand.
621
        (kind, is_executable) = mode_to_kind(filecmd.mode)
0.64.332 by Jelmer Vernooij
Cope with non-utf8 characters in paths when importing.
622
        self._modify_item(self._decode_path(filecmd.path), kind,
0.123.8 by Jelmer Vernooij
Use modes for FileModifyCommand.
623
            is_executable, data, self.inventory)
0.81.6 by Ian Clatworthy
basic DeltaCommitHandler mostly going bar rename
624
625
    def delete_handler(self, filecmd):
0.81.7 by Ian Clatworthy
merge import tests and tweaks to make them pass
626
        self.debug("deleting %s", filecmd.path)
0.64.332 by Jelmer Vernooij
Cope with non-utf8 characters in paths when importing.
627
        self._delete_item(self._decode_path(filecmd.path), self.inventory)
0.81.6 by Ian Clatworthy
basic DeltaCommitHandler mostly going bar rename
628
0.81.1 by Ian Clatworthy
move GenericCommitHandler into its own module in prep for a delta-based one
629
    def copy_handler(self, filecmd):
0.64.332 by Jelmer Vernooij
Cope with non-utf8 characters in paths when importing.
630
        src_path = self._decode_path(filecmd.src_path)
631
        dest_path = self._decode_path(filecmd.dest_path)
0.81.1 by Ian Clatworthy
move GenericCommitHandler into its own module in prep for a delta-based one
632
        self.debug("copying %s to %s", src_path, dest_path)
0.81.6 by Ian Clatworthy
basic DeltaCommitHandler mostly going bar rename
633
        self._copy_item(src_path, dest_path, self.inventory)
0.81.1 by Ian Clatworthy
move GenericCommitHandler into its own module in prep for a delta-based one
634
635
    def rename_handler(self, filecmd):
0.64.332 by Jelmer Vernooij
Cope with non-utf8 characters in paths when importing.
636
        old_path = self._decode_path(filecmd.old_path)
637
        new_path = self._decode_path(filecmd.new_path)
0.81.1 by Ian Clatworthy
move GenericCommitHandler into its own module in prep for a delta-based one
638
        self.debug("renaming %s to %s", old_path, new_path)
0.81.6 by Ian Clatworthy
basic DeltaCommitHandler mostly going bar rename
639
        self._rename_item(old_path, new_path, self.inventory)
0.81.1 by Ian Clatworthy
move GenericCommitHandler into its own module in prep for a delta-based one
640
641
    def deleteall_handler(self, filecmd):
642
        self.debug("deleting all files (and also all directories)")
0.81.6 by Ian Clatworthy
basic DeltaCommitHandler mostly going bar rename
643
        self._delete_all_items(self.inventory)
0.81.5 by Ian Clatworthy
basic DeltaCommitHandler generating deltas
644
645
0.64.171 by Ian Clatworthy
use inv deltas by default for all formats now: --classic to get old algorithm for packs
646
class InventoryDeltaCommitHandler(GenericCommitHandler):
647
    """A CommitHandler that builds Inventories by applying a delta."""
0.81.5 by Ian Clatworthy
basic DeltaCommitHandler generating deltas
648
649
    def pre_process_files(self):
0.64.171 by Ian Clatworthy
use inv deltas by default for all formats now: --classic to get old algorithm for packs
650
        super(InventoryDeltaCommitHandler, self).pre_process_files()
0.64.195 by Ian Clatworthy
prune directories that become empty after a delete or rename
651
        self._dirs_that_might_become_empty = set()
652
0.84.9 by Ian Clatworthy
get non-chk formats working again & combine delta entries when required
653
        # A given file-id can only appear once so we accumulate
654
        # the entries in a dict then build the actual delta at the end
655
        self._delta_entries_by_fileid = {}
0.84.7 by Ian Clatworthy
CHKInventory support for non rich-root repos working, for simple imports at least
656
        if len(self.parents) == 0 or not self.rev_store.expects_rich_root():
0.84.10 by Ian Clatworthy
fix TREE_ROOT delta entry after 1st revision & tweak _delete_item usage
657
            if self.parents:
658
                old_path = ''
659
            else:
660
                old_path = None
0.84.5 by Ian Clatworthy
_ensure_directory to return parent_id, not parent_ie
661
            # Need to explicitly add the root entry for the first revision
0.84.7 by Ian Clatworthy
CHKInventory support for non rich-root repos working, for simple imports at least
662
            # and for non rich-root inventories
0.84.5 by Ian Clatworthy
_ensure_directory to return parent_id, not parent_ie
663
            root_id = inventory.ROOT_ID
664
            root_ie = inventory.InventoryDirectory(root_id, u'', None)
665
            root_ie.revision = self.revision_id
0.84.10 by Ian Clatworthy
fix TREE_ROOT delta entry after 1st revision & tweak _delete_item usage
666
            self._add_entry((old_path, '', root_id, root_ie))
0.81.5 by Ian Clatworthy
basic DeltaCommitHandler generating deltas
667
668
    def post_process_files(self):
669
        """Save the revision."""
0.64.195 by Ian Clatworthy
prune directories that become empty after a delete or rename
670
        delta = self._get_final_delta()
0.64.171 by Ian Clatworthy
use inv deltas by default for all formats now: --classic to get old algorithm for packs
671
        inv = self.rev_store.load_using_delta(self.revision,
672
            self.basis_inventory, delta, None,
0.115.4 by John Arbash Meinel
(broken) Start working towards using CommitBuilder rather than using a custom implementation.
673
            self._get_data,
674
            self._get_per_file_parents,
675
            self._get_inventories)
0.81.5 by Ian Clatworthy
basic DeltaCommitHandler generating deltas
676
        self.cache_mgr.inventories[self.revision_id] = inv
0.84.8 by Ian Clatworthy
ensure the chk stuff is only used on formats actually supporting it
677
        #print "committed %s" % self.revision_id
0.81.5 by Ian Clatworthy
basic DeltaCommitHandler generating deltas
678
0.64.195 by Ian Clatworthy
prune directories that become empty after a delete or rename
679
    def _get_final_delta(self):
680
        """Generate the final delta.
681
682
        Smart post-processing of changes, e.g. pruning of directories
683
        that would become empty, goes here.
684
        """
685
        delta = list(self._delta_entries_by_fileid.values())
686
        if self.prune_empty_dirs and self._dirs_that_might_become_empty:
0.101.2 by Tom Widmer
Update pruning code to operate in multiple passes, with subsequent passes operating on the parent dirs of dirs pruned in the previous pass.
687
            candidates = self._dirs_that_might_become_empty
688
            while candidates:
689
                never_born = set()
690
                parent_dirs_that_might_become_empty = set()
691
                for path, file_id in self._empty_after_delta(delta, candidates):
692
                    newly_added = self._new_file_ids.get(path)
693
                    if newly_added:
694
                        never_born.add(newly_added)
695
                    else:
696
                        delta.append((path, None, file_id, None))
697
                    parent_dir = osutils.dirname(path)
698
                    if parent_dir:
699
                        parent_dirs_that_might_become_empty.add(parent_dir)
700
                candidates = parent_dirs_that_might_become_empty
0.101.5 by Tom Widmer
Add missing tab characters to ensure that never born dirs are correctly removed during each pass of parent directory pruning.
701
                # Clean up entries that got deleted before they were ever added
702
                if never_born:
703
                    delta = [de for de in delta if de[2] not in never_born]
0.64.195 by Ian Clatworthy
prune directories that become empty after a delete or rename
704
        return delta
705
706
    def _empty_after_delta(self, delta, candidates):
0.99.7 by Ian Clatworthy
handle a delete of a newly added file
707
        #self.mutter("delta so far is:\n%s" % "\n".join([str(de) for de in delta]))
708
        #self.mutter("candidates for deletion are:\n%s" % "\n".join([c for c in candidates]))
709
        new_inv = self._get_proposed_inventory(delta)
0.64.195 by Ian Clatworthy
prune directories that become empty after a delete or rename
710
        result = []
711
        for dir in candidates:
712
            file_id = new_inv.path2id(dir)
0.64.219 by Ian Clatworthy
More robust implicit delete logic when file-id not found
713
            if file_id is None:
714
                continue
0.96.2 by Ian Clatworthy
test and fix for implicit directory delete recursing up
715
            ie = new_inv[file_id]
0.101.2 by Tom Widmer
Update pruning code to operate in multiple passes, with subsequent passes operating on the parent dirs of dirs pruned in the previous pass.
716
            if ie.kind != 'directory':
717
                continue
0.96.2 by Ian Clatworthy
test and fix for implicit directory delete recursing up
718
            if len(ie.children) == 0:
719
                result.append((dir, file_id))
0.64.195 by Ian Clatworthy
prune directories that become empty after a delete or rename
720
                if self.verbose:
0.123.8 by Jelmer Vernooij
Use modes for FileModifyCommand.
721
                    self.note("pruning empty directory %s" % (dir,))
0.64.195 by Ian Clatworthy
prune directories that become empty after a delete or rename
722
        return result
723
0.99.7 by Ian Clatworthy
handle a delete of a newly added file
724
    def _get_proposed_inventory(self, delta):
725
        if len(self.parents):
0.114.1 by John Arbash Meinel
When post-processing the delta stream, don't ask to generate a full inventory to check for deletions.
726
            # new_inv = self.basis_inventory._get_mutable_inventory()
727
            # Note that this will create unreferenced chk pages if we end up
728
            # deleting entries, because this 'test' inventory won't end up
729
            # used. However, it is cheaper than having to create a full copy of
730
            # the inventory for every commit.
731
            new_inv = self.basis_inventory.create_by_apply_delta(delta,
732
                'not-a-valid-revision-id:')
0.99.7 by Ian Clatworthy
handle a delete of a newly added file
733
        else:
734
            new_inv = inventory.Inventory(revision_id=self.revision_id)
735
            # This is set in the delta so remove it to prevent a duplicate
736
            del new_inv[inventory.ROOT_ID]
0.114.1 by John Arbash Meinel
When post-processing the delta stream, don't ask to generate a full inventory to check for deletions.
737
            try:
738
                new_inv.apply_delta(delta)
739
            except errors.InconsistentDelta:
740
                self.mutter("INCONSISTENT DELTA IS:\n%s" % "\n".join([str(de) for de in delta]))
741
                raise
0.99.7 by Ian Clatworthy
handle a delete of a newly added file
742
        return new_inv
743
0.84.9 by Ian Clatworthy
get non-chk formats working again & combine delta entries when required
744
    def _add_entry(self, entry):
0.64.161 by Ian Clatworthy
fix per-graph parent handling for adds and renames
745
        # We need to combine the data if multiple entries have the same file-id.
0.84.9 by Ian Clatworthy
get non-chk formats working again & combine delta entries when required
746
        # For example, a rename followed by a modification looks like:
747
        #
748
        # (x, y, f, e) & (y, y, f, g) => (x, y, f, g)
749
        #
750
        # Likewise, a modification followed by a rename looks like:
751
        #
752
        # (x, x, f, e) & (x, y, f, g) => (x, y, f, g)
753
        #
754
        # Here's a rename followed by a delete and a modification followed by
755
        # a delete:
756
        #
757
        # (x, y, f, e) & (y, None, f, None) => (x, None, f, None)
758
        # (x, x, f, e) & (x, None, f, None) => (x, None, f, None)
759
        #
760
        # In summary, we use the original old-path, new new-path and new ie
761
        # when combining entries.
0.85.2 by Ian Clatworthy
improve per-file graph generation
762
        old_path = entry[0]
763
        new_path = entry[1]
0.84.9 by Ian Clatworthy
get non-chk formats working again & combine delta entries when required
764
        file_id = entry[2]
0.85.2 by Ian Clatworthy
improve per-file graph generation
765
        ie = entry[3]
0.84.9 by Ian Clatworthy
get non-chk formats working again & combine delta entries when required
766
        existing = self._delta_entries_by_fileid.get(file_id, None)
767
        if existing is not None:
0.85.2 by Ian Clatworthy
improve per-file graph generation
768
            old_path = existing[0]
769
            entry = (old_path, new_path, file_id, ie)
0.99.6 by Ian Clatworthy
Handle rename of a just added file
770
        if new_path is None and old_path is None:
771
            # This is a delete cancelling a previous add
772
            del self._delta_entries_by_fileid[file_id]
0.99.7 by Ian Clatworthy
handle a delete of a newly added file
773
            parent_dir = osutils.dirname(existing[1])
774
            self.mutter("cancelling add of %s with parent %s" % (existing[1], parent_dir))
775
            if parent_dir:
776
                self._dirs_that_might_become_empty.add(parent_dir)
0.99.6 by Ian Clatworthy
Handle rename of a just added file
777
            return
778
        else:
779
            self._delta_entries_by_fileid[file_id] = entry
0.84.9 by Ian Clatworthy
get non-chk formats working again & combine delta entries when required
780
0.99.6 by Ian Clatworthy
Handle rename of a just added file
781
        # Collect parent directories that might become empty
0.64.195 by Ian Clatworthy
prune directories that become empty after a delete or rename
782
        if new_path is None:
783
            # delete
784
            parent_dir = osutils.dirname(old_path)
785
            # note: no need to check the root
786
            if parent_dir:
787
                self._dirs_that_might_become_empty.add(parent_dir)
788
        elif old_path is not None and old_path != new_path:
789
            # rename
790
            old_parent_dir = osutils.dirname(old_path)
791
            new_parent_dir = osutils.dirname(new_path)
792
            if old_parent_dir and old_parent_dir != new_parent_dir:
793
                self._dirs_that_might_become_empty.add(old_parent_dir)
794
0.64.161 by Ian Clatworthy
fix per-graph parent handling for adds and renames
795
        # Calculate the per-file parents, if not already done
796
        if file_id in self.per_file_parents_for_commit:
797
            return
0.85.2 by Ian Clatworthy
improve per-file graph generation
798
        if old_path is None:
799
            # add
0.64.161 by Ian Clatworthy
fix per-graph parent handling for adds and renames
800
            # If this is a merge, the file was most likely added already.
801
            # The per-file parent(s) must therefore be calculated and
802
            # we can't assume there are none.
803
            per_file_parents, ie.revision = \
804
                self.rev_store.get_parents_and_revision_for_entry(ie)
805
            self.per_file_parents_for_commit[file_id] = per_file_parents
0.85.2 by Ian Clatworthy
improve per-file graph generation
806
        elif new_path is None:
807
            # delete
808
            pass
809
        elif old_path != new_path:
810
            # rename
0.64.161 by Ian Clatworthy
fix per-graph parent handling for adds and renames
811
            per_file_parents, _ = \
812
                self.rev_store.get_parents_and_revision_for_entry(ie)
813
            self.per_file_parents_for_commit[file_id] = per_file_parents
0.85.2 by Ian Clatworthy
improve per-file graph generation
814
        else:
815
            # modify
816
            per_file_parents, ie.revision = \
817
                self.rev_store.get_parents_and_revision_for_entry(ie)
818
            self.per_file_parents_for_commit[file_id] = per_file_parents
819
0.81.5 by Ian Clatworthy
basic DeltaCommitHandler generating deltas
820
    def record_new(self, path, ie):
0.84.9 by Ian Clatworthy
get non-chk formats working again & combine delta entries when required
821
        self._add_entry((None, path, ie.file_id, ie))
0.81.5 by Ian Clatworthy
basic DeltaCommitHandler generating deltas
822
0.84.5 by Ian Clatworthy
_ensure_directory to return parent_id, not parent_ie
823
    def record_changed(self, path, ie, parent_id=None):
0.84.9 by Ian Clatworthy
get non-chk formats working again & combine delta entries when required
824
        self._add_entry((path, path, ie.file_id, ie))
0.99.17 by Ian Clatworthy
Handle rename of a file/symlink modified already in this commit
825
        self._modified_file_ids[path] = ie.file_id
0.81.5 by Ian Clatworthy
basic DeltaCommitHandler generating deltas
826
0.81.9 by Ian Clatworthy
refactor delete_item
827
    def record_delete(self, path, ie):
0.84.9 by Ian Clatworthy
get non-chk formats working again & combine delta entries when required
828
        self._add_entry((path, None, ie.file_id, None))
0.99.13 by Ian Clatworthy
Handle delete then add of a file/symlink in the one commit
829
        self._paths_deleted_this_commit.add(path)
0.81.10 by Ian Clatworthy
get DeltaCommitHandler passing all tests
830
        if ie.kind == 'directory':
0.99.21 by Ian Clatworthy
Handle deleting a directory then adding a file within it in the same commit
831
            try:
832
                del self.directory_entries[path]
833
            except KeyError:
834
                pass
0.64.187 by Ian Clatworthy
fix inv-delta generation when deleting directories
835
            for child_relpath, entry in \
0.81.10 by Ian Clatworthy
get DeltaCommitHandler passing all tests
836
                self.basis_inventory.iter_entries_by_dir(from_dir=ie):
0.64.187 by Ian Clatworthy
fix inv-delta generation when deleting directories
837
                child_path = osutils.pathjoin(path, child_relpath)
0.84.9 by Ian Clatworthy
get non-chk formats working again & combine delta entries when required
838
                self._add_entry((child_path, None, entry.file_id, None))
0.99.13 by Ian Clatworthy
Handle delete then add of a file/symlink in the one commit
839
                self._paths_deleted_this_commit.add(child_path)
0.99.21 by Ian Clatworthy
Handle deleting a directory then adding a file within it in the same commit
840
                if entry.kind == 'directory':
841
                    try:
842
                        del self.directory_entries[child_path]
843
                    except KeyError:
844
                        pass
0.81.8 by Ian Clatworthy
refactor rename_item
845
0.81.10 by Ian Clatworthy
get DeltaCommitHandler passing all tests
846
    def record_rename(self, old_path, new_path, file_id, old_ie):
847
        new_ie = old_ie.copy()
0.84.5 by Ian Clatworthy
_ensure_directory to return parent_id, not parent_ie
848
        new_basename, new_parent_id = self._ensure_directory(new_path,
0.81.10 by Ian Clatworthy
get DeltaCommitHandler passing all tests
849
            self.basis_inventory)
850
        new_ie.name = new_basename
0.84.5 by Ian Clatworthy
_ensure_directory to return parent_id, not parent_ie
851
        new_ie.parent_id = new_parent_id
0.81.10 by Ian Clatworthy
get DeltaCommitHandler passing all tests
852
        new_ie.revision = self.revision_id
0.84.9 by Ian Clatworthy
get non-chk formats working again & combine delta entries when required
853
        self._add_entry((old_path, new_path, file_id, new_ie))
0.99.19 by Ian Clatworthy
Handle rename then modification of the new path
854
        self._modified_file_ids[new_path] = file_id
0.64.233 by Ian Clatworthy
Handle delete, rename then modify all in the one commit
855
        self._paths_deleted_this_commit.discard(new_path)
0.64.234 by Ian Clatworthy
Make sure renamed directories are found in file-id lookups
856
        if new_ie.kind == 'directory':
857
            self.directory_entries[new_path] = new_ie
0.81.6 by Ian Clatworthy
basic DeltaCommitHandler mostly going bar rename
858
0.99.17 by Ian Clatworthy
Handle rename of a file/symlink modified already in this commit
859
    def _rename_pending_change(self, old_path, new_path, file_id):
860
        """Instead of adding/modifying old-path, add new-path instead."""
0.99.6 by Ian Clatworthy
Handle rename of a just added file
861
        # note: delta entries look like (old, new, file-id, ie)
862
        old_ie = self._delta_entries_by_fileid[file_id][3]
863
864
        # Delete the old path. Note that this might trigger implicit
865
        # deletion of newly created parents that could now become empty.
866
        self.record_delete(old_path, old_ie)
867
0.99.17 by Ian Clatworthy
Handle rename of a file/symlink modified already in this commit
868
        # Update the dictionaries used for tracking new file-ids
869
        if old_path in self._new_file_ids:
870
            del self._new_file_ids[old_path]
871
        else:
872
            del self._modified_file_ids[old_path]
0.99.6 by Ian Clatworthy
Handle rename of a just added file
873
        self._new_file_ids[new_path] = file_id
874
875
        # Create the new InventoryEntry
876
        kind = old_ie.kind
877
        basename, parent_id = self._ensure_directory(new_path,
878
            self.basis_inventory)
879
        ie = inventory.make_entry(kind, basename, parent_id, file_id)
880
        ie.revision = self.revision_id
881
        if kind == 'file':
882
            ie.executable = old_ie.executable
883
            ie.text_sha1 = old_ie.text_sha1
884
            ie.text_size = old_ie.text_size
885
        elif kind == 'symlink':
886
            ie.symlink_target = old_ie.symlink_target
887
888
        # Record it
889
        self.record_new(new_path, ie)
890
0.81.6 by Ian Clatworthy
basic DeltaCommitHandler mostly going bar rename
891
    def modify_handler(self, filecmd):
0.123.8 by Jelmer Vernooij
Use modes for FileModifyCommand.
892
        (kind, executable) = mode_to_kind(filecmd.mode)
0.81.6 by Ian Clatworthy
basic DeltaCommitHandler mostly going bar rename
893
        if filecmd.dataref is not None:
0.123.8 by Jelmer Vernooij
Use modes for FileModifyCommand.
894
            if kind == "directory":
0.102.14 by Ian Clatworthy
export and import empty directories
895
                data = None
0.123.8 by Jelmer Vernooij
Use modes for FileModifyCommand.
896
            elif kind == "tree-reference":
0.64.229 by Ian Clatworthy
Handle git submodules in the stream by warning about + ignoring them
897
                data = filecmd.dataref
898
            else:
899
                data = self.cache_mgr.fetch_blob(filecmd.dataref)
0.81.6 by Ian Clatworthy
basic DeltaCommitHandler mostly going bar rename
900
        else:
901
            data = filecmd.data
902
        self.debug("modifying %s", filecmd.path)
0.64.332 by Jelmer Vernooij
Cope with non-utf8 characters in paths when importing.
903
        decoded_path = self._decode_path(filecmd.path)
904
        self._modify_item(decoded_path, kind,
0.123.8 by Jelmer Vernooij
Use modes for FileModifyCommand.
905
            executable, data, self.basis_inventory)
0.81.6 by Ian Clatworthy
basic DeltaCommitHandler mostly going bar rename
906
907
    def delete_handler(self, filecmd):
908
        self.debug("deleting %s", filecmd.path)
0.64.332 by Jelmer Vernooij
Cope with non-utf8 characters in paths when importing.
909
        self._delete_item(
910
            self._decode_path(filecmd.path), self.basis_inventory)
0.81.6 by Ian Clatworthy
basic DeltaCommitHandler mostly going bar rename
911
912
    def copy_handler(self, filecmd):
0.64.332 by Jelmer Vernooij
Cope with non-utf8 characters in paths when importing.
913
        src_path = self._decode_path(filecmd.src_path)
914
        dest_path = self._decode_path(filecmd.dest_path)
0.81.6 by Ian Clatworthy
basic DeltaCommitHandler mostly going bar rename
915
        self.debug("copying %s to %s", src_path, dest_path)
0.81.10 by Ian Clatworthy
get DeltaCommitHandler passing all tests
916
        self._copy_item(src_path, dest_path, self.basis_inventory)
0.81.6 by Ian Clatworthy
basic DeltaCommitHandler mostly going bar rename
917
918
    def rename_handler(self, filecmd):
0.64.332 by Jelmer Vernooij
Cope with non-utf8 characters in paths when importing.
919
        old_path = self._decode_path(filecmd.old_path)
920
        new_path = self._decode_path(filecmd.new_path)
0.81.6 by Ian Clatworthy
basic DeltaCommitHandler mostly going bar rename
921
        self.debug("renaming %s to %s", old_path, new_path)
922
        self._rename_item(old_path, new_path, self.basis_inventory)
923
924
    def deleteall_handler(self, filecmd):
925
        self.debug("deleting all files (and also all directories)")
926
        self._delete_all_items(self.basis_inventory)