BaseTools: Fix old python2 idioms

Based on "futurize -f lib2to3.fixes.fix_idioms"

* Change some type comparisons to isinstance() calls:
    type(x) == T -> isinstance(x, T)
    type(x) is T -> isinstance(x, T)
    type(x) != T -> not isinstance(x, T)
    type(x) is not T -> not isinstance(x, T)

* Change "while 1:" into "while True:".

* Change both

    v = list(EXPR)
    v.sort()
    foo(v)

and the more general

    v = EXPR
    v.sort()
    foo(v)

into

    v = sorted(EXPR)
    foo(v)

Contributed-under: TianoCore Contribution Agreement 1.1
Cc: Yonghong Zhu <yonghong.zhu@intel.com>
Cc: Liming Gao <liming.gao@intel.com>
Signed-off-by: Gary Lin <glin@suse.com>
Reviewed-by: Yonghong Zhu <yonghong.zhu@intel.com>
This commit is contained in:
Gary Lin
2018-06-25 18:31:35 +08:00
committed by Yonghong Zhu
parent 2617a73c36
commit 0d1f5b2b5d
31 changed files with 93 additions and 111 deletions

View File

@ -264,7 +264,7 @@ def main():
return 1 return 1
try: try:
while 1: while True:
line = file.readline() line = file.readline()
if not line: if not line:
break break

View File

@ -253,7 +253,7 @@ def GetSvnRevision(opts):
StatusCmd = "svn st -v --depth infinity --non-interactive" StatusCmd = "svn st -v --depth infinity --non-interactive"
contents = ShellCommandResults(StatusCmd, opts) contents = ShellCommandResults(StatusCmd, opts)
os.chdir(Cwd) os.chdir(Cwd)
if type(contents) is ListType: if isinstance(contents, ListType):
for line in contents: for line in contents:
if line.startswith("M "): if line.startswith("M "):
Modified = True Modified = True
@ -263,7 +263,7 @@ def GetSvnRevision(opts):
InfoCmd = "svn info %s" % SrcPath.replace("\\", "/").strip() InfoCmd = "svn info %s" % SrcPath.replace("\\", "/").strip()
Revision = 0 Revision = 0
contents = ShellCommandResults(InfoCmd, opts) contents = ShellCommandResults(InfoCmd, opts)
if type(contents) is IntType: if isinstance(contents, IntType):
return 0, Modified return 0, Modified
for line in contents: for line in contents:
line = line.strip() line = line.strip()
@ -284,7 +284,7 @@ def CheckSvn(opts):
VerCmd = "svn --version" VerCmd = "svn --version"
contents = ShellCommandResults(VerCmd, opts) contents = ShellCommandResults(VerCmd, opts)
opts.silent = OriginalSilent opts.silent = OriginalSilent
if type(contents) is IntType: if isinstance(contents, IntType):
if opts.verbose: if opts.verbose:
sys.stdout.write("SVN does not appear to be available.\n") sys.stdout.write("SVN does not appear to be available.\n")
sys.stdout.flush() sys.stdout.flush()

View File

@ -68,7 +68,7 @@ class TargetDescBlock(object):
return hash(self.Target.Path) return hash(self.Target.Path)
def __eq__(self, Other): def __eq__(self, Other):
if type(Other) == type(self): if isinstance(Other, type(self)):
return Other.Target.Path == self.Target.Path return Other.Target.Path == self.Target.Path
else: else:
return str(Other) == self.Target.Path return str(Other) == self.Target.Path

View File

@ -140,7 +140,7 @@ class DependencyExpression:
def __init__(self, Expression, ModuleType, Optimize=False): def __init__(self, Expression, ModuleType, Optimize=False):
self.ModuleType = ModuleType self.ModuleType = ModuleType
self.Phase = gType2Phase[ModuleType] self.Phase = gType2Phase[ModuleType]
if type(Expression) == type([]): if isinstance(Expression, type([])):
self.ExpressionString = " ".join(Expression) self.ExpressionString = " ".join(Expression)
self.TokenList = Expression self.TokenList = Expression
else: else:

View File

