File: pseudonyms.py

package info (click to toggle)
bzr-rewrite 0.6.0-1
  • links: PTS
  • area: main
  • in suites: squeeze
  • size: 252 kB
  • ctags: 256
  • sloc: python: 1,950; makefile: 45
file content (197 lines) | stat: -rw-r--r-- 6,084 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
# Copyright (C) 2009 by Jelmer Vernooij <jelmer@samba.org>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

"""Revision pseudonyms."""

from collections import defaultdict
import urllib

from bzrlib import (
    errors,
    foreign,
    ui,
    )


def parse_git_svn_id(text):
    (head, uuid) = text.rsplit(" ", 1)
    (full_url, rev) = head.rsplit("@", 1)
    return (full_url.encode("utf-8"), int(rev), uuid.encode("utf-8"))


class SubversionBranchUrlFinder(object):

    def __init__(self):
        self._roots = defaultdict(set)

    def find_root(self, uuid, url):
        for root in self._roots[uuid]:
            if url.startswith(root):
                return root
        try:
            from subvertpy.ra import RemoteAccess
        except ImportError:
            return None
        c = RemoteAccess(url)
        root = c.get_repos_root()
        self._roots[uuid].add(root)
        return root

    def find_branch_path(self, uuid, url):
        root = self.find_root(uuid, url)
        if root is None:
            return None
        assert url.startswith(root)
        return url[len(root):].strip("/")


svn_branch_path_finder = SubversionBranchUrlFinder()


def _extract_converted_from_revid(rev):
    if not "converted-from" in rev.properties:
        return

    for line in rev.properties.get("converted-from", "").splitlines():
        (kind, serialized_foreign_revid) = line.split(" ", 1)
        yield (kind, serialized_foreign_revid)


def _extract_cscvs(rev):
    """Older-style launchpad-cscvs import."""
    if not "cscvs-svn-branch-path" in rev.properties:
        return
    yield ("svn", "%s:%s:%s" % (
         rev.properties["cscvs-svn-repository-uuid"],
         rev.properties["cscvs-svn-revision-number"],
         urllib.quote(rev.properties["cscvs-svn-branch-path"].strip("/"))))


def _extract_git_svn_id(rev):
    if not "git-svn-id" in rev.properties:
        return
    (full_url, revnum, uuid) = parse_git_svn_id(rev.properties['git-svn-id'])
    branch_path = svn_branch_path_finder.find_branch_path(uuid, full_url)
    if branch_path is not None:
        yield ("svn", "%s:%d:%s" % (uuid, revnum, urllib.quote(branch_path)))


def _extract_foreign_revision(rev):
    # Perhaps 'rev' is a foreign revision ?
    if getattr(rev, "foreign_revid", None) is not None:
        yield ("svn", rev.mapping.vcs.serialize_foreign_revid(rev.foreign_revid))


def _extract_foreign_revid(rev):
    # Try parsing the revision id
    try:
        foreign_revid, mapping = \
            foreign.foreign_vcs_registry.parse_revision_id(rev.revision_id)
    except errors.InvalidRevisionId:
        pass
    else:
        yield (mapping.vcs.abbreviation,
            mapping.vcs.serialize_foreign_revid(foreign_revid))



_foreign_revid_extractors = [
    _extract_converted_from_revid,
    _extract_cscvs,
    _extract_git_svn_id,
    _extract_foreign_revision,
    _extract_foreign_revid,
    ]


def extract_foreign_revids(rev):
    """Find ids of semi-equivalent revisions in foreign VCS'es.

    :param: Bazaar revision object
    :return: Set with semi-equivalent revisions.
    """
    ret = set()
    for extractor in _foreign_revid_extractors:
        ret.update(extractor(rev))
    return ret


def find_pseudonyms(repository, revids):
    """Find revisions that are pseudonyms of each other.

    :param repository: Repository object
    :param revids: Sequence of revision ids to check
    :return: Iterable over sets of pseudonyms
    """
    # Where have foreign revids ended up?
    conversions = defaultdict(set)
    # What are native revids conversions of?
    conversion_of = defaultdict(set)
    revs = repository.get_revisions(revids)
    pb = ui.ui_factory.nested_progress_bar()
    try:
        for i, rev in enumerate(revs):
            pb.update("finding pseudonyms", i, len(revs))
            for foreign_revid in extract_foreign_revids(rev):
                conversion_of[rev.revision_id].add(foreign_revid)
                conversions[foreign_revid].add(rev.revision_id)
    finally:
        pb.finished()
    done = set()
    for foreign_revid in conversions.keys():
        ret = set()
        check = set(conversions[foreign_revid])
        while check:
            x = check.pop()
            extra = set()
            for frevid in conversion_of[x]:
                extra.update(conversions[frevid])
                del conversions[frevid]
            del conversion_of[x]
            check.update(extra)
            ret.add(x)
        if len(ret) > 1:
            yield ret


def pseudonyms_as_dict(l):
    """Convert an iterable over pseudonyms to a dictionary.

    :param l: Iterable over sets of pseudonyms
    :return: Dictionary with pseudonyms for each revid.
    """
    ret = {}
    for pns in l:
        for pn in pns:
            ret[pn] = pns - set([pn])
    return ret


def generate_rebase_map_from_pseudonyms(pseudonym_dict, existing, desired):
    """Create a rebase map from pseudonyms and existing/desired ancestry.

    :param pseudonym_dict: Dictionary with pseudonym as returned by
        pseudonyms_as_dict()
    :param existing: Existing ancestry, might need to be rebased
    :param desired: Desired ancestry
    :return: rebase map, as dictionary
    """
    rebase_map = {}
    for revid in existing:
        for pn in pseudonym_dict.get(revid, []):
            if pn in desired:
                rebase_map[revid] = pn
    return rebase_map