/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
3193.8.13 by Aaron Bentley
Update texts
1
# Copyright (C) 2009 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
3193.8.32 by Aaron Bentley
Update GPL preamble
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
3193.8.13 by Aaron Bentley
Update texts
16
6379.6.3 by Jelmer Vernooij
Use absolute_import.
17
from __future__ import absolute_import
3193.8.13 by Aaron Bentley
Update texts
18
3193.8.18 by Aaron Bentley
Move all rename-guessing into RenameMap
19
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
20
from . import (
3193.8.18 by Aaron Bentley
Move all rename-guessing into RenameMap
21
    osutils,
22
    progress,
3193.8.33 by Aaron Bentley
Add output, emit minimal inventory delta.
23
    trace,
6621.22.2 by Martin
Use BytesIO or StringIO from bzrlib.sixish
24
    )
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
25
from .i18n import gettext
26
from .sixish import (
6621.22.2 by Martin
Use BytesIO or StringIO from bzrlib.sixish
27
    BytesIO,
6656.1.1 by Martin
Apply 2to3 dict fixer and clean up resulting mess using view helpers
28
    viewitems,
6621.22.2 by Martin
Use BytesIO or StringIO from bzrlib.sixish
29
    )
6624 by Jelmer Vernooij
Merge Python3 porting work ('py3 pokes')
30
from .ui import ui_factory
3193.8.4 by Aaron Bentley
Get rename detection working for files.
31
32
class RenameMap(object):
3193.8.13 by Aaron Bentley
Update texts
33
    """Determine a mapping of renames."""
3193.8.4 by Aaron Bentley
Get rename detection working for files.
34
3193.8.24 by Aaron Bentley
Use tree member instead of passing it in
35
    def __init__(self, tree):
36
        self.tree = tree
3193.8.4 by Aaron Bentley
Get rename detection working for files.
37
        self.edge_hashes = {}
38
3193.8.11 by Aaron Bentley
Make hash iterator static
39
    @staticmethod
40
    def iter_edge_hashes(lines):
3193.8.20 by Aaron Bentley
Cleanup and enhance tests.
41
        """Iterate through the hashes of line pairs (which make up an edge).
42
43
        The hash is truncated using a modulus to avoid excessive memory
44
        consumption by the hitscount dict.  A modulus of 10Mi means that the
45
        maximum number of keys is 10Mi.  (Keys are normally 32 bits, e.g.
46
        4 Gi)
47
        """
3193.8.10 by Aaron Bentley
Update to weight hits and use 10M of keyspace
48
        modulus = 1024 * 1024 * 10
3193.8.4 by Aaron Bentley
Get rename detection working for files.
49
        for n in range(len(lines)):
3193.8.10 by Aaron Bentley
Update to weight hits and use 10M of keyspace
50
            yield hash(tuple(lines[n:n+2])) % modulus
3193.8.4 by Aaron Bentley
Get rename detection working for files.
51
52
    def add_edge_hashes(self, lines, tag):
3193.8.13 by Aaron Bentley
Update texts
53
        """Update edge_hashes to include the given lines.
54
55
        :param lines: The lines to update the hashes for.
56
        :param tag: A tag uniquely associated with these lines (i.e. file-id)
57
        """
3193.8.4 by Aaron Bentley
Get rename detection working for files.
58
        for my_hash in self.iter_edge_hashes(lines):
59
            self.edge_hashes.setdefault(my_hash, set()).add(tag)
60
61
    def add_file_edge_hashes(self, tree, file_ids):
3193.8.13 by Aaron Bentley
Update texts
62
        """Update to reflect the hashes for files in the tree.
63
64
        :param tree: The tree containing the files.
65
        :param file_ids: A list of file_ids to perform the updates for.
66
        """
3193.8.4 by Aaron Bentley
Get rename detection working for files.
67
        desired_files = [(f, f) for f in file_ids]
6861.4.1 by Jelmer Vernooij
Make progress bars context managers.
68
        with ui_factory.nested_progress_bar() as task:
3193.8.14 by Aaron Bentley
Add progress reporting to guess-renames
69
            for num, (file_id, contents) in enumerate(
70
                tree.iter_files_bytes(desired_files)):
6138.4.1 by Jonathan Riddell
add gettext to progress bar strings
71
                task.update(gettext('Calculating hashes'), num, len(file_ids))
6621.22.2 by Martin
Use BytesIO or StringIO from bzrlib.sixish
72
                s = BytesIO()
3193.8.14 by Aaron Bentley
Add progress reporting to guess-renames
73
                s.writelines(contents)