@ -245,12 +245,12 @@ class ValueExpression(BaseExpression):
WrnExp = None WrnExp = None
if Operator not in {"==", "!=", ">=", "<=", ">", "<", "in", "not in"} and \ if Operator not in {"==", "!=", ">=", "<=", ">", "<", "in", "not in"} and \
(type(Oprand1) == type('') or type(Oprand2) == type('')): (isinstance(Oprand1, type('')) or isinstance(Oprand2, type(''))):
raise BadExpression(ERR_STRING_EXPR % Operator) raise BadExpression(ERR_STRING_EXPR % Operator)
if Operator in {'in', 'not in'}: if Operator in {'in', 'not in'}:
if type(Oprand1) != type(''): if not isinstance(Oprand1, type('')):
Oprand1 = IntToStr(Oprand1) Oprand1 = IntToStr(Oprand1)
if type(Oprand2) != type(''): if not isinstance(Oprand2, type('')):
Oprand2 = IntToStr(Oprand2) Oprand2 = IntToStr(Oprand2)
TypeDict = { TypeDict = {
type(0) : 0, type(0) : 0,
@ -261,18 +261,18 @@ class ValueExpression(BaseExpression):
EvalStr = '' EvalStr = ''
if Operator in {"!", "NOT", "not"}: if Operator in {"!", "NOT", "not"}:
if type(Oprand1) == type(''): if isinstance(Oprand1, type('')):
raise BadExpression(ERR_STRING_EXPR % Operator) raise BadExpression(ERR_STRING_EXPR % Operator)
EvalStr = 'not Oprand1' EvalStr = 'not Oprand1'
elif Operator in {"~"}: elif Operator in {"~"}:
if type(Oprand1) == type(''): if isinstance(Oprand1, type('')):
raise BadExpression(ERR_STRING_EXPR % Operator) raise BadExpression(ERR_STRING_EXPR % Operator)
EvalStr = '~ Oprand1' EvalStr = '~ Oprand1'
else: else:
if Operator in {"+", "-"} and (type(True) in {type(Oprand1), type(Oprand2)}): if Operator in {"+", "-"} and (type(True) in {type(Oprand1), type(Oprand2)}):
# Boolean in '+'/'-' will be evaluated but raise warning # Boolean in '+'/'-' will be evaluated but raise warning
WrnExp = WrnExpression(WRN_BOOL_EXPR) WrnExp = WrnExpression(WRN_BOOL_EXPR)
elif type('') in {type(Oprand1), type(Oprand2)} and type(Oprand1)!= type(Oprand2): elif type('') in {type(Oprand1), type(Oprand2)} and not isinstance(Oprand1, type(Oprand2)):
# == between string and number/boolean will always return False, != return True # == between string and number/boolean will always return False, != return True
if Operator == "==": if Operator == "==":
WrnExp = WrnExpression(WRN_EQCMP_STR_OTHERS) WrnExp = WrnExpression(WRN_EQCMP_STR_OTHERS)
@ -293,11 +293,11 @@ class ValueExpression(BaseExpression):
pass pass
else: else:
raise BadExpression(ERR_EXPR_TYPE) raise BadExpression(ERR_EXPR_TYPE)
if type(Oprand1) == type('') and type(Oprand2) == type(''): if isinstance(Oprand1, type('')) and isinstance(Oprand2, type('')):
if (Oprand1.startswith('L"') and not Oprand2.startswith('L"')) or \ if (Oprand1.startswith('L"') and not Oprand2.startswith('L"')) or \
(not Oprand1.startswith('L"') and Oprand2.startswith('L"')): (not Oprand1.startswith('L"') and Oprand2.startswith('L"')):
raise BadExpression(ERR_STRING_CMP % (Oprand1, Operator, Oprand2)) raise BadExpression(ERR_STRING_CMP % (Oprand1, Operator, Oprand2))
if 'in' in Operator and type(Oprand2) == type(''): if 'in' in Operator and isinstance(Oprand2, type('')):
Oprand2 = Oprand2.split() Oprand2 = Oprand2.split()
EvalStr = 'Oprand1 ' + Operator + ' Oprand2' EvalStr = 'Oprand1 ' + Operator + ' Oprand2'
@ -325,7 +325,7 @@ class ValueExpression(BaseExpression):
def __init__(self, Expression, SymbolTable={}): def __init__(self, Expression, SymbolTable={}):
super(ValueExpression, self).__init__(self, Expression, SymbolTable) super(ValueExpression, self).__init__(self, Expression, SymbolTable)
self._NoProcess = False self._NoProcess = False
if type(Expression) != type(''): if not isinstance(Expression, type('')):
self._Expr = Expression self._Expr = Expression
self._NoProcess = True self._NoProcess = True
return return
@ -373,7 +373,7 @@ class ValueExpression(BaseExpression):
Token = self._GetToken() Token = self._GetToken()
except BadExpression: except BadExpression:
pass pass
if type(Token) == type('') and Token.startswith('{') and Token.endswith('}') and self._Idx >= self._Len: if isinstance(Token, type('')) and Token.startswith('{') and Token.endswith('}') and self._Idx >= self._Len:
return self._Expr return self._Expr
self._Idx = 0 self._Idx = 0
@ -381,7 +381,7 @@ class ValueExpression(BaseExpression):
Val = self._ConExpr() Val = self._ConExpr()
RealVal = Val RealVal = Val
if type(Val) == type(''): if isinstance(Val, type('')):
if Val == 'L""': if Val == 'L""':
Val = False Val = False
elif not Val: elif not Val:
@ -640,7 +640,7 @@ class ValueExpression(BaseExpression):
Ex.Pcd = self._Token Ex.Pcd = self._Token
raise Ex raise Ex
self._Token = ValueExpression(self._Symb[self._Token], self._Symb)(True, self._Depth+1) self._Token = ValueExpression(self._Symb[self._Token], self._Symb)(True, self._Depth+1)
if type(self._Token) != type(''): if not isinstance(self._Token, type('')):
self._LiteralToken = hex(self._Token) self._LiteralToken = hex(self._Token)
return return
@ -735,7 +735,7 @@ class ValueExpression(BaseExpression):
if Ch == ')': if Ch == ')':
TmpValue = self._Expr[Idx :self._Idx - 1] TmpValue = self._Expr[Idx :self._Idx - 1]
TmpValue = ValueExpression(TmpValue)(True) TmpValue = ValueExpression(TmpValue)(True)
TmpValue = '0x%x' % int(TmpValue) if type(TmpValue) != type('') else TmpValue TmpValue = '0x%x' % int(TmpValue) if not isinstance(TmpValue, type('')) else TmpValue
break break
self._Token, Size = ParseFieldValue(Prefix + '(' + TmpValue + ')') self._Token, Size = ParseFieldValue(Prefix + '(' + TmpValue + ')')
return self._Token return self._Token
@ -824,7 +824,7 @@ class ValueExpressionEx(ValueExpression):
PcdValue = PcdValue.strip() PcdValue = PcdValue.strip()
if PcdValue.startswith('{') and PcdValue.endswith('}'): if PcdValue.startswith('{') and PcdValue.endswith('}'):
PcdValue = SplitPcdValueString(PcdValue[1:-1]) PcdValue = SplitPcdValueString(PcdValue[1:-1])
if type(PcdValue) == type([]): if isinstance(PcdValue, type([])):
TmpValue = 0 TmpValue = 0
Size = 0 Size = 0
ValueType = '' ValueType = ''
@ -863,7 +863,7 @@ class ValueExpressionEx(ValueExpression):
else: else:
ItemValue = ParseFieldValue(Item)[0] ItemValue = ParseFieldValue(Item)[0]
if type(ItemValue) == type(''): if isinstance(ItemValue, type('')):
ItemValue = int(ItemValue, 0) ItemValue = int(ItemValue, 0)
TmpValue = (ItemValue << (Size * 8)) | TmpValue TmpValue = (ItemValue << (Size * 8)) | TmpValue
@ -873,7 +873,7 @@ class ValueExpressionEx(ValueExpression):
TmpValue, Size = ParseFieldValue(PcdValue) TmpValue, Size = ParseFieldValue(PcdValue)
except BadExpression as Value: except BadExpression as Value:
raise BadExpression("Type: %s, Value: %s, %s" % (self.PcdType, PcdValue, Value)) raise BadExpression("Type: %s, Value: %s, %s" % (self.PcdType, PcdValue, Value))
if type(TmpValue) == type(''): if isinstance(TmpValue, type('')):
try: try:
TmpValue = int(TmpValue) TmpValue = int(TmpValue)
except: except:
@ -996,7 +996,7 @@ class ValueExpressionEx(ValueExpression):
TmpValue = ValueExpressionEx(Item, ValueType, self._Symb)(True) TmpValue = ValueExpressionEx(Item, ValueType, self._Symb)(True)
else: else:
TmpValue = ValueExpressionEx(Item, self.PcdType, self._Symb)(True) TmpValue = ValueExpressionEx(Item, self.PcdType, self._Symb)(True)
Item = '0x%x' % TmpValue if type(TmpValue) != type('') else TmpValue Item = '0x%x' % TmpValue if not isinstance(TmpValue, type('')) else TmpValue
if ItemSize == 0: if ItemSize == 0:
ItemValue, ItemSize = ParseFieldValue(Item) ItemValue, ItemSize = ParseFieldValue(Item)
if Item[0] not in {'"', 'L', '{'} and ItemSize > 1: if Item[0] not in {'"', 'L', '{'} and ItemSize > 1:

View File

@ -1291,9 +1291,9 @@ def ParseDevPathValue (Value):
return '{' + out + '}', Size return '{' + out + '}', Size
def ParseFieldValue (Value): def ParseFieldValue (Value):
if type(Value) == type(0): if isinstance(Value, type(0)):
return Value, (Value.bit_length() + 7) / 8 return Value, (Value.bit_length() + 7) / 8
if type(Value) != type(''): if not isinstance(Value, type('')):
raise BadExpression('Type %s is %s' %(Value, type(Value))) raise BadExpression('Type %s is %s' %(Value, type(Value)))
Value = Value.strip() Value = Value.strip()
if Value.startswith(TAB_UINT8) and Value.endswith(')'): if Value.startswith(TAB_UINT8) and Value.endswith(')'):
@ -1584,8 +1584,7 @@ def CheckPcdDatum(Type, Value):
Printset.add(TAB_PRINTCHAR_BS) Printset.add(TAB_PRINTCHAR_BS)
Printset.add(TAB_PRINTCHAR_NUL) Printset.add(TAB_PRINTCHAR_NUL)
if not set(Value).issubset(Printset): if not set(Value).issubset(Printset):
PrintList = list(Printset) PrintList = sorted(Printset)
PrintList.sort()
return False, "Invalid PCD string value of type [%s]; must be printable chars %s." % (Type, PrintList) return False, "Invalid PCD string value of type [%s]; must be printable chars %s." % (Type, PrintList)
elif Type == 'BOOLEAN': elif Type == 'BOOLEAN':
if Value not in ['TRUE', 'True', 'true', '0x1', '0x01', '1', 'FALSE', 'False', 'false', '0x0', '0x00', '0']: if Value not in ['TRUE', 'True', 'true', '0x1', '0x01', '1', 'FALSE', 'False', 'false', '0x0', '0x00', '0']:
@ -1747,7 +1746,7 @@ class PathClass(object):
# @retval True The two PathClass are the same # @retval True The two PathClass are the same
# #
def __eq__(self, Other): def __eq__(self, Other):
if type(Other) == type(self): if isinstance(Other, type(self)):
return self.Path == Other.Path return self.Path == Other.Path
else: else:
return self.Path == str(Other) return self.Path == str(Other)
@ -1760,7 +1759,7 @@ class PathClass(object):
# @retval -1 The first PathClass is less than the second PathClass # @retval -1 The first PathClass is less than the second PathClass
# @retval 1 The first PathClass is Bigger than the second PathClass # @retval 1 The first PathClass is Bigger than the second PathClass
def __cmp__(self, Other): def __cmp__(self, Other):
if type(Other) == type(self): if isinstance(Other, type(self)):
OtherKey = Other.Path OtherKey = Other.Path
else: else:
OtherKey = str(Other) OtherKey = str(Other)
@ -2010,7 +2009,7 @@ class SkuClass():
return ["DEFAULT"] return ["DEFAULT"]
skulist = [sku] skulist = [sku]
nextsku = sku nextsku = sku
while 1: while True:
nextsku = self.GetNextSkuId(nextsku) nextsku = self.GetNextSkuId(nextsku)
skulist.append(nextsku) skulist.append(nextsku)
if nextsku == "DEFAULT": if nextsku == "DEFAULT":

View File

@ -97,7 +97,7 @@ class XOROperatorObject(object):
def __init__(self): def __init__(self):
pass pass
def Calculate(self, Operand, DataType, SymbolTable): def Calculate(self, Operand, DataType, SymbolTable):
if type(Operand) == type('') and not Operand.isalnum(): if isinstance(Operand, type('')) and not Operand.isalnum():
Expr = "XOR ..." Expr = "XOR ..."
raise BadExpression(ERR_SNYTAX % Expr) raise BadExpression(ERR_SNYTAX % Expr)
rangeId = str(uuid.uuid1()) rangeId = str(uuid.uuid1())
@ -111,7 +111,7 @@ class LEOperatorObject(object):
def __init__(self): def __init__(self):
pass pass
def Calculate(self, Operand, DataType, SymbolTable): def Calculate(self, Operand, DataType, SymbolTable):
if type(Operand) == type('') and not Operand.isalnum(): if isinstance(Operand, type('')) and not Operand.isalnum():
Expr = "LE ..." Expr = "LE ..."
raise BadExpression(ERR_SNYTAX % Expr) raise BadExpression(ERR_SNYTAX % Expr)
rangeId1 = str(uuid.uuid1()) rangeId1 = str(uuid.uuid1())
@ -123,7 +123,7 @@ class LTOperatorObject(object):
def __init__(self): def __init__(self):
pass pass
def Calculate(self, Operand, DataType, SymbolTable): def Calculate(self, Operand, DataType, SymbolTable):
if type(Operand) == type('') and not Operand.isalnum(): if isinstance(Operand, type('')) and not Operand.isalnum():
Expr = "LT ..." Expr = "LT ..."
raise BadExpression(ERR_SNYTAX % Expr) raise BadExpression(ERR_SNYTAX % Expr)
rangeId1 = str(uuid.uuid1()) rangeId1 = str(uuid.uuid1())
@ -136,7 +136,7 @@ class GEOperatorObject(object):
def __init__(self): def __init__(self):
pass pass
def Calculate(self, Operand, DataType, SymbolTable): def Calculate(self, Operand, DataType, SymbolTable):
if type(Operand) == type('') and not Operand.isalnum(): if isinstance(Operand, type('')) and not Operand.isalnum():
Expr = "GE ..." Expr = "GE ..."
raise BadExpression(ERR_SNYTAX % Expr) raise BadExpression(ERR_SNYTAX % Expr)
rangeId1 = str(uuid.uuid1()) rangeId1 = str(uuid.uuid1())
@ -149,7 +149,7 @@ class GTOperatorObject(object):
def __init__(self): def __init__(self):
pass pass
def Calculate(self, Operand, DataType, SymbolTable): def Calculate(self, Operand, DataType, SymbolTable):
if type(Operand) == type('') and not Operand.isalnum(): if isinstance(Operand, type('')) and not Operand.isalnum():
Expr = "GT ..." Expr = "GT ..."
raise BadExpression(ERR_SNYTAX % Expr) raise BadExpression(ERR_SNYTAX % Expr)
rangeId1 = str(uuid.uuid1()) rangeId1 = str(uuid.uuid1())
@ -162,7 +162,7 @@ class EQOperatorObject(object):
def __init__(self): def __init__(self):
pass pass
def Calculate(self, Operand, DataType, SymbolTable): def Calculate(self, Operand, DataType, SymbolTable):
if type(Operand) == type('') and not Operand.isalnum(): if isinstance(Operand, type('')) and not Operand.isalnum():
Expr = "EQ ..." Expr = "EQ ..."
raise BadExpression(ERR_SNYTAX % Expr) raise BadExpression(ERR_SNYTAX % Expr)
rangeId1 = str(uuid.uuid1()) rangeId1 = str(uuid.uuid1())
@ -350,7 +350,7 @@ class RangeExpression(BaseExpression):
def __init__(self, Expression, PcdDataType, SymbolTable = {}): def __init__(self, Expression, PcdDataType, SymbolTable = {}):
super(RangeExpression, self).__init__(self, Expression, PcdDataType, SymbolTable) super(RangeExpression, self).__init__(self, Expression, PcdDataType, SymbolTable)
self._NoProcess = False self._NoProcess = False
if type(Expression) != type(''): if not isinstance(Expression, type('')):
self._Expr = Expression self._Expr = Expression
self._NoProcess = True self._NoProcess = True
return return
@ -571,7 +571,7 @@ class RangeExpression(BaseExpression):
Ex.Pcd = self._Token Ex.Pcd = self._Token
raise Ex raise Ex
self._Token = RangeExpression(self._Symb[self._Token], self._Symb)(True, self._Depth + 1) self._Token = RangeExpression(self._Symb[self._Token], self._Symb)(True, self._Depth + 1)
if type(self._Token) != type(''): if not isinstance(self._Token, type('')):
self._LiteralToken = hex(self._Token) self._LiteralToken = hex(self._Token)
return return

View File

@ -251,7 +251,7 @@ def SplitModuleType(Key):
def ReplaceMacros(StringList, MacroDefinitions={}, SelfReplacement=False): def ReplaceMacros(StringList, MacroDefinitions={}, SelfReplacement=False):
NewList = [] NewList = []
for String in StringList: for String in StringList:
if type(String) == type(''): if isinstance(String, type('')):
NewList.append(ReplaceMacro(String, MacroDefinitions, SelfReplacement)) NewList.append(ReplaceMacro(String, MacroDefinitions, SelfReplacement))
else: else:
NewList.append(String) NewList.append(String)
@ -793,7 +793,7 @@ def RemoveBlockComment(Lines):
# Get String of a List # Get String of a List
# #
def GetStringOfList(List, Split=' '): def GetStringOfList(List, Split=' '):
if type(List) != type([]): if not isinstance(List, type([])):
return List return List
Str = '' Str = ''
for Item in List: for Item in List:

View File

@ -158,7 +158,7 @@ class ToolDefClassObject(object):
if ErrorCode != 0: if ErrorCode != 0:
EdkLogger.error("tools_def.txt parser", FILE_NOT_FOUND, ExtraData=IncFile) EdkLogger.error("tools_def.txt parser", FILE_NOT_FOUND, ExtraData=IncFile)
if type(IncFileTmp) is PathClass: if isinstance(IncFileTmp, PathClass):
IncFile = IncFileTmp.Path IncFile = IncFileTmp.Path
else: else:
IncFile = IncFileTmp IncFile = IncFileTmp

View File

@ -127,8 +127,7 @@ class VpdInfoFile:
"Invalid parameter FilePath: %s." % FilePath) "Invalid parameter FilePath: %s." % FilePath)
Content = FILE_COMMENT_TEMPLATE Content = FILE_COMMENT_TEMPLATE
Pcds = self._VpdArray.keys() Pcds = sorted(self._VpdArray.keys())
Pcds.sort()
for Pcd in Pcds: for Pcd in Pcds:
i = 0 i = 0
PcdTokenCName = Pcd.TokenCName PcdTokenCName = Pcd.TokenCName

