#!/usr/bin/python # This script replaces a string in a file with another. The old and new # string can either be specified on the commandline: # shader_renamd -o oldname -n newname # or it can be specified with a tab delimited inputfile where each # line must contain two names, the old and the new one seperated by a TAB # character. import os import string import sys import re import glob import scriptutil #from DebugMessage import stdMsg, dbgMsg, errMsg, setDebugging class Line: def __init__(self): self.LineNumber = -1 self.Text = "" def __repr__(self): return "[ " + self.LineNumber.__repr__() + ", '" + self.Text + "' ]" class File: def __init__(self, name): self.Filename = name self.Modified = 0 self.Line = [] self.PreLoadFile(name) def __repr__(self): return "[ '"+self.Filename+"', "+self.Modified.__repr__()+", "+len(self.Line).__repr__()+" ]" def PreLoadFile(self, filename): f = open(filename) b = f.read() f.close() b = b.replace("\r\n", "\n") b = b.replace("\r", "\n") b = b.split("\n") r = Line() nr = 0 for l in b: s = l.strip() nr = nr + 1 r.Text = l r.LineNumber = nr self.Line.append(r) r = Line() return def ReplaceString(self, old, new): rc = 0 #print old, new for i in self.Line: t = i.Text.split(old) if(len(t) <= 1): continue #print len(t), t #print old, new if(len(t[1]) > 0): #print len(t), t b = 0 if(t[1][0:1] == "\"" or t[1][0:1] == "\t" or t[1][0:1] == "," or t[1][0:1] == "(" or t[1][0:1] == ")" or t[1][0:1] == " "): b = 1 if(b != 1): continue i.Text = t[0]+new+t[1] rc = 1 return rc class ShaderRename: def __init__(self): self.Map = {} def LoadInputfile(self, filename): #name = glob.glob(filename) f = open(filename) b = f.read() f.close() b = b.replace("\r\n", "\r") b = b.split("\r") n = 0 for l in b: n = n + 1 l = l.strip() if(len(l) == 0): continue t = l.split("\t") if(len(t) <= 1): print "ERROR("+n.__repr__()+"): "+l continue self.Map[t[0]] = t[1] return def SetShadername(self, old, new): self.Map[old] = new return def Replace(self, fn): mat = File(fn) rc = 0 for i in self.Map: rc = rc + mat.ReplaceString(i, self.Map[i]) if(rc != 0): #print "... updating" fl = open(fn, "w+b") for i in mat.Line: fl.write(i.Text+"\n") fl.close() return def Usage(): print "USAGE: reorg -if " print " reorg -o -n " sys.exit(1) if __name__ == '__main__': if len(sys.argv) <= 1: Usage() sr = ShaderRename() i = 0 n = len(sys.argv) old = None new = None input = None try: opt = sys.argv[1] if(opt == "-o"): old = sys.argv[2] opt = sys.argv[3] if(opt == "-n"): new = sys.argv[4] i = 5 fl = sys.argv[i] elif(opt == "-if"): input = sys.argv[2] i = 3 fl = sys.argv[i] except IndexError: Usage() if(input != None): sr.LoadInputfile(input) else: if(old == None or new == None): Usage() sr.SetShadername(old, new) while( i < n): fn = sys.argv[i] print "Processing "+fn sr.Replace(fn) i = i + 1 sys.exit(0)