]> git.proxmox.com Git - mirror_edk2.git/blame - BaseTools/Source/Python/Common/String.py
ShellPkg: Fix EFI_SHELL_DYNAMIC_COMMAND_PROTOCOL_GUID to match UEFI Shell 2.1 spec
[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
e56468c0 404\r
405 return Line, Comment\r
406\r
30fdf114
LG
407## GetMultipleValuesOfKeyFromLines\r
408#\r
409# Parse multiple strings to clean comment and spaces\r
410# The result is saved to KeyValues\r
411#\r
412# @param Lines: The content to be parsed\r
413# @param Key: Reserved\r
414# @param KeyValues: To store data after parsing\r
415# @param CommentCharacter: Comment char, used to ignore comment content\r
416#\r
417# @retval True Successfully executed\r
418#\r
419def GetMultipleValuesOfKeyFromLines(Lines, Key, KeyValues, CommentCharacter):\r
420 Lines = Lines.split(DataType.TAB_SECTION_END, 1)[1]\r
421 LineList = Lines.split('\n')\r
422 for Line in LineList:\r
423 Line = CleanString(Line, CommentCharacter)\r
424 if Line != '' and Line[0] != CommentCharacter:\r
425 KeyValues += [Line]\r
426\r
427 return True\r
428\r
429## GetDefineValue\r
430#\r
431# Parse a DEFINE statement to get defined value\r
432# DEFINE Key Value\r
433#\r
434# @param String: The content to be parsed\r
435# @param Key: The key of DEFINE statement\r
436# @param CommentCharacter: Comment char, used to ignore comment content\r
437#\r
438# @retval string The defined value\r
439#\r
440def GetDefineValue(String, Key, CommentCharacter):\r
441 String = CleanString(String)\r
442 return String[String.find(Key + ' ') + len(Key + ' ') : ]\r
443\r
08dd311f
LG
444## GetHexVerValue\r
445#\r
446# Get a Hex Version Value\r
447#\r
448# @param VerString: The version string to be parsed\r
449#\r
450#\r
451# @retval: If VerString is incorrectly formatted, return "None" which will break the build.\r
452# If VerString is correctly formatted, return a Hex value of the Version Number (0xmmmmnnnn)\r
453# where mmmm is the major number and nnnn is the adjusted minor number.\r
454#\r
455def GetHexVerValue(VerString):\r
456 VerString = CleanString(VerString)\r
457\r
458 if gHumanReadableVerPatt.match(VerString):\r
459 ValueList = VerString.split('.')\r
460 Major = ValueList[0]\r
461 Minor = ValueList[1]\r
462 if len(Minor) == 1:\r
463 Minor += '0'\r
464 DeciValue = (int(Major) << 16) + int(Minor);\r
d40b2ee6 465 return "0x%08x" % DeciValue\r
08dd311f
LG
466 elif gHexVerPatt.match(VerString):\r
467 return VerString\r
468 else:\r
469 return None\r
470\r
471\r
30fdf114
LG
472## GetSingleValueOfKeyFromLines\r
473#\r
474# Parse multiple strings as below to get value of each definition line\r
475# Key1 = Value1\r
476# Key2 = Value2\r
477# The result is saved to Dictionary\r
478#\r
479# @param Lines: The content to be parsed\r
480# @param Dictionary: To store data after parsing\r
481# @param CommentCharacter: Comment char, be used to ignore comment content\r
482# @param KeySplitCharacter: Key split char, between key name and key value. Key1 = Value1, '=' is the key split char\r
483# @param ValueSplitFlag: Value split flag, be used to decide if has multiple values\r
484# @param ValueSplitCharacter: Value split char, be used to split multiple values. Key1 = Value1|Value2, '|' is the value split char\r
485#\r
486# @retval True Successfully executed\r
487#\r
488def GetSingleValueOfKeyFromLines(Lines, Dictionary, CommentCharacter, KeySplitCharacter, ValueSplitFlag, ValueSplitCharacter):\r
489 Lines = Lines.split('\n')\r
490 Keys = []\r
491 Value = ''\r
492 DefineValues = ['']\r
493 SpecValues = ['']\r
494\r
495 for Line in Lines:\r
496 #\r
497 # Handle DEFINE and SPEC\r
498 #\r
499 if Line.find(DataType.TAB_INF_DEFINES_DEFINE + ' ') > -1:\r
500 if '' in DefineValues:\r
501 DefineValues.remove('')\r
502 DefineValues.append(GetDefineValue(Line, DataType.TAB_INF_DEFINES_DEFINE, CommentCharacter))\r
503 continue\r
504 if Line.find(DataType.TAB_INF_DEFINES_SPEC + ' ') > -1:\r
505 if '' in SpecValues:\r
506 SpecValues.remove('')\r
507 SpecValues.append(GetDefineValue(Line, DataType.TAB_INF_DEFINES_SPEC, CommentCharacter))\r
508 continue\r
509\r
510 #\r
511 # Handle Others\r
512 #\r
513 LineList = Line.split(KeySplitCharacter, 1)\r
514 if len(LineList) >= 2:\r
515 Key = LineList[0].split()\r
516 if len(Key) == 1 and Key[0][0] != CommentCharacter:\r
517 #\r
518 # Remove comments and white spaces\r
519 #\r
520 LineList[1] = CleanString(LineList[1], CommentCharacter)\r
521 if ValueSplitFlag:\r
522 Value = map(string.strip, LineList[1].split(ValueSplitCharacter))\r
523 else:\r
524 Value = CleanString(LineList[1], CommentCharacter).splitlines()\r
525\r
526 if Key[0] in Dictionary:\r
527 if Key[0] not in Keys:\r
528 Dictionary[Key[0]] = Value\r
529 Keys.append(Key[0])\r
530 else:\r
531 Dictionary[Key[0]].extend(Value)\r
532 else:\r
533 Dictionary[DataType.TAB_INF_DEFINES_MACRO][Key[0]] = Value[0]\r
534\r
535 if DefineValues == []:\r
536 DefineValues = ['']\r
537 if SpecValues == []:\r
538 SpecValues = ['']\r
539 Dictionary[DataType.TAB_INF_DEFINES_DEFINE] = DefineValues\r
540 Dictionary[DataType.TAB_INF_DEFINES_SPEC] = SpecValues\r
541\r
542 return True\r
543\r
544## The content to be parsed\r
545#\r
546# Do pre-check for a file before it is parsed\r
547# Check $()\r
548# Check []\r
549#\r
550# @param FileName: Used for error report\r
551# @param FileContent: File content to be parsed\r
552# @param SupSectionTag: Used for error report\r
553#\r
554def PreCheck(FileName, FileContent, SupSectionTag):\r
555 LineNo = 0\r
556 IsFailed = False\r
557 NewFileContent = ''\r
558 for Line in FileContent.splitlines():\r
559 LineNo = LineNo + 1\r
560 #\r
561 # Clean current line\r
562 #\r
563 Line = CleanString(Line)\r
564\r
565 #\r
566 # Remove commented line\r
567 #\r
568 if Line.find(DataType.TAB_COMMA_SPLIT) == 0:\r
569 Line = ''\r
570 #\r
571 # Check $()\r
572 #\r
573 if Line.find('$') > -1:\r
574 if Line.find('$(') < 0 or Line.find(')') < 0:\r
d40b2ee6 575 EdkLogger.error("Parser", FORMAT_INVALID, Line=LineNo, File=FileName, RaiseError=EdkLogger.IsRaiseError)\r
30fdf114
LG
576\r
577 #\r
578 # Check []\r
579 #\r
580 if Line.find('[') > -1 or Line.find(']') > -1:\r
581 #\r
582 # Only get one '[' or one ']'\r
583 #\r
584 if not (Line.find('[') > -1 and Line.find(']') > -1):\r
d40b2ee6 585 EdkLogger.error("Parser", FORMAT_INVALID, Line=LineNo, File=FileName, RaiseError=EdkLogger.IsRaiseError)\r
30fdf114
LG
586\r
587 #\r
588 # Regenerate FileContent\r
589 #\r
590 NewFileContent = NewFileContent + Line + '\r\n'\r
591\r
592 if IsFailed:\r
d40b2ee6 593 EdkLogger.error("Parser", FORMAT_INVALID, Line=LineNo, File=FileName, RaiseError=EdkLogger.IsRaiseError)\r
30fdf114
LG
594\r
595 return NewFileContent\r
596\r
597## CheckFileType\r
598#\r
599# Check if the Filename is including ExtName\r
600# Return True if it exists\r
601# Raise a error message if it not exists\r
602#\r
603# @param CheckFilename: Name of the file to be checked\r
604# @param ExtName: Ext name of the file to be checked\r
605# @param ContainerFilename: The container file which describes the file to be checked, used for error report\r
606# @param SectionName: Used for error report\r
607# @param Line: The line in container file which defines the file to be checked\r
608#\r
609# @retval True The file type is correct\r
610#\r
d40b2ee6 611def CheckFileType(CheckFilename, ExtName, ContainerFilename, SectionName, Line, LineNo= -1):\r
30fdf114
LG
612 if CheckFilename != '' and CheckFilename != None:\r
613 (Root, Ext) = os.path.splitext(CheckFilename)\r
614 if Ext.upper() != ExtName.upper():\r
615 ContainerFile = open(ContainerFilename, 'r').read()\r
616 if LineNo == -1:\r
617 LineNo = GetLineNo(ContainerFile, Line)\r
618 ErrorMsg = "Invalid %s. '%s' is found, but '%s' file is needed" % (SectionName, CheckFilename, ExtName)\r
619 EdkLogger.error("Parser", PARSER_ERROR, ErrorMsg, Line=LineNo,\r
d40b2ee6 620 File=ContainerFilename, RaiseError=EdkLogger.IsRaiseError)\r
30fdf114
LG
621\r
622 return True\r
623\r
624## CheckFileExist\r
625#\r
626# Check if the file exists\r
627# Return True if it exists\r
628# Raise a error message if it not exists\r
629#\r
630# @param CheckFilename: Name of the file to be checked\r
631# @param WorkspaceDir: Current workspace dir\r
632# @param ContainerFilename: The container file which describes the file to be checked, used for error report\r
633# @param SectionName: Used for error report\r
634# @param Line: The line in container file which defines the file to be checked\r
635#\r
636# @retval The file full path if the file exists\r
637#\r
d40b2ee6 638def CheckFileExist(WorkspaceDir, CheckFilename, ContainerFilename, SectionName, Line, LineNo= -1):\r
30fdf114
LG
639 CheckFile = ''\r
640 if CheckFilename != '' and CheckFilename != None:\r
641 CheckFile = WorkspaceFile(WorkspaceDir, CheckFilename)\r
642 if not os.path.isfile(CheckFile):\r
643 ContainerFile = open(ContainerFilename, 'r').read()\r
644 if LineNo == -1:\r
645 LineNo = GetLineNo(ContainerFile, Line)\r
646 ErrorMsg = "Can't find file '%s' defined in section '%s'" % (CheckFile, SectionName)\r
647 EdkLogger.error("Parser", PARSER_ERROR, ErrorMsg,\r
d40b2ee6 648 File=ContainerFilename, Line=LineNo, RaiseError=EdkLogger.IsRaiseError)\r
30fdf114
LG
649\r
650 return CheckFile\r
651\r
652## GetLineNo\r
653#\r
654# Find the index of a line in a file\r
655#\r
656# @param FileContent: Search scope\r
657# @param Line: Search key\r
658#\r
659# @retval int Index of the line\r
660# @retval -1 The line is not found\r
661#\r
d40b2ee6 662def GetLineNo(FileContent, Line, IsIgnoreComment=True):\r
30fdf114
LG
663 LineList = FileContent.splitlines()\r
664 for Index in range(len(LineList)):\r
665 if LineList[Index].find(Line) > -1:\r
666 #\r
667 # Ignore statement in comment\r
668 #\r
669 if IsIgnoreComment:\r
670 if LineList[Index].strip()[0] == DataType.TAB_COMMENT_SPLIT:\r
671 continue\r
672 return Index + 1\r
673\r
674 return -1\r
675\r
676## RaiseParserError\r
677#\r
678# Raise a parser error\r
679#\r
680# @param Line: String which has error\r
681# @param Section: Used for error report\r
682# @param File: File which has the string\r
683# @param Format: Correct format\r
684#\r
d40b2ee6 685def RaiseParserError(Line, Section, File, Format='', LineNo= -1):\r
30fdf114
LG
686 if LineNo == -1:\r
687 LineNo = GetLineNo(open(os.path.normpath(File), 'r').read(), Line)\r
688 ErrorMsg = "Invalid statement '%s' is found in section '%s'" % (Line, Section)\r
689 if Format != '':\r
690 Format = "Correct format is " + Format\r
d40b2ee6 691 EdkLogger.error("Parser", PARSER_ERROR, ErrorMsg, File=File, Line=LineNo, ExtraData=Format, RaiseError=EdkLogger.IsRaiseError)\r
30fdf114
LG
692\r
693## WorkspaceFile\r
694#\r
695# Return a full path with workspace dir\r
696#\r
697# @param WorkspaceDir: Workspace dir\r
698# @param Filename: Relative file name\r
699#\r
700# @retval string A full path\r
701#\r
702def WorkspaceFile(WorkspaceDir, Filename):\r
703 return os.path.join(NormPath(WorkspaceDir), NormPath(Filename))\r
704\r
705## Split string\r
706#\r
707# Revmove '"' which startswith and endswith string\r
708#\r
709# @param String: The string need to be splited\r
710#\r
711# @retval String: The string after removed '""'\r
712#\r
713def SplitString(String):\r
714 if String.startswith('\"'):\r
715 String = String[1:]\r
716 if String.endswith('\"'):\r
717 String = String[:-1]\r
718\r
719 return String\r
720\r
721## Convert To Sql String\r
722#\r
723# 1. Replace "'" with "''" in each item of StringList\r
724#\r
725# @param StringList: A list for strings to be converted\r
726#\r
727def ConvertToSqlString(StringList):\r
728 return map(lambda s: s.replace("'", "''") , StringList)\r
729\r
730## Convert To Sql String\r
731#\r
732# 1. Replace "'" with "''" in the String\r
733#\r
734# @param String: A String to be converted\r
735#\r
736def ConvertToSqlString2(String):\r
737 return String.replace("'", "''")\r
738\r
739#\r
740# Remove comment block\r
741#\r
742def RemoveBlockComment(Lines):\r
743 IsFindBlockComment = False\r
744 IsFindBlockCode = False\r
745 ReservedLine = ''\r
746 NewLines = []\r
747\r
748 for Line in Lines:\r
749 Line = Line.strip()\r
750 #\r
751 # Remove comment block\r
752 #\r
b36d134f 753 if Line.find(DataType.TAB_COMMENT_EDK_START) > -1:\r
d40b2ee6 754 ReservedLine = GetSplitList(Line, DataType.TAB_COMMENT_EDK_START, 1)[0]\r
30fdf114 755 IsFindBlockComment = True\r
b36d134f 756 if Line.find(DataType.TAB_COMMENT_EDK_END) > -1:\r
d40b2ee6 757 Line = ReservedLine + GetSplitList(Line, DataType.TAB_COMMENT_EDK_END, 1)[1]\r
30fdf114
LG
758 ReservedLine = ''\r
759 IsFindBlockComment = False\r
760 if IsFindBlockComment:\r
761 NewLines.append('')\r
762 continue\r
763\r
764 NewLines.append(Line)\r
765 return NewLines\r
766\r
767#\r
768# Get String of a List\r
769#\r
d40b2ee6 770def GetStringOfList(List, Split=' '):\r
30fdf114
LG
771 if type(List) != type([]):\r
772 return List\r
773 Str = ''\r
774 for Item in List:\r
775 Str = Str + Item + Split\r
776\r
777 return Str.strip()\r
778\r
779#\r
780# Get HelpTextList from HelpTextClassList\r
781#\r
782def GetHelpTextList(HelpTextClassList):\r
783 List = []\r
784 if HelpTextClassList:\r
785 for HelpText in HelpTextClassList:\r
786 if HelpText.String.endswith('\n'):\r
787 HelpText.String = HelpText.String[0: len(HelpText.String) - len('\n')]\r
788 List.extend(HelpText.String.split('\n'))\r
789\r
790 return List\r
791\r
792def StringToArray(String):\r
793 if isinstance(String, unicode):\r
d40b2ee6 794 if len(unicode) == 0:\r
30fdf114
LG
795 return "{0x00, 0x00}"\r
796 return "{%s, 0x00, 0x00}" % ", ".join(["0x%02x, 0x00" % ord(C) for C in String])\r
797 elif String.startswith('L"'):\r
798 if String == "L\"\"":\r
799 return "{0x00, 0x00}"\r
800 else:\r
801 return "{%s, 0x00, 0x00}" % ", ".join(["0x%02x, 0x00" % ord(C) for C in String[2:-1]])\r
802 elif String.startswith('"'):\r
803 if String == "\"\"":\r
2bc3256c 804 return "{0x00,0x00}"\r
30fdf114 805 else:\r
2bc3256c
LG
806 StringLen = len(String[1:-1])\r
807 if StringLen % 2:\r
808 return "{%s, 0x00}" % ", ".join(["0x%02x" % ord(C) for C in String[1:-1]])\r
809 else:\r
810 return "{%s, 0x00,0x00}" % ", ".join(["0x%02x" % ord(C) for C in String[1:-1]])\r
811 elif String.startswith('{'):\r
812 StringLen = len(String.split(","))\r
813 if StringLen % 2:\r
814 return "{%s, 0x00}" % ", ".join([ C for C in String[1:-1].split(',')])\r
815 else:\r
816 return "{%s}" % ", ".join([ C for C in String[1:-1].split(',')])\r
817 \r
30fdf114 818 else:\r
2bc3256c
LG
819 if len(String.split()) % 2:\r
820 return '{%s, 0}' % ', '.join(String.split())\r
821 else:\r
822 return '{%s, 0,0}' % ', '.join(String.split())\r
30fdf114
LG
823\r
824def StringArrayLength(String):\r
825 if isinstance(String, unicode):\r
826 return (len(String) + 1) * 2 + 1;\r
827 elif String.startswith('L"'):\r
828 return (len(String) - 3 + 1) * 2\r
829 elif String.startswith('"'):\r
830 return (len(String) - 2 + 1)\r
831 else:\r
832 return len(String.split()) + 1\r
d40b2ee6 833\r
30fdf114
LG
834def RemoveDupOption(OptionString, Which="/I", Against=None):\r
835 OptionList = OptionString.split()\r
836 ValueList = []\r
837 if Against:\r
838 ValueList += Against\r
839 for Index in range(len(OptionList)):\r
840 Opt = OptionList[Index]\r
841 if not Opt.startswith(Which):\r
842 continue\r
843 if len(Opt) > len(Which):\r
844 Val = Opt[len(Which):]\r
845 else:\r
846 Val = ""\r
847 if Val in ValueList:\r
848 OptionList[Index] = ""\r
849 else:\r
850 ValueList.append(Val)\r
851 return " ".join(OptionList)\r
852\r
853##\r
854#\r
855# This acts like the main() function for the script, unless it is 'import'ed into another\r
856# script.\r
857#\r
858if __name__ == '__main__':\r
859 pass\r
860\r