PY腳本打包AS多個工程

build_quanjiatong.py

#!/usr/bin/env python
# coding:utf-8

'''
Created on Feb 16, 2017

@author: xwang

Ai學(xué)全家桶打包
'''

import os
import helper
import shutil

rootDir = '..'
configFile = 'quanjiatong.prop'
returnDir = ''
purge_log = 0
versionCode = "1000000"
versionName = "1.0.0"
minifyEnabled = "false"


def getFileList(dir, fileList):
    newDir = dir
    if os.path.isfile(dir):
        fileList.append(dir.decode('gbk'))
    elif os.path.isdir(dir):
        for s in os.listdir(dir):
            # 如果需要忽略某些文件夾治筒,使用以下代碼
            # if s == "xxx":
            # continue
            newDir = os.path.join(dir, s)
            getFileList(newDir, fileList)
    return fileList

def updateVersion():
    print("start updateVersion")
    with open("app/build.gradle", "r") as f:
        lines = f.readlines()

    spaceSplitedProps = ('versionCode',
                         'versionName',
                         'minifyEnabled')

    i = 0
    versionCodeChanged = False
    versionNameChanged = False

    for line in lines:

        line = line.strip()
        if (len(line) == 0):
            i = i + 1
            continue;

        for propName in spaceSplitedProps:
            if propName in line:
                if (propName == 'versionCode' and versionCodeChanged == False):
                    lines[i] = '        versionCode ' + versionCode + '\n'
                    print("lines[i]--》 " + lines[i])
                    versionCodeChanged = True
                if (propName == 'versionName' and versionNameChanged == False):
                    lines[i] = '        versionName ' + versionName + '\n'
                    print("lines[i]--》 " + lines[i])
                    versionNameChanged = True
                if (propName == 'minifyEnabled'):
                    lines[i] = '            minifyEnabled ' + minifyEnabled + '\n'
                    print("lines[i]--》 " + lines[i])

        i = i + 1
    fl=open('app/build.gradle', 'w')
    for ii in lines:
        fl.write(ii)
    fl.close()
    return


def buildApk(project):
    os.chdir(returnDir)
    print os.getcwd()
    # exit(0)
    os.chdir('../../../' + project)
    print("curProPath --> " + os.getcwd())

    updateVersion()
    # exit(0)

    buildApkPath = os.getcwd()
    print os.getcwd()

    apkSourceDir = buildApkPath + '/app/build/outputs/apk'
    print(os.path.exists(apkSourceDir))
    if os.path.exists(apkSourceDir):
        print ("delete origin apk folder...")
        shutil.rmtree(apkSourceDir)

    tmpRootDir = os.path.abspath(rootDir)
    dstDir = tmpRootDir + '/shared-library/comm/aixuebuild'

    print ("purge_log --> " + purge_log)
    if purge_log == '1':
        print ("purge log...")
        helper.watchExecuteCommand(dstDir + '/purge_log.py ' + project)
    helper.watchExecuteCommand('./gradlew assembleRelease')

    print("tmpRootDir : " + tmpRootDir)

    if not os.path.exists(dstDir):
        helper.watchExecuteCommand('mkdir -p', dstDir)

    print("buildApkPath : " + buildApkPath)

    print("apkSourceDir : " + apkSourceDir)

    apkSourceName = getFileList(apkSourceDir, [])
    print("apkSourceName : " + apkSourceName[0])

    cmd = 'cp ' + apkSourceName[0] + ' ' + dstDir
    print('copy cmd --> ' + cmd)
    helper.watchExecuteCommand(cmd, cmdAlias='copy plugin to: ' + dstDir)
    if purge_log == '1':
        helper.watchExecuteCommand('git reset --hard')


if __name__ == '__main__':
    configs = helper.readPropertyFile(configFile)
    quanjiatongs = configs['quanjiatongs']
    qianjiatongArray = quanjiatongs.split(',')
    qianjiatongArray = map(lambda x: x.strip(), qianjiatongArray)

    returnDir = os.getcwd()

    purge_log = configs['purge_log']
    versionCode = configs['versionCode']
    versionName = configs['versionName']
    minifyEnabled = configs['minifyEnabled']

    for e in qianjiatongArray:
        print e
        buildApk(e);

        # exit(0);


helper.py

'''
Created on Mar 7, 2016

@author: lqp
'''

import os
import re
import sys
import subprocess as subproc

projectRoot = ''

logFile = None


def buildLog(msg):
    if logFile:
        logFile.write(msg + '\n')

    print(msg)


# tool module code start
def watchExecuteCommand(cmd, args='', cmdAlias=None):
    if not cmdAlias:
        cmdAlias = cmd
    else:
        cmdAlias = '[' + cmdAlias + ']'

    buildLog('Cmd: ' + cmdAlias + " " + args)

    code = subproc.Popen(cmd + " " + args, shell=True).wait()
    if code:
        print 'Fail: ' + str(code)
        exit()
    else:
        print 'Success !!!'


