Debian Codegraph @

hgext/convert/p4.py

raw
1 # Perforce source for convert extension.
2 #
3 # Copyright 2009, Frank Kingswood <[email protected]>
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 from __future__ import annotations
9
10 import marshal
11 import re
12
13 from mercurial.i18n import _
14 from mercurial import (
15 error,
16 util,
17 )
18 from mercurial.utils import (
19 dateutil,
20 procutil,
21 stringutil,
22 )
23
24 from . import common
25
26
27 def loaditer(f):
28 """Yield the dictionary objects generated by p4"""
29 try:
30 while True:
31 d = marshal.load(f)
32 if not d:
33 break
34 yield d
35 except EOFError:
36 pass
37
38
39 def decodefilename(filename):
40 """Perforce escapes special characters @, #, *, or %
41 with %40, %23, %2A, or %25 respectively
42
43 >>> decodefilename(b'portable-net45%252Bnetcore45%252Bwp8%252BMonoAndroid')
44 'portable-net45%2Bnetcore45%2Bwp8%2BMonoAndroid'
45 >>> decodefilename(b'//Depot/Directory/%2525/%2523/%23%40.%2A')
46 '//Depot/Directory/%25/%23/#@.*'
47 """
48 replacements = [
49 (b'%2A', b'*'),
50 (b'%23', b'#'),
51 (b'%40', b'@'),
52 (b'%25', b'%'),
53 ]
54 for k, v in replacements:
55 filename = filename.replace(k, v)
56 return filename
57
58
59 class p4_source(common.converter_source):
60 def __init__(self, ui, repotype, path, revs=None):
61 # avoid import cycle
62 from . import convcmd
63
64 super().__init__(ui, repotype, path, revs=revs)
65
66 if b"/" in path and not path.startswith(b'//'):
67 raise common.NoRepo(
68 _(b'%s does not look like a P4 repository') % path
69 )
70
71 common.checktool(b'p4', abort=False)
72
73 self.revmap = {}
74 self.encoding = self.ui.config(
75 b'convert', b'p4.encoding', convcmd.orig_encoding
76 )
77 self.re_type = re.compile(
78 br"([a-z]+)?(text|binary|symlink|apple|resource|unicode|utf\d+)"
79 br"(\+\w+)?$"
80 )
81 self.re_keywords = re.compile(
82 br"\$(Id|Header|Date|DateTime|Change|File|Revision|Author)"
83 br":[^$\n]*\$"
84 )
85 self.re_keywords_old = re.compile(br"\$(Id|Header):[^$\n]*\$")
86
87 if revs and len(revs) > 1:
88 raise error.Abort(
89 _(
90 b"p4 source does not support specifying "
91 b"multiple revisions"
92 )
93 )
94
95 def setrevmap(self, revmap):
96 """Sets the parsed revmap dictionary.
97
98 Revmap stores mappings from a source revision to a target revision.
99 It is set in convertcmd.convert and provided by the user as a file
100 on the commandline.
101
102 Revisions in the map are considered beeing present in the
103 repository and ignored during _parse(). This allows for incremental
104 imports if a revmap is provided.
105 """
106 self.revmap = revmap
107
108 def _parse_view(self, path):
109 """Read changes affecting the path"""
110 cmd = b'p4 -G changes -s submitted %s' % procutil.shellquote(path)
111 stdout = procutil.popen(cmd, mode=b'rb')
112 p4changes = {}
113 for d in loaditer(stdout):
114 c = d.get(b"change", None)
115 if c:
116 p4changes[c] = True
117 return p4changes
118
119 def _parse(self, ui, path):
120 """Prepare list of P4 filenames and revisions to import"""
121 p4changes = {}
122 changeset = {}
123 files_map = {}
124 copies_map = {}
125 localname = {}
126 depotname = {}
127 heads = []
128
129 ui.status(_(b'reading p4 views\n'))
130
131 # read client spec or view
132 if b"/" in path:
133 p4changes.update(self._parse_view(path))
134 if path.startswith(b"//") and path.endswith(b"/..."):
135 views = {path[:-3]: b""}
136 else:
137 views = {b"//": b""}
138 else:
139 cmd = b'p4 -G client -o %s' % procutil.shellquote(path)
140 clientspec = marshal.load(procutil.popen(cmd, mode=b'rb'))
141
142 views = {}
143 for client in clientspec:
144 if client.startswith(b"View"):
145 sview, cview = clientspec[client].split()
146 p4changes.update(self._parse_view(sview))
147 if sview.endswith(b"...") and cview.endswith(b"..."):
148 sview = sview[:-3]
149 cview = cview[:-3]
150 cview = cview[2:]
151 cview = cview[cview.find(b"/") + 1 :]
152 views[sview] = cview
153
154 # list of changes that affect our source files
155 p4changes = sorted(p4changes.keys(), key=int)
156
157 # list with depot pathnames, longest first
158 vieworder = sorted(views.keys(), key=len, reverse=True)
159
160 # handle revision limiting
161 startrev = self.ui.config(b'convert', b'p4.startrev')
162
163 # now read the full changelists to get the list of file revisions
164 ui.status(_(b'collecting p4 changelists\n'))
165 lastid = None
166 for change in p4changes:
167 if startrev and int(change) < int(startrev):
168 continue
169 if self.revs and int(change) > int(self.revs[0]):
170 continue
171 if change in self.revmap:
172 # Ignore already present revisions, but set the parent pointer.
173 lastid = change
174 continue
175
176 if lastid:
177 parents = [lastid]
178 else:
179 parents = []
180
181 d = self._fetch_revision(change)
182 c = self._construct_commit(d, parents)
183
184 descarr = c.desc.splitlines(True)
185 if len(descarr) > 0:
186 shortdesc = descarr[0].rstrip(b'\r\n')
187 else:
188 shortdesc = b'**empty changelist description**'
189
190 t = b'%s %s' % (c.rev, shortdesc)
191 ui.status(stringutil.ellipsis(t, 80) + b'\n')
192
193 files = []
194 copies = {}
195 copiedfiles = []
196 i = 0
197 while (b"depotFile%d" % i) in d and (b"rev%d" % i) in d:
198 oldname = d[b"depotFile%d" % i]
199 filename = None
200 for v in vieworder:
201 if oldname.lower().startswith(v.lower()):
202 filename = decodefilename(views[v] + oldname[len(v) :])
203 break
204 if filename:
205 files.append((filename, d[b"rev%d" % i]))
206 depotname[filename] = oldname
207 if d.get(b"action%d" % i) == b"move/add":
208 copiedfiles.append(filename)
209 localname[oldname] = filename
210 i += 1
211
212 # Collect information about copied files
213 for filename in copiedfiles:
214 oldname = depotname[filename]
215
216 flcmd = b'p4 -G filelog %s' % procutil.shellquote(oldname)
217 flstdout = procutil.popen(flcmd, mode=b'rb')
218
219 copiedfilename = None
220 for d in loaditer(flstdout):
221 copiedoldname = None
222
223 i = 0
224 while (b"change%d" % i) in d:
225 if (
226 d[b"change%d" % i] == change
227 and d[b"action%d" % i] == b"move/add"
228 ):
229 j = 0
230 while (b"file%d,%d" % (i, j)) in d:
231 if d[b"how%d,%d" % (i, j)] == b"moved from":
232 copiedoldname = d[b"file%d,%d" % (i, j)]
233 break
234 j += 1
235 i += 1
236
237 if copiedoldname and copiedoldname in localname:
238 copiedfilename = localname[copiedoldname]
239 break
240
241 if copiedfilename:
242 copies[filename] = copiedfilename
243 else:
244 ui.warn(
245 _(b"cannot find source for copied file: %s@%s\n")
246 % (filename, change)
247 )
248
249 changeset[change] = c
250 files_map[change] = files
251 copies_map[change] = copies
252 lastid = change
253
254 if lastid and len(changeset) > 0:
255 heads = [lastid]
256
257 return {
258 b'changeset': changeset,
259 b'files': files_map,
260 b'copies': copies_map,
261 b'heads': heads,
262 b'depotname': depotname,
263 }
264
265 @util.propertycache
266 def _parse_once(self):
267 return self._parse(self.ui, self.path)
268
269 @util.propertycache
270 def copies(self):
271 return self._parse_once[b'copies']
272
273 @util.propertycache
274 def files(self):
275 return self._parse_once[b'files']
276
277 @util.propertycache
278 def changeset(self):
279 return self._parse_once[b'changeset']
280
281 @util.propertycache
282 def heads(self):
283 return self._parse_once[b'heads']
284
285 @util.propertycache
286 def depotname(self):
287 return self._parse_once[b'depotname']
288
289 def getheads(self):
290 return self.heads
291
292 def getfile(self, name, rev):
293 cmd = b'p4 -G print %s' % procutil.shellquote(
294 b"%s#%s" % (self.depotname[name], rev)
295 )
296
297 lasterror = None
298 while True:
299 stdout = procutil.popen(cmd, mode=b'rb')
300
301 mode = None
302 contents = []
303 keywords = None
304
305 for d in loaditer(stdout):
306 code = d[b"code"]
307 data = d.get(b"data")
308
309 if code == b"error":
310 # if this is the first time error happened
311 # re-attempt getting the file
312 if not lasterror:
313 lasterror = IOError(d[b"generic"], data)
314 # this will exit inner-most for-loop
315 break
316 else:
317 raise lasterror
318
319 elif code == b"stat":
320 action = d.get(b"action")
321 if action in [b"purge", b"delete", b"move/delete"]:
322 return None, None
323 p4type = self.re_type.match(d[b"type"])
324 if p4type:
325 mode = b""
326 flags = (p4type.group(1) or b"") + (
327 p4type.group(3) or b""
328 )
329 if b"x" in flags:
330 mode = b"x"
331 if p4type.group(2) == b"symlink":
332 mode = b"l"
333 if b"ko" in flags:
334 keywords = self.re_keywords_old
335 elif b"k" in flags:
336 keywords = self.re_keywords
337
338 elif code == b"text" or code == b"binary":
339 contents.append(data)
340
341 lasterror = None
342
343 if not lasterror:
344 break
345
346 if mode is None:
347 return None, None
348
349 contents = b''.join(contents)
350
351 if keywords:
352 contents = keywords.sub(b"$\\1$", contents)
353 if mode == b"l" and contents.endswith(b"\n"):
354 contents = contents[:-1]
355
356 return contents, mode
357
358 def getchanges(self, rev, full):
359 if full:
360 raise error.Abort(_(b"convert from p4 does not support --full"))
361 return self.files[rev], self.copies[rev], set()
362
363 def _construct_commit(self, obj, parents=None):
364 """
365 Constructs a common.commit object from an unmarshalled
366 `p4 describe` output
367 """
368 desc = self.recode(obj.get(b"desc", b""))
369 date = (int(obj[b"time"]), 0) # timezone not set
370 if parents is None:
371 parents = []
372
373 return common.commit(
374 author=self.recode(obj[b"user"]),
375 date=dateutil.datestr(date, b'%Y-%m-%d %H:%M:%S %1%2'),
376 parents=parents,
377 desc=desc,
378 branch=None,
379 rev=obj[b'change'],
380 extra={b"p4": obj[b'change'], b"convert_revision": obj[b'change']},
381 )
382
383 def _fetch_revision(self, rev):
384 """Return an output of `p4 describe` including author, commit date as
385 a dictionary."""
386 cmd = b"p4 -G describe -s %s" % rev
387 stdout = procutil.popen(cmd, mode=b'rb')
388 return marshal.load(stdout)
389
390 def getcommit(self, rev):
391 if rev in self.changeset:
392 return self.changeset[rev]
393 elif rev in self.revmap:
394 d = self._fetch_revision(rev)
395 return self._construct_commit(d, parents=None)
396 raise error.Abort(
397 _(b"cannot find %s in the revmap or parsed changesets") % rev
398 )
399
400 def gettags(self):
401 return {}
402
403 def getchangedfiles(self, rev, i):
404 return sorted([x[0] for x in self.files[rev]])