3 # Module ndiff version 1.7.0
4 # Released to the public domain 08-Dec-2000,
5 # by Tim Peters (tim.one@home.com).
7 # Provided as-is; use at your own risk; no warranty; no promises; enjoy!
9 # ndiff.py is now simply a front-end to the difflib.ndiff() function.
10 # Originally, it contained the difflib.SequenceMatcher class as well.
11 # This completes the raiding of reusable code from this formerly
12 # self-contained script.
14 """ndiff [-q] file1 file2
16 ndiff (-r1 | -r2) < ndiff_output > file1_or_file2
18 Print a human-friendly file difference report to stdout. Both inter-
19 and intra-line differences are noted. In the second form, recreate file1
20 (-r1) or file2 (-r2) on stdout, from an ndiff report on stdin.
22 In the first form, if -q ("quiet") is not specified, the first two lines
28 Each remaining line begins with a two-letter code:
30 "- " line unique to file1
31 "+ " line unique to file2
32 " " line common to both files
33 "? " line not present in either input file
35 Lines beginning with "? " attempt to guide the eye to intraline
36 differences, and were not present in either input file. These lines can be
37 confusing if the source files contain tab characters.
39 The first file can be recovered by retaining only lines that begin with
40 " " or "- ", and deleting those 2-character prefixes; use ndiff with -r1.
42 The second file can be recovered similarly, but by retaining only " " and
43 "+ " lines; use ndiff with -r2; or, on Unix, the second file can be
44 recovered by piping the output through
46 sed -n '/^[+ ] /s/^..//p'
54 out
= sys
.stderr
.write
59 # open a file & return the file object; gripe and return 0 if it
63 return open(fname
, 'r')
64 except IOError, detail
:
65 return fail("couldn't open " + fname
+ ": " + str(detail
))
67 # open two files & spray the diff to stdout; return false iff a problem
68 def fcompare(f1name
, f2name
):
74 a
= f1
.readlines(); f1
.close()
75 b
= f2
.readlines(); f2
.close()
77 diff
= difflib
.ndiff(a
, b
)
78 sys
.stdout
.writelines(diff
)
82 # crack args (sys.argv[1:] is normal) & compare;
83 # return false iff a problem
88 opts
, args
= getopt
.getopt(args
, "qr:")
89 except getopt
.error
, detail
:
90 return fail(str(detail
))
101 return fail("can't specify both -q and -r")
104 return fail("no args allowed with -r option")
105 if whichfile
in "12":
108 return fail("-r value must be 1 or 2")
110 return fail("need 2 filename args")
111 f1name
, f2name
= args
115 return fcompare(f1name
, f2name
)
117 # read ndiff output from stdin, and print file1 (which=='1') or
118 # file2 (which=='2') to stdout
121 restored
= difflib
.restore(sys
.stdin
.readlines(), which
)
122 sys
.stdout
.writelines(restored
)
124 if __name__
== '__main__':
126 if "-profile" in args
:
127 import profile
, pstats
128 args
.remove("-profile")
130 profile
.run("main(args)", statf
)
131 stats
= pstats
.Stats(statf
)
132 stats
.strip_dirs().sort_stats('time').print_stats()