View File

@ -68,7 +68,7 @@ def ParseMacro(Parser):
self._ItemType = MODEL_META_DATA_DEFINE self._ItemType = MODEL_META_DATA_DEFINE
# DEFINE defined macros # DEFINE defined macros
if Type == TAB_DSC_DEFINES_DEFINE: if Type == TAB_DSC_DEFINES_DEFINE:
if type(self) == DecParser: if isinstance(self, DecParser):
if MODEL_META_DATA_HEADER in self._SectionType: if MODEL_META_DATA_HEADER in self._SectionType:
self._FileLocalMacros[Name] = Value self._FileLocalMacros[Name] = Value
else: else:
@ -83,7 +83,7 @@ def ParseMacro(Parser):
SectionLocalMacros = self._SectionsMacroDict[SectionDictKey] SectionLocalMacros = self._SectionsMacroDict[SectionDictKey]
SectionLocalMacros[Name] = Value SectionLocalMacros[Name] = Value
# EDK_GLOBAL defined macros # EDK_GLOBAL defined macros
elif type(self) != DscParser: elif not isinstance(self, DscParser):
EdkLogger.error('Parser', FORMAT_INVALID, "EDK_GLOBAL can only be used in .dsc file", EdkLogger.error('Parser', FORMAT_INVALID, "EDK_GLOBAL can only be used in .dsc file",
ExtraData=self._CurrentLine, File=self.MetaFile, Line=self._LineIndex+1) ExtraData=self._CurrentLine, File=self.MetaFile, Line=self._LineIndex+1)
elif self._SectionType != MODEL_META_DATA_HEADER: elif self._SectionType != MODEL_META_DATA_HEADER:
@ -215,7 +215,7 @@ class MetaFileParser(object):
# DataInfo = [data_type, scope1(arch), scope2(platform/moduletype)] # DataInfo = [data_type, scope1(arch), scope2(platform/moduletype)]
# #
def __getitem__(self, DataInfo): def __getitem__(self, DataInfo):
if type(DataInfo) != type(()): if not isinstance(DataInfo, type(())):
DataInfo = (DataInfo,) DataInfo = (DataInfo,)
# Parse the file first, if necessary # Parse the file first, if necessary
@ -257,7 +257,7 @@ class MetaFileParser(object):
TokenList = GetSplitValueList(self._CurrentLine, TAB_VALUE_SPLIT) TokenList = GetSplitValueList(self._CurrentLine, TAB_VALUE_SPLIT)
self._ValueList[0:len(TokenList)] = TokenList self._ValueList[0:len(TokenList)] = TokenList
# Don't do macro replacement for dsc file at this point # Don't do macro replacement for dsc file at this point
if type(self) != DscParser: if not isinstance(self, DscParser):
Macros = self._Macros Macros = self._Macros
self._ValueList = [ReplaceMacro(Value, Macros) for Value in self._ValueList] self._ValueList = [ReplaceMacro(Value, Macros) for Value in self._ValueList]
@ -355,7 +355,7 @@ class MetaFileParser(object):
if os.path.exists(UniFile): if os.path.exists(UniFile):
self._UniObj = UniParser(UniFile, IsExtraUni=False, IsModuleUni=False) self._UniObj = UniParser(UniFile, IsExtraUni=False, IsModuleUni=False)
if type(self) == InfParser and self._Version < 0x00010005: if isinstance(self, InfParser) and self._Version < 0x00010005:
# EDK module allows using defines as macros # EDK module allows using defines as macros
self._FileLocalMacros[Name] = Value self._FileLocalMacros[Name] = Value
self._Defines[Name] = Value self._Defines[Name] = Value
@ -370,7 +370,7 @@ class MetaFileParser(object):
self._ValueList[1] = TokenList2[1] # keys self._ValueList[1] = TokenList2[1] # keys
else: else:
self._ValueList[1] = TokenList[0] self._ValueList[1] = TokenList[0]
if len(TokenList) == 2 and type(self) != DscParser: # value if len(TokenList) == 2 and not isinstance(self, DscParser): # value
self._ValueList[2] = ReplaceMacro(TokenList[1], self._Macros) self._ValueList[2] = ReplaceMacro(TokenList[1], self._Macros)
if self._ValueList[1].count('_') != 4: if self._ValueList[1].count('_') != 4:

