##// END OF EJS Templates
cvsps: fix up some whitespace
Matt Mackall -
r6688:5cd7a843 default
parent child Browse files
Show More
@@ -1,547 +1,552 b''
1 1 #
2 2 # Mercurial built-in replacement for cvsps.
3 3 #
4 4 # Copyright 2008, Frank Kingswood <frank@kingswood-consulting.co.uk>
5 5 #
6 6 # This software may be used and distributed according to the terms
7 7 # of the GNU General Public License, incorporated herein by reference.
8 8
9 9 import os
10 10 import re
11 11 import sys
12 12 import cPickle as pickle
13 13 from mercurial import util
14 14 from mercurial.i18n import _
15 15
16 16 def listsort(list, key):
17 17 "helper to sort by key in Python 2.3"
18 18 try:
19 19 list.sort(key=key)
20 20 except TypeError:
21 21 list.sort(lambda l, r:cmp(key(l), key(r)))
22 22
23 23 class logentry(object):
24 24 '''Class logentry has the following attributes:
25 25 .author - author name as CVS knows it
26 26 .branch - name of branch this revision is on
27 27 .branches - revision tuple of branches starting at this revision
28 28 .comment - commit message
29 29 .date - the commit date as a (time, tz) tuple
30 30 .dead - true if file revision is dead
31 31 .file - Name of file
32 32 .lines - a tuple (+lines, -lines) or None
33 33 .parent - Previous revision of this entry
34 34 .rcs - name of file as returned from CVS
35 35 .revision - revision number as tuple
36 36 .tags - list of tags on the file
37 37 '''
38 38 def __init__(self, **entries):
39 39 self.__dict__.update(entries)
40 40
41 41 class logerror(Exception):
42 42 pass
43 43
44 44 def createlog(ui, directory=None, root="", rlog=True, cache=None):
45 45 '''Collect the CVS rlog'''
46 46
47 47 # Because we store many duplicate commit log messages, reusing strings
48 48 # saves a lot of memory and pickle storage space.
49 49 _scache = {}
50 50 def scache(s):
51 51 "return a shared version of a string"
52 52 return _scache.setdefault(s, s)
53 53
54 54 ui.status(_('collecting CVS rlog\n'))
55 55
56 56 log = [] # list of logentry objects containing the CVS state
57 57
58 58 # patterns to match in CVS (r)log output, by state of use
59 59 re_00 = re.compile('RCS file: (.+)$')
60 60 re_01 = re.compile('cvs \\[r?log aborted\\]: (.+)$')
61 61 re_02 = re.compile('cvs (r?log|server): (.+)\n$')
62 62 re_03 = re.compile("(Cannot access.+CVSROOT)|(can't create temporary directory.+)$")
63 63 re_10 = re.compile('Working file: (.+)$')
64 64 re_20 = re.compile('symbolic names:')
65 65 re_30 = re.compile('\t(.+): ([\\d.]+)$')
66 66 re_31 = re.compile('----------------------------$')
67 67 re_32 = re.compile('=============================================================================$')
68 68 re_50 = re.compile('revision ([\\d.]+)(\s+locked by:\s+.+;)?$')
69 69 re_60 = re.compile(r'date:\s+(.+);\s+author:\s+(.+);\s+state:\s+(.+?);(\s+lines:\s+(\+\d+)?\s+(-\d+)?;)?')
70 70 re_70 = re.compile('branches: (.+);$')
71 71
72 72 prefix = '' # leading path to strip of what we get from CVS
73 73
74 74 if directory is None:
75 75 # Current working directory
76 76
77 77 # Get the real directory in the repository
78 78 try:
79 79 prefix = file(os.path.join('CVS','Repository')).read().strip()
80 80 if prefix == ".":
81 81 prefix=""
82 82 directory = prefix
83 83 except IOError:
84 84 raise logerror('Not a CVS sandbox')
85 85
86 86 if prefix and not prefix.endswith('/'):
87 87 prefix+='/'
88 88
89 89 # Use the Root file in the sandbox, if it exists
90 90 try:
91 91 root = file(os.path.join('CVS','Root')).read().strip()
92 92 except IOError:
93 93 pass
94 94
95 95 if not root:
96 96 root = os.environ.get('CVSROOT', '')
97 97
98 98 # read log cache if one exists
99 99 oldlog = []
100 100 date = None
101 101
102 102 if cache:
103 103 cachedir = os.path.expanduser('~/.hg.cvsps')
104 104 if not os.path.exists(cachedir):
105 105 os.mkdir(cachedir)
106 106
107 107 # The cvsps cache pickle needs a uniquified name, based on the
108 108 # repository location. The address may have all sort of nasties
109 109 # in it, slashes, colons and such. So here we take just the
110 110 # alphanumerics, concatenated in a way that does not mix up the
111 111 # various components, so that
112 112 # :pserver:user@server:/path
113 113 # and
114 114 # /pserver/user/server/path
115 115 # are mapped to different cache file names.
116 116 cachefile = root.split(":")+[directory, "cache"]
117 117 cachefile = ['-'.join(re.findall(r'\w+', s)) for s in cachefile if s]
118 cachefile = os.path.join(cachedir, '.'.join([s for s in cachefile if s]))
118 cachefile = os.path.join(cachedir,
119 '.'.join([s for s in cachefile if s]))
119 120
120 121 if cache == 'update':
121 122 try:
122 123 ui.note(_('reading cvs log cache %s\n') % cachefile)
123 124 oldlog = pickle.load(file(cachefile))
124 125 ui.note(_('cache has %d log entries\n') % len(oldlog))
125 126 except Exception, e:
126 127 ui.note(_('error reading cache: %r\n') % e)
127 128
128 129 if oldlog:
129 130 date = oldlog[-1].date # last commit date as a (time,tz) tuple
130 131 date = util.datestr(date, '%Y/%m/%d %H:%M:%S %1%2')
131 132
132 133 # build the CVS commandline
133 134 cmd = ['cvs', '-q']
134 135 if root:
135 136 cmd.append('-d%s' % root)
136 137 p = root.split(':')[-1]
137 138 if not p.endswith('/'):
138 139 p+='/'
139 140 prefix = p+prefix
140 141 cmd.append(['log', 'rlog'][rlog])
141 142 if date:
142 143 # no space between option and date string
143 144 cmd.append('-d>%s' % date)
144 145 cmd.append(directory)
145 146
146 147 # state machine begins here
147 148 tags = {} # dictionary of revisions on current file with their tags
148 149 state = 0
149 150 store = False # set when a new record can be appended
150 151
151 152 cmd = [util.shellquote(arg) for arg in cmd]
152 153 ui.note("running %s\n" % (' '.join(cmd)))
153 154 ui.debug("prefix=%r directory=%r root=%r\n" % (prefix, directory, root))
154 155
155 156 for line in util.popen(' '.join(cmd)):
156 157 if line.endswith('\n'):
157 158 line = line[:-1]
158 159 #ui.debug('state=%d line=%r\n' % (state, line))
159 160
160 161 if state == 0:
161 162 # initial state, consume input until we see 'RCS file'
162 163 match = re_00.match(line)
163 164 if match:
164 165 rcs = match.group(1)
165 166 tags = {}
166 167 if rlog:
167 168 filename = rcs[:-2]
168 169 if filename.startswith(prefix):
169 170 filename = filename[len(prefix):]
170 171 if filename.startswith('/'):
171 172 filename = filename[1:]
172 173 if filename.startswith('Attic/'):
173 174 filename = filename[6:]
174 175 else:
175 176 filename = filename.replace('/Attic/', '/')
176 177 state = 2
177 178 continue
178 179 state = 1
179 180 continue
180 181 match = re_01.match(line)
181 182 if match:
182 183 raise Exception(match.group(1))
183 184 match = re_02.match(line)
184 185 if match:
185 186 raise Exception(match.group(2))
186 187 if re_03.match(line):
187 188 raise Exception(line)
188 189
189 190 elif state == 1:
190 191 # expect 'Working file' (only when using log instead of rlog)
191 192 match = re_10.match(line)
192 193 assert match, _('RCS file must be followed by working file')
193 194 filename = match.group(1)
194 195 state = 2
195 196
196 197 elif state == 2:
197 198 # expect 'symbolic names'
198 199 if re_20.match(line):
199 200 state = 3
200 201
201 202 elif state == 3:
202 203 # read the symbolic names and store as tags
203 204 match = re_30.match(line)
204 205 if match:
205 206 rev = [int(x) for x in match.group(2).split('.')]
206 207
207 208 # Convert magic branch number to an odd-numbered one
208 209 revn = len(rev)
209 210 if revn>3 and (revn%2) == 0 and rev[-2] == 0:
210 211 rev = rev[:-2]+rev[-1:]
211 212 rev = tuple(rev)
212 213
213 214 if rev not in tags:
214 215 tags[rev] = []
215 216 tags[rev].append(match.group(1))
216 217
217 218 elif re_31.match(line):
218 219 state = 5
219 220 elif re_32.match(line):
220 221 state = 0
221 222
222 223 elif state == 4:
223 224 # expecting '------' separator before first revision
224 225 if re_31.match(line):
225 226 state = 5
226 227 else:
227 228 assert not re_32.match(line), _('Must have at least some revisions')
228 229
229 230 elif state == 5:
230 231 # expecting revision number and possibly (ignored) lock indication
231 232 # we create the logentry here from values stored in states 0 to 4,
232 233 # as this state is re-entered for subsequent revisions of a file.
233 234 match = re_50.match(line)
234 235 assert match, _('expected revision number')
235 236 e = logentry(rcs=scache(rcs), file=scache(filename),
236 237 revision=tuple([int(x) for x in match.group(1).split('.')]),
237 238 branches=[], parent=None)
238 239 state = 6
239 240
240 241 elif state == 6:
241 242 # expecting date, author, state, lines changed
242 243 match = re_60.match(line)
243 244 assert match, _('revision must be followed by date line')
244 245 d = match.group(1)
245 246 if d[2] == '/':
246 247 # Y2K
247 248 d = '19'+d
248 249
249 250 if len(d.split()) != 3:
250 251 # cvs log dates always in GMT
251 252 d = d+' UTC'
252 253 e.date = util.parsedate(d, ['%y/%m/%d %H:%M:%S', '%Y/%m/%d %H:%M:%S', '%Y-%m-%d %H:%M:%S'])
253 254 e.author = scache(match.group(2))
254 255 e.dead = match.group(3).lower() == 'dead'
255 256
256 257 if match.group(5):
257 258 if match.group(6):
258 259 e.lines = (int(match.group(5)), int(match.group(6)))
259 260 else:
260 261 e.lines = (int(match.group(5)), 0)
261 262 elif match.group(6):
262 263 e.lines = (0, int(match.group(6)))
263 264 else:
264 265 e.lines = None
265 266 e.comment = []
266 267 state = 7
267 268
268 269 elif state == 7:
269 # read the revision numbers of branches that start at this revision,
270 # read the revision numbers of branches that start at this revision
270 271 # or store the commit log message otherwise
271 272 m = re_70.match(line)
272 273 if m:
273 274 e.branches = [tuple([int(y) for y in x.strip().split('.')])
274 275 for x in m.group(1).split(';')]
275 276 state = 8
276 277 elif re_31.match(line):
277 278 state = 5
278 279 store = True
279 280 elif re_32.match(line):
280 281 state = 0
281 282 store = True
282 283 else:
283 284 e.comment.append(line)
284 285
285 286 elif state == 8:
286 287 # store commit log message
287 288 if re_31.match(line):
288 289 state = 5
289 290 store = True
290 291 elif re_32.match(line):
291 292 state = 0
292 293 store = True
293 294 else:
294 295 e.comment.append(line)
295 296
296 297 if store:
297 298 # clean up the results and save in the log.
298 299 store = False
299 300 e.tags = [scache(x) for x in tags.get(e.revision, [])]
300 301 e.tags.sort()
301 302 e.comment = scache('\n'.join(e.comment))
302 303
303 304 revn = len(e.revision)
304 305 if revn>3 and (revn%2) == 0:
305 306 e.branch = tags.get(e.revision[:-1], [None])[0]
306 307 else:
307 308 e.branch = None
308 309
309 310 log.append(e)
310 311
311 312 if len(log)%100 == 0:
312 313 ui.status(util.ellipsis('%d %s'%(len(log), e.file), 80)+'\n')
313 314
314 315 listsort(log, key=lambda x:(x.rcs, x.revision))
315 316
316 317 # find parent revisions of individual files
317 318 versions = {}
318 319 for e in log:
319 320 branch = e.revision[:-1]
320 321 p = versions.get((e.rcs, branch), None)
321 322 if p is None:
322 323 p = e.revision[:-2]
323 324 e.parent = p
324 325 versions[(e.rcs, branch)] = e.revision
325 326
326 327 # update the log cache
327 328 if cache:
328 329 if log:
329 330 # join up the old and new logs
330 331 listsort(log, key=lambda x:x.date)
331 332
332 333 if oldlog and oldlog[-1].date >= log[0].date:
333 raise logerror('Log cache overlaps with new log entries, re-run without cache.')
334 raise logerror('Log cache overlaps with new log entries,'
335 ' re-run without cache.')
334 336
335 337 log = oldlog+log
336 338
337 339 # write the new cachefile
338 340 ui.note(_('writing cvs log cache %s\n') % cachefile)
339 341 pickle.dump(log, file(cachefile, 'w'))
340 342 else:
341 343 log = oldlog
342 344
343 345 ui.status(_('%d log entries\n') % len(log))
344 346
345 347 return log
346 348
347 349
348 350 class changeset(object):
349 351 '''Class changeset has the following attributes:
350 352 .author - author name as CVS knows it
351 353 .branch - name of branch this changeset is on, or None
352 354 .comment - commit message
353 355 .date - the commit date as a (time,tz) tuple
354 356 .entries - list of logentry objects in this changeset
355 357 .parents - list of one or two parent changesets
356 358 .tags - list of tags on this changeset
357 359 '''
358 360 def __init__(self, **entries):
359 361 self.__dict__.update(entries)
360 362
361 363 def createchangeset(ui, log, fuzz=60, mergefrom=None, mergeto=None):
362 364 '''Convert log into changesets.'''
363 365
364 366 ui.status(_('creating changesets\n'))
365 367
366 368 # Merge changesets
367 369
368 370 listsort(log, key=lambda x:(x.comment, x.author, x.branch, x.date))
369 371
370 372 changesets = []
371 373 files = {}
372 374 c = None
373 375 for i, e in enumerate(log):
374 376
375 377 # Check if log entry belongs to the current changeset or not.
376 378 if not (c and
377 379 e.comment == c.comment and
378 380 e.author == c.author and
379 381 e.branch == c.branch and
380 (c.date[0]+c.date[1]) <= (e.date[0]+e.date[1]) <= (c.date[0]+c.date[1])+fuzz and
382 ((c.date[0] + c.date[1]) <=
383 (e.date[0] + e.date[1]) <=
384 (c.date[0] + c.date[1]) + fuzz) and
381 385 e.file not in files):
382 386 c = changeset(comment=e.comment, author=e.author,
383 387 branch=e.branch, date=e.date, entries=[])
384 388 changesets.append(c)
385 389 files = {}
386 390 if len(changesets)%100 == 0:
387 ui.status(util.ellipsis('%d %s'%(len(changesets), repr(e.comment)[1:-1]), 80)+'\n')
391 t = '%d %s' % (len(changesets), repr(e.comment)[1:-1])
392 ui.status(util.ellipsis(t, 80) + '\n')
388 393
389 394 e.Changeset = c
390 395 c.entries.append(e)
391 396 files[e.file] = True
392 397 c.date = e.date # changeset date is date of latest commit in it
393 398
394 399 # Sort files in each changeset
395 400
396 401 for c in changesets:
397 402 def pathcompare(l, r):
398 403 'Mimic cvsps sorting order'
399 404 l = l.split('/')
400 405 r = r.split('/')
401 406 nl = len(l)
402 407 nr = len(r)
403 408 n = min(nl, nr)
404 409 for i in range(n):
405 410 if i+1 == nl and nl<nr:
406 411 return -1
407 412 elif i+1 == nr and nl>nr:
408 413 return +1
409 414 elif l[i]<r[i]:
410 415 return -1
411 416 elif l[i]>r[i]:
412 417 return +1
413 418 return 0
414 419 def entitycompare(l, r):
415 420 return pathcompare(l.file, r.file)
416 421
417 422 c.entries.sort(entitycompare)
418 423
419 424 # Sort changesets by date
420 425
421 426 def cscmp(l, r):
422 427 d = sum(l.date)-sum(r.date)
423 428 if d:
424 429 return d
425 430
426 431 # detect vendor branches and initial commits on a branch
427 432 le = {}
428 433 for e in l.entries:
429 434 le[e.rcs] = e.revision
430 435 re = {}
431 436 for e in r.entries:
432 437 re[e.rcs] = e.revision
433 438
434 439 d = 0
435 440 for e in l.entries:
436 441 if re.get(e.rcs, None) == e.parent:
437 442 assert not d
438 443 d = 1
439 444 break
440 445
441 446 for e in r.entries:
442 447 if le.get(e.rcs, None) == e.parent:
443 448 assert not d
444 449 d = -1
445 450 break
446 451
447 452 return d
448 453
449 454 changesets.sort(cscmp)
450 455
451 456 # Collect tags
452 457
453 458 globaltags = {}
454 459 for c in changesets:
455 460 tags = {}
456 461 for e in c.entries:
457 462 for tag in e.tags:
458 463 # remember which is the latest changeset to have this tag
459 464 globaltags[tag] = c
460 465
461 466 for c in changesets:
462 467 tags = {}
463 468 for e in c.entries:
464 469 for tag in e.tags:
465 470 tags[tag] = True
466 471 # remember tags only if this is the latest changeset to have it
467 472 tagnames = [tag for tag in tags if globaltags[tag] is c]
468 473 tagnames.sort()
469 474 c.tags = tagnames
470 475
471 476 # Find parent changesets, handle {{mergetobranch BRANCHNAME}}
472 477 # by inserting dummy changesets with two parents, and handle
473 478 # {{mergefrombranch BRANCHNAME}} by setting two parents.
474 479
475 480 if mergeto is None:
476 481 mergeto = r'{{mergetobranch ([-\w]+)}}'
477 482 if mergeto:
478 483 mergeto = re.compile(mergeto)
479 484
480 485 if mergefrom is None:
481 486 mergefrom = r'{{mergefrombranch ([-\w]+)}}'
482 487 if mergefrom:
483 488 mergefrom = re.compile(mergefrom)
484 489
485 490 versions = {} # changeset index where we saw any particular file version
486 491 branches = {} # changeset index where we saw a branch
487 492 n = len(changesets)
488 493 i = 0
489 494 while i<n:
490 495 c = changesets[i]
491 496
492 497 for f in c.entries:
493 498 versions[(f.rcs, f.revision)] = i
494 499
495 500 p = None
496 501 if c.branch in branches:
497 502 p = branches[c.branch]
498 503 else:
499 504 for f in c.entries:
500 505 p = max(p, versions.get((f.rcs, f.parent), None))
501 506
502 507 c.parents = []
503 508 if p is not None:
504 509 c.parents.append(changesets[p])
505 510
506 511 if mergefrom:
507 512 m = mergefrom.search(c.comment)
508 513 if m:
509 514 m = m.group(1)
510 515 if m == 'HEAD':
511 516 m = None
512 517 if m in branches and c.branch != m:
513 518 c.parents.append(changesets[branches[m]])
514 519
515 520 if mergeto:
516 521 m = mergeto.search(c.comment)
517 522 if m:
518 523 try:
519 524 m = m.group(1)
520 525 if m == 'HEAD':
521 526 m = None
522 527 except:
523 528 m = None # if no group found then merge to HEAD
524 529 if m in branches and c.branch != m:
525 530 # insert empty changeset for merge
526 531 cc = changeset(author=c.author, branch=m, date=c.date,
527 532 comment='convert-repo: CVS merge from branch %s' % c.branch,
528 533 entries=[], tags=[], parents=[changesets[branches[m]], c])
529 534 changesets.insert(i+1, cc)
530 535 branches[m] = i+1
531 536
532 537 # adjust our loop counters now we have inserted a new entry
533 538 n += 1
534 539 i += 2
535 540 continue
536 541
537 542 branches[c.branch] = i
538 543 i += 1
539 544
540 545 # Number changesets
541 546
542 547 for i, c in enumerate(changesets):
543 548 c.id = i+1
544 549
545 550 ui.status(_('%d changeset entries\n') % len(changesets))
546 551
547 552 return changesets
General Comments 0
You need to be logged in to leave comments. Login now