32 hashPattern=re.compile(
r'(?:^|__)([0-9a-f]{64})$')
33 match=hashPattern.search(artifactId)
46 if artifactHash
and artifactId.endswith(artifactHash):
47 displayName=artifactId[:-len(artifactHash)].rstrip(
'_')
48 return displayName
or artifactHash
59 fileName=re.sub(
r'[^0-9A-Za-z_.-]+',
'_',fileName).strip(
'._')
60 length=255-len(extension)
if extension
else 255
61 if len(fileName)<=length:
62 return fileName+extension
65 return fileName[:length]+extension
66 suffix=
'__'+artifactHash
67 prefixLength=max(0,length-len(suffix))
68 prefix=fileName[:prefixLength].rstrip(
'_')
69 return prefix+suffix+extension
87 p_string=p_string.replace(
' ',
'')
103 count_single_yinhao=0
104 count_double_yinhao=0
106 for index,value
in enumerate(p_string):
108 if (value==
"'" or count_single_yinhao)
and not count_double_yinhao:
110 count_single_yinhao+=1
111 if count_single_yinhao&1:
114 elif (value==
'"' or count_double_yinhao)
and not count_single_yinhao:
116 count_double_yinhao+=1
117 if count_double_yinhao&1:
120 count_single_yinhao=0
121 count_double_yinhao=0
132 count_right_middle+=1
146 if count_left_min!=count_right_min:
149 if count_left_middle!=count_right_middle:
152 if count_left_hua!=count_right_hua:
155 if flagMin
and flagMid
and flagHua:
156 parameters.append(
''.join(stack[0:-1]))
159 elif index==len(p_string)-1:
160 parameters.append(
''.join(stack))
174 with tokenize.open(filePath)
as f:
176 root=ast.parse(s,filename=
'<unknown>',mode=
'exec')
178 root=ast.parse(filePath,filename=
'<unknown>',mode=
'exec')
190 with open(filePath,
'r',encoding=
'UTF-8')
as f:
194 if (it[0:6]==
'import' or it[0:4]==
'from')
and 'torch' in it
and 'torchvision' not in it
and 'torch_' not in it
and '.torch' not in it:
217 for index,value
in enumerate(s):
225 if left==right
and left>0
and right>0:
227 ans+=
''.join(stack[0:pos])
231 elif index==len(s)-1:
243 if left==right
and left>0
and right>0:
272 if left==right
and left>0
and right>0:
298 for i
in range(len(s)):
311 if leftMid!=rightMid:
315 if leftMin
and rightMin
and leftMin==rightMin
and flagMid:
316 ansLst.append(stack[0:i+1])
319 if leftMid
and rightMid:
324 ansLst.append(stack[0:i+1])
347 for index,value
in enumerate(s):
358 count_right_middle+=1
360 elif value==separator
and ((count_left_min>count_right_min)
or (count_left_middle>count_right_middle)):
368 if count_left_min!=count_right_min:
371 if count_left_middle!=count_right_middle:
373 if flagMin
and flagMid:
374 ansLst.append(
''.join(lst))
376 elif index==len(s)-1:
377 ansLst.append(
''.join(lst))
389 lst=list(dic.values())
391 if isinstance(it,str):
408 p = os.path.basename(p)
410 for i
in range(len(p)):
414 versionLst.append(p[index:])
415 versionLst.sort(key=
lambda it:
cmp(it))
433 for i
in range(len(version)):
434 if version[i].isalpha():
437 if index!=len(version):
438 innerVersion=re.findall(
r'\d+',version[index:])[0]
439 Type=re.findall(
r'[a-zA-Z]+',version[index:])[0]
441 if len(innerVersion)==1:
442 innerVersion=
'0.00000'+innerVersion
444 innerVersion=
'0.0000'+innerVersion
446 if len(innerVersion)==1:
447 innerVersion=
'0.000'+innerVersion
449 innerVersion=
'0.00'+innerVersion
451 if len(innerVersion)==1:
452 innerVersion=
'0.0'+innerVersion
454 innerVersion=
'0.'+innerVersion
457 lst=version[0:index].split(
'.')
468 return float(v)-(1-float(innerVersion))
482 fileName=fileName.replace(
' ',
'')
483 fileName=fileName.replace(
'/',
'')
484 fileName=fileName.replace(
'\\',
'')
485 if len(extension) != 0:
486 length=255-len(extension)
489 fileName=fileName.split(
'(')[0] +
'_' + hashlib.md5(fileName.encode()).hexdigest()[:16]
490 fileName=fileName[0:length]
508 for start
in range(0,max(len(s),1),contentWidth):
509 content=s[start:start+contentWidth]
510 tailSpaceNum=width-2-len(content)-1
511 fw.write(
'| '+content+
' '*tailSpaceNum+
'|'+
'\n')
523 fw=open(savePath,
'w',encoding=
'UTF-8')
528 unknownCompatibleNum=0
535 totalAPINum+=Tuple[2]
537 for callAPI,subDict
in dic.items():
538 if subDict[
'Coverage']==
'No':
542 if subDict[
'Compatible']==
'Yes':
544 elif subDict[
'Compatible']==
'No':
547 unknownCompatibleNum+=1
549 if 'Repair <Successful>' in subDict:
551 elif 'Repair <Failed>' in subDict:
553 elif 'Repair <Unknown>' in subDict:
557 libName=libName.capitalize()
558 fw.write(f
"Run Command: {runCommand}\n")
559 fw.write(f
"Total File Number: {totalFileNum}\n")
560 fw.write(f
"Total {libName} Invoked API Number: {totalAPINum}\n")
561 fw.write(f
"Not Covered {libName} Invoked API Number: {notCoverNum}/{totalAPINum}\n")
562 fw.write(f
"Covered {libName} Invoked API Number: {totalAPINum-notCoverNum}/{totalAPINum}\n\n")
564 fw.write(f
"Compatible {libName} Invoked API Number: {compatibleNum}/{totalAPINum-notCoverNum}\n")
565 fw.write(f
"Unknown Compatible {libName} Invoked API Number: {unknownCompatibleNum}/{totalAPINum-notCoverNum}\n\n")
567 fw.write(f
"Incompatible {libName} Invoked API Number: {incompatibleNum}/{totalAPINum-notCoverNum}\n")
568 fw.write(f
"-> Successfully Repaired {libName} Invoked API number: {successRepairNum}/{incompatibleNum}\n")
569 fw.write(f
"-> Failed to Repair {libName} Invoked API Number: {failedRepairNum}/{incompatibleNum}\n")
570 fw.write(f
"-> Unknown Repair Status {libName} Invoked API Number: {unknownRepairNum}/{incompatibleNum}\n\n")
575 invokedAPINum=Tuple[2]
578 title=f
"File #{fileCount}: {filePath} has {invokedAPINum} {libName}-Invoked API(s)"
580 fontSpaceNum=(width-len(title)-2)//2
581 tailSpaceNum=width-2-fontSpaceNum-len(title)
582 title=
'|'+
' '*fontSpaceNum+title+
' '*tailSpaceNum+
'|'+
'\n'
587 for callAPI,subDict
in dic.items():
588 displayCall=subDict.pop(
'Invoked API',callAPI)
589 tempStr1=f
"Invoked API #{index}: {displayCall}"
591 fw.write(
'|'+
' '*(width-2)+
'|'+
'\n')
593 for k,v
in subDict.items():
596 if cnt!=len(subDict):
597 fw.write(
'|'+
' '*(width-2)+
'|'+
'\n')
600 fw.write(
'|'+
' '*(width-2)+
'|'+
'\n')
601 fw.write(
'|'+
'-'*(width-2)+
'|'+
'\n')
603 fw.write(
'|'+
' '*(width-2)+
'|'+
'\n')
617 with open(configPath,
'r',encoding=
'UTF-8')
as fr:
620 if isinstance(dic[key], str):
621 dic[key] = dic[key].strip()
622 runCommand=dic[
'runCommand']
623 return dic[
'projPath'],runCommand,dic[
'runFilePath'],dic[
'libName'],dic[
'currentVersion'],dic[
'targetVersion'],dic[
'currentEnv'],dic[
'targetEnv']
633 if os.path.isabs(config):
635 if os.path.exists(config):
636 return os.path.abspath(config)
637 return os.path.join(repoRoot,
'Configure',config)
649 expanded=os.path.expanduser(path)
650 if os.name==
'nt' and expanded.startswith(
'/')
and not expanded.startswith(
'//'):
652 if os.path.isabs(expanded):
653 return os.path.abspath(expanded)
654 return os.path.abspath(os.path.join(repoRoot,expanded))
662 """Raised when PCART cannot safely execute a configured run command."""
671 baseName=os.path.basename(command.replace(
'\\',
'/')).lower()
672 if baseName
in (
'python',
'python.exe'):
674 if re.match(
r'^python3(\.\d+)?(\.exe)?$',baseName):
685 baseName=os.path.basename(command.replace(
'\\',
'/')).lower()
686 return baseName
in (
'py',
'py.exe')
695 if tokens
and re.match(
r'^-\d(\.\d+)?(-\d+)?$',tokens[0]):
708 tokens=shlex.split(runCommand)
710 return runCommand,
'python'
713 simpleTokens=runCommand.split(maxsplit=1)
715 rest=simpleTokens[1].lstrip()
if len(simpleTokens)>1
else ''
718 rest=simpleTokens[1].lstrip()
if len(simpleTokens)>1
else ''
719 restTokens=shlex.split(rest)
723 return shlex.join(tokens[1:]),
'python'
726 if tokens[0]==
'-m' or tokens[0].endswith(
'.py'):
727 return runCommand,
'python'
728 return runCommand,
'console'
738 normalizedEnvPath=os.path.abspath(envPath)
740 if platform.system()==
'Windows':
741 scriptsPath=os.path.join(normalizedEnvPath,
'Scripts')
743 os.path.join(scriptsPath,commandName),
744 os.path.join(scriptsPath,commandName+
'.exe'),
745 os.path.join(scriptsPath,commandName+
'.cmd'),
746 os.path.join(scriptsPath,commandName+
'.bat'),
749 candidates.append(os.path.join(normalizedEnvPath,
'bin',commandName))
751 for candidate
in candidates:
752 if os.path.exists(candidate):
755 candidateStr=
', '.join(candidates)
756 raise FileNotFoundError(f
"Cannot find console command '{commandName}' under virtual " f
"environment root: {normalizedEnvPath}. Tried: {candidateStr}")
767 if commandType==
'python':
770 args=shlex.split(normalizedCommand)
775 except FileNotFoundError
as e:
777 return [commandPath] + args[1:]
786 tokens=shlex.split(runCommand)
788 candidate=token.split(
'::',1)[0]
789 if candidate.endswith(
'.py'):
801 if not os.path.exists(basePath):
802 raise FileNotFoundError(f
"Cannot find Python directory: {basePath} does not exist")
804 for entry
in os.listdir(basePath):
805 full_path = os.path.join(basePath, entry)
806 if os.path.isdir(full_path):
807 if entry.startswith(
"python"):
810 raise FileNotFoundError(f
"Cannot find Python directory under {basePath}/pythonxx.xx")
820 if platform.system() ==
'Windows':
821 sitePackages=os.path.join(envPath,
"Lib",
"site-packages")
823 sitePackages=os.path.join(
findPythonDir(os.path.join(envPath,
"lib")),
"site-packages")
825 if libName==
"tensorflow":
826 tensorflowCore=os.path.join(sitePackages,
"tensorflow_core")
827 if os.path.isdir(tensorflowCore):
828 return tensorflowCore
830 return os.path.join(sitePackages, libName)
839 normalizedEnvPath = os.path.abspath(envPath)
840 if platform.system() ==
'Windows':
842 os.path.join(normalizedEnvPath,
'python.exe'),
843 os.path.join(normalizedEnvPath,
'Scripts',
'python.exe'),
847 os.path.join(normalizedEnvPath,
'bin',
'python'),
850 for candidate
in candidates:
851 if os.path.exists(candidate):
854 candidate_str =
', '.join(candidates)
855 raise FileNotFoundError(f
"Cannot find Python executable under virtual environment root: " f
"{normalizedEnvPath}. Tried: {candidate_str}")
868 repoRoot=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
870 with open(resolvedConfigPath,
'r',encoding=
'UTF-8')
as fr:
872 libName=dic[
'libName']
873 currentVersion=dic[
'currentVersion']
874 targetVersion=dic[
'targetVersion']
881 return currentVersion, targetVersion, currentSourceCodePath, targetSourceCodePath
894 if isinstance(node, ast.Return)
and isinstance(node.value, ast.IfExp):
896 newIf = ast.If(test=ifExp.test,body=[ast.Return(value=ifExp.body)],orelse=[ast.Return(value=ifExp.orelse)])