View File

@ -35,7 +35,7 @@ def CreateXmlElement(Name, String, NodeList, AttributeList):
Element.appendChild(Doc.createTextNode(String)) Element.appendChild(Doc.createTextNode(String))
for Item in NodeList: for Item in NodeList:
if type(Item) == type([]): if isinstance(Item, type([])):
Key = Item[0] Key = Item[0]
Value = Item[1] Value = Item[1]
if Key != '' and Key is not None and Value != '' and Value is not None: if Key != '' and Key is not None and Value != '' and Value is not None:

View File

@ -730,7 +730,7 @@ def GetParameter(Parameter, Index = 1):
# @return: The name of parameter # @return: The name of parameter
# #
def GetParameterName(Parameter): def GetParameterName(Parameter):
if type(Parameter) == type('') and Parameter.startswith('&'): if isinstance(Parameter, type('')) and Parameter.startswith('&'):
return Parameter[1:].replace('{', '').replace('}', '').replace('\r', '').replace('\n', '').strip() return Parameter[1:].replace('{', '').replace('}', '').replace('\r', '').replace('\n', '').strip()
else: else:
return Parameter.strip() return Parameter.strip()

View File

@ -905,7 +905,7 @@ class FdfParser:
MacroDict.update(GlobalData.gCommandLineDefines) MacroDict.update(GlobalData.gCommandLineDefines)
if GlobalData.BuildOptionPcd: if GlobalData.BuildOptionPcd:
for Item in GlobalData.BuildOptionPcd: for Item in GlobalData.BuildOptionPcd:
if type(Item) is tuple: if isinstance(Item, tuple):
continue continue
PcdName, TmpValue = Item.split("=") PcdName, TmpValue = Item.split("=")
TmpValue = BuildOptionValue(TmpValue, {}) TmpValue = BuildOptionValue(TmpValue, {})

