summaryrefslogtreecommitdiffstats
path: root/typeobject.py
blob: 9967022afc2e51fa1234d1267d124cdc7750868e (plain)
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
import sys
import re
from difflib import unified_diff

# Whitespace patterns:
req_ws = r'\s+'
opt_ws = r'\s*'
c_identifier = r'([_A-Za-z][_0-9A-Za-z]*)'

pat = ('.*' + r'PyTypeObject' + req_ws
       + c_identifier + opt_ws 
       + r'=' + opt_ws + r'\{' + opt_ws 
       + r'(PyObject_HEAD_INIT\((.*)\)' + opt_ws 
       + r'([0-9]+)' + opt_ws + r',).*'
       )

def fixup_typeobject_initializers(content):
    while True:
        m = re.match(pat, content, re.DOTALL)
        if m:
            if False:
                print m.groups()
                print m.group(2)
                print m.group(3)
                print m.group(4)
                print m.span(2)
            content = (content[:m.start(2)] 
                       + 'PyVarObject_HEAD_INIT(%s, %s)' % (m.group(3),m.group(4))
                       + content[m.end(2):])
        else:
            return content

import unittest
class TestFixups(unittest.TestCase):
    def test_fixups(self):
        self.assertEquals(fixup_typeobject_initializers('''
PyTypeObject DBusPyIntBase_Type = {
    PyObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type))
    0,
    "_dbus_bindings._IntBase",
'''
                                                        ),
                          '''
PyTypeObject DBusPyIntBase_Type = {
    PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
    "_dbus_bindings._IntBase",
'''
                          )


def fixup_file(filename, options):
    content = open(filename, 'r').read()        
    fixed_content = fixup_typeobject_initializers(content)
    if content != fixed_content:
        for line in unified_diff(content.splitlines(),
                                 fixed_content.splitlines(), 
                                 fromfile = filename+'.orig',
                                 tofile = filename,
                                 lineterm=''):
            print line

        if options.write:
            open(filename, 'w').write(fixed_content)
        
def main():
    from optparse import OptionParser
    usage = "usage: %prog [options] filenames..."
    parser = OptionParser(usage=usage)
    parser.add_option('-w', '--write',
                      action="store_true", dest="write", default=False,
                      help="Write back modified files")
    (options, args) = parser.parse_args()
    # print (options, args)
    for filename in args:
        fixup_file(filename, options)

if __name__ == '__main__':
    if len(sys.argv) == 1:
        unittest.main()
    else:
        main()