本文整理汇总了Python中mercurial.patch.diff函数的典型用法代码示例。如果您正苦于以下问题:Python diff函数的具体用法?Python diff怎么用?Python diff使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了diff函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: dohgdiff
def dohgdiff():
difftext = StringIO.StringIO()
try:
if len(files) != 0:
wfiles = [self.repo.wjoin(x) for x in files]
fns, matchfn, anypats = cmdutil.matchpats(self.repo, wfiles, self.opts)
patch.diff(self.repo, self._node1, self._node2, fns, match=matchfn,
fp=difftext, opts=patch.diffopts(self.ui, self.opts))
buffer = gtk.TextBuffer()
buffer.create_tag('removed', foreground='#900000')
buffer.create_tag('added', foreground='#006400')
buffer.create_tag('position', foreground='#FF8000')
buffer.create_tag('header', foreground='#000090')
difftext.seek(0)
iter = buffer.get_start_iter()
for line in difftext:
line = toutf(line)
if line.startswith('---') or line.startswith('+++'):
buffer.insert_with_tags_by_name(iter, line, 'header')
elif line.startswith('-'):
buffer.insert_with_tags_by_name(iter, line, 'removed')
elif line.startswith('+'):
buffer.insert_with_tags_by_name(iter, line, 'added')
elif line.startswith('@@'):
buffer.insert_with_tags_by_name(iter, line, 'position')
else:
buffer.insert(iter, line)
self.diff_text.set_buffer(buffer)
finally:
difftext.close()
示例2: recordfunc
def recordfunc(ui, repo, files, message, match, opts):
"""This is generic record driver.
It's job is to interactively filter local changes, and accordingly
prepare working dir into a state, where the job can be delegated to
non-interactive commit command such as 'commit' or 'qrefresh'.
After the actual job is done by non-interactive command, working dir
state is restored to original.
In the end we'll record intresting changes, and everything else will be
left in place, so the user can continue his work.
"""
if files:
changes = None
else:
changes = repo.status(files=files, match=match)[:5]
modified, added, removed = changes[:3]
files = modified + added + removed
diffopts = mdiff.diffopts(git=True, nodates=True)
fp = cStringIO.StringIO()
patch.diff(repo, repo.dirstate.parents()[0], files=files,
match=match, changes=changes, opts=diffopts, fp=fp)
fp.seek(0)
# 1. filter patch, so we have intending-to apply subset of it
chunks = filterpatch(ui, parsepatch(fp))
del fp
contenders = {}
for h in chunks:
try: contenders.update(dict.fromkeys(h.files()))
except AttributeError: pass
newfiles = [f for f in files if f in contenders]
if not newfiles:
ui.status(_('no changes to record\n'))
return 0
if changes is None:
changes = repo.status(files=newfiles, match=match)[:5]
modified = dict.fromkeys(changes[0])
# 2. backup changed files, so we can restore them in the end
backups = {}
backupdir = repo.join('record-backups')
try:
os.mkdir(backupdir)
except OSError, err:
if err.errno != errno.EEXIST:
raise
示例3: difftree
def difftree(ui, repo, node1=None, node2=None, *files, **opts):
"""diff trees from two commits"""
def __difftree(repo, node1, node2, files=[]):
assert node2 is not None
mmap = repo.changectx(node1).manifest()
mmap2 = repo.changectx(node2).manifest()
status = repo.status(node1, node2, files=files)[:5]
modified, added, removed, deleted, unknown = status
empty = short(nullid)
for f in modified:
# TODO get file permissions
ui.write(":100664 100664 %s %s M\t%s\t%s\n" %
(short(mmap[f]), short(mmap2[f]), f, f))
for f in added:
ui.write(":000000 100664 %s %s N\t%s\t%s\n" %
(empty, short(mmap2[f]), f, f))
for f in removed:
ui.write(":100664 000000 %s %s D\t%s\t%s\n" %
(short(mmap[f]), empty, f, f))
##
while True:
if opts['stdin']:
try:
line = raw_input().split(' ')
node1 = line[0]
if len(line) > 1:
node2 = line[1]
else:
node2 = None
except EOFError:
break
node1 = repo.lookup(node1)
if node2:
node2 = repo.lookup(node2)
else:
node2 = node1
node1 = repo.changelog.parents(node1)[0]
if opts['patch']:
if opts['pretty']:
catcommit(ui, repo, node2, "")
patch.diff(repo, node1, node2,
files=files,
opts=patch.diffopts(ui, {'git': True}))
else:
__difftree(repo, node1, node2, files=files)
if not opts['stdin']:
break
示例4: finishfold
def finishfold(ui, repo, ctx, oldctx, newnode, opts, internalchanges):
parent = ctx.parents()[0].node()
hg.update(repo, parent)
fd, patchfile = tempfile.mkstemp(prefix='hg-histedit-')
fp = os.fdopen(fd, 'w')
diffopts = patch.diffopts(ui, opts)
diffopts.git = True
gen = patch.diff(repo, parent, newnode, opts=diffopts)
for chunk in gen:
fp.write(chunk)
fp.close()
files = {}
try:
patch.patch(patchfile, ui, cwd=repo.root, files=files, eolmode=None)
finally:
files = patch.updatedir(ui, repo, files)
os.unlink(patchfile)
newmessage = '\n***\n'.join(
[ctx.description(), ] +
[repo[r].description() for r in internalchanges] +
[oldctx.description(), ])
newmessage = ui.edit(newmessage, ui.username())
n = repo.commit(text=newmessage, user=ui.username(), date=max(ctx.date(), oldctx.date()),
extra=oldctx.extra())
return repo[n], [n, ], [oldctx.node(), ctx.node() ], [newnode, ] # xxx
示例5: pick
def pick(ui, repo, ctx, ha, opts):
oldctx = repo[ha]
if oldctx.parents()[0] == ctx:
ui.debug('node %s unchanged\n' % ha)
return oldctx, [], [], []
hg.update(repo, ctx.node())
fd, patchfile = tempfile.mkstemp(prefix='hg-histedit-')
fp = os.fdopen(fd, 'w')
diffopts = patch.diffopts(ui, opts)
diffopts.git = True
gen = patch.diff(repo, oldctx.parents()[0].node(), ha, opts=diffopts)
for chunk in gen:
fp.write(chunk)
fp.close()
try:
files = {}
try:
patch.patch(patchfile, ui, cwd=repo.root, files=files, eolmode=None)
if not files:
ui.warn(_('%s: empty changeset')
% node.hex(ha))
return ctx, [], [], []
finally:
files = patch.updatedir(ui, repo, files)
os.unlink(patchfile)
except Exception, inst:
raise util.Abort(_('Fix up the change and run '
'hg histedit --continue'))
示例6: apply_change
def apply_change(node, reverse, push_patch=True, name=None):
p1, p2 = repo.changelog.parents(node)
if p2 != nullid:
raise util.Abort('cannot %s a merge changeset' % desc['action'])
opts = mdiff.defaultopts
opts.git = True
rpatch = StringIO.StringIO()
orig, mod = (node, p1) if reverse else (p1, node)
for chunk in patch.diff(repo, node1=orig, node2=mod, opts=opts):
rpatch.write(chunk)
rpatch.seek(0)
saved_stdin = None
try:
save_fin = ui.fin
ui.fin = rpatch
except:
# Old versions of hg did not use the ui.fin mechanism
saved_stdin = sys.stdin
sys.stdin = rpatch
if push_patch:
commands.import_(ui, repo, '-',
force=True,
no_commit=True,
strip=1,
base='')
else:
mq.qimport(ui, repo, '-', name=name, rev=[], git=True)
if saved_stdin is None:
ui.fin = save_fin
else:
sys.stdin = saved_stdin
示例7: diff
def diff(self, ctx, ref=None):
maxdiff = int(self.ui.config('notify', 'maxdiff', 300))
prev = ctx.p1().node()
if ref:
ref = ref.node()
else:
ref = ctx.node()
chunks = patch.diff(self.repo, prev, ref,
opts=patch.diffallopts(self.ui))
difflines = ''.join(chunks).splitlines()
if self.ui.configbool('notify', 'diffstat', True):
s = patch.diffstat(difflines)
# s may be nil, don't include the header if it is
if s:
self.ui.write('\ndiffstat:\n\n%s' % s)
if maxdiff == 0:
return
elif maxdiff > 0 and len(difflines) > maxdiff:
msg = _('\ndiffs (truncated from %d to %d lines):\n\n')
self.ui.write(msg % (len(difflines), maxdiff))
difflines = difflines[:maxdiff]
elif difflines:
self.ui.write(_('\ndiffs (%d lines):\n\n') % len(difflines))
self.ui.write("\n".join(difflines))
示例8: get_lines_and_files
def get_lines_and_files(ui, repo, ctx1, ctx2, fns):
# Returns a list of dicts:
# [{'filename': <file>, 'added': nn, 'removed': nn},
# {....},
# ]
files = []
currentfile = {}
fmatch = scmutil.matchfiles(repo, fns)
diff = ''.join(patch.diff(repo, ctx1.node(), ctx2.node(), fmatch))
for l in diff.split('\n'):
if l.startswith("diff -r"):
# If we have anything in currentfile, append to list
if currentfile:
files.append(currentfile)
currentfile = {}
# This is the first line of a file set current file
currentfile['filename'] = l.split(' ')[-1]
currentfile['added'] = 0
currentfile['removed'] = 0
if l.startswith("+") and not l.startswith("+++ "):
currentfile['added'] += 1
elif l.startswith("-") and not l.startswith("--- "):
currentfile['removed'] += 1
# The last file won't have been added to files, so add it now
files.append(currentfile)
return files
示例9: apply_change
def apply_change(node, reverse, push_patch=True, name=None):
p1, p2 = repo.changelog.parents(node)
if p2 != nullid:
raise util.Abort('cannot %s a merge changeset' % desc['action'])
opts = mdiff.defaultopts
opts.git = True
rpatch = StringIO.StringIO()
orig, mod = (node, p1) if reverse else (p1, node)
for chunk in patch.diff(repo, node1=orig, node2=mod, opts=opts):
rpatch.write(chunk)
rpatch.seek(0)
saved_stdin = None
try:
save_fin = ui.fin
ui.fin = rpatch
except:
# Old versions of hg did not use the ui.fin mechanism
saved_stdin = sys.stdin
sys.stdin = rpatch
handle_change(desc, node, qimport=(use_mq and new_opts.get('nopush')))
if saved_stdin is None:
ui.fin = save_fin
else:
sys.stdin = saved_stdin
示例10: get_gitdiff
def get_gitdiff(filenode_old, filenode_new):
"""Returns mercurial style git diff between given
``filenode_old`` and ``filenode_new``.
"""
for filenode in (filenode_old, filenode_new):
if not isinstance(filenode, FileNode):
raise VCSError("Given object should be FileNode object, not %s"
% filenode.__class__)
repo = filenode_new.changeset.repository
old_raw_id = getattr(filenode_old.changeset, 'raw_id', '0' * 40)
new_raw_id = getattr(filenode_new.changeset, 'raw_id', '0' * 40)
root = filenode_new.changeset.repository.path
file_filter = match(root, '', [filenode_new.path])
if isinstance(repo, MercurialRepository):
vcs_gitdiff = patch.diff(repo._repo,
old_raw_id,
new_raw_id,
match=file_filter,
opts=diffopts(git=True))
else:
vcs_gitdiff = repo._get_diff(old_raw_id, new_raw_id, filenode_new.path)
return vcs_gitdiff
示例11: new_commit
def new_commit(orig_commit, ui, repo, *pats, **opts):
if opts['message'] or opts['logfile']:
# don't act if user already specified a message
return orig_commit(ui, repo, *pats, **opts)
# check if changelog changed
logname = ui.config('changelog', 'filename', 'CHANGES')
if pats:
match = cmdutil.match(repo, pats, opts)
if logname not in match:
# changelog is not mentioned
return orig_commit(ui, repo, *pats, **opts)
logmatch = cmdutil.match(repo, [logname], {})
logmatch.bad = lambda f, msg: None # don't complain if file is missing
# get diff of changelog
log = []
for chunk in patch.diff(repo, None, None, match=logmatch):
for line in chunk.splitlines():
# naive: all added lines are the changelog
if line.startswith('+') and not line.startswith('+++'):
log.append(line[1:].rstrip().expandtabs())
log = normalize_log(log)
# always let the user edit the message
opts['force_editor'] = True
opts['message'] = log
return orig_commit(ui, repo, *pats, **opts)
示例12: fold
def fold(ui, repo, ctx, ha, opts):
oldctx = repo[ha]
hg.update(repo, ctx.node())
fd, patchfile = tempfile.mkstemp(prefix='hg-histedit-')
fp = os.fdopen(fd, 'w')
diffopts = patch.diffopts(ui, opts)
diffopts.git = True
diffopts.ignorews = False
diffopts.ignorewsamount = False
diffopts.ignoreblanklines = False
gen = patch.diff(repo, oldctx.parents()[0].node(), ha, opts=diffopts)
for chunk in gen:
fp.write(chunk)
fp.close()
try:
files = set()
try:
applypatch(ui, repo, patchfile, files=files, eolmode=None)
if not files:
ui.warn(_('%s: empty changeset')
% node.hex(ha))
return ctx, [], [], []
finally:
os.unlink(patchfile)
except Exception, inst:
raise util.Abort(_('Fix up the change and run '
'hg histedit --continue'))
示例13: recordfunc
def recordfunc(ui, repo, message, match, opts):
"""This is generic record driver.
Its job is to interactively filter local changes, and
accordingly prepare working directory into a state in which the
job can be delegated to a non-interactive commit command such as
'commit' or 'qrefresh'.
After the actual job is done by non-interactive command, the
working directory is restored to its original state.
In the end we'll record interesting changes, and everything else
will be left in place, so the user can continue working.
"""
cmdutil.checkunfinished(repo, commit=True)
merge = len(repo[None].parents()) > 1
if merge:
raise util.Abort(_("cannot partially commit a merge " '(use "hg commit" instead)'))
status = repo.status(match=match)
diffopts = opts.copy()
diffopts["nodates"] = True
diffopts["git"] = True
diffopts = patch.diffopts(ui, opts=diffopts)
chunks = patch.diff(repo, changes=status, opts=diffopts)
fp = cStringIO.StringIO()
fp.write("".join(chunks))
fp.seek(0)
# 1. filter patch, so we have intending-to apply subset of it
try:
chunks = filterpatch(ui, parsepatch(fp))
except patch.PatchError, err:
raise util.Abort(_("error parsing patch: %s") % err)
示例14: diff
def diff(orig, ui, repo, *args, **opts):
"""show a diff of the most recent revision against its parent from svn
"""
if not opts.get('svn', False) or opts.get('change', None):
return orig(ui, repo, *args, **opts)
meta = repo.svnmeta()
hashes = meta.revmap.hashes()
if not opts.get('rev', None):
parent = repo.parents()[0]
o_r = util.outgoing_revisions(repo, hashes, parent.node())
if o_r:
parent = repo[o_r[-1]].parents()[0]
opts['rev'] = ['%s:.' % node.hex(parent.node()), ]
node1, node2 = cmdutil.revpair(repo, opts['rev'])
baserev, _junk = hashes.get(node1, (-1, 'junk'))
newrev, _junk = hashes.get(node2, (-1, 'junk'))
it = patch.diff(repo, node1, node2,
opts=patch.diffopts(ui, opts={'git': True,
'show_function': False,
'ignore_all_space': False,
'ignore_space_change': False,
'ignore_blank_lines': False,
'unified': True,
'text': False,
}))
ui.write(util.filterdiff(''.join(it), baserev, newrev))
示例15: finishfold
def finishfold(ui, repo, ctx, oldctx, newnode, opts, internalchanges):
parent = ctx.parents()[0].node()
hg.update(repo, parent)
fd, patchfile = tempfile.mkstemp(prefix='hg-histedit-')
fp = os.fdopen(fd, 'w')
diffopts = patch.diffopts(ui, opts)
diffopts.git = True
diffopts.ignorews = False
diffopts.ignorewsamount = False
diffopts.ignoreblanklines = False
gen = patch.diff(repo, parent, newnode, opts=diffopts)
for chunk in gen:
fp.write(chunk)
fp.close()
files = set()
try:
applypatch(ui, repo, patchfile, files=files, eolmode=None)
finally:
os.unlink(patchfile)
newmessage = '\n***\n'.join(
[ctx.description(), ] +
[repo[r].description() for r in internalchanges] +
[oldctx.description(), ])
# If the changesets are from the same author, keep it.
if ctx.user() == oldctx.user():
username = ctx.user()
else:
username = ui.username()
newmessage = ui.edit(newmessage, username)
n = repo.commit(text=newmessage, user=username, date=max(ctx.date(), oldctx.date()),
extra=oldctx.extra())
return repo[n], [n, ], [oldctx.node(), ctx.node() ], [newnode, ] # xxx