View File

@ -785,7 +785,7 @@ class GenFds :
if not Name: if not Name:
continue continue
Name = ' '.join(Name) if type(Name) == type([]) else Name Name = ' '.join(Name) if isinstance(Name, type([])) else Name
GuidXRefFile.write("%s %s\n" %(FileStatementGuid, Name)) GuidXRefFile.write("%s %s\n" %(FileStatementGuid, Name))
# Append GUIDs, Protocols, and PPIs to the Xref file # Append GUIDs, Protocols, and PPIs to the Xref file

View File

@ -83,7 +83,7 @@ class TargetTool():
def Print(self): def Print(self):
errMsg = '' errMsg = ''
for Key in self.TargetTxtDictionary: for Key in self.TargetTxtDictionary:
if type(self.TargetTxtDictionary[Key]) == type([]): if isinstance(self.TargetTxtDictionary[Key], type([])):
print("%-30s = %s" % (Key, ''.join(elem + ' ' for elem in self.TargetTxtDictionary[Key]))) print("%-30s = %s" % (Key, ''.join(elem + ' ' for elem in self.TargetTxtDictionary[Key])))
elif self.TargetTxtDictionary[Key] is None: elif self.TargetTxtDictionary[Key] is None:
errMsg += " Missing %s configuration information, please use TargetTool to set value!" % Key + os.linesep errMsg += " Missing %s configuration information, please use TargetTool to set value!" % Key + os.linesep

View File

@ -123,8 +123,7 @@ def GenPcd(Package, Content):
if Pcd.GetSupModuleList(): if Pcd.GetSupModuleList():
Statement += GenDecTailComment(Pcd.GetSupModuleList()) Statement += GenDecTailComment(Pcd.GetSupModuleList())
ArchList = Pcd.GetSupArchList() ArchList = sorted(Pcd.GetSupArchList())
ArchList.sort()
SortedArch = ' '.join(ArchList) SortedArch = ' '.join(ArchList)
if SortedArch in NewSectionDict: if SortedArch in NewSectionDict:
NewSectionDict[SortedArch] = \ NewSectionDict[SortedArch] = \
@ -205,8 +204,7 @@ def GenGuidProtocolPpi(Package, Content):
# #
if Guid.GetSupModuleList(): if Guid.GetSupModuleList():
Statement += GenDecTailComment(Guid.GetSupModuleList()) Statement += GenDecTailComment(Guid.GetSupModuleList())
ArchList = Guid.GetSupArchList() ArchList = sorted(Guid.GetSupArchList())
ArchList.sort()
SortedArch = ' '.join(ArchList) SortedArch = ' '.join(ArchList)
if SortedArch in NewSectionDict: if SortedArch in NewSectionDict:
NewSectionDict[SortedArch] = \ NewSectionDict[SortedArch] = \
@ -246,8 +244,7 @@ def GenGuidProtocolPpi(Package, Content):
# #
if Protocol.GetSupModuleList(): if Protocol.GetSupModuleList():
Statement += GenDecTailComment(Protocol.GetSupModuleList()) Statement += GenDecTailComment(Protocol.GetSupModuleList())
ArchList = Protocol.GetSupArchList() ArchList = sorted(Protocol.GetSupArchList())
ArchList.sort()
SortedArch = ' '.join(ArchList) SortedArch = ' '.join(ArchList)
if SortedArch in NewSectionDict: if SortedArch in NewSectionDict:
NewSectionDict[SortedArch] = \ NewSectionDict[SortedArch] = \
@ -287,8 +284,7 @@ def GenGuidProtocolPpi(Package, Content):
# #
if Ppi.GetSupModuleList(): if Ppi.GetSupModuleList():
Statement += GenDecTailComment(Ppi.GetSupModuleList()) Statement += GenDecTailComment(Ppi.GetSupModuleList())
ArchList = Ppi.GetSupArchList() ArchList = sorted(Ppi.GetSupArchList())
ArchList.sort()
SortedArch = ' '.join(ArchList) SortedArch = ' '.join(ArchList)
if SortedArch in NewSectionDict: if SortedArch in NewSectionDict:
NewSectionDict[SortedArch] = \ NewSectionDict[SortedArch] = \
@ -463,8 +459,7 @@ def PackageToDec(Package, DistHeader = None):
if LibraryClass.GetSupModuleList(): if LibraryClass.GetSupModuleList():
Statement += \ Statement += \
GenDecTailComment(LibraryClass.GetSupModuleList()) GenDecTailComment(LibraryClass.GetSupModuleList())
ArchList = LibraryClass.GetSupArchList() ArchList = sorted(LibraryClass.GetSupArchList())
ArchList.sort()
SortedArch = ' '.join(ArchList) SortedArch = ' '.join(ArchList)
if SortedArch in NewSectionDict: if SortedArch in NewSectionDict:
NewSectionDict[SortedArch] = \ NewSectionDict[SortedArch] = \

View File

