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

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