74
                s.seek(0)
75
                self.add_edge_hashes(s.readlines(), file_id)
3193.8.4 by Aaron Bentley
Get rename detection working for files.
76
77
    def hitcounts(self, lines):
3193.8.13 by Aaron Bentley
Update texts
78
        """Count the number of hash hits for each tag, for the given lines.
79
80
        Hits are weighted according to the number of tags the hash is
3193.8.20 by Aaron Bentley
Cleanup and enhance tests.
81
        associated with; more tags means that the hash is less rare and should
82
        tend to be ignored.
3193.8.13 by Aaron Bentley
Update texts
83
        :param lines: The lines to calculate hashes of.
3193.8.20 by Aaron Bentley
Cleanup and enhance tests.
84
        :return: a dict of {tag: hitcount}
3193.8.13 by Aaron Bentley
Update texts
85
        """
3193.8.4 by Aaron Bentley
Get rename detection working for files.
86
        hits = {}
87
        for my_hash in self.iter_edge_hashes(lines):
88
            tags = self.edge_hashes.get(my_hash)
89
            if tags is None:
90
                continue
3193.8.12 by Aaron Bentley
Reorganize slightly for the benefit of kcachegrind
91
            taglen = len(tags)
3193.8.4 by Aaron Bentley
Get rename detection working for files.
92
            for tag in tags:
93
                if tag not in hits:
94
                    hits[tag] = 0
3193.8.12 by Aaron Bentley
Reorganize slightly for the benefit of kcachegrind
95
                hits[tag] += 1.0 / taglen
3193.8.4 by Aaron Bentley
Get rename detection working for files.
96
        return hits
97
3193.8.24 by Aaron Bentley
Use tree member instead of passing it in
98
    def get_all_hits(self, paths):
99
        """Find all the hit counts for the listed paths in the tree.
3193.8.13 by Aaron Bentley
Update texts
100
101
        :return: A list of tuples of count, path, file_id.
102
        """
3193.8.20 by Aaron Bentley
Cleanup and enhance tests.
103
        all_hits = []
6861.4.1 by Jelmer Vernooij
Make progress bars context managers.
104
        with ui_factory.nested_progress_bar() as task:
3193.8.14 by Aaron Bentley
Add progress reporting to guess-renames
105
            for num, path in enumerate(paths):
6138.4.1 by Jonathan Riddell
add gettext to progress bar strings
106
                task.update(gettext('Determining hash hits'), num, len(paths))
6809.4.5 by Jelmer Vernooij
Swap arguments for get_file_*.
107
                hits = self.hitcounts(self.tree.get_file_lines(path))
6656.1.1 by Martin
Apply 2to3 dict fixer and clean up resulting mess using view helpers
108
                all_hits.extend((v, path, k) for k, v in viewitems(hits))
3193.8.20 by Aaron Bentley
Cleanup and enhance tests.
109
        return all_hits
3193.8.12 by Aaron Bentley
Reorganize slightly for the benefit of kcachegrind
110
3193.8.24 by Aaron Bentley
Use tree member instead of passing it in
111
    def file_match(self, paths):
3193.8.13 by Aaron Bentley
Update texts
112
        """Return a mapping from file_ids to the supplied paths."""
3193.8.24 by Aaron Bentley
Use tree member instead of passing it in
113
        return self._match_hits(self.get_all_hits(paths))
3193.8.17 by Aaron Bentley
Get directory rename handling working.
114
115
    @staticmethod
3193.8.20 by Aaron Bentley
Cleanup and enhance tests.
116
    def _match_hits(hit_list):
3193.8.26 by Aaron Bentley
Updates from review.
117
        """Using a hit list, determine a path-to-fileid map.
3193.8.20 by Aaron Bentley
Cleanup and enhance tests.
118
119
        The hit list is a list of (count, path, file_id), where count is a
120
        (possibly float) number, with higher numbers indicating stronger
121
        matches.
122
        """
3193.8.12 by Aaron Bentley
Reorganize slightly for the benefit of kcachegrind
123
        seen_file_ids = set()
124
        path_map = {}
3193.8.20 by Aaron Bentley
Cleanup and enhance tests.
125
        for count, path, file_id in sorted(hit_list, reverse=True):
3193.8.26 by Aaron Bentley
Updates from review.
126
            if path in path_map or file_id in seen_file_ids:
3193.8.7 by Aaron Bentley
Saner algorithm for picking optimal file.
127
                continue
128
            path_map[path] = file_id
129
            seen_file_ids.add(file_id)