@ -493,8 +493,7 @@ def GenPackages(ModuleObject):
Statement += RelaPath.replace('\\', '/') Statement += RelaPath.replace('\\', '/')
if FFE: if FFE:
Statement += '|' + FFE Statement += '|' + FFE
ArchList = PackageDependency.GetSupArchList() ArchList = sorted(PackageDependency.GetSupArchList())
ArchList.sort()
SortedArch = ' '.join(ArchList) SortedArch = ' '.join(ArchList)
if SortedArch in NewSectionDict: if SortedArch in NewSectionDict:
NewSectionDict[SortedArch] = NewSectionDict[SortedArch] + [Statement] NewSectionDict[SortedArch] = NewSectionDict[SortedArch] + [Statement]
@ -513,8 +512,7 @@ def GenSources(ModuleObject):
SourceFile = Source.GetSourceFile() SourceFile = Source.GetSourceFile()
Family = Source.GetFamily() Family = Source.GetFamily()
FeatureFlag = Source.GetFeatureFlag() FeatureFlag = Source.GetFeatureFlag()
SupArchList = Source.GetSupArchList() SupArchList = sorted(Source.GetSupArchList())
SupArchList.sort()
SortedArch = ' '.join(SupArchList) SortedArch = ' '.join(SupArchList)
Statement = GenSourceStatement(ConvertPath(SourceFile), Family, FeatureFlag) Statement = GenSourceStatement(ConvertPath(SourceFile), Family, FeatureFlag)
if SortedArch in NewSectionDict: if SortedArch in NewSectionDict:
@ -722,8 +720,7 @@ def GenGuidSections(GuidObjList):
# #
# merge duplicate items # merge duplicate items
# #
ArchList = Guid.GetSupArchList() ArchList = sorted(Guid.GetSupArchList())
ArchList.sort()
SortedArch = ' '.join(ArchList) SortedArch = ' '.join(ArchList)
if (Statement, SortedArch) in GuidDict: if (Statement, SortedArch) in GuidDict:
PreviousComment = GuidDict[Statement, SortedArch] PreviousComment = GuidDict[Statement, SortedArch]
@ -782,8 +779,7 @@ def GenProtocolPPiSections(ObjList, IsProtocol):
# #
# merge duplicate items # merge duplicate items
# #
ArchList = Object.GetSupArchList() ArchList = sorted(Object.GetSupArchList())
ArchList.sort()
SortedArch = ' '.join(ArchList) SortedArch = ' '.join(ArchList)
if (Statement, SortedArch) in Dict: if (Statement, SortedArch) in Dict:
PreviousComment = Dict[Statement, SortedArch] PreviousComment = Dict[Statement, SortedArch]
@ -857,8 +853,7 @@ def GenPcdSections(ModuleObject):
# #
# Merge duplicate entries # Merge duplicate entries
# #
ArchList = Pcd.GetSupArchList() ArchList = sorted(Pcd.GetSupArchList())
ArchList.sort()
SortedArch = ' '.join(ArchList) SortedArch = ' '.join(ArchList)
if (Statement, SortedArch) in Dict: if (Statement, SortedArch) in Dict:
PreviousComment = Dict[Statement, SortedArch] PreviousComment = Dict[Statement, SortedArch]
@ -1025,8 +1020,7 @@ def GenSpecialSections(ObjectList, SectionName, UserExtensionsContent=''):
if CommentStr and not CommentStr.endswith('\n#\n'): if CommentStr and not CommentStr.endswith('\n#\n'):
CommentStr = CommentStr + '#\n' CommentStr = CommentStr + '#\n'
NewStateMent = CommentStr + Statement NewStateMent = CommentStr + Statement
SupArch = Obj.GetSupArchList() SupArch = sorted(Obj.GetSupArchList())
SupArch.sort()
SortedArch = ' '.join(SupArch) SortedArch = ' '.join(SupArch)
if SortedArch in NewSectionDict: if SortedArch in NewSectionDict:
NewSectionDict[SortedArch] = NewSectionDict[SortedArch] + [NewStateMent] NewSectionDict[SortedArch] = NewSectionDict[SortedArch] + [NewStateMent]
@ -1104,8 +1098,7 @@ def GenBinaries(ModuleObject):
FileName = ConvertPath(FileNameObj.GetFilename()) FileName = ConvertPath(FileNameObj.GetFilename())
FileType = FileNameObj.GetFileType() FileType = FileNameObj.GetFileType()
FFE = FileNameObj.GetFeatureFlag() FFE = FileNameObj.GetFeatureFlag()
ArchList = FileNameObj.GetSupArchList() ArchList = sorted(FileNameObj.GetSupArchList())
ArchList.sort()
SortedArch = ' '.join(ArchList) SortedArch = ' '.join(ArchList)
Key = (FileName, FileType, FFE, SortedArch) Key = (FileName, FileType, FFE, SortedArch)
if Key in BinariesDict: if Key in BinariesDict:

View File

@ -514,7 +514,7 @@ class PathClass(object):
# Check whether PathClass are the same # Check whether PathClass are the same
# #
def __eq__(self, Other): def __eq__(self, Other):
if type(Other) == type(self): if isinstance(Other, type(self)):
return self.Path == Other.Path return self.Path == Other.Path
else: else:
return self.Path == str(Other) return self.Path == str(Other)
@ -819,11 +819,11 @@ def ConvertArchList(ArchList):
if not ArchList: if not ArchList:
return NewArchList return NewArchList
if type(ArchList) == list: if isinstance(ArchList, list):
for Arch in ArchList: for Arch in ArchList:
Arch = Arch.upper() Arch = Arch.upper()
NewArchList.append(Arch) NewArchList.append(Arch)
elif type(ArchList) == str: elif isinstance(ArchList, str):
ArchList = ArchList.upper() ArchList = ArchList.upper()
NewArchList.append(ArchList) NewArchList.append(ArchList)

View File

@ -341,7 +341,7 @@ def IsValidCFormatGuid(Guid):
# #
# Index may out of bound # Index may out of bound
# #
if type(List[Index]) != type(1) or \ if not isinstance(List[Index], type(1)) or \
len(Value) > List[Index] or len(Value) < 3: len(Value) > List[Index] or len(Value) < 3:
return False return False

View File

@ -651,7 +651,7 @@ def ConvertToSqlString2(String):
# @param Split: split character # @param Split: split character
# #
def GetStringOfList(List, Split=' '): def GetStringOfList(List, Split=' '):
if type(List) != type([]): if not isinstance(List, type([])):
return List return List
Str = '' Str = ''
for Item in List: for Item in List:

View File

@ -40,7 +40,7 @@ def CreateXmlElement(Name, String, NodeList, AttributeList):
Element.appendChild(Doc.createTextNode(String)) Element.appendChild(Doc.createTextNode(String))
for Item in NodeList: for Item in NodeList:
if type(Item) == type([]): if isinstance(Item, type([])):
Key = Item[0] Key = Item[0]
Value = Item[1] Value = Item[1]
if Key != '' and Key is not None and Value != '' and Value is not None: if Key != '' and Key is not None and Value != '' and Value is not None:

View File

@ -409,8 +409,7 @@ class DecPomAlignment(PackageObject):
# #
PackagePath = os.path.split(self.GetFullPath())[0] PackagePath = os.path.split(self.GetFullPath())[0]
IncludePathList = \ IncludePathList = \
[os.path.normpath(Path) + sep for Path in IncludesDict.keys()] sorted([os.path.normpath(Path) + sep for Path in IncludesDict.keys()])
IncludePathList.sort()
# #
# get a non-overlap set of include path, IncludePathList should be # get a non-overlap set of include path, IncludePathList should be

View File

@ -611,8 +611,7 @@ class InfPomAlignment(ModuleObject):
SourceFile = Item.GetSourceFileName() SourceFile = Item.GetSourceFileName()
Family = Item.GetFamily() Family = Item.GetFamily()
FeatureFlag = Item.GetFeatureFlagExp() FeatureFlag = Item.GetFeatureFlagExp()
SupArchList = ConvertArchList(Item.GetSupArchList()) SupArchList = sorted(ConvertArchList(Item.GetSupArchList()))
SupArchList.sort()
Source = SourceFileObject() Source = SourceFileObject()
Source.SetSourceFile(SourceFile) Source.SetSourceFile(SourceFile)
Source.SetFamily(Family) Source.SetFamily(Family)

View File

