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