20 from Extract.getCall
import getCallFunction, modifyWithName
22 from Tool.tool
import getAst,getParameter,getLastAPIParameter,departAPI,departAPI2,ConditionalReturnTransformer, getFileName, getRunFile
23 from Tool.workspace
import getRuntimePaths
59 return minL,minR,midL,midR,huaL,huaR
70 with open(filePath,
'w',encoding=
'UTF-8')
as fw:
71 newCode=ast.unparse(root)
73 fw.write(f
"{newCode}\n")
74 except Exception
as e:
75 print(f
"oneLine --> {filePath} parse to ast failed: {e}")
85 transformer = ConditionalReturnTransformer()
86 new_root = transformer.visit(root)
88 with open(filePath,
'w',encoding=
'UTF-8')
as fw:
89 newCode=ast.unparse(root)
90 fw.write(f
"{newCode}\n")
91 except Exception
as e:
92 print(f
"expandConditionalReturn --> {filePath} parse to ast failed: {e}")
106 for node
in ast.iter_child_nodes(root):
107 if isinstance(node,ast.ListComp):
108 s=ast.unparse(node.generators).lstrip(
' ')
109 pattern=
"for (.*?) in"
110 lst=re.findall(pattern,s)
117 s1=f
"{var}=[{temp} {s}][0]"
133 for node
in ast.iter_child_nodes(root):
134 if isinstance(node,ast.DictComp):
135 s=ast.unparse(node.generators).lstrip(
' ')
136 pattern=
"for (.*?) in"
137 lst=re.findall(pattern,s)
144 s1=f
"{var}=[{temp} {s}][0]"
157 with open(filePath,
'r',encoding=
'UTF-8')
as fr:
158 codeLst=fr.readlines()
160 for i
in range(len(codeLst)):
161 s=codeLst[i].lstrip(
' ').rstrip(
' ')
163 root=ast.parse(s,filename=
'<unknown>',mode=
'exec')
164 except Exception
as e:
170 for node
in ast.walk(root):
171 if isinstance(node,ast.ListComp):
173 if isinstance(node,ast.DictComp):
176 if not listComp
and not dictComp:
182 callLst=[record[
'call_text']
for record
in callDict.values()]
184 for node
in ast.walk(root):
185 if isinstance(node, ast.Call):
186 callState=ast.unparse(node)
187 callState=callState.replace(
' ',
'').replace(
'"',
'').replace(
"'",
'')
189 if callState==it.replace(
' ',
'').replace(
'"',
'').replace(
"'",
''):
205 exceptStr=
"except:\n"
208 tryStr=
' '*spaceNum*1+tryStr
209 it=
' '*spaceNum*1+
' '*4+it+
'\n'
210 exceptStr=
' '*spaceNum*1+exceptStr
211 passStr=
' '*spaceNum*1+
' '*4+passStr
214 it=
' '*spaceNum*1+it+
'\n'
215 passStr=
' '*spaceNum*1+passStr
218 s=tryStr+it+exceptStr+passStr
229 exceptStr=
"except:\n"
232 tryStr=
' '*spaceNum*1+tryStr
233 it=
' '*spaceNum*1+
' '*4+it+
'\n'
234 exceptStr=
' '*spaceNum*1+exceptStr
235 passStr=
' '*spaceNum*1+
' '*4+passStr
238 it=
' '*spaceNum*1+it+
'\n'
239 passStr=
' '*spaceNum*1+passStr
242 s=tryStr+it+exceptStr+passStr
248 with open(filePath,
'w',encoding=
'UTF-8')
as fw:
261 for node
in ast.walk(root):
262 if isinstance(node,ast.Assign)
and isinstance(node.value,ast.Call):
263 target=ast.unparse(node.targets)
264 assignLst.append(target)
280 scopeBodies=[root.body]
281 for node
in ast.walk(root):
282 if isinstance(node,(ast.FunctionDef,ast.AsyncFunctionDef,ast.ClassDef)):
284 end=getattr(node,
'end_lineno',start)
285 if start<lineno<=end:
286 scopeBodies.append(node.body)
288 for body
in scopeBodies:
290 if not hasattr(stmt,
'lineno')
or stmt.lineno>=lineno:
292 if isinstance(stmt,(ast.If,ast.For,ast.AsyncFor,ast.While,ast.Try,ast.With,ast.AsyncWith)):
296 if isinstance(stmt,ast.Assign):
299 elif isinstance(stmt,ast.AnnAssign):
301 targets=[stmt.target]
304 for target
in targets:
305 if isinstance(target,ast.Name)
and target.id==aliasName
and stmt.lineno>bestLine:
306 sourceExpr=ast.get_source_segment(source,value)
308 expr=sourceExpr.strip()
321 for node
in ast.walk(root):
322 if not isinstance(node,ast.ClassDef):
325 end=getattr(node,
'end_lineno',start)
326 if not (start<lineno<=end)
or len(node.bases)==0:
329 for item
in ast.iter_child_nodes(node):
330 if isinstance(item,(ast.FunctionDef,ast.AsyncFunctionDef)):
331 defNames.add(item.name)
332 if methodName
in defNames:
334 return ast.unparse(node.bases[0])
366 for i
in range(len(codeLst)):
367 if 'import' in codeLst[i]
and '__future__' in codeLst[i]:
372 if index==-1
and '"""' in codeLst[0]:
373 for i
in range(0,len(codeLst)):
374 if '"""' in codeLst[i]:
393 for n
in ast.walk(root):
394 if isinstance(n, (ast.FunctionDef, ast.ClassDef))
and n.decorator_list:
395 for decorator
in n.decorator_list:
396 if isinstance(decorator, ast.Call):
397 decoratorLst.append(ast.unparse(decorator.func))
414 if not codeLst[index].lstrip().startswith(
'@'):
420 if codeLst[j].lstrip().startswith(
'@')
and countSpace(codeLst[j])==spaceNum:
437 with open(filePath,
'r',encoding=
'UTF-8')
as fr:
438 codeLst=fr.readlines()
439 source=
''.join(codeLst)
442 importDict=
'from recordValue import paraValueDict\nfrom recordValue import callsiteInfoDict\n'
443 codeLst.insert(lineno,importDict)
451 withitem_visitor = WithVisitor()
452 withitem_visitor.visit(root)
453 withitem_call_names = withitem_visitor.get_withitem_call()
455 for i
in range(len(codeLst)):
456 if callAPI.replace(
' ',
'')
in codeLst[i].replace(
' ',
'')
and 'def ' not in codeLst[i]
and 'paraValueDict' not in codeLst[i]
and 'callsiteInfoDict' not in codeLst[i]:
465 firstPart=firstPart.rstrip(
'.')
468 'call_text': callAPI,
469 'format_api': callAPI,
471 displayCall=callAPI.replace(
'\n',
' ')
472 dicStringComment=f
'# PCART callsite: {displayCall}\n'
473 dicStringKey=f
'__pcart_runtime_callsite_key__={repr(callKey)}\n'
474 dicString0=f
'callsiteInfoDict[__pcart_runtime_callsite_key__]={repr(callsiteInfo)}\n'
475 if firstPart
and (firstPart.split(
'.')[0]
in targetLst
or firstPart.split(
'.')[0]==
'self')
and len(l)==1:
478 if firstPart.split(
'.')[0]
in targetLst:
480 elif firstPart.split(
'.')[0]==
'self':
481 methodName=callAPI.split(
'(')[0].split(
'.')[-1]
484 receiverExpr=receiverExpr.replace(
'\\',
'\\\\').replace(
'"',
'\\"')
485 dicString1=f
'paraValueDict[\"@\"+__pcart_runtime_callsite_key__]={{}}; paraValueDict[\"@\"+__pcart_runtime_callsite_key__][\"object\"]={firstPart}; paraValueDict[\"@\"+__pcart_runtime_callsite_key__][\"expr\"]=\"{receiverExpr}\"\n'
487 dicString1=f
'paraValueDict[\"@\"+__pcart_runtime_callsite_key__]={firstPart}\n'
489 dicString1=f
'paraValueDict[\"@\"+__pcart_runtime_callsite_key__]={l[-2]}\n'
492 if firstPart
and firstPart.split(
'.')[0]
in withitem_call_names:
494 initialCallName =
modifyWithName(firstPart, withitem_call_names, lineNo).rstrip(
'.')
496 initialCallName=initialCallName.replace(
'\\',
'\\\\').replace(
'"',
'\\"')
497 dicString1=f
'paraValueDict[\"@\"+__pcart_runtime_callsite_key__]={{}}; paraValueDict[\"@\"+__pcart_runtime_callsite_key__][\"object\"]={firstPart}; paraValueDict[\"@\"+__pcart_runtime_callsite_key__][\"expr\"]=\"{initialCallName}\"\n'
500 dicString2=
'paraValueDict[__pcart_runtime_callsite_key__]=['
501 for para
in parameterLst:
502 if '=' in para
and "'='" not in para
and '"="' not in para:
504 if '(' not in para[0:pos]
and "'" not in para[0:pos]
and '"' not in para[0:pos]
and para[pos+1]!=
'=':
507 para=para.lstrip(
'*')
508 dicString2=dicString2+para+
','
509 dicString2=dicString2.rstrip(
',')+
']\n'
512 dicStringComment=
' '+dicStringComment
513 dicStringKey=
' '+dicStringKey
514 dicString0=
' '+dicString0
516 dicString1=
' '+dicString1
517 dicString2=
' '+dicString2
521 if 'elif' not in codeLst[i]:
523 codeLst.insert(insertIndex,dicString2)
525 codeLst.insert(insertIndex,dicString1)
526 codeLst.insert(insertIndex,dicString0)
527 codeLst.insert(insertIndex,dicStringKey)
528 codeLst.insert(insertIndex,dicStringComment)
531 dicString1=dicString1.lstrip(
' ')
532 dicStringComment=dicStringComment.lstrip(
' ')
533 dicStringKey=dicStringKey.lstrip(
' ')
534 dicString0=dicString0.lstrip(
' ')
535 dicString2=dicString2.lstrip(
' ')
536 for j
in range(i+1,len(codeLst)):
537 if codeLst[j]!=
'\n' and '#' not in codeLst[j]:
540 dicStringComment=
' '+dicStringComment
541 dicStringKey=
' '+dicStringKey
542 dicString0=
' '+dicString0
544 dicString1=
' '+dicString1
545 dicString2=
' '+dicString2
548 codeLst.insert(j,dicString2)
550 codeLst.insert(j,dicString1)
551 codeLst.insert(j,dicString0)
552 codeLst.insert(j,dicStringKey)
553 codeLst.insert(j,dicStringComment)
559 if codeLst[0]==
'pass\n':
561 with open(filePath,
'w',encoding=
'UTF-8')
as fw:
579 def addDictAll(projPath,projName,filePath,copyRoot,runFileLst,libName,runPath,runCommand,pcresolveLookup=None):
580 with open(filePath,
'r',encoding=
'UTF-8')
as fr:
583 codeLst=fr.readlines()
585 root=ast.parse(code,filename=
'<unknown>',mode=
'exec')
586 except Exception
as e:
587 print(f
"addDictAll --> ast.parse failed, {filePath}: {e}")
591 fileName = os.path.basename(filePath)[0:-3]
592 fileRelativePath=os.path.relpath(filePath,os.path.join(copyRoot,projName))
593 fileAbsolutePath=os.path.join(projPath,fileRelativePath)
596 importDict=
'from recordValue import paraValueDict\nfrom recordValue import apiCoveredSet\nfrom recordValue import callsiteInfoDict\n'
597 codeLst.insert(lineno,importDict)
598 if pcresolveLookup
is None:
601 _,callDict=
getCallFunction(fileAbsolutePath,libName,projPath,pcresolveLookup=pcresolveLookup)
607 withitem_root =
getAst(fileAbsolutePath)
610 withitem_visitor = WithVisitor()
611 withitem_visitor.visit(withitem_root)
612 withitem_call_names = withitem_visitor.get_withitem_call()
617 for artifactId,record
in callDict.items():
619 lineno=int(record[
'lineno'])
620 callState=record[
'call_text']
621 paraStr=record[
'parameters']
622 callAPI=callState.replace(
' ',
'')
623 if callAPI==preInsertAPI:
625 if preInsertAPICount<=0:
629 while i<len(codeLst):
631 if callAPI
in codeLst[i].replace(
' ',
'')
and 'def ' not in codeLst[i]
and 'paraValueDict' not in codeLst[i]
and 'apiCoveredSet' not in codeLst[i]
and 'callsiteInfoDict' not in codeLst[i]:
632 if callAPI!=preInsertAPI:
633 preInsertAPICount=codeLst[i].replace(
' ',
'').count(callAPI)
637 callSiteKey=artifactId
639 'artifact_hash': record.get(
'artifact_hash',
''),
640 'rel_path': record.get(
'rel_path',
''),
641 'lineno': record.get(
'lineno'),
642 'col_offset': record.get(
'col_offset'),
643 'end_lineno': record.get(
'end_lineno'),
644 'end_col_offset': record.get(
'end_col_offset'),
645 'call_text': record.get(
'call_text',
''),
646 'format_api': record.get(
'format_api',
''),
648 displayPath=record.get(
'rel_path',
'')
649 displayLine=record.get(
'lineno')
650 displayColumn=record.get(
'col_offset')
651 displayCall=str(record.get(
'call_text',
'')).replace(
'\n',
' ')
652 displayPrefix=f
'{displayPath}:{displayLine}:{displayColumn} ' if displayPath
else ''
653 dicStringComment=f
'# PCART callsite: {displayPrefix}{displayCall}\n'
654 dicStringKey=f
'__pcart_runtime_callsite_key__={repr(callSiteKey)}\n'
655 dicString0=f
'callsiteInfoDict[__pcart_runtime_callsite_key__]={repr(callsiteInfo)}\n'
662 firstPart=firstPart.rstrip(
'.')
670 if firstPart
and (firstPart.split(
'.')[0]
in targetLst
or firstPart.split(
'.')[0]==
'self')
and len(l)==1:
672 if firstPart.split(
'.')[0]
in targetLst:
674 elif firstPart.split(
'.')[0]==
'self':
675 methodName=callState.split(
'(')[0].split(
'.')[-1]
678 receiverExpr=receiverExpr.replace(
'\\',
'\\\\').replace(
'"',
'\\"')
679 dicString1=f
'paraValueDict[\"@\"+__pcart_runtime_callsite_key__]={{}}; paraValueDict[\"@\"+__pcart_runtime_callsite_key__][\"object\"]={firstPart}; paraValueDict[\"@\"+__pcart_runtime_callsite_key__][\"expr\"]=\"{receiverExpr}\"\n'
681 dicString1=f
'paraValueDict[\"@\"+__pcart_runtime_callsite_key__]={firstPart}\n'
683 dicString1=f
'paraValueDict[\"@\"+__pcart_runtime_callsite_key__]={l[-2]}\n'
686 if firstPart
and firstPart.split(
'.')[0]
in withitem_call_names:
687 initialCallName =
modifyWithName(firstPart, withitem_call_names, lineno).rstrip(
'.')
688 initialCallName = initialCallName.rstrip(
'.')
690 initialCallName=initialCallName.replace(
'\\',
'\\\\').replace(
'"',
'\\"')
691 dicString1=f
'paraValueDict[\"@\"+__pcart_runtime_callsite_key__]={{}}; paraValueDict[\"@\"+__pcart_runtime_callsite_key__][\"object\"]={firstPart}; paraValueDict[\"@\"+__pcart_runtime_callsite_key__][\"expr\"]=\"{initialCallName}\"\n'
693 dicString2=
'paraValueDict[__pcart_runtime_callsite_key__]=['
696 if '=' in para
and "'='" not in para
and '"="' not in para:
698 if '(' not in para[0:pos]
and "'" not in para[0:pos]
and '"' not in para[0:pos]
and para[pos+1]!=
'=':
701 para=para.lstrip(
'*')
702 dicString2=dicString2+para+
','
703 dicString2=dicString2.rstrip(
',')+
']\n'
705 dicString3=
'apiCoveredSet.add(__pcart_runtime_callsite_key__)\n'
707 dicStringComment=
' '+dicStringComment
708 dicStringKey=
' '+dicStringKey
709 dicString0=
' '+dicString0
711 dicString1=
' '+dicString1
712 dicString2=
' '+dicString2
713 dicString3=
' '+dicString3
718 if 'elif' not in codeLst[i]:
720 codeLst.insert(insertIndex,dicString3)
721 codeLst.insert(insertIndex,dicString2)
723 codeLst.insert(insertIndex,dicString1)
724 codeLst.insert(insertIndex,dicString0)
725 codeLst.insert(insertIndex,dicStringKey)
726 codeLst.insert(insertIndex,dicStringComment)
729 insertStartLine=insertIndex+6
731 insertStartLine=insertIndex+5
734 dicString1=dicString1.lstrip(
' ')
735 dicStringComment=dicStringComment.lstrip(
' ')
736 dicStringKey=dicStringKey.lstrip(
' ')
737 dicString0=dicString0.lstrip(
' ')
738 dicString2=dicString2.lstrip(
' ')
739 dicString3=dicString3.lstrip(
' ')
740 for j
in range(i+1,len(codeLst)):
741 if codeLst[j]!=
'\n' and '#' not in codeLst[j]:
744 dicStringComment=
' '+dicStringComment
745 dicStringKey=
' '+dicStringKey
746 dicString0=
' '+dicString0
748 dicString1=
' '+dicString1
749 dicString2=
' '+dicString2
750 dicString3=
' '+dicString3
752 codeLst.insert(j,dicString3)
753 codeLst.insert(j,dicString2)
755 codeLst.insert(j,dicString1)
756 codeLst.insert(j,dicString0)
757 codeLst.insert(j,dicStringKey)
758 codeLst.insert(j,dicStringComment)
773 print(f
"{fileName}#{lineno}-->{callState}\n")
775 if codeLst[0]==
'pass\n':
777 with open(filePath,
'w',encoding=
'UTF-8')
as fw:
796 with open(file,
'r',encoding=
'UTF-8')
as fr:
797 codeLst=fr.readlines()
799 codeLst.insert(lineno,f
"from recordValue import paraValueDict\n")
801 if codeLst[0]==
'pass\n':
803 with open(file,
'w',encoding=
'UTF-8')
as fw:
812 with open(sourcePath,
'r',encoding=
'UTF-8')
as fr:
815 root=ast.parse(code,filename=
'<unknown>',mode=
'exec')
819 fw=open(
'Copy/defFile.py',
'a',encoding=
'UTF-8')
820 for node
in ast.iter_child_nodes(root):
821 if isinstance(node,ast.ClassDef)
or isinstance(node,ast.FunctionDef):
834 with open(filePath,
'r', encoding=
'UTF-8')
as fr:
835 codeLst=fr.readlines()
837 s=
'\n'.join(importStatement)+
'\n'
840 with open(filePath,
'w', encoding=
'UTF-8')
as fw:
869 for n
in ast.walk(astNode):
870 if isinstance(n,ast.Assign):
872 valueAstContent = ast.dump(n.value)
873 targetAstContent = ast.dump(n.targets[0])
874 if isinstance(n.targets[0], ast.Name):
875 varName = n.targets[0].id
877 if any(varName
in decorator.split(
'.')
for decorator
in decoratorLst):
880 if isinstance(value, ast.Constant):
881 if varName
in nonConstantVar:
888 if isinstance(target, ast.Name):
889 constantVar.append(target.id)
892 pattern =
r"id='([^']*)'"
893 valueMatches = re.findall(pattern, valueAstContent)
894 targetMatches = re.findall(pattern, targetAstContent)
895 if not len(valueMatches):
896 if targetMatches[0]
in nonConstantVar:
900 for match
in valueMatches:
901 if match
not in constantVar:
902 nonConstantVar.append(targetMatches[0])
911 astBody.append(astNode)
923 pathObj.getPath(projPath)
924 filePath=[it
for it
in pathObj.path
if it.endswith(
'py')]
925 for file
in filePath:
927 callLst=[record[
'call_text']
for record
in callDict.values()]
929 with open(file,
'r', encoding=
'UTF-8')
as fr:
932 root=ast.parse(code,filename=
'<unknown>',mode=
'exec')
933 except Exception
as e:
934 print(f
"saveStructure --> ast parse failed in {file}: {e}")
941 for node
in root.body:
943 if isinstance(node,ast.Import)
or isinstance(node,ast.ImportFrom)
or isinstance(node,ast.ClassDef)
or isinstance(node,ast.FunctionDef)
or isinstance(node,ast.AsyncFunctionDef):
957 if isinstance(node,ast.Assign):
965 for node
in ast.walk(root):
966 if isinstance(node,ast.Assign):
972 if ast.dump(item)
not in [ast.dump(i)
for i
in newBody]:
976 newFile=ast.unparse(root)
977 with open(file,
'w',encoding=
'utf-8')
as fw:
978 fw.write(f
"{newFile}\n")
989 return [f
for f
in files
if os.path.islink(os.path.join(directory, f))]
1002 pathObj.getPath(projPath)
1003 filePath=[file
for file
in pathObj.path
if file.endswith(
'.py')]
1004 pattern=rf
"(from {libName}|import {libName})"
1005 for file
in filePath:
1007 with open(file,
'r', encoding=
'UTF-8')
as fr:
1010 root=ast.parse(code,filename=
'<unknown>',mode=
'exec')
1011 for node
in ast.walk(root):
1012 if isinstance(node,ast.Import)
or isinstance(node,ast.ImportFrom):
1014 if bool(re.search(pattern,s)):
1016 except Exception
as e:
1017 print(f
"getLibImportLst: ast parse failed, {file}, {e}")
1020 ansLst=list(set(lst))
1021 ansLst.sort(key=lst.index)
1031 for root, dirs, files
in os.walk(directory):
1033 if file.endswith(
'.py'):
1034 file_path = os.path.join(root, file)
1036 with open(file_path,
'r', encoding=
'utf-8')
as f:
1039 content = content.expandtabs(4)
1040 with open(file_path,
'w', encoding=
'utf-8')
as f:
1042 except Exception
as e:
1043 print(f
"Error converting file {file_path}: {e}")
1054 scriptPath=os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
1055 'Script',
'recordValue.py')
1056 with open(scriptPath,
'r',encoding=
'UTF-8')
as fr:
1058 content=content.replace(
"'__PCART_PKL_REL_PATH__'",repr(pklRelPath))
1059 content=content.replace(
'__PCART_USE_CALLSITE_NAME__',str(bool(useCallsiteName)))
1060 with open(filePath,
'w',encoding=
'UTF-8')
as fw:
1070 return os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
1071 'Script',scriptName)
1094 def codeProcess(projPath,runCommand,runPath,libName,workspace,pcresolveLookup=None):
1096 copyRoot=runtimePaths[
'copy_root']
1097 dynamicRoot=runtimePaths[
'dynamic_root']
1098 dataDir=runtimePaths[
'data_dir']
1104 if runFile
and (
'/' in runFile
or '\\' in runFile):
1106 prefix = os.path.dirname(runFile)
1108 runFile = os.path.basename(runFile)
1110 runFileLst.append(runFile)
1113 if runPath!=
'' and prefix!=runPath:
1116 projName = os.path.basename(projPath)
1117 copyProjPath=os.path.join(copyRoot,projName)
1119 for it
in runFileLst:
1122 importStatement+=f
"from {it} import *\n"
1127 libImportLst.append(importStatement)
1130 if os.path.isdir(copyRoot):
1131 shutil.rmtree(copyRoot)
1132 os.makedirs(os.path.dirname(copyRoot)
or '.',exist_ok=
True)
1133 shutil.copytree(projPath,os.path.join(copyRoot,projName),ignore=ignore_sym_links)
1134 os.mkdir(os.path.join(copyRoot,
'pkl'))
1135 if os.path.isdir(dynamicRoot):
1136 shutil.rmtree(dynamicRoot)
1137 os.makedirs(os.path.dirname(dynamicRoot)
or '.',exist_ok=
True)
1138 shutil.copytree(projPath,os.path.join(dynamicRoot,projName),ignore=ignore_sym_links)
1143 dynamicScriptDir=os.path.join(dynamicRoot,projName,prefix)
1144 shutil.copy2(
scriptPath(
'addValueForAPI.py'),dynamicScriptDir)
1145 shutil.copy2(
scriptPath(
'codeUtils.py'),dynamicScriptDir)
1146 shutil.copy2(
scriptPath(
'dynamicMatch.py'),dynamicScriptDir)
1147 shutil.copy2(
scriptPath(
'verifySingle.py'),dynamicScriptDir)
1150 modifyFromImport(os.path.join(dynamicScriptDir,
'addValueForAPI.py'),libImportLst)
1151 modifyFromImport(os.path.join(dynamicScriptDir,
'dynamicMatch.py'),libImportLst)
1152 modifyFromImport(os.path.join(dynamicScriptDir,
'verifySingle.py'),libImportLst)
1155 if os.path.isdir(dataDir):
1156 shutil.rmtree(dataDir)
1157 os.makedirs(dataDir)
1165 pathObj.getPath(copyProjPath)
1166 filePath=[file
for file
in pathObj.path
if file.endswith(
'.py')]
1167 for file
in filePath:
1171 for file
in filePath:
1175 for file
in filePath:
1179 shutil.copytree(os.path.join(copyRoot,projName),os.path.join(copyRoot,f
'bak_{projName}'))
1184 pklDepth+=len([s
for s
in prefix.replace(
'\\',
'/').strip(
'/').split(
'/')
if s])
1185 pklRelPath=
'/'.join([
'..']*pklDepth+[
'pkl'])
1186 writeRecordValue(os.path.join(copyRoot,f
'bak_{projName}',prefix,
'recordValue.py'),pklRelPath,0)
1189 for file
in filePath:
1190 if pcresolveLookup
is None:
1191 addDictAll(projPath,projName,file,copyRoot,runFileLst,libName,runPath,runCommand)
1193 addDictAll(projPath,projName,file,copyRoot,runFileLst,libName,runPath,runCommand,pcresolveLookup=pcresolveLookup)
1196 for file
in runFileLst:
1197 file=os.path.join(copyRoot,f
'bak_{projName}',prefix,file)
1200 shutil.copy2(
scriptPath(
'codeUtils.py'),os.path.join(copyRoot,f
'bak_{projName}',prefix))
1203 writeRecordValue(os.path.join(copyRoot,projName,prefix,
'recordValue.py'),pklRelPath,1)
1205 shutil.copy2(
scriptPath(
'codeUtils.py'),os.path.join(copyRoot,projName,runPath))
1207 shutil.copy2(
scriptPath(
'codeUtils.py'),os.path.join(copyRoot,projName,prefix))
def getCallFunction(filePath, libName, projPath=None, pcresolveLookup=None)
Extract all API calls from a given .py file 每次传进来一个.py文件,抽取所有的调用API.
def modifyWithName(callName, withitemCallName, lineno=None)
Restore the conventional API call path in the withitem (including AsyncWith) call form 还原withitemAPI调...
def convertLocalVar(filePath, libName)
Convert the ListComp and DictComp statements to variable assignment statements 将列表推导式listComp和字典推导式Di...
def codeProcess(projPath, runCommand, runPath, libName, workspace, pcresolveLookup=None)
Code processing 代码预处理
def convertTabsToSpaces(directory)
Convert tabs to spaces in all Python files within a directory 将目录下所有Python文件中的制表符转换为空格
def getDictVar(root, ansLst)
Get the local variable in the dictionary comprehension 获取字典推导式中的局部变量
def oneLine(filePath)
Convert the multi-line parameter calls in the code into a single line to facilitate insertion into di...
def expandConditionalReturn(filePath)
Expand the single-line conditional return statement into a multi-line if-else structure 展开单行条件retur...
def obtainDef(sourcePath)
Extract class and function definitions from a source file 从源文件中提取类和函数定义
def getAssignReceiverExpr(root, source, aliasName, lineno)
Resolve the source expression assigned to a receiver alias 还原调用者别名在当前作用域内的赋值来源表达式
def addDictSingle(callAPI, filePath, callKey)
Code instrumentation for a single API call within a source file 源文件单个API调用代码插桩
def getImportLine(codeLst)
Determine the instrumentation line for import statements 确定import语句插桩行
def writeRecordValue(filePath, pklRelPath, useCallsiteName)
Write recordValue.py used by instrumented project files 写入插桩文件共享的recordValue.py.
def getLibImportLst(projPath, libName)
Get all lib-related import statements 获取所有第三方库相关的import语句
def getListVar(root, ansLst)
Get the local variable in the list comprehension 获取列表推导式中的局部变量
def countBracket(s)
Count the number of different types of brackets ((), [], {}) in a string 计算字符串中各类括号((),...
def getSelfReceiverExpr(root, lineno, methodName)
Resolve the visible base-class expression for an inherited self receiver 还原继承场景中self调用者可见的基类表达式
def scriptPath(scriptName)
Get source script path from PCART repository 获取PCART仓库中的辅助脚本路径
def countSpace(s)
Count the number of spaces at the beginning of a string 计算字符串的前面有多少个空格
def saveConstantAssign(astNode, constantVar, nonConstantVar, decoratorLst)
Save assignment statement with constant values 保存常量赋值语句
def addDictAll(projPath, projName, filePath, copyRoot, runFileLst, libName, runPath, runCommand, pcresolveLookup=None)
Code instrumentation for all API calls within a project source file 项目源文件所有API调用代码插桩
def modifyFromImport(filePath, importStatement)
Save import statement to source file 将import语句保存到源码中
def ignore_sym_links(directory, files)
Determine the soft link files in a directory 确定文件夹中的软链接文件
def handleRunFile(file, runPath, runCommand)
Code instrumentation for project run file 项目运行文件代码插桩
def findAssignCall(root)
Find assignment call statements 获取赋值调用语句
def extractDecorator(root)
Extract decorator API calls 抽取项目中第三方库装饰器调用
def saveStructure(projPath, libName)
Save structure information of the project 保存项目的结构信息
def getDecoratorInsertIndex(codeLst, index)
Get decorator block start index 获取装饰器块起始行号
def getRuntimePaths(workspace)
Return runtime artifact paths for the current execution 返回当前执行使用的运行产物路径