格式化protobuf文件

 
 

import getopt,sys,re


def getLength(base, str, bblack):
    strlen = len(str)
    if base > strlen:
        if bblack == True:
            return base
        else:
            return ((base-strlen)/4 + 1)*4 + strlen
    else:
        if bblack == True:
            return strlen + 1
        else:
            return strlen + 4

def formatOutWords(mgroup, bblack):
    importword = mgroup[0]
    typeword = mgroup[1]
    keyword = mgroup[2]
    indexword = mgroup[3].strip()
    infoword = mgroup[4]
    if(len(infoword) > 0):
        format = '\t%-*s%-*s%-*s= %-*s;\t\t%s'
        infostr = format %(getLength(10,importword,bblack),importword,getLength(32,typeword,bblack),typeword,getLength(32,keyword,bblack),keyword,getLength(15,indexword,bblack),indexword,infoword)
    else:
        format = '\t%-*s%-*s%-*s= %s;'
        infostr = format %(getLength(10,importword,bblack),importword,getLength(32,typeword,bblack),typeword,getLength(32,keyword,bblack),keyword,indexword)
    if bblack == False:
        return  infostr.replace("    ","\t")
    else:
        return infostr

def stylePythonFile(infile, outfile, bblack):
    filein = open(infile, 'r')
    inlines = filein.readlines()
    filein.close()
    fileout = open(outfile, 'w')
    pattern = re.compile('[\t ]*(\S+)\s+(\S+)\s+(\S+)\s*=\s*([^;]+);[^\n\r\S]*([^\n\r]*)')
    for line in inlines:
        if len(line) > 0:
            line = line.replace("\n","")
            match = pattern.match(line)
            if match:
                mgroup = match.groups()
                if len(mgroup) >= 5:
                    line = formatOutWords(mgroup, bblack)
            line = line + "\n"
        fileout.write(line)
    fileout.close()

def usage():
    print("Usage %s: [-h|-i|-o|-b] [--help|--input|--output] args ..."%sys.argv[0])
##========================================================================================
if __name__ == '__main__':
    inputFile = ""
    outPutFile = ""
    bblack = False
    bexit = False
    try:
        opts,args = getopt.getopt(sys.argv[1:], "hi:o:b",["help","input=","output="])
        for opt,arg in opts:
            if opt in ("-i","--input"):
                inputFile = arg
            elif opt in ("-o","--output"):
                outPutFile = arg
            elif opt in ("-b"):
                bblack = True
            else:
                bexit = True
    except getopt.GetoptError:
        bexit = True

    if bexit == True or (len(inputFile) == 0 and len(outPutFile) == 0):
        usage()
        sys.exit(1)

    if len(inputFile) == 0:
        inputFile = outPutFile
    if len(outPutFile) == 0:
        outPutFile = inputFile

    stylePythonFile(inputFile, outPutFile, bblack)



你可能感兴趣的:(格式化protobuf文件)