Skip to content

Commit e40ca1a

Browse files
author
rhettinger
committed
Added a command line interface for difflib.py
git-svn-id: http://svn.python.org/projects/python/trunk@33042 6015fed2-1504-0410-9fe1-9d1591cc4771
1 parent 3fa1dbb commit e40ca1a

2 files changed

Lines changed: 42 additions & 0 deletions

File tree

Tools/scripts/README

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ copytime.py Copy one file's atime and mtime to another
1515
crlf.py Change CRLF line endings to LF (Windows to Unix)
1616
cvsfiles.py Print a list of files that are under CVS
1717
db2pickle.py Dump a database file to a pickle
18+
diff.py Print file diffs in context, unified, or ndiff formats
1819
dutree.py Format du(1) output as a tree sorted by size
1920
eptags.py Create Emacs TAGS file for Python modules
2021
finddiv.py A grep-like tool that looks for division operators.

Tools/scripts/diff.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
""" Command line interface to difflib.py providing diffs in three formats:
2+
3+
* ndiff: lists every line and highlights interline changes.
4+
* context: highlights clusters of changes in a before/after format
5+
* unified: highlights clusters of changes in an inline format.
6+
7+
"""
8+
9+
import sys, os, time, difflib, optparse
10+
11+
usage = "usage: %prog [options] fromfile tofile"
12+
parser = optparse.OptionParser(usage)
13+
parser.add_option("-c", action="store_true", default=False, help='Produce a context format diff (default)')
14+
parser.add_option("-u", action="store_true", default=False, help='Produce a unified format diff')
15+
parser.add_option("-n", action="store_true", default=False, help='Produce a ndiff format diff')
16+
parser.add_option("-l", "--lines", type="int", default=3, help='Set number of context lines (default 3)')
17+
(options, args) = parser.parse_args()
18+
19+
if len(args) == 0:
20+
parser.print_help()
21+
sys.exit(1)
22+
if len(args) != 2:
23+
parser.error("need to specify both a fromfile and tofile")
24+
25+
n = options.lines
26+
fromfile, tofile = args
27+
28+
fromdate = time.ctime(os.stat(fromfile).st_mtime)
29+
todate = time.ctime(os.stat(tofile).st_mtime)
30+
fromlines = open(fromfile).readlines()
31+
tolines = open(tofile).readlines()
32+
33+
if options.u:
34+
diff = difflib.unified_diff(fromlines, tolines, fromfile, tofile, fromdate, todate, n=n)
35+
elif options.n:
36+
diff = difflib.ndiff(fromlines, tolines)
37+
else:
38+
diff = difflib.context_diff(fromlines, tolines, fromfile, tofile, fromdate, todate, n=n)
39+
40+
sys.stdout.writelines(diff)
41+

0 commit comments

Comments
 (0)