Debian Codegraph @

hgext/convert/bzr.py

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 # bzr.py - bzr support for the convert extension
2 #
3 # Copyright 2008, 2009 Marek Kubica <[email protected]> and others
4 #
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
7
8 # This module is for handling Breezy imports or `brz`, but it's also compatible
9 # with Bazaar or `bzr`, that was formerly known as Bazaar-NG;
10 # it cannot access `bar` repositories, but they were never used very much.
11
12 from __future__ import annotations
13
14 import os
15
16 from mercurial.i18n import _
17 from mercurial import (
18 demandimport,
19 error,
20 util,
21 )
22 from . import common
23
24
25 # these do not work with demandimport, blacklist
26 demandimport.IGNORES.update(
27 [
28 'breezy.transactions',
29 'breezy.urlutils',
30 'ElementPath',
31 ]
32 )
33
34 try:
35 # bazaar imports
36 # pytype: disable=import-error
37 import breezy.bzr.bzrdir
38 import breezy.errors
39 import breezy.revision
40 import breezy.revisionspec
41
42 # pytype: enable=import-error
43
44 bzrdir = breezy.bzr.bzrdir
45 errors = breezy.errors
46 revision = breezy.revision
47 revisionspec = breezy.revisionspec
48 revisionspec.RevisionSpec
49
50 try:
51 # brz 3.3.0 (revno: 7614.2.2)
52 from breezy.transport import NoSuchFile
53 except ImportError:
54 from breezy.errors import NoSuchFile
55 except ImportError:
56 pass
57
58 supportedkinds = ('file', 'symlink')
59
60
61 class bzr_source(common.converter_source):
62 """Reads Bazaar repositories by using the Bazaar Python libraries"""
63
64 def __init__(self, ui, repotype, path, revs=None):
65 super().__init__(ui, repotype, path, revs=revs)
66
67 if not os.path.exists(os.path.join(path, b'.bzr')):
68 raise common.NoRepo(
69 _(b'%s does not look like a Bazaar repository') % path
70 )
71
72 try:
73 # access breezy stuff
74 bzrdir
75 except NameError:
76 raise common.NoRepo(_(b'Bazaar modules could not be loaded'))
77
78 path = util.abspath(path)
79 self._checkrepotype(path)
80 try:
81 bzr_dir = bzrdir.BzrDir.open(path.decode())
82 self.sourcerepo = bzr_dir.open_repository()
83 except errors.NoRepositoryPresent:
84 raise common.NoRepo(
85 _(b'%s does not look like a Bazaar repository') % path
86 )
87 self._parentids = {}
88 self._saverev = ui.configbool(b'convert', b'bzr.saverev')
89
90 def _checkrepotype(self, path):
91 # Lightweight checkouts detection is informational but probably
92 # fragile at API level. It should not terminate the conversion.
93 try:
94 dir = bzrdir.BzrDir.open_containing(path.decode())[0]
95 try:
96 tree = dir.open_workingtree(recommend_upgrade=False)
97 branch = tree.branch
98 except (errors.NoWorkingTree, errors.NotLocalUrl):
99 tree = None
100 branch = dir.open_branch()
101 if (
102 tree is not None
103 and tree.controldir.root_transport.base
104 != branch.controldir.root_transport.base
105 ):
106 self.ui.warn(
107 _(
108 b'warning: lightweight checkouts may cause '
109 b'conversion failures, try with a regular '
110 b'branch instead.\n'
111 )
112 )
113 except Exception:
114 self.ui.note(_(b'bzr source type could not be determined\n'))
115
116 def before(self):
117 """Before the conversion begins, acquire a read lock
118 for all the operations that might need it. Fortunately
119 read locks don't block other reads or writes to the
120 repository, so this shouldn't have any impact on the usage of
121 the source repository.
122
123 The alternative would be locking on every operation that
124 needs locks (there are currently two: getting the file and
125 getting the parent map) and releasing immediately after,
126 but this approach can take even 40% longer."""
127 self.sourcerepo.lock_read()
128
129 def after(self):
130 self.sourcerepo.unlock()
131
132 def _bzrbranches(self):
133 return self.sourcerepo.find_branches(using=True)
134
135 def getheads(self):
136 if not self.revs:
137 # Set using=True to avoid nested repositories (see issue3254)
138 heads = sorted([b.last_revision() for b in self._bzrbranches()])
139 else:
140 revid = None
141 for branch in self._bzrbranches():
142 try:
143 revspec = self.revs[0].decode()
144 r = revisionspec.RevisionSpec.from_string(revspec)
145 info = r.in_history(branch)
146 except errors.BzrError:
147 pass
148 revid = info.rev_id
149 if revid is None:
150 raise error.Abort(
151 _(b'%s is not a valid revision') % self.revs[0]
152 )
153 heads = [revid]
154 # Empty repositories return 'null:', which cannot be retrieved
155 heads = [h for h in heads if h != b'null:']
156 return heads
157
158 def getfile(self, name, rev):
159 name = name.decode()
160 revtree = self.sourcerepo.revision_tree(rev)
161
162 try:
163 kind = revtree.kind(name)
164 except NoSuchFile:
165 return None, None
166 if kind not in supportedkinds:
167 # the file is not available anymore - was deleted
168 return None, None
169 mode = self._modecache[(name.encode(), rev)]
170 if kind == 'symlink':
171 target = revtree.get_symlink_target(name)
172 if target is None:
173 raise error.Abort(
174 _(b'%s.%s symlink has no target') % (name, rev)
175 )
176 return target.encode(), mode
177 else:
178 sio = revtree.get_file(name)
179 return sio.read(), mode
180
181 def getchanges(self, version, full):
182 if full:
183 raise error.Abort(_(b"convert from cvs does not support --full"))
184 self._modecache = {}
185 self._revtree = self.sourcerepo.revision_tree(version)
186 # get the parentids from the cache
187 parentids = self._parentids.pop(version)
188 # only diff against first parent id
189 prevtree = self.sourcerepo.revision_tree(parentids[0])
190 files, changes = self._gettreechanges(self._revtree, prevtree)
191 return files, changes, set()
192
193 def getcommit(self, version):
194 rev = self.sourcerepo.get_revision(version)
195 # populate parent id cache
196 if not rev.parent_ids:
197 parents = []
198 self._parentids[version] = (revision.NULL_REVISION,)
199 else:
200 parents = self._filterghosts(rev.parent_ids)
201 self._parentids[version] = parents
202
203 branch = rev.properties.get('branch-nick', 'default')
204 if branch == 'trunk':
205 branch = 'default'
206 return common.commit(
207 parents=parents,
208 date=b'%d %d' % (rev.timestamp, -rev.timezone),
209 author=self.recode(rev.committer),
210 desc=self.recode(rev.message),
211 branch=branch.encode('utf8'),
212 rev=version,
213 saverev=self._saverev,
214 )
215
216 def gettags(self):
217 bytetags = {}
218 for branch in self._bzrbranches():
219 if not branch.supports_tags():
220 return {}
221 tagdict = branch.tags.get_tag_dict()
222 for name, rev in tagdict.items():
223 bytetags[self.recode(name)] = rev
224 return bytetags
225
226 def getchangedfiles(self, rev, i):
227 self._modecache = {}
228 curtree = self.sourcerepo.revision_tree(rev)
229 if i is not None:
230 parentid = self._parentids[rev][i]
231 else:
232 # no parent id, get the empty revision
233 parentid = revision.NULL_REVISION
234
235 prevtree = self.sourcerepo.revision_tree(parentid)
236 changes = [e[0] for e in self._gettreechanges(curtree, prevtree)[0]]
237 return changes
238
239 def _gettreechanges(self, current, origin):
240 revid = current._revision_id
241 changes = []
242 renames = {}
243 seen = set()
244
245 # Fall back to the deprecated attribute for legacy installations.
246 try:
247 inventory = origin.root_inventory
248 except AttributeError:
249 inventory = origin.inventory
250
251 # Process the entries by reverse lexicographic name order to
252 # handle nested renames correctly, most specific first.
253
254 def key(c):
255 return c.path[0] or c.path[1] or ""
256
257 curchanges = sorted(
258 current.iter_changes(origin),
259 key=key,
260 reverse=True,
261 )
262 for change in curchanges:
263 paths = change.path
264 kind = change.kind
265 executable = change.executable
266 if paths[0] == '' or paths[1] == '':
267 # ignore changes to tree root
268 continue
269
270 # bazaar tracks directories, mercurial does not, so
271 # we have to rename the directory contents
272 if kind[1] == 'directory':
273 if kind[0] not in (None, 'directory'):
274 # Replacing 'something' with a directory, record it
275 # so it can be removed.
276 changes.append((self.recode(paths[0]), revid))
277
278 if kind[0] == 'directory' and None not in paths:
279 renaming = paths[0] != paths[1]
280 # neither an add nor an delete - a move
281 # rename all directory contents manually
282 subdir = inventory.path2id(paths[0])
283 # get all child-entries of the directory
284 for name, entry in inventory.iter_entries(subdir):
285 # hg does not track directory renames
286 if entry.kind == 'directory':
287 continue
288 frompath = self.recode(paths[0] + '/' + name)
289 if frompath in seen:
290 # Already handled by a more specific change entry
291 # This is important when you have:
292 # a => b
293 # a/c => a/c
294 # Here a/c must not be renamed into b/c
295 continue
296 seen.add(frompath)
297 if not renaming:
298 continue
299 topath = self.recode(paths[1] + '/' + name)
300 # register the files as changed
301 changes.append((frompath, revid))
302 changes.append((topath, revid))
303 # add to mode cache
304 mode = (
305 (entry.executable and b'x')
306 or (entry.kind == 'symlink' and b's')
307 or b''
308 )
309 self._modecache[(topath, revid)] = mode
310 # register the change as move
311 renames[topath] = frompath
312
313 # no further changes, go to the next change
314 continue
315
316 # we got unicode paths, need to convert them
317 path, topath = paths
318 if path is not None:
319 path = self.recode(path)
320 if topath is not None:
321 topath = self.recode(topath)
322 seen.add(path or topath)
323
324 if topath is None:
325 # file deleted
326 changes.append((path, revid))
327 continue
328
329 # renamed
330 if path and path != topath:
331 renames[topath] = path
332 changes.append((path, revid))
333
334 # populate the mode cache
335 kind, executable = (e[1] for e in (kind, executable))
336 mode = (executable and b'x') or (kind == 'symlink' and b'l') or b''
337 self._modecache[(topath, revid)] = mode
338 changes.append((topath, revid))
339
340 return changes, renames
341
342 def _filterghosts(self, ids):
343 """Filters out ghost revisions which hg does not support, see
344 <http://bazaar-vcs.org/GhostRevision>
345 """
346 parentmap = self.sourcerepo.get_parent_map(ids)
347 parents = tuple([parent for parent in ids if parent in parentmap])
348 return parents