Debian Codegraph @

hgext/convert/gnuarch.py

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 # gnuarch.py - GNU Arch support for the convert extension
2 #
3 # Copyright 2008, 2009 Aleix Conchillo Flaque <[email protected]>
4 # and others
5 #
6 # This software may be used and distributed according to the terms of the
7 # GNU General Public License version 2 or any later version.
8
9 from __future__ import annotations
10
11 import os
12 import shutil
13 import stat
14 import tempfile
15
16 from mercurial.i18n import _
17 from mercurial import (
18 encoding,
19 error,
20 mail,
21 pycompat,
22 util,
23 )
24 from mercurial.utils import (
25 dateutil,
26 procutil,
27 )
28 from . import common
29
30
31 class gnuarch_source(common.converter_source, common.commandline):
32 class gnuarch_rev:
33 def __init__(self, rev):
34 self.rev = rev
35 self.summary = b''
36 self.date = None
37 self.author = b''
38 self.continuationof = None
39 self.add_files = []
40 self.mod_files = []
41 self.del_files = []
42 self.ren_files = {}
43 self.ren_dirs = {}
44
45 def __init__(self, ui, repotype, path, revs=None):
46 super().__init__(ui, repotype, path, revs=revs)
47
48 if not os.path.exists(os.path.join(path, b'{arch}')):
49 raise common.NoRepo(
50 _(b"%s does not look like a GNU Arch repository") % path
51 )
52
53 # Could use checktool, but we want to check for baz or tla.
54 self.execmd = None
55 if procutil.findexe(b'baz'):
56 self.execmd = b'baz'
57 else:
58 if procutil.findexe(b'tla'):
59 self.execmd = b'tla'
60 else:
61 raise error.Abort(_(b'cannot find a GNU Arch tool'))
62
63 common.commandline.__init__(self, ui, self.execmd)
64
65 self.path = os.path.realpath(path)
66 self.tmppath = None
67
68 self.treeversion = None
69 self.lastrev = None
70 self.changes = {}
71 self.parents = {}
72 self.tags = {}
73 self.encoding = encoding.encoding
74 self.archives = []
75
76 def before(self):
77 # Get registered archives
78 self.archives = [
79 i.rstrip(b'\n') for i in self.runlines0(b'archives', b'-n')
80 ]
81
82 if self.execmd == b'tla':
83 output = self.run0(b'tree-version', self.path)
84 else:
85 output = self.run0(b'tree-version', b'-d', self.path)
86 self.treeversion = output.strip()
87
88 # Get name of temporary directory
89 version = self.treeversion.split(b'/')
90 self.tmppath = os.path.join(
91 pycompat.fsencode(tempfile.gettempdir()), b'hg-%s' % version[1]
92 )
93
94 # Generate parents dictionary
95 self.parents[None] = []
96 treeversion = self.treeversion
97 child = None
98 while treeversion:
99 self.ui.status(_(b'analyzing tree version %s...\n') % treeversion)
100
101 archive = treeversion.split(b'/')[0]
102 if archive not in self.archives:
103 self.ui.status(
104 _(
105 b'tree analysis stopped because it points to '
106 b'an unregistered archive %s...\n'
107 )
108 % archive
109 )
110 break
111
112 # Get the complete list of revisions for that tree version
113 output, status = self.runlines(
114 b'revisions', b'-r', b'-f', treeversion
115 )
116 self.checkexit(
117 status, b'failed retrieving revisions for %s' % treeversion
118 )
119
120 # No new iteration unless a revision has a continuation-of header
121 treeversion = None
122
123 for l in output:
124 rev = l.strip()
125 self.changes[rev] = self.gnuarch_rev(rev)
126 self.parents[rev] = []
127
128 # Read author, date and summary
129 catlog, status = self.run(b'cat-log', b'-d', self.path, rev)
130 if status:
131 catlog = self.run0(b'cat-archive-log', rev)
132 self._parsecatlog(catlog, rev)
133
134 # Populate the parents map
135 self.parents[child].append(rev)
136
137 # Keep track of the current revision as the child of the next
138 # revision scanned
139 child = rev
140
141 # Check if we have to follow the usual incremental history
142 # or if we have to 'jump' to a different treeversion given
143 # by the continuation-of header.
144 if self.changes[rev].continuationof:
145 treeversion = b'--'.join(
146 self.changes[rev].continuationof.split(b'--')[:-1]
147 )
148 break
149
150 # If we reached a base-0 revision w/o any continuation-of
151 # header, it means the tree history ends here.
152 if rev[-6:] == b'base-0':
153 break
154
155 def after(self):
156 self.ui.debug(b'cleaning up %s\n' % self.tmppath)
157 shutil.rmtree(self.tmppath, ignore_errors=True)
158
159 def getheads(self):
160 return self.parents[None]
161
162 def getfile(self, name, rev):
163 if rev != self.lastrev:
164 raise error.Abort(_(b'internal calling inconsistency'))
165
166 if not os.path.lexists(os.path.join(self.tmppath, name)):
167 return None, None
168
169 return self._getfile(name, rev)
170
171 def getchanges(self, rev, full):
172 if full:
173 raise error.Abort(_(b"convert from arch does not support --full"))
174 self._update(rev)
175 changes = []
176 copies = {}
177
178 for f in self.changes[rev].add_files:
179 changes.append((f, rev))
180
181 for f in self.changes[rev].mod_files:
182 changes.append((f, rev))
183
184 for f in self.changes[rev].del_files:
185 changes.append((f, rev))
186
187 for src in self.changes[rev].ren_files:
188 to = self.changes[rev].ren_files[src]
189 changes.append((src, rev))
190 changes.append((to, rev))
191 copies[to] = src
192
193 for src in self.changes[rev].ren_dirs:
194 to = self.changes[rev].ren_dirs[src]
195 chgs, cps = self._rendirchanges(src, to)
196 changes += [(f, rev) for f in chgs]
197 copies.update(cps)
198
199 self.lastrev = rev
200 return sorted(set(changes)), copies, set()
201
202 def getcommit(self, rev):
203 changes = self.changes[rev]
204 return common.commit(
205 author=changes.author,
206 date=changes.date,
207 desc=changes.summary,
208 parents=self.parents[rev],
209 rev=rev,
210 )
211
212 def gettags(self):
213 return self.tags
214
215 def _execute(self, cmd, *args, **kwargs):
216 cmdline = [self.execmd, cmd]
217 cmdline += args
218 cmdline = [procutil.shellquote(arg) for arg in cmdline]
219 bdevnull = pycompat.bytestr(os.devnull)
220 cmdline += [b'>', bdevnull, b'2>', bdevnull]
221 cmdline = b' '.join(cmdline)
222 self.ui.debug(cmdline, b'\n')
223 return os.system(pycompat.rapply(procutil.tonativestr, cmdline))
224
225 def _update(self, rev):
226 self.ui.debug(b'applying revision %s...\n' % rev)
227 changeset, status = self.runlines(b'replay', b'-d', self.tmppath, rev)
228 if status:
229 # Something went wrong while merging (baz or tla
230 # issue?), get latest revision and try from there
231 shutil.rmtree(self.tmppath, ignore_errors=True)
232 self._obtainrevision(rev)
233 else:
234 old_rev = self.parents[rev][0]
235 self.ui.debug(
236 b'computing changeset between %s and %s...\n' % (old_rev, rev)
237 )
238 self._parsechangeset(changeset, rev)
239
240 def _getfile(self, name, rev):
241 mode = os.lstat(os.path.join(self.tmppath, name)).st_mode
242 if stat.S_ISLNK(mode):
243 data = util.readlink(os.path.join(self.tmppath, name))
244 if mode:
245 mode = b'l'
246 else:
247 mode = b''
248 else:
249 data = util.readfile(os.path.join(self.tmppath, name))
250 mode = (mode & 0o111) and b'x' or b''
251 return data, mode
252
253 def _exclude(self, name):
254 exclude = [b'{arch}', b'.arch-ids', b'.arch-inventory']
255 for exc in exclude:
256 if name.find(exc) != -1:
257 return True
258 return False
259
260 def _readcontents(self, path):
261 files = []
262 contents = os.listdir(path)
263 while len(contents) > 0:
264 c = contents.pop()
265 p = os.path.join(path, c)
266 # os.walk could be used, but here we avoid internal GNU
267 # Arch files and directories, thus saving a lot time.
268 if not self._exclude(p):
269 if os.path.isdir(p):
270 contents += [os.path.join(c, f) for f in os.listdir(p)]
271 else:
272 files.append(c)
273 return files
274
275 def _rendirchanges(self, src, dest):
276 changes = []
277 copies = {}
278 files = self._readcontents(os.path.join(self.tmppath, dest))
279 for f in files:
280 s = os.path.join(src, f)
281 d = os.path.join(dest, f)
282 changes.append(s)
283 changes.append(d)
284 copies[d] = s
285 return changes, copies
286
287 def _obtainrevision(self, rev):
288 self.ui.debug(b'obtaining revision %s...\n' % rev)
289 output = self._execute(b'get', rev, self.tmppath)
290 self.checkexit(output)
291 self.ui.debug(b'analyzing revision %s...\n' % rev)
292 files = self._readcontents(self.tmppath)
293 self.changes[rev].add_files += files
294
295 def _stripbasepath(self, path):
296 if path.startswith(b'./'):
297 return path[2:]
298 return path
299
300 def _parsecatlog(self, data, rev):
301 try:
302 catlog = mail.parsebytes(data)
303
304 # Commit date
305 self.changes[rev].date = dateutil.datestr(
306 dateutil.strdate(catlog['Standard-date'], b'%Y-%m-%d %H:%M:%S')
307 )
308
309 # Commit author
310 self.changes[rev].author = self.recode(catlog['Creator'])
311
312 # Commit description
313 self.changes[rev].summary = b'\n\n'.join(
314 (
315 self.recode(catlog['Summary']),
316 self.recode(catlog.get_payload()),
317 )
318 )
319 self.changes[rev].summary = self.recode(self.changes[rev].summary)
320
321 # Commit revision origin when dealing with a branch or tag
322 if 'Continuation-of' in catlog:
323 self.changes[rev].continuationof = self.recode(
324 catlog['Continuation-of']
325 )
326 except Exception:
327 raise error.Abort(_(b'could not parse cat-log of %s') % rev)
328
329 def _parsechangeset(self, data, rev):
330 for l in data:
331 l = l.strip()
332 # Added file (ignore added directory)
333 if l.startswith(b'A') and not l.startswith(b'A/'):
334 file = self._stripbasepath(l[1:].strip())
335 if not self._exclude(file):
336 self.changes[rev].add_files.append(file)
337 # Deleted file (ignore deleted directory)
338 elif l.startswith(b'D') and not l.startswith(b'D/'):
339 file = self._stripbasepath(l[1:].strip())
340 if not self._exclude(file):
341 self.changes[rev].del_files.append(file)
342 # Modified binary file
343 elif l.startswith(b'Mb'):
344 file = self._stripbasepath(l[2:].strip())
345 if not self._exclude(file):
346 self.changes[rev].mod_files.append(file)
347 # Modified link
348 elif l.startswith(b'M->'):
349 file = self._stripbasepath(l[3:].strip())
350 if not self._exclude(file):
351 self.changes[rev].mod_files.append(file)
352 # Modified file
353 elif l.startswith(b'M'):
354 file = self._stripbasepath(l[1:].strip())
355 if not self._exclude(file):
356 self.changes[rev].mod_files.append(file)
357 # Renamed file (or link)
358 elif l.startswith(b'=>'):
359 files = l[2:].strip().split(b' ')
360 if len(files) == 1:
361 files = l[2:].strip().split(b'\t')
362 src = self._stripbasepath(files[0])
363 dst = self._stripbasepath(files[1])
364 if not self._exclude(src) and not self._exclude(dst):
365 self.changes[rev].ren_files[src] = dst
366 # Conversion from file to link or from link to file (modified)
367 elif l.startswith(b'ch'):
368 file = self._stripbasepath(l[2:].strip())
369 if not self._exclude(file):
370 self.changes[rev].mod_files.append(file)
371 # Renamed directory
372 elif l.startswith(b'/>'):
373 dirs = l[2:].strip().split(b' ')
374 if len(dirs) == 1:
375 dirs = l[2:].strip().split(b'\t')
376 src = self._stripbasepath(dirs[0])
377 dst = self._stripbasepath(dirs[1])
378 if not self._exclude(src) and not self._exclude(dst):
379 self.changes[rev].ren_dirs[src] = dst