File: xxdiff-patch-UNFINISHED

package info (click to toggle)
xxdiff 1%3A3.1-3
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 3,936 kB
  • ctags: 2,393
  • sloc: cpp: 19,971; python: 3,334; ansic: 1,505; sh: 1,466; perl: 308; yacc: 273; lex: 219; lisp: 115; makefile: 101
file content (305 lines) | stat: -rwxr-xr-x 10,946 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
#!/usr/bin/env python
#******************************************************************************\
#* $Source: /u/blais/cvsroot/xxdiff/bin/xxdiff-patch-UNFINISHED,v $
#* $Id: xxdiff-patch-UNFINISHED,v 1.8 2004/02/25 17:37:35 blais Exp $
#* $Date: 2004/02/25 17:37:35 $
#*
#* Copyright (C) 2003-2004 Martin Blais <blais@furius.ca>
#*
#* This program is free software; you can redistribute it and/or modify
#* it under the terms of the GNU General Public License as published by
#* the Free Software Foundation; either version 2 of the License, or
#* (at your option) any later version.
#*
#* This program is distributed in the hope that it will be useful,
#* but WITHOUT ANY WARRANTY; without even the implied warranty of
#* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#* GNU General Public License for more details.
#*
#* You should have received a copy of the GNU General Public License
#* along with this program; if not, write to the Free Software
#* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#*
#*****************************************************************************/

"""xxdiff-patch [<options>] [<patchfile>]

This simple script splits the input patch for the individual files it
represents, applies the individual patches to temporary files and for each,
spawns an xxdiff for it.  This effectively allows you merge the patch
interactively.  You can accept or reject a patch for each file.  You can also
merge the patch interactively with xxdiff, and select for the merged results to
be applied on the output file.

If no <patchfile> is specified, xxdiff-patch attempts to read the patch from
stdin.

Important: the new (patched) file will always be shown on the right.  The
patched file will display (patched) in its filename title.  When a decision is
asked to the user, ACCEPT always means keep/save the file that appears on the
right.  The script takes the following actions upon the answer:

- ACCEPT: keep/copy the file on the right side to the output file;
- REJECT: keep/copy the file on the left side to the output file;
- MERGED: copy the merged file on the output file;

If a patch for a file is accepted or merged, before being overwritten, a copy of
the original files are saved with the extension .orig, like patch itself.

Note: notice that the --reverse and --invert options below are implementing
orthogonal behaviour.  It can be confusing to understand the differences
between these two.  If the a reverse patch is indeed reverting changes (and
not constructed in the incorrect order), applying the patch will revert the
changes as well (the display order is not changed).  This behaviour is
exactly like that of patch.  Using invert, however, changes the logic of
what this script does upon accepting or rejecting a patch.  In any case, you
will always find the 'new file if accepted' on the right side and the
patched file is indicated with a string in the filename title.

Examples
--------

  To apply a patch, simply cd into the root of the directory where the patch
  should be applied, and invoke like this:

     cat patchfile | xxdiff-patch

  To preview the changes that have been made in a cvs checkout area, use the
  following command::

     cvs diff | xxdiff-patch --reverse --invert --preview

  (For better cvs-specific behaviour about committing changes, see script
  xxdiff-cvs-diff.)

.. important::

   This script is unfinished, we still need to implement file addition/removal
   support.

"""

__title__ = 'xxdiff-patch'
__version__ = "$Revision: 1.8 $"
__author__ = "Martin Blais <blais@furius.ca>"
__depends__ = ['xxdiff', 'Python-2.3', 'diffutils (patch)']
__copyright__ = """Copyright (C) 2003-2004 Martin Blais <blais@furius.ca>.
This code is distributed under the terms of the GNU General Public License."""

import sys
print >> sys.stderr, \
    "Error: FIXME not finished have yet to deal with deleted and added files"

#===============================================================================
# EXTERNAL DECLARATIONS
#===============================================================================

import sys, os, os.path
import re
import commands, shutil
from tempfile import NamedTemporaryFile

#===============================================================================
# LOCAL DECLARATIONS
#===============================================================================

tmppfx = '%s.' % os.path.basename(sys.argv[0])

#-------------------------------------------------------------------------------
#
def splitpatch( text ):

    """Split output in chunks starting with ^Index.  Returns a list of pairs
    (tuples), each with (filename, patch) contents."""

    ## splitre = re.compile('^Index: (.*)$', re.M)
    splitre = re.compile('^diff (.*)\s+(\S+)\s+(\S+)\s*$', re.M)
    chunks = []
    curbeg, curfn = None, None
    for mo in splitre.finditer(text):
        if curbeg != None:
            assert curfn
            chunks.append( (curfn, text[curbeg:mo.start()]) )
        curbeg = mo.start()
        curfn = mo.groups()[-1]
    if curbeg != None:
        chunks.append( (curfn, text[curbeg:]) )

    return chunks

