def replaceRequire(source, fi, pkg, cache): #匹配 require reg = re.compile('require\([\'"]([^\)]+)[\'|"]\)') reqs = reg.findall(source) #缓存标记 localcache = {} #匹配上级目录 updir = re.compile(r'^\.\./') samedir = re.compile(r'^\./') #匹配间隔符 sep = re.compile(r'/') if not reg.search(source): return source for req in reqs: #匹配后缀 postfix = re.compile(r'\.js$') if not postfix.search(req): req = req + '.js' name = getName(req) if not cache.has_key(name): rpath = pkg + '/' + req if samedir.match(req): ps = sep.split(fi) ps.pop() ps.append(samedir.sub('', req)) rpath = '/'.join(ps) elif updir.match(req): rpath = pkg + '/' + updir.sub('', req) #匹配 /../ mistake = re.compile('/\.\./') rpath = mistake.sub('/', rpath) s = fixPath(getSource(rpath), req) localcache[name] = s cache[name] = s # print cache[name] vars = getList(localcache) # print ret result = ''.join(vars) return result
def toAlias(pkg, fi, cache): print 'file path: ' + fi fi = fi.encode('UTF-8') #读取文件 source = getSource(pkg + '/' + fi) #匹配 require req = re.compile(r'require\([\'"](.+?)[\'"]\)') #替换路径 def replacePath(match): #匹配路径 sep = re.compile(r'/') paths = sep.split(fi) paths.pop() rel = sep.split(match.group(1)) if '.' == rel[0]: rel.pop(0) path = '/'.join(rel) relreg = re.compile(r'\.\./') ps = relreg.findall(path) if len(ps): for x in ps: if '..' != x: paths.pop() if paths: ret = '/'.join(paths) + '/' + relreg.sub('', path) else: ret = relreg.sub('', path) return 'require(\'' + ret + '\')' if not cache.has_key(fi): cache[fi] = 'true' if req.search(source): source = req.sub(replacePath, source) # print cache return getName(fi) + ': ' + source