@ -194,8 +194,7 @@ def GenBinaryData(BinaryData, BinaryObj, BinariesDict, AsBuildIns, BinaryFileObj
# can be used for the attribute. # can be used for the attribute.
# If both not have VALID_ARCHITECTURE comment and no architecturie specified, then keep it empty. # If both not have VALID_ARCHITECTURE comment and no architecturie specified, then keep it empty.
# #
SupArchList = ConvertArchList(ItemObj.GetSupArchList()) SupArchList = sorted(ConvertArchList(ItemObj.GetSupArchList()))
SupArchList.sort()
if len(SupArchList) == 1 and SupArchList[0] == 'COMMON': if len(SupArchList) == 1 and SupArchList[0] == 'COMMON':
if not (len(OriSupArchList) == 1 or OriSupArchList[0] == 'COMMON'): if not (len(OriSupArchList) == 1 or OriSupArchList[0] == 'COMMON'):
SupArchList = OriSupArchList SupArchList = OriSupArchList

View File

@ -217,7 +217,7 @@ class StructurePcd(PcdClassObject):
self.DscRawValue = PcdObject.DscRawValue if PcdObject.DscRawValue else self.DscRawValue self.DscRawValue = PcdObject.DscRawValue if PcdObject.DscRawValue else self.DscRawValue
self.PcdValueFromComm = PcdObject.PcdValueFromComm if PcdObject.PcdValueFromComm else self.PcdValueFromComm self.PcdValueFromComm = PcdObject.PcdValueFromComm if PcdObject.PcdValueFromComm else self.PcdValueFromComm
self.DefinitionPosition = PcdObject.DefinitionPosition if PcdObject.DefinitionPosition else self.DefinitionPosition self.DefinitionPosition = PcdObject.DefinitionPosition if PcdObject.DefinitionPosition else self.DefinitionPosition
if type(PcdObject) is StructurePcd: if isinstance(PcdObject, StructurePcd):
self.StructuredPcdIncludeFile = PcdObject.StructuredPcdIncludeFile if PcdObject.StructuredPcdIncludeFile else self.StructuredPcdIncludeFile self.StructuredPcdIncludeFile = PcdObject.StructuredPcdIncludeFile if PcdObject.StructuredPcdIncludeFile else self.StructuredPcdIncludeFile
self.PackageDecs = PcdObject.PackageDecs if PcdObject.PackageDecs else self.PackageDecs self.PackageDecs = PcdObject.PackageDecs if PcdObject.PackageDecs else self.PackageDecs
self.DefaultValues = PcdObject.DefaultValues if PcdObject.DefaultValues else self.DefaultValues self.DefaultValues = PcdObject.DefaultValues if PcdObject.DefaultValues else self.DefaultValues

View File

@ -927,13 +927,13 @@ class DscBuildData(PlatformBuildClassObject):
for pcdname in Pcds: for pcdname in Pcds:
pcd = Pcds[pcdname] pcd = Pcds[pcdname]
Pcds[pcdname].SkuInfoList = {TAB_DEFAULT:pcd.SkuInfoList[skuid] for skuid in pcd.SkuInfoList if skuid in available_sku} Pcds[pcdname].SkuInfoList = {TAB_DEFAULT:pcd.SkuInfoList[skuid] for skuid in pcd.SkuInfoList if skuid in available_sku}
if type(pcd) is StructurePcd and pcd.SkuOverrideValues: if isinstance(pcd, StructurePcd) and pcd.SkuOverrideValues:
Pcds[pcdname].SkuOverrideValues = {TAB_DEFAULT:pcd.SkuOverrideValues[skuid] for skuid in pcd.SkuOverrideValues if skuid in available_sku} Pcds[pcdname].SkuOverrideValues = {TAB_DEFAULT:pcd.SkuOverrideValues[skuid] for skuid in pcd.SkuOverrideValues if skuid in available_sku}
else: else:
for pcdname in Pcds: for pcdname in Pcds:
pcd = Pcds[pcdname] pcd = Pcds[pcdname]
Pcds[pcdname].SkuInfoList = {skuid:pcd.SkuInfoList[skuid] for skuid in pcd.SkuInfoList if skuid in available_sku} Pcds[pcdname].SkuInfoList = {skuid:pcd.SkuInfoList[skuid] for skuid in pcd.SkuInfoList if skuid in available_sku}
if type(pcd) is StructurePcd and pcd.SkuOverrideValues: if isinstance(pcd, StructurePcd) and pcd.SkuOverrideValues:
Pcds[pcdname].SkuOverrideValues = {skuid:pcd.SkuOverrideValues[skuid] for skuid in pcd.SkuOverrideValues if skuid in available_sku} Pcds[pcdname].SkuOverrideValues = {skuid:pcd.SkuOverrideValues[skuid] for skuid in pcd.SkuOverrideValues if skuid in available_sku}
return Pcds return Pcds
def CompleteHiiPcdsDefaultStores(self, Pcds): def CompleteHiiPcdsDefaultStores(self, Pcds):
@ -964,7 +964,7 @@ class DscBuildData(PlatformBuildClassObject):
def __ParsePcdFromCommandLine(self): def __ParsePcdFromCommandLine(self):
if GlobalData.BuildOptionPcd: if GlobalData.BuildOptionPcd:
for i, pcd in enumerate(GlobalData.BuildOptionPcd): for i, pcd in enumerate(GlobalData.BuildOptionPcd):
if type(pcd) is tuple: if isinstance(pcd, tuple):
continue continue
(pcdname, pcdvalue) = pcd.split('=') (pcdname, pcdvalue) = pcd.split('=')
if not pcdvalue: if not pcdvalue:
@ -1320,7 +1320,7 @@ class DscBuildData(PlatformBuildClassObject):
File=self.MetaFile, Line = StrPcdSet[str_pcd][0][5]) File=self.MetaFile, Line = StrPcdSet[str_pcd][0][5])
# Add the Structure PCD that only defined in DEC, don't have override in DSC file # Add the Structure PCD that only defined in DEC, don't have override in DSC file
for Pcd in self.DecPcds: for Pcd in self.DecPcds:
if type (self._DecPcds[Pcd]) is StructurePcd: if isinstance(self._DecPcds[Pcd], StructurePcd):
if Pcd not in S_pcd_set: if Pcd not in S_pcd_set:
str_pcd_obj_str = StructurePcd() str_pcd_obj_str = StructurePcd()
str_pcd_obj_str.copy(self._DecPcds[Pcd]) str_pcd_obj_str.copy(self._DecPcds[Pcd])

View File

