/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
0.436.2 by Jelmer Vernooij
Add stubs for testsuite, rebase-continue and rebase-abort commands.
1
# Copyright (C) 2006-2007 by Jelmer Vernooij
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
0.436.131 by Jelmer Vernooij
Change license back to GPLv2+
5
# the Free Software Foundation; either version 2 of the License, or
0.436.2 by Jelmer Vernooij
Add stubs for testsuite, rebase-continue and rebase-abort commands.
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
0.436.16 by Jelmer Vernooij
Some more work on maptree.
16
"""Rebase."""
0.436.3 by Jelmer Vernooij
Fill in commands.
17
0.436.5 by Jelmer Vernooij
Import change_revision_parent from bzr-svn.
18
from bzrlib.config import Config
0.441.4 by Robert Collins
* Fixed O(history) access during plan creation (Robert Collins, lp:#249823).
19
from bzrlib.errors import (BzrError, NoSuchFile, UnknownFormatError,
0.436.121 by Jelmer Vernooij
Simplify replay snapshot functions.
20
                           NoCommonAncestor, NoSuchId, UnrelatedBranches)
0.436.4 by Jelmer Vernooij
Add some tests.
21
from bzrlib.generate_ids import gen_revision_id
0.441.4 by Robert Collins
* Fixed O(history) access during plan creation (Robert Collins, lp:#249823).
22
from bzrlib.graph import FrozenHeadsCache
0.438.2 by Jelmer Vernooij
More work using proper merge bases.
23
from bzrlib.merge import Merger
0.436.10 by Jelmer Vernooij
Add more agressive version of revert.
24
from bzrlib import osutils
0.436.9 by Jelmer Vernooij
Add rebase-todo command, fix rebase-continue.
25
from bzrlib.revision import NULL_REVISION
0.436.4 by Jelmer Vernooij
Add some tests.
26
from bzrlib.trace import mutter
0.441.4 by Robert Collins
* Fixed O(history) access during plan creation (Robert Collins, lp:#249823).
27
from bzrlib.tsort import topo_sort
0.436.5 by Jelmer Vernooij
Import change_revision_parent from bzr-svn.
28
import bzrlib.ui as ui
0.436.4 by Jelmer Vernooij
Add some tests.
29
0.436.17 by Jelmer Vernooij
Move maptree code to separate files.
30
from maptree import MapTree, map_file_ids
0.436.38 by Jelmer Vernooij
Handle directories in revert.
31
import os
0.436.17 by Jelmer Vernooij
Move maptree code to separate files.
32
0.436.3 by Jelmer Vernooij
Fill in commands.
33
REBASE_PLAN_FILENAME = 'rebase-plan'
0.436.9 by Jelmer Vernooij
Add rebase-todo command, fix rebase-continue.
34
REBASE_CURRENT_REVID_FILENAME = 'rebase-current'
0.436.4 by Jelmer Vernooij
Add some tests.
35
REBASE_PLAN_VERSION = 1
0.436.27 by Jelmer Vernooij
Note revision property 'rebase-of', add explanation of use of pregenerated revision ids.
36
REVPROP_REBASE_OF = 'rebase-of'
0.436.3 by Jelmer Vernooij
Fill in commands.
37
38
def rebase_plan_exists(wt):
39
    """Check whether there is a rebase plan present.
40
41
    :param wt: Working tree for which to check.
42
    :return: boolean
43
    """
0.436.7 by Jelmer Vernooij
Add more test, make basic rebase work.
44
    try:
0.441.3 by Robert Collins
Update rebase to 1.6b3 API changes.
45
        return wt._transport.get_bytes(REBASE_PLAN_FILENAME) != ''
0.436.7 by Jelmer Vernooij
Add more test, make basic rebase work.
46
    except NoSuchFile:
47
        return False
0.436.3 by Jelmer Vernooij
Fill in commands.
48
49
50
def read_rebase_plan(wt):
51
    """Read a rebase plan file.
52
53
    :param wt: Working Tree for which to write the plan.
0.436.4 by Jelmer Vernooij
Add some tests.
54
    :return: Tuple with last revision info and replace map.
0.436.3 by Jelmer Vernooij
Fill in commands.
55
    """
0.441.3 by Robert Collins
Update rebase to 1.6b3 API changes.
56
    text = wt._transport.get_bytes(REBASE_PLAN_FILENAME)
0.436.3 by Jelmer Vernooij
Fill in commands.
57
    if text == '':
0.436.7 by Jelmer Vernooij
Add more test, make basic rebase work.
58
        raise NoSuchFile(REBASE_PLAN_FILENAME)
0.436.4 by Jelmer Vernooij
Add some tests.
59
    return unmarshall_rebase_plan(text)
60
61
62
def write_rebase_plan(wt, replace_map):
0.436.3 by Jelmer Vernooij
Fill in commands.
63
    """Write a rebase plan file.
64
65
    :param wt: Working Tree for which to write the plan.
0.436.4 by Jelmer Vernooij
Add some tests.
66
    :param replace_map: Replace map (old revid -> (new revid, new parents))
0.436.3 by Jelmer Vernooij
Fill in commands.
67
    """
0.441.3 by Robert Collins
Update rebase to 1.6b3 API changes.
68
    content = marshall_rebase_plan(wt.branch.last_revision_info(), replace_map)
69
    assert type(content) == str
70
    wt._transport.put_bytes(REBASE_PLAN_FILENAME, content)
0.436.3 by Jelmer Vernooij
Fill in commands.
71
72
73
def remove_rebase_plan(wt):
74
    """Remove a rebase plan file.
75
76
    :param wt: Working Tree for which to remove the plan.
77
    """
0.441.3 by Robert Collins
Update rebase to 1.6b3 API changes.
78
    wt._transport.put_bytes(REBASE_PLAN_FILENAME, '')
0.436.3 by Jelmer Vernooij
Fill in commands.
79
80
0.436.4 by Jelmer Vernooij
Add some tests.
81
def marshall_rebase_plan(last_rev_info, replace_map):
0.436.3 by Jelmer Vernooij
Fill in commands.
82
    """Marshall a rebase plan.
83
84
    :param last_rev_info: Last revision info tuple.
0.436.4 by Jelmer Vernooij
Add some tests.
85
    :param replace_map: Replace map (old revid -> (new revid, new parents))
0.436.3 by Jelmer Vernooij
Fill in commands.
86
    :return: string
87
    """
0.436.4 by Jelmer Vernooij
Add some tests.
88
    ret = "# Bazaar rebase plan %d\n" % REBASE_PLAN_VERSION
89
    ret += "%d %s\n" % last_rev_info
90
    for oldrev in replace_map:
91
        (newrev, newparents) = replace_map[oldrev]
92
        ret += "%s %s" % (oldrev, newrev) + \
93
            "".join([" %s" % p for p in newparents]) + "\n"
94
    return ret
95
96
97
def unmarshall_rebase_plan(text):
0.436.3 by Jelmer Vernooij
Fill in commands.
98
    """Unmarshall a rebase plan.
99
100
    :param text: Text to parse
0.436.4 by Jelmer Vernooij
Add some tests.
101
    :return: Tuple with last revision info, replace map.
0.436.3 by Jelmer Vernooij
Fill in commands.
102
    """
0.436.4 by Jelmer Vernooij
Add some tests.
103
    lines = text.split('\n')
104
    # Make sure header is there
105
    if lines[0] != "# Bazaar rebase plan %d" % REBASE_PLAN_VERSION:
106
        raise UnknownFormatError(lines[0])
107
108
    pts = lines[1].split(" ", 1)
109
    last_revision_info = (int(pts[0]), pts[1])
110
    replace_map = {}
111
    for l in lines[2:]:
112
        if l == "":
113
            # Skip empty lines
114
            continue
115
        pts = l.split(" ")
0.436.95 by Jelmer Vernooij
Use tuples more consistently.
116
        replace_map[pts[0]] = (pts[1], tuple(pts[2:]))
0.436.4 by Jelmer Vernooij
Add some tests.
117
    return (last_revision_info, replace_map)
118
0.436.6 by Jelmer Vernooij
Add somewhat more complex plan generation function, rebase implementation.
119
0.436.39 by Jelmer Vernooij
Some more refactoring, add test that demonstrates #126743.
120
def regenerate_default_revid(repository, revid):
0.436.52 by Jelmer Vernooij
Add docstrings, update NEWS.
121
    """Generate a revision id for the rebase of an existing revision.
122
    
123
    :param repository: Repository in which the revision is present.
124
    :param revid: Revision id of the revision that is being rebased.
125
    :return: new revision id."""
0.436.39 by Jelmer Vernooij
Some more refactoring, add test that demonstrates #126743.
126
    rev = repository.get_revision(revid)
0.436.6 by Jelmer Vernooij
Add somewhat more complex plan generation function, rebase implementation.
127
    return gen_revision_id(rev.committer, rev.timestamp)
128
129
0.441.4 by Robert Collins
* Fixed O(history) access during plan creation (Robert Collins, lp:#249823).
130
def generate_simple_plan(todo_set, start_revid, stop_revid, onto_revid, graph,
131
    generate_revid, skip_full_merged=False):
0.436.3 by Jelmer Vernooij
Fill in commands.
132
    """Create a simple rebase plan that replays history based 
0.436.6 by Jelmer Vernooij
Add somewhat more complex plan generation function, rebase implementation.
133
    on one revision being replayed on top of another.
0.436.3 by Jelmer Vernooij
Fill in commands.
134
0.441.4 by Robert Collins
* Fixed O(history) access during plan creation (Robert Collins, lp:#249823).
135
    :param todo_set: A set of revisions to rebase. Only the revisions from
136
        stop_revid back through the left hand ancestry are rebased; other
137
        revisions are ignored (and references to them are preserved).
0.436.6 by Jelmer Vernooij
Add somewhat more complex plan generation function, rebase implementation.
138
    :param start_revid: Id of revision at which to start replaying
0.438.3 by Jelmer Vernooij
Add stop_revid argumen to generate_simple_plan.
139
    :param stop_revid: Id of revision until which to stop replaying
0.436.6 by Jelmer Vernooij
Add somewhat more complex plan generation function, rebase implementation.
140
    :param onto_revid: Id of revision on top of which to replay
0.436.86 by Jelmer Vernooij
Fix some uses of get_revision_graph().
141
    :param graph: Graph object
0.436.6 by Jelmer Vernooij
Add somewhat more complex plan generation function, rebase implementation.
142
    :param generate_revid: Function for generating new revision ids
0.436.55 by Jelmer Vernooij
Add functinality for skipping duplicate merges.
143
    :param skip_full_merged: Skip revisions that merge already merged 
144
                             revisions.
0.436.3 by Jelmer Vernooij
Fill in commands.
145
0.436.4 by Jelmer Vernooij
Add some tests.
146
    :return: replace map
0.436.3 by Jelmer Vernooij
Fill in commands.
147
    """
0.441.4 by Robert Collins
* Fixed O(history) access during plan creation (Robert Collins, lp:#249823).
148
    assert start_revid is None or start_revid in todo_set, \
149
        "invalid start revid(%r), todo_set(%r)" % (start_revid, todo_set)
150
    assert stop_revid is None or stop_revid in todo_set, "invalid stop_revid"
0.436.6 by Jelmer Vernooij
Add somewhat more complex plan generation function, rebase implementation.
151
    replace_map = {}
0.441.4 by Robert Collins
* Fixed O(history) access during plan creation (Robert Collins, lp:#249823).
152
    parent_map = graph.get_parent_map(todo_set)
153
    order = topo_sort(parent_map)
154
    left_most_path = []
155
    if stop_revid is None:
156
        stop_revid = order[-1]
157
    rev = stop_revid
158
    while rev in parent_map:
159
        left_most_path.append(rev)
160
        if rev == start_revid:
161
            # manual specified early-stop
162
            break
163
        rev = parent_map[rev][0]
164
    left_most_path.reverse()
165
    if start_revid is None:
166
        # We need a common base.
167
        lca = graph.find_lca(stop_revid, onto_revid)
168
        if lca == set([NULL_REVISION]):
169
            raise UnrelatedBranches()
0.436.6 by Jelmer Vernooij
Add somewhat more complex plan generation function, rebase implementation.
170
    new_parent = onto_revid
0.441.4 by Robert Collins
* Fixed O(history) access during plan creation (Robert Collins, lp:#249823).
171
    todo = left_most_path
172
    heads_cache = FrozenHeadsCache(graph)
173
    # XXX: The output replacemap'd parents should get looked up in some manner
174
    # by the heads cache? RBC 20080719
175
    for oldrevid in todo:
0.436.86 by Jelmer Vernooij
Fix some uses of get_revision_graph().
176
        oldparents = parent_map[oldrevid]
177
        assert isinstance(oldparents, tuple), "not tuple: %r" % oldparents
0.436.55 by Jelmer Vernooij
Add functinality for skipping duplicate merges.
178
        if len(oldparents) > 1:
0.441.4 by Robert Collins
* Fixed O(history) access during plan creation (Robert Collins, lp:#249823).
179
            additional_parents = heads_cache.heads(oldparents[1:])
180
            parents = [new_parent]
181
            for parent in parents:
182
                if parent in additional_parents and parent not in parents:
183
                    # Use as a parent
184
                    parent = replace_map.get(parent, (parent,))[0]
185
                    parents.append(parent)
186
            parents = tuple(parents)
0.436.55 by Jelmer Vernooij
Add functinality for skipping duplicate merges.
187
            if len(parents) == 1 and skip_full_merged:
188
                continue
189
        else:
0.436.91 by Jelmer Vernooij
Fix blackbox tests, add comments to assertions.
190
            parents = (new_parent,)
0.436.39 by Jelmer Vernooij
Some more refactoring, add test that demonstrates #126743.
191
        newrevid = generate_revid(oldrevid)
0.436.91 by Jelmer Vernooij
Fix blackbox tests, add comments to assertions.
192
        assert newrevid != oldrevid, "old and newrevid equal (%r)" % newrevid
193
        assert isinstance(parents, tuple), "parents not tuple: %r" % parents
0.436.6 by Jelmer Vernooij
Add somewhat more complex plan generation function, rebase implementation.
194
        replace_map[oldrevid] = (newrevid, parents)
195
        new_parent = newrevid
196
    return replace_map
197
198
0.436.88 by Jelmer Vernooij
Avoid use of get_revision_graph() calls.
199
def generate_transpose_plan(ancestry, renames, graph, generate_revid):
0.436.31 by Jelmer Vernooij
Refactor generate_transpose_plan() to not take a repository object but
200
    """Create a rebase plan that replaces a bunch of revisions
201
    in a revision graph.
0.436.6 by Jelmer Vernooij
Add somewhat more complex plan generation function, rebase implementation.
202
0.436.88 by Jelmer Vernooij
Avoid use of get_revision_graph() calls.
203
    :param ancestry: Ancestry to consider
0.436.6 by Jelmer Vernooij
Add somewhat more complex plan generation function, rebase implementation.
204
    :param renames: Renames of revision
0.436.88 by Jelmer Vernooij
Avoid use of get_revision_graph() calls.
205
    :param graph: Graph object
0.436.6 by Jelmer Vernooij
Add somewhat more complex plan generation function, rebase implementation.
206
    :param generate_revid: Function for creating new revision ids
207
    """
208
    replace_map = {}
209
    todo = []
0.436.13 by Jelmer Vernooij
Add progress bar, some optimizations. Make merge type configurable.
210
    children = {}
0.436.88 by Jelmer Vernooij
Avoid use of get_revision_graph() calls.
211
    parent_map = {}
212
    for r, ps in ancestry:
0.436.118 by Jelmer Vernooij
Cope with ghosts in svn-upgrade.
213
        if not children.has_key(r):
214
            children[r] = []
215
        if ps is None: # Ghost
216
            continue
0.436.88 by Jelmer Vernooij
Avoid use of get_revision_graph() calls.
217
        parent_map[r] = ps
0.436.13 by Jelmer Vernooij
Add progress bar, some optimizations. Make merge type configurable.
218
        if not children.has_key(r):
219
            children[r] = []
0.436.88 by Jelmer Vernooij
Avoid use of get_revision_graph() calls.
220
        for p in ps:
0.436.13 by Jelmer Vernooij
Add progress bar, some optimizations. Make merge type configurable.
221
            if not children.has_key(p):
222
                children[p] = []
223
            children[p].append(r)
224
0.436.88 by Jelmer Vernooij
Avoid use of get_revision_graph() calls.
225
    parent_map.update(graph.get_parent_map(filter(lambda x: not x in parent_map, renames.values())))
226
0.436.31 by Jelmer Vernooij
Refactor generate_transpose_plan() to not take a repository object but
227
    # todo contains a list of revisions that need to 
228
    # be rewritten
0.436.88 by Jelmer Vernooij
Avoid use of get_revision_graph() calls.
229
    for r, v in renames.items():
230
        replace_map[r] = (v, parent_map[v])
0.436.31 by Jelmer Vernooij
Refactor generate_transpose_plan() to not take a repository object but
231
        todo.append(r)
232
0.436.13 by Jelmer Vernooij
Add progress bar, some optimizations. Make merge type configurable.
233
    total = len(todo)
234
    processed = set()
235
    i = 0
236
    pb = ui.ui_factory.nested_progress_bar()
237
    try:
238
        while len(todo) > 0:
239
            r = todo.pop()
0.436.123 by Jelmer Vernooij
Cope with revision ids not changing.
240
            processed.add(r)
0.436.13 by Jelmer Vernooij
Add progress bar, some optimizations. Make merge type configurable.
241
            i += 1
242
            pb.update('determining dependencies', i, total)
243
            # Add entry for them in replace_map
244
            for c in children[r]:
245
                if c in renames:
246
                    continue
247
                if replace_map.has_key(c):
0.436.89 by Jelmer Vernooij
Use tuples for parents.
248
                    parents = replace_map[c][1]
0.436.13 by Jelmer Vernooij
Add progress bar, some optimizations. Make merge type configurable.
249
                else:
0.436.89 by Jelmer Vernooij
Use tuples for parents.
250
                    parents = parent_map[c]
251
                assert isinstance(parents, tuple), \
252
                        "Expected tuple of parents, got: %r" % parents
0.436.13 by Jelmer Vernooij
Add progress bar, some optimizations. Make merge type configurable.
253
                # replace r in parents with replace_map[r][0]
254
                if not replace_map[r][0] in parents:
0.436.90 by Jelmer Vernooij
Deal with parents being a tuple.
255
                    parents = list(parents)
256
                    parents[parents.index(r)] = replace_map[r][0]
257
                    parents = tuple(parents)
0.436.89 by Jelmer Vernooij
Use tuples for parents.
258
                replace_map[c] = (generate_revid(c), tuple(parents))
0.436.123 by Jelmer Vernooij
Cope with revision ids not changing.
259
                if replace_map[c][0] == c:
0.436.124 by Jelmer Vernooij
Remove erroneus [0].
260
                    del replace_map[c]
0.436.123 by Jelmer Vernooij
Cope with revision ids not changing.
261
                elif c not in processed:
262
                    todo.append(c)
0.436.13 by Jelmer Vernooij
Add progress bar, some optimizations. Make merge type configurable.
263
    finally:
264
        pb.finished()
0.436.6 by Jelmer Vernooij
Add somewhat more complex plan generation function, rebase implementation.
265
0.436.31 by Jelmer Vernooij
Refactor generate_transpose_plan() to not take a repository object but
266
    # Remove items from the map that already exist
267
    for revid in renames:
268
        if replace_map.has_key(revid):
269
            del replace_map[revid]
270
0.436.6 by Jelmer Vernooij
Add somewhat more complex plan generation function, rebase implementation.
271
    return replace_map
272
273
0.436.9 by Jelmer Vernooij
Add rebase-todo command, fix rebase-continue.
274
def rebase_todo(repository, replace_map):
275
    """Figure out what revisions still need to be rebased.
276
277
    :param repository: Repository that contains the revisions
278
    :param replace_map: Replace map
279
    """
0.436.91 by Jelmer Vernooij
Fix blackbox tests, add comments to assertions.
280
    for revid, parent_ids in replace_map.items():
281
        assert isinstance(parent_ids, tuple), "replace map parents not tuple"
282
        if not repository.has_revision(parent_ids[0]):
0.436.9 by Jelmer Vernooij
Add rebase-todo command, fix rebase-continue.
283
            yield revid
284
285
0.436.6 by Jelmer Vernooij
Add somewhat more complex plan generation function, rebase implementation.
286
def rebase(repository, replace_map, replay_fn):
0.436.5 by Jelmer Vernooij
Import change_revision_parent from bzr-svn.
287
    """Rebase a working tree according to the specified map.
288
0.436.6 by Jelmer Vernooij
Add somewhat more complex plan generation function, rebase implementation.
289
    :param repository: Repository that contains the revisions
0.436.5 by Jelmer Vernooij
Import change_revision_parent from bzr-svn.
290
    :param replace_map: Dictionary with revisions to (optionally) rewrite
0.436.6 by Jelmer Vernooij
Add somewhat more complex plan generation function, rebase implementation.
291
    :param merge_fn: Function for replaying a revision
0.436.5 by Jelmer Vernooij
Import change_revision_parent from bzr-svn.
292
    """
0.436.6 by Jelmer Vernooij
Add somewhat more complex plan generation function, rebase implementation.
293
    # Figure out the dependencies
0.436.127 by Jelmer Vernooij
Use standard graph functions.
294
    graph = repository.get_graph()
295
    todo = list(graph.iter_topo_order(replace_map.keys()))
0.436.125 by Jelmer Vernooij
Use single call to find present revisions.
296
    pb = ui.ui_factory.nested_progress_bar()
0.436.6 by Jelmer Vernooij
Add somewhat more complex plan generation function, rebase implementation.
297
    try:
0.436.127 by Jelmer Vernooij
Use standard graph functions.
298
        for i, revid in enumerate(todo):
299
            pb.update('rebase revisions', i, len(todo))
0.436.6 by Jelmer Vernooij
Add somewhat more complex plan generation function, rebase implementation.
300
            (newrevid, newparents) = replace_map[revid]
0.436.91 by Jelmer Vernooij
Fix blackbox tests, add comments to assertions.
301
            assert isinstance(newparents, tuple), "Expected tuple for %r" % newparents
0.436.6 by Jelmer Vernooij
Add somewhat more complex plan generation function, rebase implementation.
302
            if repository.has_revision(newrevid):
303
                # Was already converted, no need to worry about it again
304
                continue
305
            replay_fn(repository, revid, newrevid, newparents)
306
    finally:
307
        pb.finished()
308
        
0.436.32 by Jelmer Vernooij
Properly detect invalid snapshot replays.
309
0.436.121 by Jelmer Vernooij
Simplify replay snapshot functions.
310
def replay_snapshot(repository, oldrevid, newrevid, new_parents):
0.436.32 by Jelmer Vernooij
Properly detect invalid snapshot replays.
311
    """Replay a commit by simply commiting the same snapshot with different 
312
    parents.
0.436.5 by Jelmer Vernooij
Import change_revision_parent from bzr-svn.
313
314
    :param repository: Repository in which the revision is present.
315
    :param oldrevid: Revision id of the revision to copy.
316
    :param newrevid: Revision id of the revision to create.
317
    :param new_parents: Revision ids of the new parent revisions.
318
    """
0.436.91 by Jelmer Vernooij
Fix blackbox tests, add comments to assertions.
319
    assert isinstance(new_parents, tuple), "replay_snapshot: Expected tuple for %r" % new_parents
0.436.16 by Jelmer Vernooij
Some more work on maptree.
320
    mutter('creating copy %r of %r with new parents %r' % 
321
                               (newrevid, oldrevid, new_parents))
0.436.5 by Jelmer Vernooij
Import change_revision_parent from bzr-svn.
322
    oldrev = repository.get_revision(oldrevid)
323
0.436.7 by Jelmer Vernooij
Add more test, make basic rebase work.
324
    revprops = dict(oldrev.properties)
0.436.27 by Jelmer Vernooij
Note revision property 'rebase-of', add explanation of use of pregenerated revision ids.
325
    revprops[REVPROP_REBASE_OF] = oldrevid
0.436.7 by Jelmer Vernooij
Add more test, make basic rebase work.
326
0.436.49 by Jelmer Vernooij
Fix locking.
327
    builder = repository.get_commit_builder(branch=None, 
328
                                            parents=new_parents, 
329
                                            config=Config(),
330
                                            committer=oldrev.committer,
331
                                            timestamp=oldrev.timestamp,
332
                                            timezone=oldrev.timezone,
333
                                            revprops=revprops,
334
                                            revision_id=newrevid)
0.436.5 by Jelmer Vernooij
Import change_revision_parent from bzr-svn.
335
    try:
0.436.47 by Jelmer Vernooij
Add progress bar, fix compatibility with bzr.dev.
336
        # Check what new_ie.file_id should be
337
        # use old and new parent inventories to generate new_id map
0.436.128 by Jelmer Vernooij
Deal with ghost parents in svn-upgrade.
338
        nonghost_oldparents = tuple([p for p in oldrev.parent_ids if repository.has_revision(p)])
339
        nonghost_newparents = tuple([p for p in new_parents if repository.has_revision(p)])
340
        fileid_map = map_file_ids(repository, nonghost_oldparents, nonghost_newparents)
0.436.121 by Jelmer Vernooij
Simplify replay snapshot functions.
341
        oldtree = repository.revision_tree(oldrevid)
342
        mappedtree = MapTree(oldtree, fileid_map)
0.436.47 by Jelmer Vernooij
Add progress bar, fix compatibility with bzr.dev.
343
        pb = ui.ui_factory.nested_progress_bar()
344
        try:
0.436.128 by Jelmer Vernooij
Deal with ghost parents in svn-upgrade.
345
            old_parent_invs = list(repository.iter_inventories(nonghost_oldparents))
346
            new_parent_invs = list(repository.iter_inventories(nonghost_newparents))
0.436.121 by Jelmer Vernooij
Simplify replay snapshot functions.
347
            for i, (path, old_ie) in enumerate(mappedtree.inventory.iter_entries()):
348
                pb.update('upgrading file', i, len(mappedtree.inventory))
0.436.120 by Jelmer Vernooij
Simplify.
349
                ie = old_ie.copy()
0.436.47 by Jelmer Vernooij
Add progress bar, fix compatibility with bzr.dev.
350
                # Either this file was modified last in this revision, 
351
                # in which case it has to be rewritten
0.436.121 by Jelmer Vernooij
Simplify replay snapshot functions.
352
                if old_ie.revision == oldrevid:
353
                    if repository.texts.has_key((ie.file_id, newrevid)):
354
                        # Use the existing text
0.436.47 by Jelmer Vernooij
Add progress bar, fix compatibility with bzr.dev.
355
                        ie.revision = newrevid
356
                    else:
0.436.121 by Jelmer Vernooij
Simplify replay snapshot functions.
357
                        # Create a new text
0.436.47 by Jelmer Vernooij
Add progress bar, fix compatibility with bzr.dev.
358
                        ie.revision = None
359
                else:
360
                    # or it was already there before the commit, in 
361
                    # which case the right revision should be used
0.436.121 by Jelmer Vernooij
Simplify replay snapshot functions.
362
                    # one of the old parents had this revision, so find that
363
                    # and then use the matching new parent
364
                    old_file_id = oldtree.inventory.path2id(path)
365
                    assert old_file_id is not None
366
                    ie = None
367
                    for (old_pinv, new_pinv) in zip(old_parent_invs, new_parent_invs):
368
                        if (old_pinv.has_id(old_file_id) and
369
                            old_pinv[old_file_id].revision == old_ie.revision):
370
                            try:
371
                                ie = new_pinv[old_ie.file_id].copy()
372
                            except NoSuchId:
373
                                raise ReplayParentsInconsistent(old_ie.file_id, old_ie.revision)
374
                            break
375
                    assert ie is not None
376
                builder.record_entry_contents(ie, new_parent_invs, path, mappedtree,
377
                        mappedtree.path_content_summary(path))
0.436.47 by Jelmer Vernooij
Add progress bar, fix compatibility with bzr.dev.
378
        finally:
379
            pb.finished()
380
        builder.finish_inventory()
0.436.62 by Jelmer Vernooij
Fix compatibility with packs.
381
        return builder.commit(oldrev.message)
0.436.47 by Jelmer Vernooij
Add progress bar, fix compatibility with bzr.dev.
382
    except:
0.436.62 by Jelmer Vernooij
Fix compatibility with packs.
383
        builder.abort()
0.436.47 by Jelmer Vernooij
Add progress bar, fix compatibility with bzr.dev.
384
        raise
0.436.5 by Jelmer Vernooij
Import change_revision_parent from bzr-svn.
385
386
0.436.9 by Jelmer Vernooij
Add rebase-todo command, fix rebase-continue.
387
def commit_rebase(wt, oldrev, newrevid):
388
    """Commit a rebase.
389
    
390
    :param wt: Mutable tree with the changes.
391
    :param oldrev: Revision info of new revision to commit.
392
    :param newrevid: New revision id."""
0.436.91 by Jelmer Vernooij
Fix blackbox tests, add comments to assertions.
393
    assert oldrev.revision_id != newrevid, "Invalid revid %r" % newrevid
0.436.9 by Jelmer Vernooij
Add rebase-todo command, fix rebase-continue.
394
    revprops = dict(oldrev.properties)
0.436.27 by Jelmer Vernooij
Note revision property 'rebase-of', add explanation of use of pregenerated revision ids.
395
    revprops[REVPROP_REBASE_OF] = oldrev.revision_id
0.439.3 by Lukáš Lalinský
Copy author or committer name from the old revision to the author property in the new revision
396
    committer = wt.branch.get_config().username()
0.436.135 by Jelmer Vernooij
Remove use of deprecated Revision.get_apparent_author().
397
    authors = oldrev.get_apparent_authors()
398
    if oldrev.committer == committer:
399
        # No need to explicitly record the authors if the original 
400
        # committer is rebasing.
401
        if [oldrev.committer] == authors:
402
            authors = None
403
    else:
404
        authors.append(oldrev.committer)
0.436.136 by Jelmer Vernooij
Avoid setting authors property twice.
405
    if 'author' in revprops:
406
        del revprops['author']
407
    if 'authors' in revprops:
408
        del revprops['authors']
0.436.37 by Jelmer Vernooij
Store parents correctly.
409
    wt.commit(message=oldrev.message, timestamp=oldrev.timestamp, 
0.439.3 by Lukáš Lalinský
Copy author or committer name from the old revision to the author property in the new revision
410
              timezone=oldrev.timezone, revprops=revprops, rev_id=newrevid,
0.436.135 by Jelmer Vernooij
Remove use of deprecated Revision.get_apparent_author().
411
              committer=committer, authors=authors)
0.436.9 by Jelmer Vernooij
Add rebase-todo command, fix rebase-continue.
412
    write_active_rebase_revid(wt, None)
413
414
0.436.54 by Jelmer Vernooij
Move determination of merge base to separate function.
415
def replay_determine_base(graph, oldrevid, oldparents, newrevid, newparents):
0.436.74 by Jelmer Vernooij
Add pydoctor file, more docstrings.
416
    """Determine the base for replaying a revision using merge.
417
418
    :param graph: Revision graph.
419
    :param oldrevid: Revid of old revision.
420
    :param oldparents: List of old parents revids.
421
    :param newrevid: Revid of new revision.
422
    :param newparents: List of new parents revids.
423
    :return: Revision id of the new new revision.
424
    """
0.436.54 by Jelmer Vernooij
Move determination of merge base to separate function.
425
    # If this was the first commit, no base is needed
426
    if len(oldparents) == 0:
427
        return NULL_REVISION
428
429
    # In the case of a "simple" revision with just one parent, 
430
    # that parent should be the base
431
    if len(oldparents) == 1:
432
        return oldparents[0]
433
0.436.55 by Jelmer Vernooij
Add functinality for skipping duplicate merges.
434
    # In case the rhs parent(s) of the origin revision has already been merged
435
    # in the new branch, use diff between rhs parent and diff from 
436
    # original revision
437
    if len(newparents) == 1:
438
        # FIXME: Find oldparents entry that matches newparents[0] 
439
        # and return it
440
        return oldparents[1]
441
0.436.57 by Jelmer Vernooij
Allow overridding whether merges of already merged revisions should be replayed.
442
    try:
443
        return graph.find_unique_lca(*[oldparents[0],newparents[1]])
444
    except NoCommonAncestor:
445
        return oldparents[0]
0.436.54 by Jelmer Vernooij
Move determination of merge base to separate function.
446
447
0.438.1 by Jelmer Vernooij
Split out function for determining rebase base.
448
def replay_delta_workingtree(wt, oldrevid, newrevid, newparents, 
0.438.2 by Jelmer Vernooij
More work using proper merge bases.
449
                             merge_type=None):
0.436.7 by Jelmer Vernooij
Add more test, make basic rebase work.
450
    """Replay a commit in a working tree, with a different base.
451
452
    :param wt: Working tree in which to do the replays.
453
    :param oldrevid: Old revision id
454
    :param newrevid: New revision id
455
    :param newparents: New parent revision ids
456
    """
457
    repository = wt.branch.repository
458
    if merge_type is None:
459
        from bzrlib.merge import Merge3Merger
460
        merge_type = Merge3Merger
461
    oldrev = wt.branch.repository.get_revision(oldrevid)
462
    # Make sure there are no conflicts or pending merges/changes 
463
    # in the working tree
0.438.2 by Jelmer Vernooij
More work using proper merge bases.
464
    complete_revert(wt, [newparents[0]])
0.436.91 by Jelmer Vernooij
Fix blackbox tests, add comments to assertions.
465
    assert not wt.changes_from(wt.basis_tree()).has_changed(), "Changes in rev"
0.436.7 by Jelmer Vernooij
Add more test, make basic rebase work.
466
467
    oldtree = repository.revision_tree(oldrevid)
0.436.9 by Jelmer Vernooij
Add rebase-todo command, fix rebase-continue.
468
    write_active_rebase_revid(wt, oldrevid)
0.438.2 by Jelmer Vernooij
More work using proper merge bases.
469
    merger = Merger(wt.branch, this_tree=wt)
470
    merger.set_other_revision(oldrevid, wt.branch)
0.441.3 by Robert Collins
Update rebase to 1.6b3 API changes.
471
    base_revid = replay_determine_base(repository.get_graph(),
0.436.54 by Jelmer Vernooij
Move determination of merge base to separate function.
472
                                       oldrevid, oldrev.parent_ids,
473
                                       newrevid, newparents)
0.441.3 by Robert Collins
Update rebase to 1.6b3 API changes.
474
    mutter('replaying %r as %r with base %r and new parents %r' %
0.436.55 by Jelmer Vernooij
Add functinality for skipping duplicate merges.
475
           (oldrevid, newrevid, base_revid, newparents))
0.436.54 by Jelmer Vernooij
Move determination of merge base to separate function.
476
    merger.set_base_revision(base_revid, wt.branch)
0.438.2 by Jelmer Vernooij
More work using proper merge bases.
477
    merger.merge_type = merge_type
478
    merger.do_merge()
479
    for newparent in newparents[1:]:
480
        wt.add_pending_merge(newparent)
0.436.9 by Jelmer Vernooij
Add rebase-todo command, fix rebase-continue.
481
    commit_rebase(wt, oldrev, newrevid)
0.436.8 by Jelmer Vernooij
Couple more minor fixes.
482
0.436.10 by Jelmer Vernooij
Add more agressive version of revert.
483
0.436.13 by Jelmer Vernooij
Add progress bar, some optimizations. Make merge type configurable.
484
def workingtree_replay(wt, map_ids=False, merge_type=None):
0.436.6 by Jelmer Vernooij
Add somewhat more complex plan generation function, rebase implementation.
485
    """Returns a function that can replay revisions in wt.
486
487
    :param wt: Working tree in which to do the replays.
0.436.7 by Jelmer Vernooij
Add more test, make basic rebase work.
488
    :param map_ids: Whether to try to map between file ids (False for path-based merge)
0.436.6 by Jelmer Vernooij
Add somewhat more complex plan generation function, rebase implementation.
489
    """
490
    def replay(repository, oldrevid, newrevid, newparents):
0.436.91 by Jelmer Vernooij
Fix blackbox tests, add comments to assertions.
491
        assert wt.branch.repository == repository, "Different repository"
0.436.16 by Jelmer Vernooij
Some more work on maptree.
492
        return replay_delta_workingtree(wt, oldrevid, newrevid, newparents, 
493
                                        merge_type=merge_type)
0.436.6 by Jelmer Vernooij
Add somewhat more complex plan generation function, rebase implementation.
494
    return replay
0.436.7 by Jelmer Vernooij
Add more test, make basic rebase work.
495
0.436.9 by Jelmer Vernooij
Add rebase-todo command, fix rebase-continue.
496
497
def write_active_rebase_revid(wt, revid):
0.436.16 by Jelmer Vernooij
Some more work on maptree.
498
    """Write the id of the revision that is currently being rebased. 
499
500
    :param wt: Working Tree that is being used for the rebase.
501
    :param revid: Revision id to write
502
    """
0.436.9 by Jelmer Vernooij
Add rebase-todo command, fix rebase-continue.
503
    if revid is None:
504
        revid = NULL_REVISION
0.441.3 by Robert Collins
Update rebase to 1.6b3 API changes.
505
    assert type(revid) == str
506
    wt._transport.put_bytes(REBASE_CURRENT_REVID_FILENAME, revid)
0.436.9 by Jelmer Vernooij
Add rebase-todo command, fix rebase-continue.
507
0.436.10 by Jelmer Vernooij
Add more agressive version of revert.
508
0.436.9 by Jelmer Vernooij
Add rebase-todo command, fix rebase-continue.
509
def read_active_rebase_revid(wt):
0.436.16 by Jelmer Vernooij
Some more work on maptree.
510
    """Read the id of the revision that is currently being rebased.
511
512
    :param wt: Working Tree that is being used for the rebase.
513
    :return: Id of the revision that is being rebased.
514
    """
0.436.9 by Jelmer Vernooij
Add rebase-todo command, fix rebase-continue.
515
    try:
0.441.3 by Robert Collins
Update rebase to 1.6b3 API changes.
516
        text = wt._transport.get_bytes(REBASE_CURRENT_REVID_FILENAME).rstrip("\n")
0.436.9 by Jelmer Vernooij
Add rebase-todo command, fix rebase-continue.
517
        if text == NULL_REVISION:
518
            return None
519
        return text
520
    except NoSuchFile:
521
        return None
0.436.10 by Jelmer Vernooij
Add more agressive version of revert.
522
523
524
def complete_revert(wt, newparents):
0.436.16 by Jelmer Vernooij
Some more work on maptree.
525
    """Simple helper that reverts to specified new parents and makes sure none 
526
    of the extra files are left around.
527
528
    :param wt: Working tree to use for rebase
529
    :param newparents: New parents of the working tree
0.436.10 by Jelmer Vernooij
Add more agressive version of revert.
530
    """
531
    newtree = wt.branch.repository.revision_tree(newparents[0])
532
    delta = wt.changes_from(newtree)
533
    wt.branch.generate_revision_history(newparents[0])
0.436.138 by Jelmer Vernooij
Support replaying in empty branch.
534
    wt.set_parent_ids([r for r in newparents[:1] if r != NULL_REVISION])
0.436.10 by Jelmer Vernooij
Add more agressive version of revert.
535
    for (f, _, _) in delta.added:
536
        abs_path = wt.abspath(f)
537
        if osutils.lexists(abs_path):
0.436.38 by Jelmer Vernooij
Handle directories in revert.
538
            if osutils.isdir(abs_path):
539
                osutils.rmtree(abs_path)
540
            else:
541
                os.unlink(abs_path)
0.436.48 by Jelmer Vernooij
Add replay command.
542
    wt.revert(None, old_tree=newtree, backups=False)
0.436.91 by Jelmer Vernooij
Fix blackbox tests, add comments to assertions.
543
    assert not wt.changes_from(wt.basis_tree()).has_changed(), "Rev changed"
0.436.138 by Jelmer Vernooij
Support replaying in empty branch.
544
    wt.set_parent_ids([r for r in newparents if r != NULL_REVISION])
0.436.32 by Jelmer Vernooij
Properly detect invalid snapshot replays.
545
546
0.436.34 by Jelmer Vernooij
Some more tests.
547
class ReplaySnapshotError(BzrError):
0.436.74 by Jelmer Vernooij
Add pydoctor file, more docstrings.
548
    """Raised when replaying a snapshot failed."""
0.436.151 by Jelmer Vernooij
Rename message to msg because the first happens to have the same name as an attribute that is deprecated in python 2.6.
549
    _fmt = """Replaying the snapshot failed: %(msg)s."""
0.436.32 by Jelmer Vernooij
Properly detect invalid snapshot replays.
550
0.436.151 by Jelmer Vernooij
Rename message to msg because the first happens to have the same name as an attribute that is deprecated in python 2.6.
551
    def __init__(self, msg):
0.436.32 by Jelmer Vernooij
Properly detect invalid snapshot replays.
552
        BzrError.__init__(self)
0.436.151 by Jelmer Vernooij
Rename message to msg because the first happens to have the same name as an attribute that is deprecated in python 2.6.
553
        self.msg = msg
0.436.34 by Jelmer Vernooij
Some more tests.
554
555
556
class ReplayParentsInconsistent(BzrError):
0.436.74 by Jelmer Vernooij
Add pydoctor file, more docstrings.
557
    """Raised when parents were inconsistent."""
0.436.34 by Jelmer Vernooij
Some more tests.
558
    _fmt = """Parents were inconsistent while replaying commit for file id %(fileid)s, revision %(revid)s."""
559
560
    def __init__(self, fileid, revid):
561
        BzrError.__init__(self)
562
        self.fileid = fileid
563
        self.revid = revid