~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/fetch.py

  • Committer: Martin Pool
  • Date: 2005-09-13 01:37:23 UTC
  • Revision ID: mbp@sourcefrog.net-20050913013723-7e0026b48cbf08ff
- BROKEN: start refactoring fetch code to work well with weaves

Show diffs side-by-side

added added

removed removed

Lines of Context:
14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
 
17
import sys
17
18
import os
18
 
from cStringIO import StringIO
19
19
 
20
20
import bzrlib.errors
21
 
from bzrlib.trace import mutter, note, warning
22
 
from bzrlib.branch import Branch, INVENTORY_FILEID, ANCESTRY_FILEID
 
21
from bzrlib.trace import mutter, note
 
22
from bzrlib.branch import Branch
23
23
from bzrlib.progress import ProgressBar
24
 
from bzrlib.xml5 import serializer_v5
25
 
from bzrlib.osutils import sha_string, split_lines
26
 
from bzrlib.errors import NoSuchRevision
27
 
 
28
 
"""Copying of history from one branch to another.
29
 
 
30
 
The basic plan is that every branch knows the history of everything
31
 
that has merged into it.  As the first step of a merge, pull, or
32
 
branch operation we copy history from the source into the destination
33
 
branch.
34
 
 
35
 
The copying is done in a slightly complicated order.  We don't want to
36
 
add a revision to the store until everything it refers to is also
37
 
stored, so that if a revision is present we can totally recreate it.
38
 
However, we can't know what files are included in a revision until we
39
 
read its inventory.  Therefore, we first pull the XML and hold it in
40
 
memory until we've updated all of the files referenced.
41
 
"""
42
 
 
43
 
# TODO: Avoid repeatedly opening weaves so many times.
44
 
 
45
 
# XXX: This doesn't handle ghost (not present in branch) revisions at
46
 
# all yet.  I'm not sure they really should be supported.
47
 
 
48
 
# NOTE: This doesn't copy revisions which may be present but not
49
 
# merged into the last revision.  I'm not sure we want to do that.
50
 
 
51
 
# - get a list of revisions that need to be pulled in
52
 
# - for each one, pull in that revision file
53
 
#   and get the inventory, and store the inventory with right
54
 
#   parents.
55
 
# - and get the ancestry, and store that with right parents too
56
 
# - and keep a note of all file ids and version seen
57
 
# - then go through all files; for each one get the weave,
58
 
#   and add in all file versions
59
 
 
60
 
 
61
 
 
62
 
def greedy_fetch(to_branch, from_branch, revision=None, pb=None):
 
24
 
 
25
 
 
26
def greedy_fetch(to_branch, from_branch, revision, pb):
63
27
    f = Fetcher(to_branch, from_branch, revision, pb)
64
28
    return f.count_copied, f.failed_revisions
65
29
 
66
30
 
67
 
 
68
31
class Fetcher(object):
69
 
    """Pull revisions and texts from one branch to another.
70
 
 
71
 
    This doesn't update the destination's history; that can be done
72
 
    separately if desired.  
73
 
 
74
 
    revision_limit
75
 
        If set, pull only up to this revision_id.
76
 
 
77
 
    After running:
78
 
 
79
 
    last_revision -- if last_revision
80
 
        is given it will be that, otherwise the last revision of
81
 
        from_branch
82
 
 
83
 
    count_copied -- number of revisions copied
84
 
 
85
 
    count_texts -- number of file texts copied
86
 
    """
87
 
    def __init__(self, to_branch, from_branch, last_revision=None, pb=None):
 
32
    """Pull history from one branch to another."""
 
33
    def __init__(self, to_branch, from_branch, revision_limit=None, pb=None):
88
34
        self.to_branch = to_branch
89
 
        self.to_weaves = to_branch.weave_store
90
35
        self.from_branch = from_branch
91
 
        self.from_weaves = from_branch.weave_store
92
 
        self.failed_revisions = []
93
 
        self.count_copied = 0
94
 
        self.count_total = 0
95
 
        self.count_texts = 0
 
