Crossfire Server, Branches 1.12  R18729
arch2xml.py
Go to the documentation of this file.
1 #arch2xml - Todd Mitchell - work in progress - use if you like
2 #usage : python arch2xml.py <directory> <xml file name>
3 #FYI - the Walk function is very useful for other python programs as well
4 
5 import fnmatch, os, string
6 
7 #Flexable Directory Walker from the Python CookBook
8 
9 def Walk( root, recurse=0, pattern='*', return_folders=0 ):
10 
11 
12  # initialize
13  result = []
14 
15  # must have at least root folder
16  try:
17  names = os.listdir(root)
18  except os.error:
19  return result
20 
21  # expand pattern
22  pattern = pattern or '*'
23  pat_list = string.splitfields( pattern , ';' )
24 
25  # check each file
26  for name in names:
27  fullname = os.path.normpath(os.path.join(root, name))
28 
29  # grab if it matches our pattern and entry type
30  for pat in pat_list:
31  if fnmatch.fnmatch(name, pat):
32  if os.path.isfile(fullname) or (return_folders and os.path.isdir(fullname)):
33  result.append(fullname)
34  continue
35 
36  # recursively scan other folders, appending results
37  if recurse:
38  if os.path.isdir(fullname) and not os.path.islink(fullname):
39  result = result + Walk( fullname, recurse, pattern, return_folders )
40 
41  return result
42 
43 def arch2xml(root,filename,xsl_file='cfarches.xsl'):
44  files = Walk(root, 1, '*.arc', 1)
45  print 'searching for arch files in %s' %root
46  xml = open(filename,'w')
47  xml.write('<?xml version="1.0"?>\n<?xml-stylesheet type="text/xsl" href="%s"?>\n<ARCHES>'%xsl_file)
48  for file in files:
49  arc = open(file,'r')
50  contents = arc.read().split('\n')
51  xml.write('<arch>\n')
52  mess = 0
53  for line in contents:
54  xp = line.split()
55  if mess == 1 and len(xp)>1:
56  str = string.join(xp[0:])
57  xml.write('%s\n' %str)
58  elif len(xp) == 1:
59  tag = string.lower(xp[0])
60  if tag == 'end':
61  tag = ' <END />\n'
62  elif tag == 'more':
63  tag = ' <MORE />\n'
64  elif tag =='msg':
65  tag = ' <message>\n'
66  mess = 1
67  elif tag =='endmsg':
68  tag = ' </message>\n'
69  mess = 0
70  elif tag == 'anim':
71  tag = ' <anim>\n'
72  elif tag =='mina':
73  tag = '\n </anim>\n'
74  else:
75  tag = '[%s]'%(tag)
76  xml.write('%s' %(tag))
77  elif len(xp)>1:
78  tag = string.lower(xp[0])
79  if (tag[0] == "#"):
80  str = string.join(xp)[1:]
81  xml.write(' <comment>%s</comment>\n' %(str))
82  else:
83  str = string.join(xp[1:])
84  xml.write(' <%s>%s</%s>\n' %(tag,str,tag))
85  xml.write('\n</arch>\n')
86  arc.close()
87  xml.write('\n</ARCHES>')
88  xml.close()
89  print "DONE"
90 
91 if __name__ == '__main__':
92  import sys
93  if len(sys.argv) < 3:
94  sys.stderr.write ('Converts arc files in a directory and all sub directories to an xml file\nUsage: arch2xml.py <directory> <XML-filename>\n')
95  sys.exit()
96  else:
97  arch2xml(sys.argv[1],sys.argv[2])
def Walk
Definition: arch2xml.py:9
def arch2xml
Definition: arch2xml.py:43