def upload_dir(dir_name, upload_dir, ftp_conf): check_ftp_conf(ftp_conf) ftp, ftpStr = get_ftp(ftp_conf) if dir_name not in ftp.nlst(): ftp.mkd(dir_name) ftp.cwd(dir_name) slog.info('Uploading "%s" to "%s/%s" ......' % (upload_dir, ftpStr, dir_name)) subDirs = ftp.nlst() rootLen = len(upload_dir) + 1 for r, d, fl in os.walk(upload_dir): if r.split('/')[-1].startswith('.'): continue for sdir in d: if not sdir.startswith('.') \ and sdir not in subDirs: dirPath = os.path.join(r, sdir)[rootLen:] ftp.mkd(dirPath) for sf in fl: filePath = os.path.join(r, sf) f = open(filePath, 'rb') ftpPath = filePath[rootLen:] slog.info('%s -> %s', filePath, ftpPath) ftp.storbinary('STOR %s' % ftpPath, f) f.close() ftp.quit()
def plst(self, plist): print_sep('Start to process %s in directory plst.' %plist, True, 40) default, special = self._getSpecialDir('plst') if not default: return if len(plist) == 0: plist = list_dir(default) outputDir = self.conf.getClientPath('res', 'plst') self._rebuildDir(outputDir) sourceDir = default tmpDir = None if special: tmpDir = self._merge2Tmp(default, special, plist) plist = list_dir(tmpDir) sourceDir = tmpDir print_sep('Start to convert spritesheet.') for dir_name in plist: self._convertSS(sourceDir, outputDir, dir_name, self.args.disable_rotation) print_sep('Spritsheet converting has done.', False) if tmpDir: slog.info('Remove temporary directory [%s].'%tmpDir) shutil.rmtree(tmpDir) print_sep('Process %s in directory plst has done.' %list(plist), False, 40)
def upload(appid, token, typ, fil): if not os.path.exists(fil): print_sep( 'File [%s] is not found, please check ' '[pub_conf.file.ios.file] in config file.' % fil, True, 40) return # 1. get upload info info = requests.get(_getInfo(appid, token, typ)) infoJson = info.json() # 2. upload files slog.info('upload files ...') pkg = infoJson['bundle']['pkg'] req = requests.post(url=pkg['url'], data={ 'key': pkg['key'], 'token': pkg['token'] }, files={ 'file': (os.path.split(fil)[1], open(fil, 'rb'), 'application/octet-stream') }) reqJson = req.json() if reqJson['code'] == 0: if args.desc: desc = {'changelog': args.desc} else: desc = { 'changelog': str(datetime.now().strftime('%y-%m-%d %I:%M:%S')) } req = requests.put(url='http://fir.im/api/v2/app/%s?token=%s' % (infoJson['id'], token), data=desc) print_sep(req.json()['short'] + ' upload complete!', False, 40)
def upload_dir(dir_name, upload_dir, ftp_conf): check_ftp_conf(ftp_conf) ftp, ftpStr = get_ftp(ftp_conf) if dir_name not in ftp.nlst(): ftp.mkd(dir_name) ftp.cwd(dir_name) slog.info('Uploading "%s" to "%s/%s" ......'%(upload_dir, ftpStr, dir_name)) subDirs = ftp.nlst() rootLen = len(upload_dir)+1 for r,d,fl in os.walk(upload_dir): if r.split('/')[-1].startswith('.'): continue for sdir in d: if not sdir.startswith('.') \ and sdir not in subDirs: dirPath = os.path.join(r, sdir)[rootLen:] ftp.mkd(dirPath) for sf in fl: filePath = os.path.join(r, sf) f = open(filePath, 'rb') ftpPath = filePath[rootLen:] slog.info('%s -> %s', filePath, ftpPath) ftp.storbinary('STOR %s'%ftpPath, f) f.close() ftp.quit()
def upload(appid, token, typ, fil): if not os.path.exists(fil): print_sep('File [%s] is not found, please check ' '[pub_conf.file.ios.file] in config file.'%fil, True, 40) return # 1. get upload info info = requests.get(_getInfo(appid,token,typ)) infoJson = info.json() # 2. upload files slog.info('upload files ...') pkg = infoJson['bundle']['pkg'] req = requests.post( url = pkg['url'], data={'key':pkg['key'], 'token':pkg['token']}, files={ 'file':(os.path.split(fil)[1], open(fil,'rb'), 'application/octet-stream')} ) reqJson = req.json() if reqJson['code'] == 0: if args.desc: desc = {'changelog': args.desc} else: desc = {'changelog': str(datetime.now().strftime('%y-%m-%d %I:%M:%S'))} req = requests.put( url = 'http://fir.im/api/v2/app/%s?token=%s'%(infoJson['id'], token), data=desc ) print_sep(req.json()['short'] + ' upload complete!', False, 40)
def cocos(self): if not self.isAdmin(): return cocosdir = os.getenv("COCOS_DIR") cocos2dx = os.path.abspath(os.path.join(cocosdir, 'cocos2d-x')) if not os.path.exists(cocos2dx): raise TEAM1201Error('Cannot find cocos2d-x!') slog.info('Packaging cocos2d-x library "%s" to a tempfile.'%cocos2dx) files = [] for p, d, fs in os.walk(cocos2dx, followlinks=True): ignore = False for ignoreFile in ('.git', 'docs', 'tests', 'licenses'): if os.path.join(cocos2dx, ignoreFile) in p: ignore = True break if ignore: continue for f in fs: path = os.path.join(p,f) ignore = False for part in ('.git', '.DS_Store'): if part in path: ignore = True break if ignore: continue if os.path.islink(path): continue files.append(path) pre = len(cocosdir)+1 self.upload218Lib(create_zip(files, pre), self.conf.lib_conf.cocos)
def get_ftp(ftp_conf, debug=0): """得到一个 已经打开的FTP 实例,和一个 ftp 路径。 :param dict ftp_conf: ftp配置文件,格式如下: >>> { >>> 'server':'127.0.0.1', >>> 'start_path':None, >>> 'user':'******', >>> 'password':'******', >>> } :returns: ftp, ftpserverstr :rtype: :class:`ftplib.FTP` , str """ server = ftp_conf.get('server') user = ftp_conf.get('user') password = ftp_conf.get('password') start_path = ftp_conf.get('start_path') slog.info("Connecting FTP server %s ......", server) ftpStr = 'ftp://%s/' % server if start_path: ftpStr = ftpStr + start_path ftp = ftplib.FTP(server, user, password) ftp.set_debuglevel(debug) if start_path: ftp.cwd(start_path) serverFiles = ftp.nlst() slog.info('There are some files in %s:\n[%s]' % (ftpStr, ', '.join(serverFiles))) return ftp, ftpStr
def upload_file(file_path, remote_path, ftp_conf, remove_file=False): """上传第一个指定的文件到 FTP 服务器。 :param str file_path: 待上传文件的绝对路径。 :param str remote_path: 文件在 FTP 服务器上的相对路径(相对于 FTP 服务器的初始路径)。 :param dict ftp_conf: ftp配置文件,详见 :func:`get_ftp` 。 :param bool remove_file: 上传成功后是否删除本地文件。 :returns: FTP 服务器上的文件列表 :rtype: list """ check_ftp_conf(ftp_conf) ftp, ftpStr = get_ftp(ftp_conf) lf = open(file_path, 'rb') slog.info('Uploading "%s" to "%s/%s" ......' % (file_path, ftpStr, remote_path)) ftp.storbinary("STOR %s" % remote_path, lf) filelist = ftp.nlst() ftp.quit() lf.close() if remove_file: os.remove(file_path) slog.info('Upload done.') return filelist
def get_ftp(ftp_conf, debug=0): """得到一个 已经打开的FTP 实例,和一个 ftp 路径。 :param dict ftp_conf: ftp配置文件,格式如下: >>> { >>> 'server':'127.0.0.1', >>> 'start_path':None, >>> 'user':'******', >>> 'password':'******', >>> } :returns: ftp, ftpserverstr :rtype: :class:`ftplib.FTP` , str """ server = ftp_conf.get('server') user = ftp_conf.get('user') password = ftp_conf.get('password') start_path = ftp_conf.get('start_path') slog.info("Connecting FTP server %s ......", server) ftpStr = 'ftp://%s/'%server if start_path: ftpStr = ftpStr+start_path ftp = ftplib.FTP(server, user, password) ftp.set_debuglevel(debug) if start_path: ftp.cwd(start_path) serverFiles = ftp.nlst() slog.info('There are some files in %s:\n[%s]'%(ftpStr, ', '.join(serverFiles))) return ftp, ftpStr
def plst(self, plist): print_sep('Start to process %s in directory plst.' % plist, True, 40) default, special = self._getSpecialDir('plst') if not default: return if len(plist) == 0: plist = list_dir(default) outputDir = self.conf.getClientPath('res', 'plst') self._rebuildDir(outputDir) sourceDir = default tmpDir = None if special: tmpDir = self._merge2Tmp(default, special, plist) plist = list_dir(tmpDir) sourceDir = tmpDir print_sep('Start to convert spritesheet.') for dir_name in plist: self._convertSS(sourceDir, outputDir, dir_name, self.args.disable_rotation) print_sep('Spritsheet converting has done.', False) if tmpDir: slog.info('Remove temporary directory [%s].' % tmpDir) shutil.rmtree(tmpDir) print_sep('Process %s in directory plst has done.' % list(plist), False, 40)
def get_max_ver(fmt, filelist): """有一堆字符串,文件名均包含 %d.%d.%d 形式版本号,返回其中版本号最大的那个。 我一般用它来检测一堆发行版中版本号最大的那个文件。 :param str fmt: 要检测测字符串形式,例如 zrong-%s.tar.gz ,其中 %s 会被正则替换。 :param list files: 字符串列表。 :returns: 版本号最大的字符串。 :rtype: str """ x, y, z = 0,0,0 verpat = fmt%'(\d+).(\d+).(\d+)' verre = re.compile(r''+verpat+'', re.M) for f in filelist: match = verre.search(f) if match: x1 = int(match.group(1)) y1 = int(match.group(2)) z1 = int(match.group(3)) if x1 >= x and y1 >= y: x = x1 y = y1 z = z1 verfmt = fmt%('%d.%d.%d') name = verfmt%(x, y, z) if x == 0 and y == 0 and z == 0: slog.info('Can not find the string "%s" !'%name) return None return name
def cocos(self): if not self.isAdmin(): return cocosdir = os.getenv("COCOS_DIR") cocos2dx = os.path.abspath(os.path.join(cocosdir, 'cocos2d-x')) if not os.path.exists(cocos2dx): raise TEAM1201Error('Cannot find cocos2d-x!') slog.info('Packaging cocos2d-x library "%s" to a tempfile.' % cocos2dx) files = [] for p, d, fs in os.walk(cocos2dx, followlinks=True): ignore = False for ignoreFile in ('.git', 'docs', 'tests', 'licenses'): if os.path.join(cocos2dx, ignoreFile) in p: ignore = True break if ignore: continue for f in fs: path = os.path.join(p, f) ignore = False for part in ('.git', '.DS_Store'): if part in path: ignore = True break if ignore: continue if os.path.islink(path): continue files.append(path) pre = len(cocosdir) + 1 self.upload218Lib(create_zip(files, pre), self.conf.lib_conf.cocos)
def rebuildConf(self): if os.path.exists(self.conf.conf_file): os.remove(self.conf.conf_file) workDir = self.conf.getPath('work') confFile = self.conf.conf_file self.conf = self.newConf() self.conf.init(workDir, confFile) slog.info('Regenerate "%s" done.' % confFile)
def rebuildConf(self): if os.path.exists(self.conf.conf_file): os.remove(self.conf.conf_file) workDir = self.conf.getPath('work') confFile = self.conf.conf_file self.conf = self.newConf() self.conf.init(workDir, confFile) slog.info('Regenerate "%s" done.'%confFile)
def save_to_file(self, path, human=True): """将自身内容保存到文件。 :param str path: 保存的文件路径。 :param bool human: 参见 :func:`dump()` """ write_file(path, self.dump(human)) slog.info("Save %a done.", path)
def clone(giturl, gitpath): """clone 一个 git 库。 :param str giturl: git 仓库的 url 地址。 :param str gitpath: git 仓库保存路径。 """ gitArgs = ['git', 'clone', giturl, gitpath] slog.info(' '.join(gitArgs)) return subprocess.call(gitArgs)
def cpp(self): print_sep('\nStart to update the runtime-src directory.', True, 40) gitdir = self.conf.getDistPath('.git') if os.path.isdir(gitdir): slog.info('%s is a git repostory. Do nothing.' % gitdir) return runtimeDir = self.conf.getDistPath('runtime-src') self._downloadAndUnzip(self.conf.lib_conf.cpp, [runtimeDir], self.conf.getDistPath()) print_sep('\nUpdate the runtime-src directory has done.', False, 40)
def cpp(self): print_sep('\nStart to update the runtime-src directory.', True, 40) gitdir = self.conf.getDistPath('.git') if os.path.isdir(gitdir): slog.info('%s is a git repostory. Do nothing.'%gitdir) return runtimeDir = self.conf.getDistPath('runtime-src') self._downloadAndUnzip(self.conf.lib_conf.cpp, [runtimeDir], self.conf.getDistPath()) print_sep('\nUpdate the runtime-src directory has done.', False, 40)
def download_file(remote_path, file_path, ftp_conf): check_ftp_conf(ftp_conf) ftp, ftpstr = get_ftp(ftp_conf) lf = open(file_path, 'wb') slog.info('Downloading "%s/%s" to "%s" ......'%(ftpstr, remote_path, lf.name)) ftp.retrbinary('RETR %s'%remote_path, lf.write) ftp.quit() lf.close() slog.info('Download done.') return lf.name
def download_file(remote_path, file_path, ftp_conf): check_ftp_conf(ftp_conf) ftp, ftpstr = get_ftp(ftp_conf) lf = open(file_path, 'wb') slog.info('Downloading "%s/%s" to "%s" ......' % (ftpstr, remote_path, lf.name)) ftp.retrbinary('RETR %s' % remote_path, lf.write) ftp.quit() lf.close() slog.info('Download done.') return lf.name
def test(self): res = self.conf.getGit('resource', 'path') sourcedir = os.path.join(res, 'test') targetdir = self.conf.getClientPath('res', 'test') self._print_copy(sourcedir, targetdir) if not os.path.exists(sourcedir): slog.error('No such file or directory: [%s].' % sourcedir) return if os.path.exists(targetdir): shutil.rmtree(targetdir) shutil.copytree(sourcedir, targetdir) slog.info('Copy done.')
def test(self): res = self.conf.getGit('resource', 'path') sourcedir = os.path.join(res, 'test') targetdir = self.conf.getClientPath('res', 'test') self._print_copy(sourcedir, targetdir) if not os.path.exists(sourcedir): slog.error('No such file or directory: [%s].'%sourcedir) return if os.path.exists(targetdir): shutil.rmtree(targetdir) shutil.copytree(sourcedir, targetdir) slog.info('Copy done.')
def convert_to_cocos2d(tpexe, source, output, dirname, disable_rotation=False, options=None): plist_file = os.path.join(output, dirname+".plist") png_file = os.path.join(output, dirname+".png") imagefolder = os.path.join(source, dirname) xargs = ["--sheet", png_file, "--data", plist_file] if options: xargs = xargs + _get_args_list(options) if disable_rotation: xargs.append('--disable-rotation') succ = convert_by_options(tpexe, xargs, imagefolder) if succ: slog.info("\n.... converting %s", dirname)
def _merge(self, reponame): repopath, curbr = self._check_branch(reponame) if not repopath or not curbr: return code, output = git.call(repopath, 'fetch') if code > 0: slog.error(output) return code, output = git.call(repopath, 'merge', 'master') if code > 0: slog.error(output) return slog.info(output)
def src(self): srcDIR = self.conf.getClientPath('src') slog.info('Packaging lua framework to a tempfile') files = [] for p, d, fs in os.walk(srcDIR, followlinks=True): for f in fs: path = os.path.join(p, f) if '.DS_Store' in path: continue files.append(path) pre = len(srcDIR) - 3 self.upload218Sim(create_zip(files, pre), self.conf.lib_conf.src)
def src(self): srcDIR = self.conf.getClientPath('src') slog.info('Packaging lua framework to a tempfile') files = [] for p, d, fs in os.walk(srcDIR, followlinks=True): for f in fs: path = os.path.join(p,f) if '.DS_Store' in path: continue files.append(path) pre = len(srcDIR)-3 self.upload218Sim(create_zip(files, pre), self.conf.lib_conf.src)
def _merge(self, reponame): repopath, curbr = self._check_branch(reponame) if not repopath or not curbr: return code, output = git.call(repopath, 'fetch') if code > 0: slog.error(output) return code, output = git.call(repopath, 'merge', 'master') if code > 0: slog.error(output) return slog.info(output)
def res(self): resDir = self.conf.getClientPath('res') slog.info('Packaging resources to a tempfile') files = [] for p, d, fs in os.walk(resDir): for f in fs: path = os.path.join(p, f) if '.DS_Store' in path: continue files.append(path) # len('res') == 3, it will includ 'res' prefix in zip file pre = len(resDir)-3 self.upload218Sim(create_zip(files, pre), self.conf.lib_conf.res)
def cocos(self): print_sep('\nStart to update the cocos2d-x framewroks.', True, 40) cocos2dx = self.conf.getDistPath('cocos2d-x') if os.path.islink(cocos2dx): slog.info('%s is a link. Do nothing.' % cocos2dx) return None if os.path.isdir(os.path.join(cocos2dx, '.git')): slog.info('%s is a git repostory. Do nothing.' % cocos2dx) return self._downloadAndUnzip(self.conf.lib_conf.cocos, [cocos2dx], self.conf.getDistPath()) print_sep('Update the cocos2d-x frameworks has done.', False, 40)
def _processAGit(self, gitConf): print_sep('\nStart to update the git repository [%s].'%gitConf.path, True, 40) exists = os.path.exists(gitConf.path) if exists: if self.args.force: gitArgs = git.get_args(gitConf.path, 'reset', '--hard') slog.info(' '.join(gitArgs)) subprocess.call(gitArgs) gitArgs = git.get_args(gitConf.path, 'pull', 'origin', 'master') slog.info(' '.join(gitArgs)) subprocess.call(gitArgs) print_sep('Update the git repository [%s] has done.'%gitConf.path, False, 40) else: slog.warning('%s is not exists!'%gitConf.path)
def _commit_empty(self, reponame, msg): repopath, curbr = self._check_branch(reponame) if not repopath or not curbr: return False code, output = git.call(repopath, 'commit', '--allow-empty', '-m', msg) if code > 0: slog.error(output) return code, output = git.call(repopath, 'push', 'origin', curbr) if code > 0: slog.error(output) return False slog.info(output) return True
def _commit_empty(self, reponame, msg): repopath, curbr = self._check_branch(reponame) if not repopath or not curbr: return False code, output = git.call(repopath, 'commit', '--allow-empty', '-m', msg) if code > 0: slog.error(output) return code, output = git.call(repopath, 'push', 'origin', curbr) if code > 0: slog.error(output) return False slog.info(output) return True
def res(self): resDir = self.conf.getClientPath('res') slog.info('Packaging resources to a tempfile') files = [] for p, d, fs in os.walk(resDir): for f in fs: path = os.path.join(p, f) if '.DS_Store' in path: continue files.append(path) # len('res') == 3, it will includ 'res' prefix in zip file pre = len(resDir) - 3 self.upload218Sim(create_zip(files, pre), self.conf.lib_conf.res)
def cocos(self): print_sep('\nStart to update the cocos2d-x framewroks.', True, 40) cocos2dx = self.conf.getDistPath('cocos2d-x') if os.path.islink(cocos2dx): slog.info('%s is a link. Do nothing.'%cocos2dx) return None if os.path.isdir(os.path.join(cocos2dx, '.git')): slog.info('%s is a git repostory. Do nothing.'%cocos2dx) return self._downloadAndUnzip(self.conf.lib_conf.cocos, [cocos2dx], self.conf.getDistPath()) print_sep('Update the cocos2d-x frameworks has done.', False, 40)
def lua(self): print_sep('\nStart to update the lua framworks.', True, 40) src = self.conf.getClientPath('src') cocos = os.path.join(src, 'cocos') quick = os.path.join(src, 'quick') zrong = os.path.join(src, 'zrong') if os.path.islink(cocos) or \ os.path.islink(quick) or \ os.path.islink(zrong): slog.info('%s OR %s OR %s is a link. Remove a link is forbidden.'%( cocos, quick, zrong)) return self._downloadAndUnzip(self.conf.lib_conf.lua, [cocos, quick, zrong], src) print_sep('Update lua framworks has done.', False, 40)
def fmt(self, po_file, mo_file): """将 po 文件转换成 mo 文件。 :param string po_file: 待转换的 po 文件路径。 :param string mo_file: 目标 mo 文件的路径。 """ if not os.path.exists(po_file): slog.error('The PO file [%s] is non-existen!'%po_file) return txt = subprocess.check_output([self._msgfmt, '--check', "--strict", '--verbose', "--output-file", mo_file, po_file], stderr=subprocess.STDOUT, universal_newlines=True) slog.info(txt)
def _merge2Tmp(self, default, special, dirList=None): tempDir = tempfile.mkdtemp(prefix='tbbl_') slog.info("Make a temporary directory: %s", tempDir) print_sep('Start to merge directory [%s] and [%s] to temporary directory.' %(default, special)) # Merge sub-directory one by one. if dirList: self._mergeSpecial(dirList, tempDir, default, special) # Merge root directory. else: if os.path.isdir(default): slog.warning('The directory [%s] is not existed.'%sourcePath) return None copy_dir(default, tempDir) copy_dir(special, tempDir) print_sep('Merging has done.', False) return tempDir
def _processAGit(self, gitConf): print_sep('\nStart to update the git repository [%s].' % gitConf.path, True, 40) exists = os.path.exists(gitConf.path) if exists: if self.args.force: gitArgs = git.get_args(gitConf.path, 'reset', '--hard') slog.info(' '.join(gitArgs)) subprocess.call(gitArgs) gitArgs = git.get_args(gitConf.path, 'pull', 'origin', 'master') slog.info(' '.join(gitArgs)) subprocess.call(gitArgs) print_sep( 'Update the git repository [%s] has done.' % gitConf.path, False, 40) else: slog.warning('%s is not exists!' % gitConf.path)
def fmt(self, po_file, mo_file): """将 po 文件转换成 mo 文件。 :param string po_file: 待转换的 po 文件路径。 :param string mo_file: 目标 mo 文件的路径。 """ if not os.path.exists(po_file): slog.error('The PO file [%s] is non-existen!' % po_file) return txt = subprocess.check_output([ self._msgfmt, '--check', "--strict", '--verbose', "--output-file", mo_file, po_file ], stderr=subprocess.STDOUT, universal_newlines=True) slog.info(txt)
def lua(self): print_sep('\nStart to update the lua framworks.', True, 40) src = self.conf.getClientPath('src') cocos = os.path.join(src, 'cocos') quick = os.path.join(src, 'quick') zrong = os.path.join(src, 'zrong') if os.path.islink(cocos) or \ os.path.islink(quick) or \ os.path.islink(zrong): slog.info('%s OR %s OR %s is a link. Remove a link is forbidden.' % (cocos, quick, zrong)) return self._downloadAndUnzip(self.conf.lib_conf.lua, [cocos, quick, zrong], src) print_sep('Update lua framworks has done.', False, 40)
def convert_to_cocos2d(tpexe, source, output, dirname, disable_rotation=False, options=None): plist_file = os.path.join(output, dirname + ".plist") png_file = os.path.join(output, dirname + ".png") imagefolder = os.path.join(source, dirname) xargs = ["--sheet", png_file, "--data", plist_file] if options: xargs = xargs + _get_args_list(options) if disable_rotation: xargs.append('--disable-rotation') succ = convert_by_options(tpexe, xargs, imagefolder) if succ: slog.info("\n.... converting %s", dirname)
def _merge2Tmp(self, default, special, dirList=None): tempDir = tempfile.mkdtemp(prefix='tbbl_') slog.info("Make a temporary directory: %s", tempDir) print_sep( 'Start to merge directory [%s] and [%s] to temporary directory.' % (default, special)) # Merge sub-directory one by one. if dirList: self._mergeSpecial(dirList, tempDir, default, special) # Merge root directory. else: if os.path.isdir(default): slog.warning('The directory [%s] is not existed.' % sourcePath) return None copy_dir(default, tempDir) copy_dir(special, tempDir) print_sep('Merging has done.', False) return tempDir
def call(heroPath, sszPath, exportPath): parser = Parser(exportPath) #parse tmpl parser.parseTmpl(heroPath) # parse heros files = filter(herosFiles, get_files(heroPath, ["json"])) slog.info("parse: etc.json") parser.parseHero(files) # parse ssz files = filter(confFiles, get_files(sszPath, ["json"])) for path in files: slog.info("parse: %s", os.path.basename(path)) jsontxt = read_file(path) jsontxt = re.sub(r'\/\/.*$', '', jsontxt, flags=re.M) obj = json.loads(jsontxt) parser.parseConf(obj, os.path.basename(path).split('.')[0])
def call(heroPath, sszPath, exportPath): parser = Parser(exportPath) #parse tmpl parser.parseTmpl(heroPath) # parse heros files = filter(herosFiles, get_files(heroPath, ["json"])) slog.info("parse: etc.json") parser.parseHero(files) # parse ssz files = filter(confFiles, get_files(sszPath, ["json"])) for path in files: slog.info("parse: %s", os.path.basename(path)) jsontxt = read_file(path) jsontxt = re.sub(r'\/\/.*$', '', jsontxt, flags=re.M) obj = json.loads(jsontxt) parser.parseConf(obj, os.path.basename(path).split('.')[0])
def renderLua(ps): global verNum, protocolNum slog.info('rendering ...') datatypes = { "uvint":"R", "vint":"r", "string":"S", "list":"t" } def _items(das): ts = [] keys = [] for da in das: #slog.info(da.datatype) ts.append(datatypes[da.datatype]) keys.append(da.fieldname) d = { "fmt":''.join(ts), "keys":keys } return d for p in ps: _c = str(p.code)[0:1] if _c == '1': pps = pclient elif _c == '2': pps = pserver else: pps = pupdate p.code = int(p.code) if p.code not in pps: pps[p.code] = {} pps[p.code][int(p.ver)] = _items(p.datas) #slog.info('//-----// protocolNum:%d, code: %s',protocolNum,p.code) if p.code: protocolNum += 1 verNum += p.ver + 1
def generateADef(self, ani): if not self._gendef: return pieceNum = len(list(list_dir(os.path.join(self._aniDir, ani)))) sub = { 'spritesheets':[ani], 'animations' :[{ 'name':ani, 'delay_per_unit':0.042, 'loops':1, 'restore_original_frame':'false', 'range':{'start':1,'end':pieceNum}, }], } # animation file is started by "ani_", main name starts from index 4. defName = 'ani_def_%s.lua'%ani[4:] defFile = self._conf.getClientPath('res', 'ani', defName) write_by_jinja(self._conf.getJinjaTempl('ani_def.lua'), defFile, sub) slog.info('Generate a ani_def file: %s.'%defFile)
def cpp(self): if not self.isAdmin(): return dirname = 'runtime-src' runtimeDir = self.conf.getDistPath(dirname) slog.info('Packaging C++ project files to a tempfile.') files = [] for p, d, fs in os.walk(runtimeDir, followlinks=True): for f in fs: path = os.path.join(p,f) if '.DS_Store' in path: continue files.append(path) slog.info('runtimeDir:%s', runtimeDir) # Save dirname in zip. pre = len(runtimeDir)-len(dirname) self.upload218Lib(create_zip(files, pre), self.conf.lib_conf.cpp)
def cpp(self): if not self.isAdmin(): return dirname = 'runtime-src' runtimeDir = self.conf.getDistPath(dirname) slog.info('Packaging C++ project files to a tempfile.') files = [] for p, d, fs in os.walk(runtimeDir, followlinks=True): for f in fs: path = os.path.join(p, f) if '.DS_Store' in path: continue files.append(path) slog.info('runtimeDir:%s', runtimeDir) # Save dirname in zip. pre = len(runtimeDir) - len(dirname) self.upload218Lib(create_zip(files, pre), self.conf.lib_conf.cpp)
def convert_by_options(tpexe, options, imagefolder): """ options must be a list or a string """ xargs = [tpexe] argslist = None if isinstance(options, list): argslist = options elif isinstance(options, str): argslist = _get_args_list(options) if not argslist: slog.error("Please give some options.") return False for value in argslist: xargs.append(value) xargs.append(imagefolder) tpout = subprocess.check_output(xargs, universal_newlines=True) slog.info("Call TexturePacker, command line is: \n") slog.warning("%s\n", " ".join(xargs)) slog.info("%s\n", tpout) return True
def convert_by_options(tpexe, options, imagefolder): """ options must be a list or a string """ xargs = [tpexe] argslist = None if isinstance(options, list): argslist = options elif isinstance(options, str): argslist = _get_args_list(options) if not argslist: slog.error("Please give some options.") return False for value in argslist: xargs.append(value) xargs.append(imagefolder) tpout = subprocess.check_output(xargs, universal_newlines=True) slog.info("Call TexturePacker, command line is: \n") slog.warning("%s\n", " ".join(xargs)) slog.info("%s\n", tpout) return True
def merge(self, po_file, source_files): """从源码中获取所有条目,合并到 po_file 中。 :param string po_file: 待写入的 po 文件路径。 :param list source_files : 所有待处理的原文件路径 list。 """ # Create a temporary file to write pot file pot_file = tempfile.NamedTemporaryFile(mode='wb', prefix='hhlb_', delete=False) pot_filename = pot_file.name slog.info('Create POT file [%s].', pot_filename) xargs = [ self._xgettext, "--package-name=main", "--package-version=0.1", "--default-domain=main", "--from-code=UTF-8", "-C", "-k_", "--output", pot_filename ] txt = subprocess.check_output(xargs + source_files, stderr=subprocess.STDOUT, universal_newlines=True) if len(txt) > 0: raise (ZrongError(txt)) slog.info('Start merge [%s] to [%s].', pot_filename, po_file) xargs = [self._msgmerge, "-U", po_file, pot_filename] txt = subprocess.check_output(xargs, universal_newlines=True) slog.info(txt) pot_file.close() os.remove(pot_filename)
def merge(self, po_file, source_files): """从源码中获取所有条目,合并到 po_file 中。 :param string po_file: 待写入的 po 文件路径。 :param list source_files : 所有待处理的原文件路径 list。 """ # Create a temporary file to write pot file pot_file = tempfile.NamedTemporaryFile(mode='wb', prefix='hhlb_', delete=False) pot_filename = pot_file.name slog.info('Create POT file [%s].', pot_filename) xargs = [self._xgettext, "--package-name=main", "--package-version=0.1", "--default-domain=main", "--from-code=UTF-8", "-C", "-k_", "--output", pot_filename] txt = subprocess.check_output(xargs+source_files, stderr=subprocess.STDOUT, universal_newlines=True) if len(txt) > 0: raise(ZrongError(txt)) slog.info('Start merge [%s] to [%s].', pot_filename, po_file) xargs = [self._msgmerge, "-U", po_file, pot_filename] txt = subprocess.check_output(xargs, universal_newlines=True) slog.info(txt) pot_file.close() os.remove(pot_filename)
def generateADef(self, ani): if not self._gendef: return pieceNum = len(list(list_dir(os.path.join(self._aniDir, ani)))) sub = { 'spritesheets': [ani], 'animations': [{ 'name': ani, 'delay_per_unit': 0.042, 'loops': 1, 'restore_original_frame': 'false', 'range': { 'start': 1, 'end': pieceNum }, }], } # animation file is started by "ani_", main name starts from index 4. defName = 'ani_def_%s.lua' % ani[4:] defFile = self._conf.getClientPath('res', 'ani', defName) write_by_jinja(self._conf.getJinjaTempl('ani_def.lua'), defFile, sub) slog.info('Generate a ani_def file: %s.' % defFile)
def lua(self): if not self.isAdmin(): return srcDIR = self.conf.getClientPath('src') slog.info('Packaging lua framework to a tempfile') files = [] for aDIR in ( os.path.join(srcDIR, 'zrong'), os.path.join(srcDIR, 'quick'), os.path.join(srcDIR, 'cocos'), ): for p, d, fs in os.walk(aDIR, followlinks=True): for f in fs: path = os.path.join(p,f) if '.DS_Store' in path: continue files.append(path) pre = len(srcDIR)+1 self.upload218Lib(create_zip(files, pre), self.conf.lib_conf.lua)
def lua(self): if not self.isAdmin(): return srcDIR = self.conf.getClientPath('src') slog.info('Packaging lua framework to a tempfile') files = [] for aDIR in ( os.path.join(srcDIR, 'zrong'), os.path.join(srcDIR, 'quick'), os.path.join(srcDIR, 'cocos'), ): for p, d, fs in os.walk(aDIR, followlinks=True): for f in fs: path = os.path.join(p, f) if '.DS_Store' in path: continue files.append(path) pre = len(srcDIR) + 1 self.upload218Lib(create_zip(files, pre), self.conf.lib_conf.lua)
def create_zip(files, trim_arcname=None, target_file=None, **zipfile_args): """创建一个 zip 文件。 :param list files: 要创建zip 的文件列表。 :param int trim_arcname: 若提供这个值,则使用 ZipFile.write(filename, filename[trim_arcname:]) 进行调用。 :returns: zip 文件的路径。 :rtype: str """ zipname = None azip = None if not target_file: azip = tempfile.NamedTemporaryFile(mode='wb', delete=False) zipname = azip.name else: azip = target_file zipname = target_file.name if hasattr(azip, 'read') else azip slog.info('Package %d files to "%s"'%(len(files), azip.name)) fileNum = len(files) curFile = 0 zipfile_args['mode'] = 'w' if not zipfile_args.get('compression'): zipfile_args['compression'] = zipfile.ZIP_DEFLATED with zipfile.ZipFile(azip, **zipfile_args) as zipf: for f in files: percent = round(curFile/fileNum*100) sys.stdout.write('\r%d%%'%(percent)) sys.stdout.flush() zipf.write(f, f[trim_arcname:] if trim_arcname else None ) curFile = curFile+1 sys.stdout.write('\r100%\n') sys.stdout.flush() if hasattr(azip, 'close'): azip.close() return zipname