36
        self.revision_limit = revision_limit
96
37
        if pb is None:
97
38
            self.pb = bzrlib.ui.ui_factory.progress_bar()
98
39
        else:
99
40
            self.pb = pb
100
 
        self.last_revision = self._find_last_revision(last_revision)
101
 
        mutter('fetch up to rev {%s}', self.last_revision)
102
 
        revs_to_fetch = self._compare_ancestries()
103
 
        self._copy_revisions(revs_to_fetch)
104
 
        self.new_ancestry = revs_to_fetch
105
 
 
106
 
        
107
 
 
108
 
    def _find_last_revision(self, last_revision):
109
 
        """Find the limiting source revision.
110
 
 
111
 
        Every ancestor of that revision will be merged across.
112
 
 
113
 
        Returns the revision_id, or returns None if there's no history
114
 
        in the source branch."""
115
 
        self.pb.update('get source history')
116
 
        from_history = self.from_branch.revision_history()
117
 
        self.pb.update('get destination history')
118
 
        if last_revision:
119
 
            if last_revision not in from_history:
120
 
                raise NoSuchRevision(self.from_branch, last_revision)
121
 
            else:
122
 
                return last_revision
123
 
        elif from_history:
124
 
            return from_history[-1]
125
 
        else:
126
 
            return None                 # no history in the source branch
127
 
            
128
 
 
129
 
    def _compare_ancestries(self):
130
 
        """Get a list of revisions that must be copied.
131
 
 
132
 
        That is, every revision that's in the ancestry of the source
133
 
        branch and not in the destination branch."""
134
 
        self.pb.update('get source ancestry')
135
 
        self.from_ancestry = self.from_branch.get_ancestry(self.last_revision)
136
 
 
137
 
        dest_last_rev = self.to_branch.last_revision()
138
 
        self.pb.update('get destination ancestry')
139
 
        if dest_last_rev:
140
 
            dest_ancestry = self.to_branch.get_ancestry(dest_last_rev)
141
 
        else:
142
 
            dest_ancestry = []
143
 
        ss = set(dest_ancestry)
144
 
        to_fetch = []
145
 
        for rev_id in self.from_ancestry:
146
 
            if rev_id not in ss:
147
 
                to_fetch.append(rev_id)
 
41
        self._scan_histories()
 
42
        self.failed_revisions = []
 
43
        self.count_copied = 0
 
44
        self._copy()
 
45
 
 
46
 
 
47
    def _scan_histories(self):
 
48
        self.from_history = from_branch.revision_history()
 
49
        self.required_revisions = set(from_history)
 
50
        self.to_history = to_branch.revision_history()
 
51
        if self.revision_limit:
 
52
            raise NotImplementedError('sorry, revision_limit not handled yet')
 
53
        self.need_revisions = []
 
54
        for rev_id in self.from_history:
 
55
            if not has_revision(self.to_branch):
 
56
                self.need_revisions.append(rev_id)
148
57
                mutter('need to get revision {%s}', rev_id)
149
 
        mutter('need to get %d revisions in total', len(to_fetch))
150
 
        self.count_total = len(to_fetch)
151
 
        return to_fetch
152
 
                
153
 
 
154
 
 
155
 
    def _copy_revisions(self, revs_to_fetch):
156
 
        i = 0
157
 
        for rev_id in revs_to_fetch:
158
 
            i += 1
159
 
            if self.to_branch.has_revision(rev_id):
160
 
                continue
161
 
            self.pb.update('fetch revision', i, self.count_total)
162
 
            self._copy_one_revision(rev_id)
163
 
            self.count_copied += 1
164
 
 
165
 
 
166
 
    def _copy_one_revision(self, rev_id):
167
 
        """Copy revision and everything referenced by it."""
168
 
        mutter('copying revision {%s}', rev_id)
169
 
        rev_xml = self.from_branch.get_revision_xml(rev_id)
170
 
        inv_xml = self.from_branch.get_inventory_xml(rev_id)
171
 
        rev = serializer_v5.read_revision_from_string(rev_xml)
