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