@ -78,10 +78,10 @@ def ParseMacro(Parser):
# #
# First judge whether this DEFINE is in conditional directive statements or not. # First judge whether this DEFINE is in conditional directive statements or not.
# #
if type(self) == DscParser and self._InDirective > -1: if isinstance(self, DscParser) and self._InDirective > -1:
pass pass
else: else:
if type(self) == DecParser: if isinstance(self, DecParser):
if MODEL_META_DATA_HEADER in self._SectionType: if MODEL_META_DATA_HEADER in self._SectionType:
self._FileLocalMacros[Name] = Value self._FileLocalMacros[Name] = Value
else: else:
@ -92,7 +92,7 @@ def ParseMacro(Parser):
self._ConstructSectionMacroDict(Name, Value) self._ConstructSectionMacroDict(Name, Value)
# EDK_GLOBAL defined macros # EDK_GLOBAL defined macros
elif type(self) != DscParser: elif not isinstance(self, DscParser):
EdkLogger.error('Parser', FORMAT_INVALID, "EDK_GLOBAL can only be used in .dsc file", EdkLogger.error('Parser', FORMAT_INVALID, "EDK_GLOBAL can only be used in .dsc file",
ExtraData=self._CurrentLine, File=self.MetaFile, Line=self._LineIndex + 1) ExtraData=self._CurrentLine, File=self.MetaFile, Line=self._LineIndex + 1)
elif self._SectionType != MODEL_META_DATA_HEADER: elif self._SectionType != MODEL_META_DATA_HEADER:
@ -233,7 +233,7 @@ class MetaFileParser(object):
# DataInfo = [data_type, scope1(arch), scope2(platform/moduletype)] # DataInfo = [data_type, scope1(arch), scope2(platform/moduletype)]
# #
def __getitem__(self, DataInfo): def __getitem__(self, DataInfo):
if type(DataInfo) != type(()): if not isinstance(DataInfo, type(())):
DataInfo = (DataInfo,) DataInfo = (DataInfo,)
# Parse the file first, if necessary # Parse the file first, if necessary
@ -275,7 +275,7 @@ class MetaFileParser(object):
TokenList = GetSplitValueList(self._CurrentLine, TAB_VALUE_SPLIT) TokenList = GetSplitValueList(self._CurrentLine, TAB_VALUE_SPLIT)
self._ValueList[0:len(TokenList)] = TokenList self._ValueList[0:len(TokenList)] = TokenList
# Don't do macro replacement for dsc file at this point # Don't do macro replacement for dsc file at this point
if type(self) != DscParser: if not isinstance(self, DscParser):
Macros = self._Macros Macros = self._Macros
self._ValueList = [ReplaceMacro(Value, Macros) for Value in self._ValueList] self._ValueList = [ReplaceMacro(Value, Macros) for Value in self._ValueList]
@ -382,7 +382,7 @@ class MetaFileParser(object):
EdkLogger.error('Parser', FORMAT_INVALID, "Invalid version number", EdkLogger.error('Parser', FORMAT_INVALID, "Invalid version number",
ExtraData=self._CurrentLine, File=self.MetaFile, Line=self._LineIndex + 1) ExtraData=self._CurrentLine, File=self.MetaFile, Line=self._LineIndex + 1)
if type(self) == InfParser and self._Version < 0x00010005: if isinstance(self, InfParser) and self._Version < 0x00010005:
# EDK module allows using defines as macros # EDK module allows using defines as macros
self._FileLocalMacros[Name] = Value self._FileLocalMacros[Name] = Value
self._Defines[Name] = Value self._Defines[Name] = Value
@ -398,7 +398,7 @@ class MetaFileParser(object):
self._ValueList[1] = TokenList2[1] # keys self._ValueList[1] = TokenList2[1] # keys
else: else:
self._ValueList[1] = TokenList[0] self._ValueList[1] = TokenList[0]
if len(TokenList) == 2 and type(self) != DscParser: # value if len(TokenList) == 2 and not isinstance(self, DscParser): # value
self._ValueList[2] = ReplaceMacro(TokenList[1], self._Macros) self._ValueList[2] = ReplaceMacro(TokenList[1], self._Macros)
if self._ValueList[1].count('_') != 4: if self._ValueList[1].count('_') != 4:
@ -426,7 +426,7 @@ class MetaFileParser(object):
# DecParser SectionType is a list, will contain more than one item only in Pcd Section # DecParser SectionType is a list, will contain more than one item only in Pcd Section
# As Pcd section macro usage is not alllowed, so here it is safe # As Pcd section macro usage is not alllowed, so here it is safe
# #
if type(self) == DecParser: if isinstance(self, DecParser):
SectionDictKey = self._SectionType[0], ScopeKey SectionDictKey = self._SectionType[0], ScopeKey
else: else:
SectionDictKey = self._SectionType, ScopeKey SectionDictKey = self._SectionType, ScopeKey
@ -443,7 +443,7 @@ class MetaFileParser(object):
SpeSpeMacroDict = {} SpeSpeMacroDict = {}
ActiveSectionType = self._SectionType ActiveSectionType = self._SectionType
if type(self) == DecParser: if isinstance(self, DecParser):
ActiveSectionType = self._SectionType[0] ActiveSectionType = self._SectionType[0]
for (SectionType, Scope) in self._SectionsMacroDict: for (SectionType, Scope) in self._SectionsMacroDict:
@ -1252,7 +1252,7 @@ class DscParser(MetaFileParser):
Macros.update(self._Symbols) Macros.update(self._Symbols)
if GlobalData.BuildOptionPcd: if GlobalData.BuildOptionPcd:
for Item in GlobalData.BuildOptionPcd: for Item in GlobalData.BuildOptionPcd:
if type(Item) is tuple: if isinstance(Item, tuple):
continue continue
PcdName, TmpValue = Item.split("=") PcdName, TmpValue = Item.split("=")
TmpValue = BuildOptionValue(TmpValue, self._GuidDict) TmpValue = BuildOptionValue(TmpValue, self._GuidDict)

View File

@ -1865,8 +1865,7 @@ class FdRegionReport(object):
for Match in gOffsetGuidPattern.finditer(FvReport): for Match in gOffsetGuidPattern.finditer(FvReport):
Guid = Match.group(2).upper() Guid = Match.group(2).upper()
OffsetInfo[Match.group(1)] = self._GuidsDb.get(Guid, Guid) OffsetInfo[Match.group(1)] = self._GuidsDb.get(Guid, Guid)
OffsetList = OffsetInfo.keys() OffsetList = sorted(OffsetInfo.keys())
OffsetList.sort()
for Offset in OffsetList: for Offset in OffsetList:
FileWrite (File, "%s %s" % (Offset, OffsetInfo[Offset])) FileWrite (File, "%s %s" % (Offset, OffsetInfo[Offset]))
except IOError: except IOError:

View File

@ -305,7 +305,7 @@ def LaunchCommand(Command, WorkingDir):
if EndOfProcedure is not None: if EndOfProcedure is not None:
EndOfProcedure.set() EndOfProcedure.set()
if Proc is None: if Proc is None:
if type(Command) != type(""): if not isinstance(Command, type("")):
Command = " ".join(Command) Command = " ".join(Command)
EdkLogger.error("build", COMMAND_FAILURE, "Failed to start command", ExtraData="%s [%s]" % (Command, WorkingDir)) EdkLogger.error("build", COMMAND_FAILURE, "Failed to start command", ExtraData="%s [%s]" % (Command, WorkingDir))
@ -316,7 +316,7 @@ def LaunchCommand(Command, WorkingDir):
# check the return code of the program # check the return code of the program
if Proc.returncode != 0: if Proc.returncode != 0:
if type(Command) != type(""): if not isinstance(Command, type("")):
Command = " ".join(Command) Command = " ".join(Command)
# print out the Response file and its content when make failure # print out the Response file and its content when make failure
RespFile = os.path.join(WorkingDir, 'OUTPUT', 'respfilelist.txt') RespFile = os.path.join(WorkingDir, 'OUTPUT', 'respfilelist.txt')

View File

@ -257,9 +257,9 @@ class SourceFiles:
replaceables = ('extract-dir', 'filename', 'url') replaceables = ('extract-dir', 'filename', 'url')
for replaceItem in fdata: for replaceItem in fdata:
if replaceItem in replaceables: continue if replaceItem in replaceables: continue
if type(fdata[replaceItem]) != str: continue if not isinstance(fdata[replaceItem], str): continue
for replaceable in replaceables: for replaceable in replaceables:
if type(fdata[replaceable]) != str: continue if not isinstance(fdata[replaceable], str): continue
if replaceable in fdata: if replaceable in fdata:
fdata[replaceable] = \ fdata[replaceable] = \
fdata[replaceable].replace( fdata[replaceable].replace(