172
 
        inv = serializer_v5.read_inventory_from_string(inv_xml)
173
 
        assert rev.revision_id == rev_id
174
 
        assert rev.inventory_sha1 == sha_string(inv_xml)
175
 
        mutter('  commiter %s, %d parents',
176
 
               rev.committer,
177
 
               len(rev.parents))
178
 
        self._copy_new_texts(rev_id, inv)
179
 
        parent_ids = [x.revision_id for x in rev.parents]
180
 
        self._copy_inventory(rev_id, inv_xml, parent_ids)
181
 
        self._copy_ancestry(rev_id, parent_ids)
182
 
        self.to_branch.revision_store.add(StringIO(rev_xml), rev_id)
183
 
 
184
 
 
185
 
    def _copy_inventory(self, rev_id, inv_xml, parent_ids):
186
 
        self.to_weaves.add_text(INVENTORY_FILEID, rev_id,
187
 
                                split_lines(inv_xml), parent_ids)
188
 
 
189
 
 
190
 
    def _copy_ancestry(self, rev_id, parent_ids):
191
 
        ancestry_lines = self.from_weaves.get_lines(ANCESTRY_FILEID, rev_id)
192
 
        self.to_weaves.add_text(ANCESTRY_FILEID, rev_id, ancestry_lines,
193
 
                                parent_ids)
194
 
 
 
58
 
 
59
 
 
60
    def _copy(self):
 
61
        while self.need_revisions:
 
62
            rev_id = self.need_revisions.pop()
 
63
            mutter('try to get revision {%s}', rev_id)
 
64
 
 
65
    
195
66
        
196
 
    def _copy_new_texts(self, rev_id, inv):
197
 
        """Copy any new texts occuring in this revision."""
198
 
        # TODO: Rather than writing out weaves every time, hold them
199
 
        # in memory until everything's done?  But this way is nicer
200
 
        # if it's interrupted.
201
 
        for path, ie in inv.iter_entries():
202
 
            if ie.kind != 'file':
203
 
                continue
204
 
            if ie.text_version != rev_id:
205
 
                continue
206
 
            mutter('%s {%s} is changed in this revision',
207
 
                   path, ie.file_id)
208
 
            self._copy_one_text(rev_id, ie.file_id)
209
 
 
210
 
 
211
 
    def _copy_one_text(self, rev_id, file_id):
212
 
        """Copy one file text."""
213
 
        mutter('copy text version {%s} of file {%s}',
214
 
               rev_id, file_id)
215
 
        from_weave = self.from_weaves.get_weave(file_id)
216
 
        from_idx = from_weave.lookup(rev_id)
217
 
        from_parents = map(from_weave.idx_to_name, from_weave.parents(from_idx))
218
 
        text_lines = from_weave.get(from_idx)
219
 
        to_weave = self.to_weaves.get_weave_or_empty(file_id)
220
 
        to_parents = map(to_weave.lookup, from_parents)
221
 
        # it's ok to add even if the text is already there
222
 
        to_weave.add(rev_id, to_parents, text_lines)
223
 
        self.to_weaves.put_weave(file_id, to_weave)
224
 
        self.count_texts += 1
225
 
 
226
 
 
227
 
fetch = Fetcher
 
67
    
 
68
 
 
69
def has_revision(branch, revision_id):
 
70
    try:
 
71
        branch.get_revision_xml(revision_id)
 
72
        return True
 
73
    except bzrlib.errors.NoSuchRevision:
 
74
        return False
 
75
 
 
76
 
 
77
def old_greedy_fetch(to_branch, from_branch, revision=None, pb=None):
 
78
    """Copy all history from one branch to another.
 
79
 
 
80
    revision
 
81
        If set, copy only up to this point in the source branch.
 
82
 
 
83
    @returns: number copied, missing ids       
 
84
    """
 
85
    from_history = from_branch.revision_history()
 
86
    required_revisions = set(from_history)
 
87
    all_failed = set()
 
88
    if revision is not None:
 
89
        required_revisions.add(revision)
 