def collectFilesByPattern(folder, include=None, exclude=None):
    if not os.path.isdir(folder):
        buildLog('collectFilesByPattern: folder not exist: ' + folder)
        return []

    srcFiles = []

    fileList = os.listdir(folder)
    for i in fileList:
        i = folder + '/' + i
        if os.path.isdir(i):
            srcFiles += collectFilesByPattern(i, include, exclude)
        else:
            if include and not re.match(include, i):
                continue

            if exclude and re.match(exclude, i):
                continue

            srcFiles.append(i)

    return srcFiles


def strUntil(string, endChar):
    res = ''

    for c in string:
        if c == endChar:
            break;

        res += c

    return res


def error(string):
    sys.exit("Error: " + string)
    return


def stripQuotedString(string):
    res = string

    if (string.startswith('\'') and string.endswith('\'')) \
            or (string.startswith('"') and string.endswith('"')):
        res = string[1:-1]

    return res


def stripProjectString(string):
    res = string

    if (string.startswith('\'') and string.endswith('\'')) \
            or (string.startswith('"') and string.endswith('"')):
        res = string[1:-1]

    if res.startswith(":"):
        res = res[1:]

    return res


def expandJarPath(libString, pathPrefix=None):
    pathList = []

    splitItems = libString.split(',')
    for item in splitItems:
        if 'dir' in item:
            dirItem = item.split(':')[1].strip()
            dirItem = stripQuotedString(dirItem)
        elif 'include' in item:
            pass

    libDir = dirItem
    if pathPrefix:
        libDir = projectRoot + '/' + pathPrefix + '/' + libDir
    else:
        libDir = os.getcwd() + '/' + libDir

    if not os.path.exists(libDir):
        # print("libPath: " + libDir + " not exist")
        return

    libFiles = os.listdir(libDir)
    for libFile in libFiles:
        if libFile.endswith('.jar'):
            pathList.append(libDir + '/' + libFile)

    return pathList


def deDuplicateStringList(srcList):
    if len(srcList) == 0:
        return srcList

    item = srcList.pop()
    dstList = []

    while item:

        if item not in dstList:
            dstList.append(item);

        if len(srcList) > 0:
            item = srcList.pop()
        else:
            item = None

    srcList += dstList
    return


def readPropertyFile(path):
    dicts = {}

    lines = []
    with open(path) as fd:
        for line in fd.readlines():
            if re.match(r'^\s*#', line) or '=' not in line:
                continue
            else:
                # print('append property line:' + line)
                if line.endswith('\n'):
                    line = line[:len(line) - 1]
                    
                lines.append(line)

    for line in lines:
        items = line.split('=')

        dicts[items[0].strip()] = items[1].strip()

    return dicts

    # tool module code end

purge_log.py

#!/usr/bin/env python
# -*- coding: UTF-8 -*-

'''
Created on Mar 5, 2015

@author: lqp
'''

import os
import re
import helper

import os.path as pathUtil

bbLogRegPattern = re.compile(r'(^\s*)(BBLog\.[^;]+;)', re.DOTALL | re.MULTILINE);
normalLogRegPattern = re.compile(r'(^\s*)(Log\.[^;]+;)', re.DOTALL | re.MULTILINE);

workDir = '../';
srcFolder = ['app/src/main/java'
              ];
processCount = 0


def listFiles(path, outList):
    files = os.listdir(path);

    for item in files:
        item = path + pathUtil.sep + item;

        if pathUtil.isdir(item):
            listFiles(item, outList);
        else:
            if pathUtil.splitext(item)[1] == '.java':
                outList.append(item)

    return


def processFile(fileName):
    srcFile = open(fileName, "r");
    content = srcFile.read()
    srcFile.close()

    global workDir
    needWrite = 0

    # replace BBlog
    groups = bbLogRegPattern.findall(content);
    if len(groups) > 0:
        global processCount

        print 'purge BBLog in: ' + pathUtil.relpath(fileName, workDir);

        content = re.sub(bbLogRegPattern, r'\1//BBLog call replaced', content);

        needWrite = 1

    ##replace Log.x()
    groups = normalLogRegPattern.findall(content);
    if len(groups) > 0:
        global processCount

        print 'purge Log.x in: ' + pathUtil.relpath(fileName, workDir);

        content = re.sub(normalLogRegPattern, r'\1//Log.x call replaced', content);

        needWrite = 1

    if needWrite:
        srcFile = open(fileName, "w");
        srcFile.write(content)
        srcFile.close()
        processCount = processCount + 1

    return


