PageRenderTime 37ms CodeModel.GetById 7ms RepoModel.GetById 0ms app.codeStats 0ms

/hgext/record.py

https://bitbucket.org/mirror/mercurial/
Python | 662 lines | 585 code | 19 blank | 58 comment | 25 complexity | 85d18b848574f3e526f227358429dc9d MD5 | raw file
Possible License(s): GPL-2.0
  1. # record.py
  2. #
  3. # Copyright 2007 Bryan O'Sullivan <bos@serpentine.com>
  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. '''commands to interactively select changes for commit/qrefresh'''
  8. from mercurial.i18n import _
  9. from mercurial import cmdutil, commands, extensions, hg, patch
  10. from mercurial import util
  11. import copy, cStringIO, errno, os, re, shutil, tempfile
  12. cmdtable = {}
  13. command = cmdutil.command(cmdtable)
  14. testedwith = 'internal'
  15. lines_re = re.compile(r'@@ -(\d+),(\d+) \+(\d+),(\d+) @@\s*(.*)')
  16. def scanpatch(fp):
  17. """like patch.iterhunks, but yield different events
  18. - ('file', [header_lines + fromfile + tofile])
  19. - ('context', [context_lines])
  20. - ('hunk', [hunk_lines])
  21. - ('range', (-start,len, +start,len, proc))
  22. """
  23. lr = patch.linereader(fp)
  24. def scanwhile(first, p):
  25. """scan lr while predicate holds"""
  26. lines = [first]
  27. while True:
  28. line = lr.readline()
  29. if not line:
  30. break
  31. if p(line):
  32. lines.append(line)
  33. else:
  34. lr.push(line)
  35. break
  36. return lines
  37. while True:
  38. line = lr.readline()
  39. if not line:
  40. break
  41. if line.startswith('diff --git a/') or line.startswith('diff -r '):
  42. def notheader(line):
  43. s = line.split(None, 1)
  44. return not s or s[0] not in ('---', 'diff')
  45. header = scanwhile(line, notheader)
  46. fromfile = lr.readline()
  47. if fromfile.startswith('---'):
  48. tofile = lr.readline()
  49. header += [fromfile, tofile]
  50. else:
  51. lr.push(fromfile)
  52. yield 'file', header
  53. elif line[0] == ' ':
  54. yield 'context', scanwhile(line, lambda l: l[0] in ' \\')
  55. elif line[0] in '-+':
  56. yield 'hunk', scanwhile(line, lambda l: l[0] in '-+\\')
  57. else:
  58. m = lines_re.match(line)
  59. if m:
  60. yield 'range', m.groups()
  61. else:
  62. yield 'other', line
  63. class header(object):
  64. """patch header
  65. XXX shouldn't we move this to mercurial/patch.py ?
  66. """
  67. diffgit_re = re.compile('diff --git a/(.*) b/(.*)$')
  68. diff_re = re.compile('diff -r .* (.*)$')
  69. allhunks_re = re.compile('(?:index|new file|deleted file) ')
  70. pretty_re = re.compile('(?:new file|deleted file) ')
  71. special_re = re.compile('(?:index|new|deleted|copy|rename) ')
  72. def __init__(self, header):
  73. self.header = header
  74. self.hunks = []
  75. def binary(self):
  76. return util.any(h.startswith('index ') for h in self.header)
  77. def pretty(self, fp):
  78. for h in self.header:
  79. if h.startswith('index '):
  80. fp.write(_('this modifies a binary file (all or nothing)\n'))
  81. break
  82. if self.pretty_re.match(h):
  83. fp.write(h)
  84. if self.binary():
  85. fp.write(_('this is a binary file\n'))
  86. break
  87. if h.startswith('---'):
  88. fp.write(_('%d hunks, %d lines changed\n') %
  89. (len(self.hunks),
  90. sum([max(h.added, h.removed) for h in self.hunks])))
  91. break
  92. fp.write(h)
  93. def write(self, fp):
  94. fp.write(''.join(self.header))
  95. def allhunks(self):
  96. return util.any(self.allhunks_re.match(h) for h in self.header)
  97. def files(self):
  98. match = self.diffgit_re.match(self.header[0])
  99. if match:
  100. fromfile, tofile = match.groups()
  101. if fromfile == tofile:
  102. return [fromfile]
  103. return [fromfile, tofile]
  104. else:
  105. return self.diff_re.match(self.header[0]).groups()
  106. def filename(self):
  107. return self.files()[-1]
  108. def __repr__(self):
  109. return '<header %s>' % (' '.join(map(repr, self.files())))
  110. def special(self):
  111. return util.any(self.special_re.match(h) for h in self.header)
  112. def countchanges(hunk):
  113. """hunk -> (n+,n-)"""
  114. add = len([h for h in hunk if h[0] == '+'])
  115. rem = len([h for h in hunk if h[0] == '-'])
  116. return add, rem
  117. class hunk(object):
  118. """patch hunk
  119. XXX shouldn't we merge this with patch.hunk ?
  120. """
  121. maxcontext = 3
  122. def __init__(self, header, fromline, toline, proc, before, hunk, after):
  123. def trimcontext(number, lines):
  124. delta = len(lines) - self.maxcontext
  125. if False and delta > 0:
  126. return number + delta, lines[:self.maxcontext]
  127. return number, lines
  128. self.header = header
  129. self.fromline, self.before = trimcontext(fromline, before)
  130. self.toline, self.after = trimcontext(toline, after)
  131. self.proc = proc
  132. self.hunk = hunk
  133. self.added, self.removed = countchanges(self.hunk)
  134. def write(self, fp):
  135. delta = len(self.before) + len(self.after)
  136. if self.after and self.after[-1] == '\\ No newline at end of file\n':
  137. delta -= 1
  138. fromlen = delta + self.removed
  139. tolen = delta + self.added
  140. fp.write('@@ -%d,%d +%d,%d @@%s\n' %
  141. (self.fromline, fromlen, self.toline, tolen,
  142. self.proc and (' ' + self.proc)))
  143. fp.write(''.join(self.before + self.hunk + self.after))
  144. pretty = write
  145. def filename(self):
  146. return self.header.filename()
  147. def __repr__(self):
  148. return '<hunk %r@%d>' % (self.filename(), self.fromline)
  149. def parsepatch(fp):
  150. """patch -> [] of headers -> [] of hunks """
  151. class parser(object):
  152. """patch parsing state machine"""
  153. def __init__(self):
  154. self.fromline = 0
  155. self.toline = 0
  156. self.proc = ''
  157. self.header = None
  158. self.context = []
  159. self.before = []
  160. self.hunk = []
  161. self.headers = []
  162. def addrange(self, limits):
  163. fromstart, fromend, tostart, toend, proc = limits
  164. self.fromline = int(fromstart)
  165. self.toline = int(tostart)
  166. self.proc = proc
  167. def addcontext(self, context):
  168. if self.hunk:
  169. h = hunk(self.header, self.fromline, self.toline, self.proc,
  170. self.before, self.hunk, context)
  171. self.header.hunks.append(h)
  172. self.fromline += len(self.before) + h.removed
  173. self.toline += len(self.before) + h.added
  174. self.before = []
  175. self.hunk = []
  176. self.proc = ''
  177. self.context = context
  178. def addhunk(self, hunk):
  179. if self.context:
  180. self.before = self.context
  181. self.context = []
  182. self.hunk = hunk
  183. def newfile(self, hdr):
  184. self.addcontext([])
  185. h = header(hdr)
  186. self.headers.append(h)
  187. self.header = h
  188. def addother(self, line):
  189. pass # 'other' lines are ignored
  190. def finished(self):
  191. self.addcontext([])
  192. return self.headers
  193. transitions = {
  194. 'file': {'context': addcontext,
  195. 'file': newfile,
  196. 'hunk': addhunk,
  197. 'range': addrange},
  198. 'context': {'file': newfile,
  199. 'hunk': addhunk,
  200. 'range': addrange,
  201. 'other': addother},
  202. 'hunk': {'context': addcontext,
  203. 'file': newfile,
  204. 'range': addrange},
  205. 'range': {'context': addcontext,
  206. 'hunk': addhunk},
  207. 'other': {'other': addother},
  208. }
  209. p = parser()
  210. state = 'context'
  211. for newstate, data in scanpatch(fp):
  212. try:
  213. p.transitions[state][newstate](p, data)
  214. except KeyError:
  215. raise patch.PatchError('unhandled transition: %s -> %s' %
  216. (state, newstate))
  217. state = newstate
  218. return p.finished()
  219. def filterpatch(ui, headers):
  220. """Interactively filter patch chunks into applied-only chunks"""
  221. def prompt(skipfile, skipall, query, chunk):
  222. """prompt query, and process base inputs
  223. - y/n for the rest of file
  224. - y/n for the rest
  225. - ? (help)
  226. - q (quit)
  227. Return True/False and possibly updated skipfile and skipall.
  228. """
  229. newpatches = None
  230. if skipall is not None:
  231. return skipall, skipfile, skipall, newpatches
  232. if skipfile is not None:
  233. return skipfile, skipfile, skipall, newpatches
  234. while True:
  235. resps = _('[Ynesfdaq?]'
  236. '$$ &Yes, record this change'
  237. '$$ &No, skip this change'
  238. '$$ &Edit this change manually'
  239. '$$ &Skip remaining changes to this file'
  240. '$$ Record remaining changes to this &file'
  241. '$$ &Done, skip remaining changes and files'
  242. '$$ Record &all changes to all remaining files'
  243. '$$ &Quit, recording no changes'
  244. '$$ &? (display help)')
  245. r = ui.promptchoice("%s %s" % (query, resps))
  246. ui.write("\n")
  247. if r == 8: # ?
  248. for c, t in ui.extractchoices(resps)[1]:
  249. ui.write('%s - %s\n' % (c, t.lower()))
  250. continue
  251. elif r == 0: # yes
  252. ret = True
  253. elif r == 1: # no
  254. ret = False
  255. elif r == 2: # Edit patch
  256. if chunk is None:
  257. ui.write(_('cannot edit patch for whole file'))
  258. ui.write("\n")
  259. continue
  260. if chunk.header.binary():
  261. ui.write(_('cannot edit patch for binary file'))
  262. ui.write("\n")
  263. continue
  264. # Patch comment based on the Git one (based on comment at end of
  265. # http://mercurial.selenic.com/wiki/RecordExtension)
  266. phelp = '---' + _("""
  267. To remove '-' lines, make them ' ' lines (context).
  268. To remove '+' lines, delete them.
  269. Lines starting with # will be removed from the patch.
  270. If the patch applies cleanly, the edited hunk will immediately be
  271. added to the record list. If it does not apply cleanly, a rejects
  272. file will be generated: you can use that when you try again. If
  273. all lines of the hunk are removed, then the edit is aborted and
  274. the hunk is left unchanged.
  275. """)
  276. (patchfd, patchfn) = tempfile.mkstemp(prefix="hg-editor-",
  277. suffix=".diff", text=True)
  278. ncpatchfp = None
  279. try:
  280. # Write the initial patch
  281. f = os.fdopen(patchfd, "w")
  282. chunk.header.write(f)
  283. chunk.write(f)
  284. f.write('\n'.join(['# ' + i for i in phelp.splitlines()]))
  285. f.close()
  286. # Start the editor and wait for it to complete
  287. editor = ui.geteditor()
  288. util.system("%s \"%s\"" % (editor, patchfn),
  289. environ={'HGUSER': ui.username()},
  290. onerr=util.Abort, errprefix=_("edit failed"),
  291. out=ui.fout)
  292. # Remove comment lines
  293. patchfp = open(patchfn)
  294. ncpatchfp = cStringIO.StringIO()
  295. for line in patchfp:
  296. if not line.startswith('#'):
  297. ncpatchfp.write(line)
  298. patchfp.close()
  299. ncpatchfp.seek(0)
  300. newpatches = parsepatch(ncpatchfp)
  301. finally:
  302. os.unlink(patchfn)
  303. del ncpatchfp
  304. # Signal that the chunk shouldn't be applied as-is, but
  305. # provide the new patch to be used instead.
  306. ret = False
  307. elif r == 3: # Skip
  308. ret = skipfile = False
  309. elif r == 4: # file (Record remaining)
  310. ret = skipfile = True
  311. elif r == 5: # done, skip remaining
  312. ret = skipall = False
  313. elif r == 6: # all
  314. ret = skipall = True
  315. elif r == 7: # quit
  316. raise util.Abort(_('user quit'))
  317. return ret, skipfile, skipall, newpatches
  318. seen = set()
  319. applied = {} # 'filename' -> [] of chunks
  320. skipfile, skipall = None, None
  321. pos, total = 1, sum(len(h.hunks) for h in headers)
  322. for h in headers:
  323. pos += len(h.hunks)
  324. skipfile = None
  325. fixoffset = 0
  326. hdr = ''.join(h.header)
  327. if hdr in seen:
  328. continue
  329. seen.add(hdr)
  330. if skipall is None:
  331. h.pretty(ui)
  332. msg = (_('examine changes to %s?') %
  333. _(' and ').join("'%s'" % f for f in h.files()))
  334. r, skipfile, skipall, np = prompt(skipfile, skipall, msg, None)
  335. if not r:
  336. continue
  337. applied[h.filename()] = [h]
  338. if h.allhunks():
  339. applied[h.filename()] += h.hunks
  340. continue
  341. for i, chunk in enumerate(h.hunks):
  342. if skipfile is None and skipall is None:
  343. chunk.pretty(ui)
  344. if total == 1:
  345. msg = _("record this change to '%s'?") % chunk.filename()
  346. else:
  347. idx = pos - len(h.hunks) + i
  348. msg = _("record change %d/%d to '%s'?") % (idx, total,
  349. chunk.filename())
  350. r, skipfile, skipall, newpatches = prompt(skipfile,
  351. skipall, msg, chunk)
  352. if r:
  353. if fixoffset:
  354. chunk = copy.copy(chunk)
  355. chunk.toline += fixoffset
  356. applied[chunk.filename()].append(chunk)
  357. elif newpatches is not None:
  358. for newpatch in newpatches:
  359. for newhunk in newpatch.hunks:
  360. if fixoffset:
  361. newhunk.toline += fixoffset
  362. applied[newhunk.filename()].append(newhunk)
  363. else:
  364. fixoffset += chunk.removed - chunk.added
  365. return sum([h for h in applied.itervalues()
  366. if h[0].special() or len(h) > 1], [])
  367. @command("record",
  368. # same options as commit + white space diff options
  369. commands.table['^commit|ci'][1][:] + commands.diffwsopts,
  370. _('hg record [OPTION]... [FILE]...'))
  371. def record(ui, repo, *pats, **opts):
  372. '''interactively select changes to commit
  373. If a list of files is omitted, all changes reported by :hg:`status`
  374. will be candidates for recording.
  375. See :hg:`help dates` for a list of formats valid for -d/--date.
  376. You will be prompted for whether to record changes to each
  377. modified file, and for files with multiple changes, for each
  378. change to use. For each query, the following responses are
  379. possible::
  380. y - record this change
  381. n - skip this change
  382. e - edit this change manually
  383. s - skip remaining changes to this file
  384. f - record remaining changes to this file
  385. d - done, skip remaining changes and files
  386. a - record all changes to all remaining files
  387. q - quit, recording no changes
  388. ? - display help
  389. This command is not available when committing a merge.'''
  390. dorecord(ui, repo, commands.commit, 'commit', False, *pats, **opts)
  391. def qrefresh(origfn, ui, repo, *pats, **opts):
  392. if not opts['interactive']:
  393. return origfn(ui, repo, *pats, **opts)
  394. mq = extensions.find('mq')
  395. def committomq(ui, repo, *pats, **opts):
  396. # At this point the working copy contains only changes that
  397. # were accepted. All other changes were reverted.
  398. # We can't pass *pats here since qrefresh will undo all other
  399. # changed files in the patch that aren't in pats.
  400. mq.refresh(ui, repo, **opts)
  401. # backup all changed files
  402. dorecord(ui, repo, committomq, 'qrefresh', True, *pats, **opts)
  403. # This command registration is replaced during uisetup().
  404. @command('qrecord',
  405. [],
  406. _('hg qrecord [OPTION]... PATCH [FILE]...'),
  407. inferrepo=True)
  408. def qrecord(ui, repo, patch, *pats, **opts):
  409. '''interactively record a new patch
  410. See :hg:`help qnew` & :hg:`help record` for more information and
  411. usage.
  412. '''
  413. try:
  414. mq = extensions.find('mq')
  415. except KeyError:
  416. raise util.Abort(_("'mq' extension not loaded"))
  417. repo.mq.checkpatchname(patch)
  418. def committomq(ui, repo, *pats, **opts):
  419. opts['checkname'] = False
  420. mq.new(ui, repo, patch, *pats, **opts)
  421. dorecord(ui, repo, committomq, 'qnew', False, *pats, **opts)
  422. def qnew(origfn, ui, repo, patch, *args, **opts):
  423. if opts['interactive']:
  424. return qrecord(ui, repo, patch, *args, **opts)
  425. return origfn(ui, repo, patch, *args, **opts)
  426. def dorecord(ui, repo, commitfunc, cmdsuggest, backupall, *pats, **opts):
  427. if not ui.interactive():
  428. raise util.Abort(_('running non-interactively, use %s instead') %
  429. cmdsuggest)
  430. # make sure username is set before going interactive
  431. if not opts.get('user'):
  432. ui.username() # raise exception, username not provided
  433. def recordfunc(ui, repo, message, match, opts):
  434. """This is generic record driver.
  435. Its job is to interactively filter local changes, and
  436. accordingly prepare working directory into a state in which the
  437. job can be delegated to a non-interactive commit command such as
  438. 'commit' or 'qrefresh'.
  439. After the actual job is done by non-interactive command, the
  440. working directory is restored to its original state.
  441. In the end we'll record interesting changes, and everything else
  442. will be left in place, so the user can continue working.
  443. """
  444. cmdutil.checkunfinished(repo, commit=True)
  445. merge = len(repo[None].parents()) > 1
  446. if merge:
  447. raise util.Abort(_('cannot partially commit a merge '
  448. '(use "hg commit" instead)'))
  449. changes = repo.status(match=match)[:3]
  450. diffopts = opts.copy()
  451. diffopts['nodates'] = True
  452. diffopts['git'] = True
  453. diffopts = patch.diffopts(ui, opts=diffopts)
  454. chunks = patch.diff(repo, changes=changes, opts=diffopts)
  455. fp = cStringIO.StringIO()
  456. fp.write(''.join(chunks))
  457. fp.seek(0)
  458. # 1. filter patch, so we have intending-to apply subset of it
  459. try:
  460. chunks = filterpatch(ui, parsepatch(fp))
  461. except patch.PatchError, err:
  462. raise util.Abort(_('error parsing patch: %s') % err)
  463. del fp
  464. contenders = set()
  465. for h in chunks:
  466. try:
  467. contenders.update(set(h.files()))
  468. except AttributeError:
  469. pass
  470. changed = changes[0] + changes[1] + changes[2]
  471. newfiles = [f for f in changed if f in contenders]
  472. if not newfiles:
  473. ui.status(_('no changes to record\n'))
  474. return 0
  475. modified = set(changes[0])
  476. # 2. backup changed files, so we can restore them in the end
  477. if backupall:
  478. tobackup = changed
  479. else:
  480. tobackup = [f for f in newfiles if f in modified]
  481. backups = {}
  482. if tobackup:
  483. backupdir = repo.join('record-backups')
  484. try:
  485. os.mkdir(backupdir)
  486. except OSError, err:
  487. if err.errno != errno.EEXIST:
  488. raise
  489. try:
  490. # backup continues
  491. for f in tobackup:
  492. fd, tmpname = tempfile.mkstemp(prefix=f.replace('/', '_')+'.',
  493. dir=backupdir)
  494. os.close(fd)
  495. ui.debug('backup %r as %r\n' % (f, tmpname))
  496. util.copyfile(repo.wjoin(f), tmpname)
  497. shutil.copystat(repo.wjoin(f), tmpname)
  498. backups[f] = tmpname
  499. fp = cStringIO.StringIO()
  500. for c in chunks:
  501. if c.filename() in backups:
  502. c.write(fp)
  503. dopatch = fp.tell()
  504. fp.seek(0)
  505. # 3a. apply filtered patch to clean repo (clean)
  506. if backups:
  507. hg.revert(repo, repo.dirstate.p1(),
  508. lambda key: key in backups)
  509. # 3b. (apply)
  510. if dopatch:
  511. try:
  512. ui.debug('applying patch\n')
  513. ui.debug(fp.getvalue())
  514. patch.internalpatch(ui, repo, fp, 1, eolmode=None)
  515. except patch.PatchError, err:
  516. raise util.Abort(str(err))
  517. del fp
  518. # 4. We prepared working directory according to filtered
  519. # patch. Now is the time to delegate the job to
  520. # commit/qrefresh or the like!
  521. # Make all of the pathnames absolute.
  522. newfiles = [repo.wjoin(nf) for nf in newfiles]
  523. commitfunc(ui, repo, *newfiles, **opts)
  524. return 0
  525. finally:
  526. # 5. finally restore backed-up files
  527. try:
  528. for realname, tmpname in backups.iteritems():
  529. ui.debug('restoring %r to %r\n' % (tmpname, realname))
  530. util.copyfile(tmpname, repo.wjoin(realname))
  531. # Our calls to copystat() here and above are a
  532. # hack to trick any editors that have f open that
  533. # we haven't modified them.
  534. #
  535. # Also note that this racy as an editor could
  536. # notice the file's mtime before we've finished
  537. # writing it.
  538. shutil.copystat(tmpname, repo.wjoin(realname))
  539. os.unlink(tmpname)
  540. if tobackup:
  541. os.rmdir(backupdir)
  542. except OSError:
  543. pass
  544. # wrap ui.write so diff output can be labeled/colorized
  545. def wrapwrite(orig, *args, **kw):
  546. label = kw.pop('label', '')
  547. for chunk, l in patch.difflabel(lambda: args):
  548. orig(chunk, label=label + l)
  549. oldwrite = ui.write
  550. extensions.wrapfunction(ui, 'write', wrapwrite)
  551. try:
  552. return cmdutil.commit(ui, repo, recordfunc, pats, opts)
  553. finally:
  554. ui.write = oldwrite
  555. def uisetup(ui):
  556. try:
  557. mq = extensions.find('mq')
  558. except KeyError:
  559. return
  560. cmdtable["qrecord"] = \
  561. (qrecord,
  562. # same options as qnew, but copy them so we don't get
  563. # -i/--interactive for qrecord and add white space diff options
  564. mq.cmdtable['^qnew'][1][:] + commands.diffwsopts,
  565. _('hg qrecord [OPTION]... PATCH [FILE]...'))
  566. _wrapcmd('qnew', mq.cmdtable, qnew, _("interactively record a new patch"))
  567. _wrapcmd('qrefresh', mq.cmdtable, qrefresh,
  568. _("interactively select changes to refresh"))
  569. def _wrapcmd(cmd, table, wrapfn, msg):
  570. entry = extensions.wrapcommand(table, cmd, wrapfn)
  571. entry[1].append(('i', 'interactive', None, msg))