格式化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)



转载于:https://my.oschina.net/u/659405/blog/398029

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值