]> git.proxmox.com Git - mirror_edk2.git/blobdiff - BaseTools/Source/Python/UPT/Library/String.py
BaseTools/UPT: Fix UNI file name issue
[mirror_edk2.git] / BaseTools / Source / Python / UPT / Library / String.py
index 0953e47cb1db74541aa059cf22e719fb8de11602..278073e4a379786ba26c5f1b832bec32f1fb7049 100644 (file)
@@ -1,12 +1,12 @@
 ## @file\r
-# This file is used to define common string related functions used in parsing \r
+# This file is used to define common string related functions used in parsing\r
 # process\r
 #\r
-# Copyright (c) 2011 - 2012, Intel Corporation. All rights reserved.<BR>\r
+# Copyright (c) 2011 - 2016, Intel Corporation. All rights reserved.<BR>\r
 #\r
-# This program and the accompanying materials are licensed and made available \r
-# under the terms and conditions of the BSD License which accompanies this \r
-# distribution. The full text of the license may be found at \r
+# This program and the accompanying materials are licensed and made available\r
+# under the terms and conditions of the BSD License which accompanies this\r
+# distribution. The full text of the license may be found at\r
 # http://opensource.org/licenses/bsd-license.php\r
 #\r
 # THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,\r
@@ -43,7 +43,7 @@ gMACRO_PATTERN = re.compile("\$\(([_A-Z][_A-Z0-9]*)\)", re.UNICODE)
 # @param MaxSplit:  The max number of split values, default is -1\r
 #\r
 #\r
-def GetSplitValueList(String, SplitTag=DataType.TAB_VALUE_SPLIT, MaxSplit=-1):\r
+def GetSplitValueList(String, SplitTag=DataType.TAB_VALUE_SPLIT, MaxSplit= -1):\r
     return map(lambda l: l.strip(), String.split(SplitTag, MaxSplit))\r
 \r
 ## MergeArches\r
@@ -129,7 +129,7 @@ def GetDynamics(Lines, Key, KeyValues, CommentCharacter):
 ## SplitModuleType\r
 #\r
 # Split ModuleType out of section defien to get key\r
-# [LibraryClass.Arch.ModuleType|ModuleType|ModuleType] -> [ \r
+# [LibraryClass.Arch.ModuleType|ModuleType|ModuleType] -> [\r
 # 'LibraryClass.Arch', ['ModuleType', 'ModuleType', 'ModuleType'] ]\r
 #\r
 # @param Key:  String to be parsed\r
@@ -164,7 +164,7 @@ def SplitModuleType(Key):
 # @param Line:              The content contain line string and line number\r
 # @param FileName:        The meta-file file name\r
 #\r
-def ReplaceMacro(String, MacroDefinitions = None,  SelfReplacement = False, Line = None, FileName = None, Flag = False):\r
+def ReplaceMacro(String, MacroDefinitions=None, SelfReplacement=False, Line=None, FileName=None, Flag=False):\r
     LastString = String\r
     if MacroDefinitions == None:\r
         MacroDefinitions = {}\r