3193.8.4 by Aaron Bentley
Get rename detection working for files.
130
        return path_map
3193.8.16 by Aaron Bentley
Get a dict of required parents.
131
3193.8.24 by Aaron Bentley
Use tree member instead of passing it in
132
    def get_required_parents(self, matches):
3193.8.20 by Aaron Bentley
Cleanup and enhance tests.
133
        """Return a dict of all file parents that must be versioned.
134
135
        The keys are the required parents and the values are sets of their
136
        children.
137
        """
3193.8.16 by Aaron Bentley
Get a dict of required parents.
138
        required_parents = {}
139
        for path in matches:
140
            while True:
141
                child = path
142
                path = osutils.dirname(path)
6852.3.1 by Jelmer Vernooij
add Tree.is_versioned.
143
                if self.tree.is_versioned(path):
3193.8.16 by Aaron Bentley
Get a dict of required parents.
144
                    break
145
                required_parents.setdefault(path, []).append(child)
3193.8.17 by Aaron Bentley
Get directory rename handling working.
146
        require_ids = {}
6656.1.1 by Martin
Apply 2to3 dict fixer and clean up resulting mess using view helpers
147
        for parent, children in viewitems(required_parents):
3193.8.17 by Aaron Bentley
Get directory rename handling working.
148
            child_file_ids = set()
149
            for child in children:
150
                file_id = matches.get(child)
151
                if file_id is not None:
152
                    child_file_ids.add(file_id)
153
            require_ids[parent] = child_file_ids
154
        return require_ids
155
156
    def match_parents(self, required_parents, missing_parents):
3193.8.20 by Aaron Bentley
Cleanup and enhance tests.
157
        """Map parent directories to file-ids.
158
159
        This is done by finding similarity between the file-ids of children of
160
        required parent directories and the file-ids of children of missing
161
        parent directories.
162
        """
163
        all_hits = []
6656.1.1 by Martin
Apply 2to3 dict fixer and clean up resulting mess using view helpers
164
        for file_id, file_id_children in viewitems(missing_parents):
165
            for path, path_children in viewitems(required_parents):
3193.8.17 by Aaron Bentley
Get directory rename handling working.
166
                hits = len(path_children.intersection(file_id_children))
167
                if hits > 0:
3193.8.20 by Aaron Bentley
Cleanup and enhance tests.
168
                    all_hits.append((hits, path, file_id))
169
        return self._match_hits(all_hits)
3193.8.18 by Aaron Bentley
Move all rename-guessing into RenameMap
170
3193.8.24 by Aaron Bentley
Use tree member instead of passing it in
171
    def _find_missing_files(self, basis):
3193.8.22 by Aaron Bentley
Reduce unnecessary locking.
172
        missing_files = set()
173
        missing_parents = {}
174
        candidate_files = set()
6861.4.1 by Jelmer Vernooij
Make progress bars context managers.
175
        with ui_factory.nested_progress_bar() as task:
176
            iterator = self.tree.iter_changes(basis, want_unversioned=True,
177
                                              pb=task)
3193.8.25 by Aaron Bentley
Improve progress reporting.
178
            for (file_id, paths, changed_content, versioned, parent, name,
179
                 kind, executable) in iterator:
180
                if kind[1] is None and versioned[1]:
6547.1.5 by Jelmer Vernooij
Address review comments.
181
                    if not self.tree.has_filename(self.tree.id2path(parent[0])):
6547.1.1 by mnn
Fixed issue with RenameMap - also it supports renaming into new unversioned directory
182
                        missing_parents.setdefault(parent[0], set()).add(file_id)
3193.8.25 by Aaron Bentley
Improve progress reporting.
183
                    if kind[0] == 'file':
184
                        missing_files.add(file_id)
185
                    else:
186
                        #other kinds are not handled
187
                        pass
188
                if versioned == (False, False):
189
                    if self.tree.is_ignored(paths[1]):
190
                        continue
191
                    if kind[1] == 'file':
192
                        candidate_files.add(paths[1])
193
                    if kind[1] == 'directory':
194
                        for _dir, children in self.tree.walkdirs(paths[1]):
195
                            for child in children:
196
                                if child[2] == 'file':
197
                                    candidate_files.add(child[0])
3193.8.22 by Aaron Bentley
Reduce unnecessary locking.
198
        return missing_files, missing_parents, candidate_files
199
200
    @classmethod
3193.8.33 by Aaron Bentley
Add output, emit minimal inventory delta.
201
    def guess_renames(klass, tree, dry_run=False):
