source: trunk/libIGCM/libIGCM_post/xios_parser.py @ 1340

Last change on this file since 1340 was 1340, checked in by sdipsl, 8 years ago
  • correct email contact
  • Property svn:executable set to *
  • Property svn:keywords set to Revision Date Author
File size: 7.1 KB
Line 
1#! /usr/bin/env python
2# coding: utf-8
3
4#**************************************************************
5# Author: Sebastien Denvil
6# Contact: Sebastien.Denvil__at__ipsl.jussieu.fr
7# $Revision::                                         $ Revision of last commit
8# $Author::                                           $ Author of last commit
9# $Date::                                             $ Date of last commit
10# IPSL (2006)
11#  This software is governed by the CeCILL licence see libIGCM/libIGCM_CeCILL.LIC
12#
13#**************************************************************
14
15import os, pwd, sys, traceback, argparse
16import xml.etree.ElementTree as ET
17#import readline, rlcompleter
18#readline.parse_and_bind("tab: complete")
19
20indent = 0
21currentDepth = 0
22ignoreElems = []
23fromField=[]
24fromFile=[]
25
26def dump(args):
27    """Dump XIOS xmls files."""
28    # Read and dump xios_def_xml
29    for inputFile in args.file:       
30        # Read the file_def_xml
31        print '\nReading %s \n|' % (inputFile)
32        tree = ET.parse(inputFile)
33        root=tree.getroot()
34        # Call the recursive print
35        printRecur(root)
36
37def printRecur(root):
38    """Recursively prints the tree."""
39    global indent
40    global currentDepth
41    if root.tag in ignoreElems:
42        return
43    print ' '*indent + '|--> %s: %s' % (root.tag, root.attrib)
44    currentDepth += 1
45    indent += 4
46    if currentDepth <= args.depth or args.depth == None:
47        for elem in list(root):
48            printRecur(elem)
49    currentDepth -= 1
50    indent -= 4
51
52def findField(root):
53    """Recursively find and list field tag with "id" or "field_ref" attribute."""
54    global fromField
55    global fromFile
56    if root.tag in ignoreElems:
57        return   
58    if root.tag == 'field' and root.attrib.get('id'):
59        fromField.append(root.attrib.get('id'))
60    elif root.tag == 'field' and root.attrib.get('field_ref'):
61        fromFile.append(root.attrib.get('field_ref'))
62    else:
63        for elem in list(root):
64            findField(elem)
65
66def findFieldToRemove(root, fieldToRemove):
67    """Recursively find tag having a field_ref in fieldToRemove."""
68    if args.verbosity >= 3 and root.tag == 'file' and root.attrib.get('id'):
69        print '\nFIELDS FROM FILE_DEF with id', root.attrib.get('id')
70    for field in root.findall('field'):
71        if args.verbosity >= 3: print 'field_ref=', field.attrib.get('field_ref')
72        if field.attrib.get('field_ref') in fieldToRemove:
73            if args.correction:
74                if args.verbosity >= 2: print 'removing ', field.attrib.get('field_ref')
75                root.remove(field)
76            else:
77                if args.verbosity >= 2: print 'To be removed ', field.attrib.get('field_ref')
78    for elem in list(root):
79        findFieldToRemove(elem, fieldToRemove)
80       
81def check(args):
82    global fromFile
83    # Read the field_def_xml
84    if args.verbosity >= 1: print '\nReading field_def_xml=',args.field[0]
85    tree = ET.parse(args.field[0])
86    root=tree.getroot()
87    exitCode=0
88    if args.verbosity >= 3: print root.tag, root.attrib, '\n'
89    # Build a list of field.id from field_def
90    findField(root)
91
92    # Loop over file_def files
93    for inputFile in args.file:       
94        # Read the file_def_xml
95        if args.verbosity >= 1: print '\nReading file_def_xml=',inputFile
96        tree = ET.parse(inputFile)
97        root=tree.getroot()
98        fromFile=[]
99        if args.verbosity >= 3: print root.tag, root.attrib, '\n'
100
101        # Build a list of field_ref from file_def
102        findField(root)
103        #print '4. fromFile=', fromFile
104       
105        # Compare the two lists. fromField must be a superset of fromFile.
106        if set(fromField).issuperset(set(fromFile)):
107            if args.verbosity >= 1: print '\nALL GOOD with %s' % (inputFile)
108            if args.verbosity >= 3: print 'fromField=', fromField
109            if args.verbosity >= 3: print 'fromFile=', fromFile
110        else:
111            if args.verbosity >= 1: print '\nTROUBLE AHEAD with %s' % (inputFile)
112            if args.verbosity >= 3: print ', '.join(sorted(list(set(fromFile)-set(fromField))))
113            # Identify fields in fromFile but not in fromField
114            fieldToRemove=list(set(fromFile)-set(fromField))
115            if args.verbosity >= 3: print 'fieldToRemove=', fieldToRemove
116            #
117            # And now locate and remove them if the modify command has been called
118            findFieldToRemove(root, fieldToRemove)
119            # Final steps
120            if args.correction: tree.write('modified.'+inputFile)
121            if not len(fieldToRemove) == 0 and not args.correction:
122                exitCode=1
123    # The end
124    sys.exit(exitCode)
125
126def showtime(args):
127    """
128    prints table of formatted text format options
129    """
130    for style in xrange(6):
131        for fg in xrange(30,36):
132            s1 = ''
133            for bg in xrange(40,46):
134                format = ';'.join([str(style), str(fg), str(bg)])
135                s1 += '\x1b[%sm %s \x1b[0m' % (format, pwd.getpwuid(os.getuid())[4]+' is on fire')
136            print s1
137        print '\n'
138   
139if __name__ == '__main__':
140
141    try:
142        # Create the top-level parser
143        parser = argparse.ArgumentParser(description='XIOS2 xml files tooling and ironsmith')
144        subparsers = parser.add_subparsers(description='Dump, check or modify xios xml files')
145
146        # create the parser for the "dump" command
147        parser_dump = subparsers.add_parser('dump',help='Dump the xml content without all the xml\'s ironsmith')
148        parser_dump.add_argument('-d', '--depth', type=int, default=None, help='How deep do we go. Full tree by default')
149        parser_dump.add_argument('file', nargs='+', help='XIOS xml file(s) to dump')
150        parser_dump.set_defaults(func=dump)
151
152        # create the parser for the "check" command
153        parser_check = subparsers.add_parser('check', help='Check consistency between field_def and file_def files')
154        parser_check.add_argument('--field', nargs=1, required=True, help='XIOS xml field_def type')
155        parser_check.add_argument('--file', nargs='+', required=True, help='XIOS xml file_def type')
156        parser_check.set_defaults(func=check, correction=False)
157
158        # create the parser for the "modify" command
159        parser_check = subparsers.add_parser('modify', help='Will make sure field_def is a superset of file_def')
160        parser_check.add_argument('--field', nargs=1, required=True, help='XIOS xml field_def type')
161        parser_check.add_argument('--file', nargs='+', required=True, help='XIOS xml file_def type')
162        parser_check.set_defaults(func=check, correction=True)
163
164        # create the parser for the "modify" command
165        parser_check = subparsers.add_parser('showtime', help='Just want to make sure you feel good today')
166        parser_check.set_defaults(func=showtime)
167       
168        # Each possible option
169        parser.add_argument('-v', '--verbosity', action='count', default=0)
170
171        # Parse the args.
172        args = parser.parse_args()
173
174        # And call whatever function was selected
175        args.func(args)
176    except KeyboardInterrupt:
177        print "Shutdown requested...exiting"
178    #except Exception:
179    #    traceback.print_exc(file=sys.stdout)
180    sys.exit(0)
Note: See TracBrowser for help on using the repository browser.