]> git.proxmox.com Git - mirror_edk2.git/blame - BaseTools/Source/Python/Common/String.py
EmulatorPkg/build.sh: Use GCC49 toolchain with GCC 5.*
[mirror_edk2.git] / BaseTools / Source / Python / Common / String.py
CommitLineData
30fdf114
LG
1## @file\r
2# This file is used to define common string related functions used in parsing process\r
3#\r
ce2f5940 4# Copyright (c) 2007 - 2015, Intel Corporation. All rights reserved.<BR>\r
40d841f6 5# This program and the accompanying materials\r
30fdf114
LG
6# are licensed and made available under the terms and conditions of the BSD License\r
7# which accompanies this distribution. The full text of the license may be found at\r
8# http://opensource.org/licenses/bsd-license.php\r
9#\r
10# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,\r
11# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\r
12#\r
13\r
14##\r
15# Import Modules\r
16#\r
17import re\r
18import DataType\r
1be2ed90 19import Common.LongFilePathOs as os\r
30fdf114
LG
20import string\r
21import EdkLogger as EdkLogger\r
22\r
b36d134f 23import GlobalData\r
30fdf114 24from BuildToolError import *\r
0d2711a6 25from CommonDataClass.Exceptions import *\r
1be2ed90 26from Common.LongFilePathSupport import OpenLongFilePath as open\r
30fdf114 27\r
d40b2ee6 28gHexVerPatt = re.compile('0x[a-f0-9]{4}[a-f0-9]{4}$', re.IGNORECASE)\r
08dd311f
LG
29gHumanReadableVerPatt = re.compile(r'([1-9][0-9]*|0)\.[0-9]{1,2}$')\r
30\r
30fdf114
LG
31## GetSplitValueList\r
32#\r
33# Get a value list from a string with multiple values splited with SplitTag\r
34# The default SplitTag is DataType.TAB_VALUE_SPLIT\r
35# 'AAA|BBB|CCC' -> ['AAA', 'BBB', 'CCC']\r
36#\r
37# @param String: The input string to be splitted\r
38# @param SplitTag: The split key, default is DataType.TAB_VALUE_SPLIT\r
39# @param MaxSplit: The max number of split values, default is -1\r
40#\r
41# @retval list() A list for splitted string\r
42#\r
d40b2ee6 43def GetSplitValueList(String, SplitTag=DataType.TAB_VALUE_SPLIT, MaxSplit= -1):\r
0d2711a6
LG
44 ValueList = []\r
45 Last = 0\r
46 Escaped = False\r
47 InString = False\r
48 for Index in range(0, len(String)):\r
49 Char = String[Index]\r
50\r
51 if not Escaped:\r
52 # Found a splitter not in a string, split it\r
53 if not InString and Char == SplitTag:\r
54 ValueList.append(String[Last:Index].strip())\r
d40b2ee6 55 Last = Index + 1\r
0d2711a6
LG
56 if MaxSplit > 0 and len(ValueList) >= MaxSplit:\r
57 break\r
58\r
59 if Char == '\\' and InString:\r
60 Escaped = True\r
61 elif Char == '"':\r
62 if not InString:\r
63 InString = True\r
64 else:\r
65 InString = False\r
66 else:\r
67 Escaped = False\r
68\r
69 if Last < len(String):\r
70 ValueList.append(String[Last:].strip())\r
71 elif Last == len(String):\r
72 ValueList.append('')\r
73\r
74 return ValueList\r
75\r
76## GetSplitList\r
77#\r
78# Get a value list from a string with multiple values splited with SplitString\r
79# The default SplitTag is DataType.TAB_VALUE_SPLIT\r
80# 'AAA|BBB|CCC' -> ['AAA', 'BBB', 'CCC']\r
81#\r
82# @param String: The input string to be splitted\r
83# @param SplitStr: The split key, default is DataType.TAB_VALUE_SPLIT\r
84# @param MaxSplit: The max number of split values, default is -1\r
85#\r
86# @retval list() A list for splitted string\r
87#\r
d40b2ee6 88def GetSplitList(String, SplitStr=DataType.TAB_VALUE_SPLIT, MaxSplit= -1):\r
0d2711a6 89 return map(lambda l: l.strip(), String.split(SplitStr, MaxSplit))\r
30fdf114
LG
90\r
91## MergeArches\r
92#\r
93# Find a key's all arches in dict, add the new arch to the list\r
94# If not exist any arch, set the arch directly\r
95#\r
96# @param Dict: The input value for Dict\r
97# @param Key: The input value for Key\r
98# @param Arch: The Arch to be added or merged\r
99#\r
100def MergeArches(Dict, Key, Arch):\r
101 if Key in Dict.keys():\r
102 Dict[Key].append(Arch)\r
103 else:\r
104 Dict[Key] = Arch.split()\r
105\r
106## GenDefines\r
107#\r
108# Parse a string with format "DEFINE <VarName> = <PATH>"\r
109# Generate a map Defines[VarName] = PATH\r
110# Return False if invalid format\r
111#\r
112# @param String: String with DEFINE statement\r
113# @param Arch: Supportted Arch\r
114# @param Defines: DEFINE statement to be parsed\r
115#\r
116# @retval 0 DEFINE statement found, and valid\r
117# @retval 1 DEFINE statement found, but not valid\r
118# @retval -1 DEFINE statement not found\r
119#\r
120def GenDefines(String, Arch, Defines):\r
121 if String.find(DataType.TAB_DEFINE + ' ') > -1:\r
122 List = String.replace(DataType.TAB_DEFINE + ' ', '').split(DataType.TAB_EQUAL_SPLIT)\r
123 if len(List) == 2:\r
124 Defines[(CleanString(List[0]), Arch)] = CleanString(List[1])\r
125 return 0\r
126 else:\r
127 return -1\r
128\r
129 return 1\r
130\r
131## GenInclude\r
132#\r
133# Parse a string with format "!include <Filename>"\r
134# Return the file path\r
135# Return False if invalid format or NOT FOUND\r
136#\r
137# @param String: String with INCLUDE statement\r
138# @param IncludeFiles: INCLUDE statement to be parsed\r
139# @param Arch: Supportted Arch\r
140#\r
141# @retval True\r
142# @retval False\r
143#\r
144def GenInclude(String, IncludeFiles, Arch):\r
145 if String.upper().find(DataType.TAB_INCLUDE.upper() + ' ') > -1:\r
146 IncludeFile = CleanString(String[String.upper().find(DataType.TAB_INCLUDE.upper() + ' ') + len(DataType.TAB_INCLUDE + ' ') : ])\r
147 MergeArches(IncludeFiles, IncludeFile, Arch)\r
148 return True\r
149 else:\r
150 return False\r
151\r
152## GetLibraryClassesWithModuleType\r
153#\r
154# Get Library Class definition when no module type defined\r
155#\r
156# @param Lines: The content to be parsed\r
157# @param Key: Reserved\r
158# @param KeyValues: To store data after parsing\r
159# @param CommentCharacter: Comment char, used to ignore comment content\r
160#\r
161# @retval True Get library classes successfully\r
162#\r
163def GetLibraryClassesWithModuleType(Lines, Key, KeyValues, CommentCharacter):\r
164 newKey = SplitModuleType(Key)\r
165 Lines = Lines.split(DataType.TAB_SECTION_END, 1)[1]\r
166 LineList = Lines.splitlines()\r
167 for Line in LineList:\r
168 Line = CleanString(Line, CommentCharacter)\r
169 if Line != '' and Line[0] != CommentCharacter:\r
170 KeyValues.append([CleanString(Line, CommentCharacter), newKey[1]])\r
171\r
172 return True\r
173\r
174## GetDynamics\r
175#\r
176# Get Dynamic Pcds\r
177#\r
178# @param Lines: The content to be parsed\r
179# @param Key: Reserved\r
180# @param KeyValues: To store data after parsing\r
181# @param CommentCharacter: Comment char, used to ignore comment content\r
182#\r
183# @retval True Get Dynamic Pcds successfully\r
184#\r
185def GetDynamics(Lines, Key, KeyValues, CommentCharacter):\r
186 #\r
187 # Get SkuId Name List\r
188 #\r
189 SkuIdNameList = SplitModuleType(Key)\r
190\r
191 Lines = Lines.split(DataType.TAB_SECTION_END, 1)[1]\r
192 LineList = Lines.splitlines()\r
193 for Line in LineList:\r
194 Line = CleanString(Line, CommentCharacter)\r
195 if Line != '' and Line[0] != CommentCharacter:\r
196 KeyValues.append([CleanString(Line, CommentCharacter), SkuIdNameList[1]])\r
197\r
198 return True\r
199\r
200## SplitModuleType\r
201#\r
202# Split ModuleType out of section defien to get key\r
203# [LibraryClass.Arch.ModuleType|ModuleType|ModuleType] -> [ 'LibraryClass.Arch', ['ModuleType', 'ModuleType', 'ModuleType'] ]\r
204#\r
205# @param Key: String to be parsed\r
206#\r
207# @retval ReturnValue A list for module types\r
208#\r
209def SplitModuleType(Key):\r
210 KeyList = Key.split(DataType.TAB_SPLIT)\r
211 #\r
212 # Fill in for arch\r
213 #\r
214 KeyList.append('')\r
215 #\r
216 # Fill in for moduletype\r
217 #\r
218 KeyList.append('')\r
219 ReturnValue = []\r
220 KeyValue = KeyList[0]\r
221 if KeyList[1] != '':\r
222 KeyValue = KeyValue + DataType.TAB_SPLIT + KeyList[1]\r
223 ReturnValue.append(KeyValue)\r
224 ReturnValue.append(GetSplitValueList(KeyList[2]))\r
225\r
226 return ReturnValue\r
227\r
228## Replace macro in strings list\r
229#\r
230# This method replace macros used in a given string list. The macros are\r
231# given in a dictionary.\r
232#\r
233# @param StringList StringList to be processed\r
234# @param MacroDefinitions The macro definitions in the form of dictionary\r
235# @param SelfReplacement To decide whether replace un-defined macro to ''\r
236#\r
237# @retval NewList A new string list whose macros are replaced\r
238#\r
d40b2ee6 239def ReplaceMacros(StringList, MacroDefinitions={}, SelfReplacement=False):\r
30fdf114
LG
240 NewList = []\r
241 for String in StringList:\r
242 if type(String) == type(''):\r
243 NewList.append(ReplaceMacro(String, MacroDefinitions, SelfReplacement))\r
244 else:\r
245 NewList.append(String)\r
246\r
247 return NewList\r
248\r
249## Replace macro in string\r
250#\r
251# This method replace macros used in given string. The macros are given in a\r
252# dictionary.\r
253#\r
254# @param String String to be processed\r
255# @param MacroDefinitions The macro definitions in the form of dictionary\r
256# @param SelfReplacement To decide whether replace un-defined macro to ''\r
257#\r
258# @retval string The string whose macros are replaced\r
259#\r
0d2711a6 260def ReplaceMacro(String, MacroDefinitions={}, SelfReplacement=False, RaiseError=False):\r
30fdf114 261 LastString = String\r
0d2711a6
LG
262 while String and MacroDefinitions:\r
263 MacroUsed = GlobalData.gMacroRefPattern.findall(String)\r
30fdf114
LG
264 # no macro found in String, stop replacing\r
265 if len(MacroUsed) == 0:\r
266 break\r
267\r
268 for Macro in MacroUsed:\r
269 if Macro not in MacroDefinitions:\r
0d2711a6
LG
270 if RaiseError:\r
271 raise SymbolNotFound("%s not defined" % Macro)\r
30fdf114
LG
272 if SelfReplacement:\r
273 String = String.replace("$(%s)" % Macro, '')\r
274 continue\r
ce2f5940
HC
275 if "$(%s)" % Macro not in MacroDefinitions[Macro]:\r
276 String = String.replace("$(%s)" % Macro, MacroDefinitions[Macro])\r
30fdf114
LG
277 # in case there's macro not defined\r
278 if String == LastString:\r
279 break\r
280 LastString = String\r
281\r
282 return String\r
283\r
284## NormPath\r
285#\r
286# Create a normal path\r
287# And replace DFEINE in the path\r
288#\r
289# @param Path: The input value for Path to be converted\r
290# @param Defines: A set for DEFINE statement\r
291#\r
292# @retval Path Formatted path\r
293#\r
d40b2ee6 294def NormPath(Path, Defines={}):\r
30fdf114
LG
295 IsRelativePath = False\r
296 if Path:\r
297 if Path[0] == '.':\r
298 IsRelativePath = True\r
299 #\r
300 # Replace with Define\r
301 #\r
302 if Defines:\r
303 Path = ReplaceMacro(Path, Defines)\r
304 #\r
305 # To local path format\r
306 #\r
307 Path = os.path.normpath(Path)\r
308\r
309 if IsRelativePath and Path[0] != '.':\r
310 Path = os.path.join('.', Path)\r
311\r
312 return Path\r
313\r
314## CleanString\r
315#\r
316# Remove comments in a string\r
317# Remove spaces\r
318#\r
319# @param Line: The string to be cleaned\r
320# @param CommentCharacter: Comment char, used to ignore comment content, default is DataType.TAB_COMMENT_SPLIT\r
321#\r
322# @retval Path Formatted path\r
323#\r
64b2609f 324def CleanString(Line, CommentCharacter=DataType.TAB_COMMENT_SPLIT, AllowCppStyleComment=False, BuildOption=False):\r
30fdf114
LG
325 #\r
326 # remove whitespace\r
327 #\r
328 Line = Line.strip();\r
329 #\r
b36d134f 330 # Replace Edk's comment character\r
30fdf114
LG
331 #\r
332 if AllowCppStyleComment:\r
b36d134f 333 Line = Line.replace(DataType.TAB_COMMENT_EDK_SPLIT, CommentCharacter)\r
30fdf114 334 #\r
9053bc51 335 # remove comments, but we should escape comment character in string\r
30fdf114 336 #\r
9053bc51 337 InString = False\r
b36d134f 338 CommentInString = False\r
9053bc51 339 for Index in range(0, len(Line)):\r
340 if Line[Index] == '"':\r
341 InString = not InString\r
b36d134f
LG
342 elif Line[Index] == CommentCharacter and InString :\r
343 CommentInString = True\r
344 elif Line[Index] == CommentCharacter and not InString :\r
9053bc51 345 Line = Line[0: Index]\r
346 break\r
d40b2ee6 347\r
64b2609f 348 if CommentInString and BuildOption:\r
b36d134f
LG
349 Line = Line.replace('"', '')\r
350 ChIndex = Line.find('#')\r
351 while ChIndex >= 0:\r
352 if GlobalData.gIsWindows:\r
d40b2ee6 353 if ChIndex == 0 or Line[ChIndex - 1] != '^':\r
b36d134f
LG
354 Line = Line[0:ChIndex] + '^' + Line[ChIndex:]\r
355 ChIndex = Line.find('#', ChIndex + 2)\r
356 else:\r
357 ChIndex = Line.find('#', ChIndex + 1)\r
358 else:\r
d40b2ee6 359 if ChIndex == 0 or Line[ChIndex - 1] != '\\':\r
b36d134f
LG
360 Line = Line[0:ChIndex] + '\\' + Line[ChIndex:]\r
361 ChIndex = Line.find('#', ChIndex + 2)\r
362 else:\r
363 ChIndex = Line.find('#', ChIndex + 1)\r
30fdf114
LG
364 #\r
365 # remove whitespace again\r
366 #\r
367 Line = Line.strip();\r
368\r
369 return Line\r
370\r
e56468c0 371## CleanString2\r
372#\r
4afd3d04 373# Split statement with comments in a string\r
e56468c0 374# Remove spaces\r
375#\r
376# @param Line: The string to be cleaned\r
377# @param CommentCharacter: Comment char, used to ignore comment content, default is DataType.TAB_COMMENT_SPLIT\r
378#\r
379# @retval Path Formatted path\r
380#\r
d40b2ee6 381def CleanString2(Line, CommentCharacter=DataType.TAB_COMMENT_SPLIT, AllowCppStyleComment=False):\r
e56468c0 382 #\r
383 # remove whitespace\r
384 #\r
385 Line = Line.strip();\r
386 #\r
b36d134f 387 # Replace Edk's comment character\r
e56468c0 388 #\r
389 if AllowCppStyleComment:\r
b36d134f 390 Line = Line.replace(DataType.TAB_COMMENT_EDK_SPLIT, CommentCharacter)\r
e56468c0 391 #\r
4afd3d04 392 # separate comments and statements, but we should escape comment character in string\r
e56468c0 393 #\r
4afd3d04
LG
394 InString = False\r
395 CommentInString = False\r
396 Comment = ''\r
397 for Index in range(0, len(Line)):\r
398 if Line[Index] == '"':\r
399 InString = not InString\r
400 elif Line[Index] == CommentCharacter and InString:\r
401 CommentInString = True\r
402 elif Line[Index] == CommentCharacter and not InString:\r
403 Comment = Line[Index:].strip()\r
404 Line = Line[0:Index].strip()\r
405 break\r
e56468c0 406\r
407 return Line, Comment\r
408\r
30fdf114
LG
409## GetMultipleValuesOfKeyFromLines\r
410#\r
411# Parse multiple strings to clean comment and spaces\r
412# The result is saved to KeyValues\r
413#\r
414# @param Lines: The content to be parsed\r
415# @param Key: Reserved\r
416# @param KeyValues: To store data after parsing\r
417# @param CommentCharacter: Comment char, used to ignore comment content\r
418#\r
419# @retval True Successfully executed\r
420#\r
421def GetMultipleValuesOfKeyFromLines(Lines, Key, KeyValues, CommentCharacter):\r
422 Lines = Lines.split(DataType.TAB_SECTION_END, 1)[1]\r
423 LineList = Lines.split('\n')\r
424 for Line in LineList:\r
425 Line = CleanString(Line, CommentCharacter)\r
426 if Line != '' and Line[0] != CommentCharacter:\r
427 KeyValues += [Line]\r
428\r
429 return True\r
430\r
431## GetDefineValue\r
432#\r
433# Parse a DEFINE statement to get defined value\r
434# DEFINE Key Value\r
435#\r
436# @param String: The content to be parsed\r
437# @param Key: The key of DEFINE statement\r
438# @param CommentCharacter: Comment char, used to ignore comment content\r
439#\r
440# @retval string The defined value\r
441#\r
442def GetDefineValue(String, Key, CommentCharacter):\r
443 String = CleanString(String)\r
444 return String[String.find(Key + ' ') + len(Key + ' ') : ]\r
445\r
08dd311f
LG
446## GetHexVerValue\r
447#\r
448# Get a Hex Version Value\r
449#\r
450# @param VerString: The version string to be parsed\r
451#\r
452#\r
453# @retval: If VerString is incorrectly formatted, return "None" which will break the build.\r
454# If VerString is correctly formatted, return a Hex value of the Version Number (0xmmmmnnnn)\r
455# where mmmm is the major number and nnnn is the adjusted minor number.\r
456#\r
457def GetHexVerValue(VerString):\r
458 VerString = CleanString(VerString)\r
459\r
460 if gHumanReadableVerPatt.match(VerString):\r
461 ValueList = VerString.split('.')\r
462 Major = ValueList[0]\r
463 Minor = ValueList[1]\r
464 if len(Minor) == 1:\r
465 Minor += '0'\r
466 DeciValue = (int(Major) << 16) + int(Minor);\r
d40b2ee6 467 return "0x%08x" % DeciValue\r
08dd311f
LG
468 elif gHexVerPatt.match(VerString):\r
469 return VerString\r
470 else:\r
471 return None\r
472\r
473\r
30fdf114
LG
474## GetSingleValueOfKeyFromLines\r
475#\r
476# Parse multiple strings as below to get value of each definition line\r
477# Key1 = Value1\r
478# Key2 = Value2\r
479# The result is saved to Dictionary\r
480#\r
481# @param Lines: The content to be parsed\r
482# @param Dictionary: To store data after parsing\r
483# @param CommentCharacter: Comment char, be used to ignore comment content\r
484# @param KeySplitCharacter: Key split char, between key name and key value. Key1 = Value1, '=' is the key split char\r
485# @param ValueSplitFlag: Value split flag, be used to decide if has multiple values\r
486# @param ValueSplitCharacter: Value split char, be used to split multiple values. Key1 = Value1|Value2, '|' is the value split char\r
487#\r
488# @retval True Successfully executed\r
489#\r
490def GetSingleValueOfKeyFromLines(Lines, Dictionary, CommentCharacter, KeySplitCharacter, ValueSplitFlag, ValueSplitCharacter):\r
491 Lines = Lines.split('\n')\r
492 Keys = []\r
493 Value = ''\r
494 DefineValues = ['']\r
495 SpecValues = ['']\r
496\r
497 for Line in Lines:\r
498 #\r
499 # Handle DEFINE and SPEC\r
500 #\r
501 if Line.find(DataType.TAB_INF_DEFINES_DEFINE + ' ') > -1:\r
502 if '' in DefineValues:\r
503 DefineValues.remove('')\r
504 DefineValues.append(GetDefineValue(Line, DataType.TAB_INF_DEFINES_DEFINE, CommentCharacter))\r
505 continue\r
506 if Line.find(DataType.TAB_INF_DEFINES_SPEC + ' ') > -1:\r
507 if '' in SpecValues:\r
508 SpecValues.remove('')\r
509 SpecValues.append(GetDefineValue(Line, DataType.TAB_INF_DEFINES_SPEC, CommentCharacter))\r
510 continue\r
511\r
512 #\r
513 # Handle Others\r
514 #\r
515 LineList = Line.split(KeySplitCharacter, 1)\r
516 if len(LineList) >= 2:\r
517 Key = LineList[0].split()\r
518 if len(Key) == 1 and Key[0][0] != CommentCharacter:\r
519 #\r
520 # Remove comments and white spaces\r
521 #\r
522 LineList[1] = CleanString(LineList[1], CommentCharacter)\r
523 if ValueSplitFlag:\r
524 Value = map(string.strip, LineList[1].split(ValueSplitCharacter))\r
525 else:\r
526 Value = CleanString(LineList[1], CommentCharacter).splitlines()\r
527\r
528 if Key[0] in Dictionary:\r
529 if Key[0] not in Keys:\r
530 Dictionary[Key[0]] = Value\r
531 Keys.append(Key[0])\r
532 else:\r
533 Dictionary[Key[0]].extend(Value)\r
534 else:\r
535 Dictionary[DataType.TAB_INF_DEFINES_MACRO][Key[0]] = Value[0]\r
536\r
537 if DefineValues == []:\r
538 DefineValues = ['']\r
539 if SpecValues == []:\r
540 SpecValues = ['']\r
541 Dictionary[DataType.TAB_INF_DEFINES_DEFINE] = DefineValues\r
542 Dictionary[DataType.TAB_INF_DEFINES_SPEC] = SpecValues\r
543\r
544 return True\r
545\r
546## The content to be parsed\r
547#\r
548# Do pre-check for a file before it is parsed\r
549# Check $()\r
550# Check []\r
551#\r
552# @param FileName: Used for error report\r
553# @param FileContent: File content to be parsed\r
554# @param SupSectionTag: Used for error report\r
555#\r
556def PreCheck(FileName, FileContent, SupSectionTag):\r
557 LineNo = 0\r
558 IsFailed = False\r
559 NewFileContent = ''\r
560 for Line in FileContent.splitlines():\r
561 LineNo = LineNo + 1\r
562 #\r
563 # Clean current line\r
564 #\r
565 Line = CleanString(Line)\r
566\r
567 #\r
568 # Remove commented line\r
569 #\r
570 if Line.find(DataType.TAB_COMMA_SPLIT) == 0:\r
571 Line = ''\r
572 #\r
573 # Check $()\r
574 #\r
575 if Line.find('$') > -1:\r
576 if Line.find('$(') < 0 or Line.find(')') < 0:\r
d40b2ee6 577 EdkLogger.error("Parser", FORMAT_INVALID, Line=LineNo, File=FileName, RaiseError=EdkLogger.IsRaiseError)\r
30fdf114
LG
578\r
579 #\r
580 # Check []\r
581 #\r
582 if Line.find('[') > -1 or Line.find(']') > -1:\r
583 #\r
584 # Only get one '[' or one ']'\r
585 #\r
586 if not (Line.find('[') > -1 and Line.find(']') > -1):\r
d40b2ee6 587 EdkLogger.error("Parser", FORMAT_INVALID, Line=LineNo, File=FileName, RaiseError=EdkLogger.IsRaiseError)\r
30fdf114
LG
588\r
589 #\r
590 # Regenerate FileContent\r
591 #\r
592 NewFileContent = NewFileContent + Line + '\r\n'\r
593\r
594 if IsFailed:\r
d40b2ee6 595 EdkLogger.error("Parser", FORMAT_INVALID, Line=LineNo, File=FileName, RaiseError=EdkLogger.IsRaiseError)\r
30fdf114
LG
596\r
597 return NewFileContent\r
598\r
599## CheckFileType\r
600#\r
601# Check if the Filename is including ExtName\r
602# Return True if it exists\r
603# Raise a error message if it not exists\r
604#\r
605# @param CheckFilename: Name of the file to be checked\r
606# @param ExtName: Ext name of the file to be checked\r
607# @param ContainerFilename: The container file which describes the file to be checked, used for error report\r
608# @param SectionName: Used for error report\r
609# @param Line: The line in container file which defines the file to be checked\r
610#\r
611# @retval True The file type is correct\r
612#\r
d40b2ee6 613def CheckFileType(CheckFilename, ExtName, ContainerFilename, SectionName, Line, LineNo= -1):\r
30fdf114
LG
614 if CheckFilename != '' and CheckFilename != None:\r
615 (Root, Ext) = os.path.splitext(CheckFilename)\r
616 if Ext.upper() != ExtName.upper():\r
617 ContainerFile = open(ContainerFilename, 'r').read()\r
618 if LineNo == -1:\r
619 LineNo = GetLineNo(ContainerFile, Line)\r
620 ErrorMsg = "Invalid %s. '%s' is found, but '%s' file is needed" % (SectionName, CheckFilename, ExtName)\r
621 EdkLogger.error("Parser", PARSER_ERROR, ErrorMsg, Line=LineNo,\r
d40b2ee6 622 File=ContainerFilename, RaiseError=EdkLogger.IsRaiseError)\r
30fdf114
LG
623\r
624 return True\r
625\r
626## CheckFileExist\r
627#\r
628# Check if the file exists\r
629# Return True if it exists\r
630# Raise a error message if it not exists\r
631#\r
632# @param CheckFilename: Name of the file to be checked\r
633# @param WorkspaceDir: Current workspace dir\r
634# @param ContainerFilename: The container file which describes the file to be checked, used for error report\r
635# @param SectionName: Used for error report\r
636# @param Line: The line in container file which defines the file to be checked\r
637#\r
638# @retval The file full path if the file exists\r
639#\r
d40b2ee6 640def CheckFileExist(WorkspaceDir, CheckFilename, ContainerFilename, SectionName, Line, LineNo= -1):\r
30fdf114
LG
641 CheckFile = ''\r
642 if CheckFilename != '' and CheckFilename != None:\r
643 CheckFile = WorkspaceFile(WorkspaceDir, CheckFilename)\r
644 if not os.path.isfile(CheckFile):\r
645 ContainerFile = open(ContainerFilename, 'r').read()\r
646 if LineNo == -1:\r
647 LineNo = GetLineNo(ContainerFile, Line)\r
648 ErrorMsg = "Can't find file '%s' defined in section '%s'" % (CheckFile, SectionName)\r
649 EdkLogger.error("Parser", PARSER_ERROR, ErrorMsg,\r
d40b2ee6 650 File=ContainerFilename, Line=LineNo, RaiseError=EdkLogger.IsRaiseError)\r
30fdf114
LG
651\r
652 return CheckFile\r
653\r
654## GetLineNo\r
655#\r
656# Find the index of a line in a file\r
657#\r
658# @param FileContent: Search scope\r
659# @param Line: Search key\r
660#\r
661# @retval int Index of the line\r
662# @retval -1 The line is not found\r
663#\r
d40b2ee6 664def GetLineNo(FileContent, Line, IsIgnoreComment=True):\r
30fdf114
LG
665 LineList = FileContent.splitlines()\r
666 for Index in range(len(LineList)):\r
667 if LineList[Index].find(Line) > -1:\r
668 #\r
669 # Ignore statement in comment\r
670 #\r
671 if IsIgnoreComment:\r
672 if LineList[Index].strip()[0] == DataType.TAB_COMMENT_SPLIT:\r
673 continue\r
674 return Index + 1\r
675\r
676 return -1\r
677\r
678## RaiseParserError\r
679#\r
680# Raise a parser error\r
681#\r
682# @param Line: String which has error\r
683# @param Section: Used for error report\r
684# @param File: File which has the string\r
685# @param Format: Correct format\r
686#\r
d40b2ee6 687def RaiseParserError(Line, Section, File, Format='', LineNo= -1):\r
30fdf114
LG
688 if LineNo == -1:\r
689 LineNo = GetLineNo(open(os.path.normpath(File), 'r').read(), Line)\r
690 ErrorMsg = "Invalid statement '%s' is found in section '%s'" % (Line, Section)\r
691 if Format != '':\r
692 Format = "Correct format is " + Format\r
d40b2ee6 693 EdkLogger.error("Parser", PARSER_ERROR, ErrorMsg, File=File, Line=LineNo, ExtraData=Format, RaiseError=EdkLogger.IsRaiseError)\r
30fdf114
LG
694\r
695## WorkspaceFile\r
696#\r
697# Return a full path with workspace dir\r
698#\r
699# @param WorkspaceDir: Workspace dir\r
700# @param Filename: Relative file name\r
701#\r
702# @retval string A full path\r
703#\r
704def WorkspaceFile(WorkspaceDir, Filename):\r
705 return os.path.join(NormPath(WorkspaceDir), NormPath(Filename))\r
706\r
707## Split string\r
708#\r
709# Revmove '"' which startswith and endswith string\r
710#\r
711# @param String: The string need to be splited\r
712#\r
713# @retval String: The string after removed '""'\r
714#\r
715def SplitString(String):\r
716 if String.startswith('\"'):\r
717 String = String[1:]\r
718 if String.endswith('\"'):\r
719 String = String[:-1]\r
720\r
721 return String\r
722\r
723## Convert To Sql String\r
724#\r
725# 1. Replace "'" with "''" in each item of StringList\r
726#\r
727# @param StringList: A list for strings to be converted\r
728#\r
729def ConvertToSqlString(StringList):\r
730 return map(lambda s: s.replace("'", "''") , StringList)\r
731\r
732## Convert To Sql String\r
733#\r
734# 1. Replace "'" with "''" in the String\r
735#\r
736# @param String: A String to be converted\r
737#\r
738def ConvertToSqlString2(String):\r
739 return String.replace("'", "''")\r
740\r
741#\r
742# Remove comment block\r
743#\r
744def RemoveBlockComment(Lines):\r
745 IsFindBlockComment = False\r
746 IsFindBlockCode = False\r
747 ReservedLine = ''\r
748 NewLines = []\r
749\r
750 for Line in Lines:\r
751 Line = Line.strip()\r
752 #\r
753 # Remove comment block\r
754 #\r
b36d134f 755 if Line.find(DataType.TAB_COMMENT_EDK_START) > -1:\r
d40b2ee6 756 ReservedLine = GetSplitList(Line, DataType.TAB_COMMENT_EDK_START, 1)[0]\r
30fdf114 757 IsFindBlockComment = True\r
b36d134f 758 if Line.find(DataType.TAB_COMMENT_EDK_END) > -1:\r
d40b2ee6 759 Line = ReservedLine + GetSplitList(Line, DataType.TAB_COMMENT_EDK_END, 1)[1]\r
30fdf114
LG
760 ReservedLine = ''\r
761 IsFindBlockComment = False\r
762 if IsFindBlockComment:\r
763 NewLines.append('')\r
764 continue\r
765\r
766 NewLines.append(Line)\r
767 return NewLines\r
768\r
769#\r
770# Get String of a List\r
771#\r
d40b2ee6 772def GetStringOfList(List, Split=' '):\r
30fdf114
LG
773 if type(List) != type([]):\r
774 return List\r
775 Str = ''\r
776 for Item in List:\r
777 Str = Str + Item + Split\r
778\r
779 return Str.strip()\r
780\r
781#\r
782# Get HelpTextList from HelpTextClassList\r
783#\r
784def GetHelpTextList(HelpTextClassList):\r
785 List = []\r
786 if HelpTextClassList:\r
787 for HelpText in HelpTextClassList:\r
788 if HelpText.String.endswith('\n'):\r
789 HelpText.String = HelpText.String[0: len(HelpText.String) - len('\n')]\r
790 List.extend(HelpText.String.split('\n'))\r
791\r
792 return List\r
793\r
794def StringToArray(String):\r
795 if isinstance(String, unicode):\r
d40b2ee6 796 if len(unicode) == 0:\r
30fdf114
LG
797 return "{0x00, 0x00}"\r
798 return "{%s, 0x00, 0x00}" % ", ".join(["0x%02x, 0x00" % ord(C) for C in String])\r
799 elif String.startswith('L"'):\r
800 if String == "L\"\"":\r
801 return "{0x00, 0x00}"\r
802 else:\r
803 return "{%s, 0x00, 0x00}" % ", ".join(["0x%02x, 0x00" % ord(C) for C in String[2:-1]])\r
804 elif String.startswith('"'):\r
805 if String == "\"\"":\r
2bc3256c 806 return "{0x00,0x00}"\r
30fdf114 807 else:\r
2bc3256c
LG
808 StringLen = len(String[1:-1])\r
809 if StringLen % 2:\r
810 return "{%s, 0x00}" % ", ".join(["0x%02x" % ord(C) for C in String[1:-1]])\r
811 else:\r
812 return "{%s, 0x00,0x00}" % ", ".join(["0x%02x" % ord(C) for C in String[1:-1]])\r
813 elif String.startswith('{'):\r
814 StringLen = len(String.split(","))\r
815 if StringLen % 2:\r
816 return "{%s, 0x00}" % ", ".join([ C for C in String[1:-1].split(',')])\r
817 else:\r
818 return "{%s}" % ", ".join([ C for C in String[1:-1].split(',')])\r
819 \r
30fdf114 820 else:\r
2bc3256c
LG
821 if len(String.split()) % 2:\r
822 return '{%s, 0}' % ', '.join(String.split())\r
823 else:\r
824 return '{%s, 0,0}' % ', '.join(String.split())\r
30fdf114
LG
825\r
826def StringArrayLength(String):\r
827 if isinstance(String, unicode):\r
828 return (len(String) + 1) * 2 + 1;\r
829 elif String.startswith('L"'):\r
830 return (len(String) - 3 + 1) * 2\r
831 elif String.startswith('"'):\r
832 return (len(String) - 2 + 1)\r
833 else:\r
834 return len(String.split()) + 1\r
d40b2ee6 835\r
30fdf114
LG
836def RemoveDupOption(OptionString, Which="/I", Against=None):\r
837 OptionList = OptionString.split()\r
838 ValueList = []\r
839 if Against:\r
840 ValueList += Against\r
841 for Index in range(len(OptionList)):\r
842 Opt = OptionList[Index]\r
843 if not Opt.startswith(Which):\r
844 continue\r
845 if len(Opt) > len(Which):\r
846 Val = Opt[len(Which):]\r
847 else:\r
848 Val = ""\r
849 if Val in ValueList:\r
850 OptionList[Index] = ""\r
851 else:\r
852 ValueList.append(Val)\r
853 return " ".join(OptionList)\r
854\r
855##\r
856#\r
857# This acts like the main() function for the script, unless it is 'import'ed into another\r
858# script.\r
859#\r
860if __name__ == '__main__':\r
861 pass\r
862\r