Merge from vendor branch GCC:
[dragonfly.git] / tools / tools / splitpatch / splitpatch.py
1 #!/usr/local/bin/python
2 # $DragonFly: src/tools/tools/splitpatch/splitpatch.py,v 1.2 2005/05/21 10:47:43 corecode Exp $
3
4 """Split a patch file into one patch for each file."""
5
6 __copyright__ = """
7 Copyright (c) 2004 Joerg Sonnenberger.  All rights reserved.
8
9 Redistribution and use in source and binary forms, with or without
10 modification, are permitted provided that the following conditions are
11 met:
12
13   * Redistributions of source code must retain the above copyright
14     notice, this list of conditions and the following disclaimer.
15
16   * Redistributions in binary form must reproduce the above copyright
17     notice, this list of conditions and the following disclaimer in the
18     documentation and/or other materials provided with the distribution.
19
20   * Neither the name of the authors nor the names of there
21     contributors may be used to endorse or promote products derived from
22     this software without specific prior written permission.
23
24 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
25 IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
26 TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
27 PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR
28 CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
30 PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
31 PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
32 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
33 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
34 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35 """
36
37
38 import os.path
39
40 def directory_save(filename, patch, suffix = None, root = None, forceful = False):
41         """
42         Saves patch into filename.suffix relative to root.
43         """
44         if suffix is None:
45                 suffix = ".patch"
46         if root is None:
47                 root = ""
48         output_name  = os.path.join(root, "%s%s" % (filename.replace('/',','), suffix))
49         
50         if os.path.exists(output_name) and not forceful:
51                 raise IOError, 'file exists'
52         f = open(output_name,"w")
53         f.write(patch)
54         f.close()
55
56 def splitpatch(source, output = directory_save, quiet = False, tag = False):
57         """
58         Split the patch in source into independent pieces
59         and call output on the result with the guessed filename
60         and the patch itself.
61         
62         source has to provide an iterator like file objects.
63         """
64         diff_line = { " ": True, "+": True, "-": True, "@": True, "!": True, '*': True }
65         buf = []
66         if tag:
67                 buf.append('$''DragonFly$\n')
68         filename = None
69         for line in source:
70                 if not filename:
71                         if line.startswith('***'):
72                                 # context diff
73                                 filename = line.split()[1]
74                         elif line.startswith('+++'):
75                                 # unified diff
76                                 filename = line.split()[1]
77
78                         if filename and not quiet:
79                                 print "Found patch for %s" % filename
80
81                         buf.append(line)
82                 elif diff_line.get(line[0]):
83                         # valid line for a patch
84                         buf.append(line)
85                 else:
86                         # invalid line for a patch, write out current buffer
87                         output(filename, "".join(buf))
88
89                         filename = None
90                         buf = []
91                         if tag:
92                                 buf.append('$''DragonFly$\n')
93
94         if filename:
95                 output(filename, "".join(buf))
96
97 def main():
98         from optparse import OptionParser
99         import sys
100         parser = OptionParser("usage: %prog [-q] [-f] [-s suffix] [input]")
101         parser.add_option("-q", "--quiet", action="store_true", dest="quiet", help="do not print names of the subpatches")
102         parser.add_option("-f", "--force", action="store_true", dest="force", help="overwrite existing patches")
103         parser.add_option("-s", "--suffix", type="string", dest="suffix", help="use SUFFIX instead of .patch for the created patches")
104         parser.add_option("-d", "--directory", type="string", dest="directory", help="create patches in DIRECTORY")
105         parser.add_option("-t", "--tag", action="store_true", dest="tag", help="add DragonFly CVS tag")
106         (options, args) = parser.parse_args()
107         if len(args) > 1:
108                 parser.error("incorrect number of arguments")
109         if args:
110                 source = open(args[0])
111         else:
112                 source = sys.stdin
113         splitpatch(source, lambda filename, patch: directory_save(filename, patch, forceful = options.force,
114                                 suffix = options.suffix, root = options.directory), quiet = options.quiet, tag = options.tag)
115
116 if __name__ == '__main__':
117         main()