if __name__ == '__main__':
    if len(os.sys.argv) < 2:
        helper.error('Usage: ' + os.sys.argv[0] + ' projectName')

    projectName = os.sys.argv[1]
    print("projectName --> " + projectName)

    holderList = []

    workDir = pathUtil.abspath(workDir) + "/" + projectName

    print 'start work at dir: ' + workDir

    for folder in srcFolder:
        listFiles(workDir + os.path.sep + folder, holderList);
    #listFiles(workDir, holderList);

for item in holderList:
    print("item --> " + item)
    processFile(item)

print 'process complete: ' + str(processCount) + ' files changed'
pass

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末旺坠,一起剝皮案震驚了整個濱河市纽帖,隨后出現(xiàn)的幾起案子啸盏,更是在濱河造成了極大的恐慌,老刑警劉巖徘公,帶你破解...
    沈念sama閱讀 211,423評論 6 491
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件竣贪,死亡現(xiàn)場離奇詭異,居然都是意外死亡玫荣,警方通過查閱死者的電腦和手機甚淡,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,147評論 2 385
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來捅厂,“玉大人贯卦,你說我怎么就攤上這事资柔。” “怎么了撵割?”我有些...
    開封第一講書人閱讀 157,019評論 0 348
  • 文/不壞的土叔 我叫張陵贿堰,是天一觀的道長。 經(jīng)常有香客問我啡彬,道長官边,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 56,443評論 1 283
  • 正文 為了忘掉前任外遇,我火速辦了婚禮注簿,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘跳仿。我一直安慰自己诡渴,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 65,535評論 6 385
  • 文/花漫 我一把揭開白布菲语。 她就那樣靜靜地躺著妄辩,像睡著了一般。 火紅的嫁衣襯著肌膚如雪山上。 梳的紋絲不亂的頭發(fā)上眼耀,一...
    開封第一講書人閱讀 49,798評論 1 290
  • 那天,我揣著相機與錄音佩憾,去河邊找鬼哮伟。 笑死,一個胖子當(dāng)著我的面吹牛妄帘,可吹牛的內(nèi)容都是我干的楞黄。 我是一名探鬼主播,決...
    沈念sama閱讀 38,941評論 3 407
  • 文/蒼蘭香墨 我猛地睜開眼抡驼,長吁一口氣:“原來是場噩夢啊……” “哼鬼廓!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起致盟,我...
    開封第一講書人閱讀 37,704評論 0 266
  • 序言:老撾萬榮一對情侶失蹤碎税,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后馏锡,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體雷蹂,經(jīng)...
    沈念sama閱讀 44,152評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 36,494評論 2 327
  • 正文 我和宋清朗相戀三年眷篇,在試婚紗的時候發(fā)現(xiàn)自己被綠了萎河。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 38,629評論 1 340
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖虐杯,靈堂內(nèi)的尸體忽然破棺而出玛歌,到底是詐尸還是另有隱情,我是刑警寧澤擎椰,帶...
    沈念sama閱讀 34,295評論 4 329
  • 正文 年R本政府宣布支子,位于F島的核電站,受9級特大地震影響达舒,放射性物質(zhì)發(fā)生泄漏值朋。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 39,901評論 3 313
  • 文/蒙蒙 一巩搏、第九天 我趴在偏房一處隱蔽的房頂上張望昨登。 院中可真熱鬧,春花似錦贯底、人聲如沸丰辣。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,742評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽笙什。三九已至,卻和暖如春胚想,著一層夾襖步出監(jiān)牢的瞬間琐凭,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 31,978評論 1 266
  • 我被黑心中介騙來泰國打工浊服, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留统屈,地道東北人。 一個月前我還...
    沈念sama閱讀 46,333評論 2 360
  • 正文 我出身青樓臼闻,卻偏偏與公主長得像鸿吆,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子述呐,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 43,499評論 2 348

推薦閱讀更多精彩內(nèi)容

  • http://192.168.136.131/sqlmap/mysql/get_int.php?id=1 當(dāng)給sq...
    xuningbo閱讀 10,277評論 2 22
  • 昨天的童心,我珍藏著 今天的痛苦蕉毯,我把它變成了詩 明天的夢想乓搬,我用它擦亮黑夜 我是誰?我從哪里來代虾?要到哪里去进肯?對于...
    鴻蒙一葉閱讀 314評論 4 6
  • 故事發(fā)生在1938年的印度,恒河邊上棉磨,關(guān)于印度的寡婦江掩。 楚亞,一個八歲的女孩,她的丈夫因病去世了环形,她被自己的父親收...
    末末書屋閱讀 746評論 3 4
  • 第一抬吟,什么是自媒體萨咕? 自媒體又稱“公民媒體”或“個人媒體”,是指私人化火本、平民化危队、普泛化、自主化的傳播者钙畔,以現(xiàn)代化茫陆、...
    云創(chuàng)煮夫閱讀 1,034評論 0 0