#-------------------------------------------------------------------------------
#
def complete( parser ):
    "Programmable completion support. Script should work without it."
    try:
        import optcomplete
        optcomplete.autocomplete(parser)
    except ImportError:
        pass

#===============================================================================
# MAIN
#===============================================================================

def main():
    import optparse
    parser = optparse.OptionParser(__doc__.strip(), version=__version__)

    parser.add_option('-x', '--xxdiff-options', action='store', metavar="OPTS",
                      default='',
                      help="specifies additional options to pass on to xxdiff.")

    parser.add_option('-p', '--patch-options', action='store', metavar="OPTS",
                      default='',
                      help="specifies additional options to pass on to patch.")
    parser.add_option('-s', '--strip', action='store', type='int',
                      help="strip option to patch, provided for convenience.")

    parser.add_option('-R', '--reverse', action='store_true',
                      help="""apply the patch as a reverse patch (see
                      patch(1) option --reverse).  The patched file will be
                      shown as the new file regardless.""")

    parser.add_option('-I', '--invert', action='store_true',
                      help="""change the order of the displayed files, so that
                      the patched file shows as the old file.  Accepting a
                      change will thus do nothing and rejecting a change
                      will copy the patched file over.""")

    parser.add_option('-n', '--dry-run', '--preview', action='store_true',
                      help="""don't apply the patch, just show the
                      differences (you don't have to make any decisions).""")

    parser.add_option('-B', '--no-backup', action='store_true',
                      help="disable backup filesa")

    complete(parser)
    opts, args = parser.parse_args()

    #
    # read the input file.
    #
    if not args:
        args = ['-']

    chunks = []
    for fn in args:
        try:
            if fn == '-':
                iif = sys.stdin
            else:
                iif = open(fn, 'r')
            text = iif.read()
            iif.close()
        except IOError, e:
            raise SystemExit(
                "Error: reading patchfile %s: %s" % (fn, str(e)))

        chunks += splitpatch(text)

    #
    # For each subpatch, apply it individually
    #
    for filename, patch in chunks:
        ## print '*' * 80
        ## print fn
        ## print text

        # print patch contents for this file.
        print
        print
        print "FILE:", filename
        print '*' * 40
        print patch
        print '*' * 40

        # feed diffs to patch, patch will do its deed and save the output to
        # a temporary file.
        tmpfp = NamedTemporaryFile(prefix=tmppfx)

        popts = opts.patch_options
        popts += ['--reverse', ''][ opts.reverse == None ]
        if opts.strip:
            popts += '--strip=%d' % opts.strip
        cmd = 'patch %s --output "%s"' % (popts, tmpfp.name)
        cin, cout = os.popen2(cmd, 'rw')
        cin.write('Index: %s\n' % filename)
        cin.write(patch)
        cin.close()

        # read output from patch.
        print cout.read()
        if cout.close() != None:
            print >> sys.stderr, "Error: running patch."

        #
        # spawn xxdiff
        #

        # compute stripped filename
        sfilename = filename
        if opts.strip:
            sfilename = os.sep.join(sfilename.split(os.sep)[opts.strip:])

        pno = 2
        leftfn, rightfn = sfilename, tmpfp.name

###FIXME not finished have to deal with deleted and added files

        # swap files if requested
        if opts.invert:
            leftfn, rightfn = rightfn, leftfn
            pno = 1

        # calculate xxdiff options
        dopts = ''
        if not opts.dry_run:
            # create temporary file to hold merged results.
            tmpfm = NamedTemporaryFile('w', prefix=tmppfx)
            dopts += '--decision --merged-filename "%s" ' % tmpfm.name

        dopts += '--title%d="%s (patched)"' % (pno, sfilename)
        dopts += opts.xxdiff_options
        cmd = 'xxdiff %s "%s" "%s"' % (dopts, leftfn, rightfn)

        try:
            s, o = commands.getstatusoutput(cmd)
        except KeyboardInterrupt:
            raise SystemExit("Interrupted.")

        # print output of xxdiff command.
        if o: print o

        # perform the requested action
        if o and not opts.dry_run:

            if o == 'ACCEPT':
                if not opts.invert:
                    if not opts.no_backup:
                        shutil.copyfile(sfilename, "%s.bak" % sfilename)
                    shutil.copyfile(rightfn, sfilename)
                else:
                    assert rightfn == sfilename

            elif o == 'REJECT':
                if not opts.invert:
                    if not opts.no_backup:
                        shutil.copyfile(sfilename, "%s.bak" % sfilename)
                    shutil.copyfile(leftfn, sfilename)
                else:
                    assert leftfn == sfilename

            elif o == 'MERGED':
                if not opts.no_backup:
                    shutil.copyfile(sfilename, "%s.bak" % sfilename)
                shutil.copyfile(tmpfm.name, sfilename)

            elif o == 'NODECISION':
                pass # do nothing

            else:
                raise SystemExit(
                        "Error: unexpected answer from xxdiff: %s" % o)

if __name__ == '__main__':
    main()