@@ -184,10 +184,10 @@ def ReplaceMacro(String, MacroDefinitions = None,  SelfReplacement = False, Line
                 Count += 1\r
                 if Count % 2 != 0:\r
                     MacroString += QuotedStringItem\r
-                \r
-                if Count == len(QuotedStringList) and Count%2 == 0:\r
+\r
+                if Count == len(QuotedStringList) and Count % 2 == 0:\r
                     MacroString += QuotedStringItem\r
-                    \r
+\r
             MacroUsed = gMACRO_PATTERN.findall(MacroString)\r
         #\r
         # no macro found in String, stop replacing\r
@@ -198,7 +198,7 @@ def ReplaceMacro(String, MacroDefinitions = None,  SelfReplacement = False, Line
             if Macro not in MacroDefinitions:\r
                 if SelfReplacement:\r
                     String = String.replace("$(%s)" % Macro, '')\r
-                    Logger.Debug(5, "Delete undefined MACROs in file %s line %d: %s!" %(FileName, Line[1], Line[0]))\r
+                    Logger.Debug(5, "Delete undefined MACROs in file %s line %d: %s!" % (FileName, Line[1], Line[0]))\r
                 continue\r
             if not HaveQuotedMacroFlag:\r
                 String = String.replace("$(%s)" % Macro, MacroDefinitions[Macro])\r
@@ -207,25 +207,25 @@ def ReplaceMacro(String, MacroDefinitions = None,  SelfReplacement = False, Line
                 for QuotedStringItem in QuotedStringList:\r
                     Count += 1\r
                     if Count % 2 != 0:\r
-                        QuotedStringList[Count-1] = QuotedStringList[Count-1].replace("$(%s)" % Macro, \r
+                        QuotedStringList[Count - 1] = QuotedStringList[Count - 1].replace("$(%s)" % Macro,\r
                                                                         MacroDefinitions[Macro])\r
-                    elif Count == len(QuotedStringList) and Count%2 == 0:\r
-                        QuotedStringList[Count-1] = QuotedStringList[Count-1].replace("$(%s)" % Macro,\r
+                    elif Count == len(QuotedStringList) and Count % 2 == 0:\r
+                        QuotedStringList[Count - 1] = QuotedStringList[Count - 1].replace("$(%s)" % Macro,\r
                                                                         MacroDefinitions[Macro])\r
-    \r
+\r
         RetString = ''\r
         if HaveQuotedMacroFlag:\r
             Count = 0\r
             for QuotedStringItem in QuotedStringList:\r
-                Count += 1            \r
+                Count += 1\r
                 if Count != len(QuotedStringList):\r
-                    RetString += QuotedStringList[Count-1] + "\""\r
+                    RetString += QuotedStringList[Count - 1] + "\""\r
                 else:\r
-                    RetString += QuotedStringList[Count-1]\r
-                \r
+                    RetString += QuotedStringList[Count - 1]\r
+\r
             String = RetString\r
-                          \r
-        #    \r
+\r
+        #\r
         # in case there's macro not defined\r
         #\r
         if String == LastString:\r
@@ -242,7 +242,7 @@ def ReplaceMacro(String, MacroDefinitions = None,  SelfReplacement = False, Line
 # @param Path:     The input value for Path to be converted\r
 # @param Defines:  A set for DEFINE statement\r
 #\r
-def NormPath(Path, Defines = None):\r
+def NormPath(Path, Defines=None):\r
     IsRelativePath = False\r
     if Defines == None:\r
         Defines = {}\r
@@ -269,7 +269,7 @@ def NormPath(Path, Defines = None):
 # Remove spaces\r
 #\r
 # @param Line:              The string to be cleaned\r
-# @param CommentCharacter:  Comment char, used to ignore comment content, \r
+# @param CommentCharacter:  Comment char, used to ignore comment content,\r
 #                           default is DataType.TAB_COMMENT_SPLIT\r
 #\r
 def CleanString(Line, CommentCharacter=DataType.TAB_COMMENT_SPLIT, AllowCppStyleComment=False):\r
@@ -305,7 +305,7 @@ def CleanString(Line, CommentCharacter=DataType.TAB_COMMENT_SPLIT, AllowCppStyle
 # Remove spaces\r
 #\r
 # @param Line:              The string to be cleaned\r
-# @param CommentCharacter:  Comment char, used to ignore comment content, \r
+# @param CommentCharacter:  Comment char, used to ignore comment content,\r
 #                           default is DataType.TAB_COMMENT_SPLIT\r
 #\r
 def CleanString2(Line, CommentCharacter=DataType.TAB_COMMENT_SPLIT, AllowCppStyleComment=False):\r
@@ -394,10 +394,10 @@ def GetDefineValue(String, Key, CommentCharacter):
 # @param CommentCharacter:     Comment char, be used to ignore comment content\r
 # @param KeySplitCharacter:    Key split char, between key name and key value.\r
 #                              Key1 = Value1, '=' is the key split char\r
-# @param ValueSplitFlag:       Value split flag, be used to decide if has \r
+# @param ValueSplitFlag:       Value split flag, be used to decide if has\r
 #                              multiple values\r
-# @param ValueSplitCharacter:  Value split char, be used to split multiple \r
-#                              values. Key1 = Value1|Value2, '|' is the value \r
+# @param ValueSplitCharacter:  Value split char, be used to split multiple\r
+#                              values. Key1 = Value1|Value2, '|' is the value\r
 #                              split char\r
 #\r
 def GetSingleValueOfKeyFromLines(Lines, Dictionary, CommentCharacter, KeySplitCharacter, \\r
@@ -489,7 +489,7 @@ def PreCheck(FileName, FileContent, SupSectionTag):
         #\r
         if Line.find('$') > -1:\r
             if Line.find('$(') < 0 or Line.find(')') < 0:\r
-                Logger.Error("Parser", FORMAT_INVALID, Line=LineNo, File=FileName, RaiseError = Logger.IS_RAISE_ERROR)\r
+                Logger.Error("Parser", FORMAT_INVALID, Line=LineNo, File=FileName, RaiseError=Logger.IS_RAISE_ERROR)\r
         #\r
         # Check []\r
         #\r
@@ -498,14 +498,14 @@ def PreCheck(FileName, FileContent, SupSectionTag):
             # Only get one '[' or one ']'\r
             #\r
             if not (Line.find('[') > -1 and Line.find(']') > -1):\r
-                Logger.Error("Parser", FORMAT_INVALID, Line=LineNo, File=FileName, RaiseError = Logger.IS_RAISE_ERROR)\r
+                Logger.Error("Parser", FORMAT_INVALID, Line=LineNo, File=FileName, RaiseError=Logger.IS_RAISE_ERROR)\r
         #\r
         # Regenerate FileContent\r
         #\r
         NewFileContent = NewFileContent + Line + '\r\n'\r
 \r
     if IsFailed:\r
-        Logger.Error("Parser", FORMAT_INVALID, Line=LineNo, File=FileName, RaiseError = Logger.IS_RAISE_ERROR)\r
+        Logger.Error("Parser", FORMAT_INVALID, Line=LineNo, File=FileName, RaiseError=Logger.IS_RAISE_ERROR)\r
 \r
     return NewFileContent\r
 \r
@@ -523,7 +523,7 @@ def PreCheck(FileName, FileContent, SupSectionTag):
 # @param Line:               The line in container file which defines the file\r
 #                            to be checked\r
 #\r
-def CheckFileType(CheckFilename, ExtName, ContainerFilename, SectionName, Line, LineNo=-1):\r
+def CheckFileType(CheckFilename, ExtName, ContainerFilename, SectionName, Line, LineNo= -1):\r
     if CheckFilename != '' and CheckFilename != None:\r
         (Root, Ext) = os.path.splitext(CheckFilename)\r
         if Ext.upper() != ExtName.upper() and Root:\r
@@ -544,13 +544,13 @@ def CheckFileType(CheckFilename, ExtName, ContainerFilename, SectionName, Line,
 #\r
 # @param CheckFilename:      Name of the file to be checked\r
 # @param WorkspaceDir:       Current workspace dir\r
-# @param ContainerFilename:  The container file which describes the file to \r
+# @param ContainerFilename:  The container file which describes the file to\r
 #                            be checked, used for error report\r
 # @param SectionName:        Used for error report\r
-# @param Line:               The line in container file which defines the \r
+# @param Line:               The line in container file which defines the\r
 #                            file to be checked\r
 #\r
-def CheckFileExist(WorkspaceDir, CheckFilename, ContainerFilename, SectionName, Line, LineNo=-1):\r
+def CheckFileExist(WorkspaceDir, CheckFilename, ContainerFilename, SectionName, Line, LineNo= -1):\r
     CheckFile = ''\r
     if CheckFilename != '' and CheckFilename != None:\r
         CheckFile = WorkspaceFile(WorkspaceDir, CheckFilename)\r
@@ -560,7 +560,7 @@ def CheckFileExist(WorkspaceDir, CheckFilename, ContainerFilename, SectionName,
                 LineNo = GetLineNo(ContainerFile, Line)\r
             ErrorMsg = ST.ERR_CHECKFILE_NOTFOUND % (CheckFile, SectionName)\r
             Logger.Error("Parser", PARSER_ERROR, ErrorMsg,\r
-                            File=ContainerFilename, Line = LineNo, RaiseError=Logger.IS_RAISE_ERROR)\r
+                            File=ContainerFilename, Line=LineNo, RaiseError=Logger.IS_RAISE_ERROR)\r
     return CheckFile\r
 \r
 ## GetLineNo\r
@@ -593,7 +593,7 @@ def GetLineNo(FileContent, Line, IsIgnoreComment=True):
 # @param File:     File which has the string\r
 # @param Format:   Correct format\r
 #\r
-def RaiseParserError(Line, Section, File, Format='', LineNo=-1):\r
+def RaiseParserError(Line, Section, File, Format='', LineNo= -1):\r
     if LineNo == -1:\r
         LineNo = GetLineNo(open(os.path.normpath(File), 'r').read(), Line)\r
     ErrorMsg = ST.ERR_INVALID_NOTFOUND % (Line, Section)\r
@@ -650,7 +650,7 @@ def ConvertToSqlString2(String):
 # @param Lines: string list\r
 # @param Split: split character\r
 #\r
-def GetStringOfList(List, Split = ' '):\r
+def GetStringOfList(List, Split=' '):\r
     if type(List) != type([]):\r
         return List\r
     Str = ''\r
@@ -696,7 +696,7 @@ def StringArrayLength(String):
 # @param OptionString: the option string\r
 # @param Which: Which flag\r
 # @param Against: Against flag\r
-#    \r
+#\r
 def RemoveDupOption(OptionString, Which="/I", Against=None):\r
     OptionList = OptionString.split()\r
     ValueList = []\r
@@ -718,14 +718,14 @@ def RemoveDupOption(OptionString, Which="/I", Against=None):
 \r
 ## Check if the string is HexDgit\r
 #\r
-# Return true if all characters in the string are digits and there is at \r
-# least one character \r
+# Return true if all characters in the string are digits and there is at\r
+# least one character\r
 # or valid Hexs (started with 0x, following by hexdigit letters)\r
-# , false otherwise. \r
+# , false otherwise.\r
 # @param string: input string\r
 #\r
 def IsHexDigit(Str):\r
-    try: \r
+    try:\r
         int(Str, 10)\r
         return True\r
     except ValueError:\r
@@ -737,16 +737,16 @@ def IsHexDigit(Str):
                 return False\r
     return False\r
 \r
-## Check if the string is HexDgit and its integer value within limit of UINT32 \r
+## Check if the string is HexDgit and its interger value within limit of UINT32\r
 #\r
-# Return true if all characters in the string are digits and there is at \r
-# least one character \r
+# Return true if all characters in the string are digits and there is at\r
+# least one character\r
 # or valid Hexs (started with 0x, following by hexdigit letters)\r
-# , false otherwise. \r
+# , false otherwise.\r
 # @param string: input string\r
 #\r
 def IsHexDigitUINT32(Str):\r
-    try: \r
+    try:\r
         Value = int(Str, 10)\r
         if (Value <= 0xFFFFFFFF) and (Value >= 0):\r
             return True\r
@@ -761,11 +761,11 @@ def IsHexDigitUINT32(Str):
     return False\r
 \r
 ## CleanSpecialChar\r
-#  \r
-# The ASCII text files of type INF, DEC, INI are edited by developers, \r
+#\r
+# The ASCII text files of type INF, DEC, INI are edited by developers,\r
 # and may contain characters that cannot be directly translated to strings that\r
-# are conformant with the UDP XML Schema.  Any characters in this category \r
-# (0x00-0x08, TAB [0x09], 0x0B, 0x0C, 0x0E-0x1F, 0x80-0xFF) \r
+# are conformant with the UDP XML Schema.  Any characters in this category\r
+# (0x00-0x08, TAB [0x09], 0x0B, 0x0C, 0x0E-0x1F, 0x80-0xFF)\r
 # must be converted to a space character[0x20] as part of the parsing process.\r
 #\r
 def ConvertSpecialChar(Lines):\r
@@ -773,7 +773,7 @@ def ConvertSpecialChar(Lines):
     for line in Lines:\r
         ReMatchSpecialChar = re.compile(r"[\x00-\x08]|\x09|\x0b|\x0c|[\x0e-\x1f]|[\x7f-\xff]")\r
         RetLines.append(ReMatchSpecialChar.sub(' ', line))\r
-    \r
+\r
     return RetLines\r
 \r
 ## __GetTokenList\r
@@ -817,7 +817,7 @@ def __GetTokenList(Str):
             if TokenOP:\r
                 List.append(TokenOP)\r
                 TokenOP = ''\r
-        \r
+\r
         if PreChar == '\\' and Char == '\\':\r
             PreChar = ''\r
         else:\r
@@ -870,61 +870,55 @@ def ConvertNOTEQToNE(Expr):
     return ''.join(RetList)\r
 \r
 ## SplitPcdEntry\r
-# \r
+#\r
 # Split an PCD entry string to Token.CName and PCD value and FFE.\r
 # NOTE: PCD Value and FFE can contain "|" in it's expression. And in INF specification, have below rule.\r
-# When using the characters "|" or "||" in an expression, the expression must be encapsulated in \r
+# When using the characters "|" or "||" in an expression, the expression must be encapsulated in\r
 # open "(" and close ")" parenthesis.\r
-# \r
+#\r
 # @param String    An PCD entry string need to be split.\r
-# \r
-# @return List     [PcdTokenCName, Value, FFE] \r
+#\r
+# @return List     [PcdTokenCName, Value, FFE]\r
 #\r
 def SplitPcdEntry(String):\r
     if not String:\r
-        return ['', '',''], False\r
-    \r
+        return ['', '', ''], False\r
+\r
     PcdTokenCName = ''\r
     PcdValue = ''\r
     PcdFeatureFlagExp = ''\r
-    \r
+\r
     ValueList = GetSplitValueList(String, "|", 1)\r
-    \r
+\r
     #\r
     # Only contain TokenCName\r
     #\r
     if len(ValueList) == 1:\r
         return [ValueList[0]], True\r
-    \r
+\r
     NewValueList = []\r
-    \r
+\r
     if len(ValueList) == 2:\r
         PcdTokenCName = ValueList[0]\r
-        ValueList = GetSplitValueList(ValueList[1], "|")\r
-        \r
-        RemainCount = 0\r
-        for Item in ValueList:\r
-            ParenthesisCount = 0\r
-            for Char in Item:\r
-                if Char == "(":\r
-                    ParenthesisCount += 1\r
-                if Char == ")":\r
-                    ParenthesisCount -= 1\r
-                 \r
-            #\r
-            # An individual item\r
-            #\r
-            if RemainCount == 0 and ParenthesisCount >= 0:\r
-                NewValueList.append(Item)\r
-                RemainCount = ParenthesisCount\r
-            elif RemainCount > 0 and RemainCount + ParenthesisCount >= 0:\r
-                NewValueList[-1] = NewValueList[-1] + '|' + Item         \r
-                RemainCount = RemainCount + ParenthesisCount\r
-            elif RemainCount > 0 and RemainCount + ParenthesisCount < 0:\r
-                #\r
-                # ERROR, return\r
-                #\r
-                return ['', '', ''], False\r
+\r
+        InQuote = False\r
+        InParenthesis = False\r
+        StrItem = ''\r
+        for StrCh in ValueList[1]:\r
+            if StrCh == '"':\r
+                InQuote = not InQuote\r
+            elif StrCh == '(' or StrCh == ')':\r
+                InParenthesis = not InParenthesis\r
+\r
+            if StrCh == '|':\r
+                if not InQuote or not InParenthesis:\r
+                    NewValueList.append(StrItem.strip())\r
+                    StrItem = ' '\r
+                    continue\r
+\r
+            StrItem += StrCh\r
+\r
+        NewValueList.append(StrItem.strip())\r
 \r
         if len(NewValueList) == 1:\r
             PcdValue = NewValueList[0]\r
@@ -935,5 +929,62 @@ def SplitPcdEntry(String):
             return [PcdTokenCName, PcdValue, PcdFeatureFlagExp], True\r
         else:\r
             return ['', '', ''], False\r
-        \r
+\r
     return ['', '', ''], False\r
+\r
+## Check if two arches matched?\r
+#\r
+# @param Arch1\r
+# @param Arch2\r
+#\r
+def IsMatchArch(Arch1, Arch2):\r
+    if 'COMMON' in Arch1 or 'COMMON' in Arch2:\r
+        return True\r
+    if isinstance(Arch1, basestring) and isinstance(Arch2, basestring):\r
+        if Arch1 == Arch2:\r
+            return True\r
+\r
+    if isinstance(Arch1, basestring) and isinstance(Arch2, list):\r
+        return Arch1 in Arch2\r
+\r
+    if isinstance(Arch2, basestring) and isinstance(Arch1, list):\r
+        return Arch2 in Arch1\r
+\r
+    if isinstance(Arch1, list) and isinstance(Arch2, list):\r
+        for Item1 in Arch1:\r
+            for Item2 in Arch2:\r
+                if Item1 == Item2:\r
+                    return True\r
+\r
+    return False\r
+\r
+# Search all files in FilePath to find the FileName with the largest index\r
+# Return the FileName with index +1 under the FilePath\r
+#\r
+def GetUniFileName(FilePath, FileName):\r
+    Files = []\r
+    try:\r
+        Files = os.listdir(FilePath)\r
+    except:\r
+        pass\r
+\r
+    LargestIndex = -1\r
+    IndexNotFound = True\r
+    for File in Files:\r
+        if File.upper().startswith(FileName.upper()) and File.upper().endswith('.UNI'):\r
+            Index = File.upper().replace(FileName.upper(), '').replace('.UNI', '')\r
+            if Index:\r
+                try:\r
+                    Index = int(Index)\r
+                except Exception:\r
+                    Index = -1\r
+            else:\r
+                IndexNotFound = False\r
+                Index = 0\r
+            if Index > LargestIndex:\r
+                LargestIndex = Index + 1\r
+\r
+    if LargestIndex > -1 and not IndexNotFound:\r
+        return os.path.normpath(os.path.join(FilePath, FileName + str(LargestIndex) + '.uni'))\r
+    else:\r
+        return os.path.normpath(os.path.join(FilePath, FileName + '.uni'))\r