90
        try:
 
91
            rev_index = from_history.index(revision)
 
92
        except ValueError:
 
93
            rev_index = None
 
94
        if rev_index is not None:
 
95
            from_history = from_history[:rev_index + 1]
 
96
        else:
 
97
            from_history = [revision]
 
98
    to_history = to_branch.revision_history()
 
99
    missing = []
 
100
    for rev_id in from_history:
 
101
        if not has_revision(to_branch, rev_id):
 
102
            missing.append(rev_id)
 
103
 
 
104
    # recurse down through the revision graph, looking for things that
 
105
    # can't be found.
 
106
    count = 0
 
107
    while len(missing) > 0:
 
108
        installed, failed = to_branch.install_revisions(from_branch, 
 
109
                                                        revision_ids=missing,
 
110
                                                        pb=pb)
 
111
        count += installed
 
112
        required_failed = failed.intersection(required_revisions)
 
113
        if len(required_failed) > 0:
 
114
            raise bzrlib.errors.InstallFailed(required_failed)
 
115
        for rev_id in failed:
 
116
            note("Failed to install %s" % rev_id)
 
117
        all_failed.update(failed)
 
118
        new_missing = set() 
 
119
        for rev_id in missing:
 
120
            try:
 
121
                revision = from_branch.get_revision(rev_id)
 
122
            except bzrlib.errors.NoSuchRevision:
 
123
                if revision in from_history:
 
124
                    raise
 
125
                else:
 
126
                    continue
 
127
            for parent in [p.revision_id for p in revision.parents]:
 
128
                if not has_revision(to_branch, parent):
 
129
                    new_missing.add(parent)
 
130
        missing = new_missing
 
131
    return count, all_failed
 
132
 
 
133
 
 
134
def old_install_revisions(branch, other, revision_ids, pb):
 
135
    """Copy revisions from other branch into branch.
 
136
 
 
137
    This is a lower-level function used by a pull or a merge.  It
 
138
    incorporates some history from one branch into another, but
 
139
    does not update the revision history or operate on the working
 
140
    copy.
 
141
 
 
142
    revision_ids
 
143
        Sequence of revisions to copy.
 
144
 
 
145
    pb
 
146
        Progress bar for copying.
 
147
    """
 
148
    if False:
 
149
        if hasattr(other.revision_store, "prefetch"):
 
150
            other.revision_store.prefetch(revision_ids)
 
151
        if hasattr(other.inventory_store, "prefetch"):
 
152
            other.inventory_store.prefetch(revision_ids)
 
153
 
 
154
    if pb is None:
 
155
        pb = bzrlib.ui.ui_factory.progress_bar()
 
156
 
 
157
    revisions = []
 
158
    needed_texts = set()
 
159
    i = 0
 
160
 
 
161
    failures = set()
 
162
    for i, rev_id in enumerate(revision_ids):
 
163
        pb.update('fetching revision', i+1, len(revision_ids))
 
164
        try:
 
165
            rev = other.get_revision(rev_id)
 
166
        except bzrlib.errors.NoSuchRevision:
 
167
            failures.add(rev_id)
 
168
            continue
 
169
 
 
170
        revisions.append(rev)
 
171
        inv = other.get_inventory(rev_id)
 
172
        for key, entry in inv.iter_entries():
 
173
            if entry.text_id is None:
 
174
                continue
 
175
            if entry.text_id not in branch.text_store:
 
176
                needed_texts.add(entry.text_id)
 
177
 
 
178
    pb.clear()
 
179
 
 
180
    count, cp_fail = branch.text_store.copy_multi(other.text_store, 
 
181
                                                needed_texts)
 
182
    count, cp_fail = branch.inventory_store.copy_multi(other.inventory_store, 
 
183
                                                     revision_ids)
 
184
    count, cp_fail = branch.revision_store.copy_multi(other.revision_store, 
 
185
                                                    revision_ids,
 
186
                                                    permit_failure=True)
 
187
    assert len(cp_fail) == 0 
 
188
    return count, failures
 
189
 
 
190