3193.8.18 by Aaron Bentley
Move all rename-guessing into RenameMap
202
        """Guess which files to rename, and perform the rename.
203
204
        We assume that unversioned files and missing files indicate that
205
        versioned files have been renamed outside of Bazaar.
3193.8.26 by Aaron Bentley
Updates from review.
206
207
        :param tree: A write-locked working tree.
3193.8.18 by Aaron Bentley
Move all rename-guessing into RenameMap
208
        """
3193.8.22 by Aaron Bentley
Reduce unnecessary locking.
209
        required_parents = {}
6861.4.1 by Jelmer Vernooij
Make progress bars context managers.
210
        with ui_factory.nested_progress_bar() as task:
3193.8.25 by Aaron Bentley
Improve progress reporting.
211
            pp = progress.ProgressPhase('Guessing renames', 4, task)
212
            basis = tree.basis_tree()
213
            basis.lock_read()
3193.8.18 by Aaron Bentley
Move all rename-guessing into RenameMap
214
            try:
3193.8.25 by Aaron Bentley
Improve progress reporting.
215
                rn = klass(tree)
216
                pp.next_phase()
217
                missing_files, missing_parents, candidate_files = (
218
                    rn._find_missing_files(basis))
3193.8.18 by Aaron Bentley
Move all rename-guessing into RenameMap
219
                pp.next_phase()
220
                rn.add_file_edge_hashes(basis, missing_files)
221
            finally:
3193.8.25 by Aaron Bentley
Improve progress reporting.
222
                basis.unlock()
223
            pp.next_phase()
224
            matches = rn.file_match(candidate_files)
225
            parents_matches = matches
226
            while len(parents_matches) > 0:
227
                required_parents = rn.get_required_parents(
228
                    parents_matches)
229
                parents_matches = rn.match_parents(required_parents,
230
                                                   missing_parents)
231
                matches.update(parents_matches)
232
            pp.next_phase()
3193.8.33 by Aaron Bentley
Add output, emit minimal inventory delta.
233
            delta = rn._make_inventory_delta(matches)
234
            for old, new, file_id, entry in delta:
6138.3.4 by Jonathan Riddell
add gettext() to uses of trace.note()
235
                trace.note( gettext("{0} => {1}").format(old, new) )
3193.8.33 by Aaron Bentley
Add output, emit minimal inventory delta.
236
            if not dry_run:
237
                tree.add(required_parents)
238
                tree.apply_inventory_delta(delta)
3193.8.23 by Aaron Bentley
Split up guess_renames further.
239
3193.8.33 by Aaron Bentley
Add output, emit minimal inventory delta.
240
    def _make_inventory_delta(self, matches):
3193.8.27 by Aaron Bentley
Use apply_inventory_delta to rename files.
241
        delta = []
6656.1.1 by Martin
Apply 2to3 dict fixer and clean up resulting mess using view helpers
242
        file_id_matches = dict((f, p) for p, f in viewitems(matches))
243
        for old_path, entry in self.tree.iter_entries_by_dir(file_id_matches):
3193.8.27 by Aaron Bentley
Use apply_inventory_delta to rename files.
244
            new_path = file_id_matches[entry.file_id]
3193.8.29 by Aaron Bentley
Use split instead of basename/dirname
245
            parent_path, new_name = osutils.split(new_path)
3193.8.27 by Aaron Bentley
Use apply_inventory_delta to rename files.
246
            parent_id = matches.get(parent_path)
247
            if parent_id is None:
248
                parent_id = self.tree.path2id(parent_path)
6547.1.1 by mnn
Fixed issue with RenameMap - also it supports renaming into new unversioned directory
249
                if parent_id is None:
250
                    added, ignored = self.tree.smart_add([parent_path], recurse=False)
251
                    if len(ignored) > 0 and ignored[0] == parent_path:
252
                        continue
253
                    else:
254
                        parent_id = self.tree.path2id(parent_path)
3193.8.33 by Aaron Bentley
Add output, emit minimal inventory delta.
255
            if entry.name == new_name and entry.parent_id == parent_id:
256
                continue
3193.8.27 by Aaron Bentley
Use apply_inventory_delta to rename files.
257
            new_entry = entry.copy()
258
            new_entry.parent_id = parent_id
3193.8.29 by Aaron Bentley
Use split instead of basename/dirname
259
            new_entry.name = new_name
3193.8.27 by Aaron Bentley
Use apply_inventory_delta to rename files.
260
            delta.append((old_path, new_path, new_entry.file_id, new_entry))
3193.8.33 by Aaron Bentley
Add output, emit minimal inventory delta.
261
        return delta