]>
git.proxmox.com Git - mirror_edk2.git/blob - BaseTools/Source/Python/Common/String.py
2 # This file is used to define common string related functions used in parsing process
4 # Copyright (c) 2007 - 2018, Intel Corporation. All rights reserved.<BR>
5 # This program and the accompanying materials
6 # are licensed and made available under the terms and conditions of the BSD License
7 # which accompanies this distribution. The full text of the license may be found at
8 # http://opensource.org/licenses/bsd-license.php
10 # THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
19 import Common
.LongFilePathOs
as os
21 import EdkLogger
as EdkLogger
24 from BuildToolError
import *
25 from CommonDataClass
.Exceptions
import *
26 from Common
.LongFilePathSupport
import OpenLongFilePath
as open
27 from Common
.MultipleWorkspace
import MultipleWorkspace
as mws
29 gHexVerPatt
= re
.compile('0x[a-f0-9]{4}[a-f0-9]{4}$', re
.IGNORECASE
)
30 gHumanReadableVerPatt
= re
.compile(r
'([1-9][0-9]*|0)\.[0-9]{1,2}$')
34 # Get a value list from a string with multiple values splited with SplitTag
35 # The default SplitTag is DataType.TAB_VALUE_SPLIT
36 # 'AAA|BBB|CCC' -> ['AAA', 'BBB', 'CCC']
38 # @param String: The input string to be splitted
39 # @param SplitTag: The split key, default is DataType.TAB_VALUE_SPLIT
40 # @param MaxSplit: The max number of split values, default is -1
42 # @retval list() A list for splitted string
44 def GetSplitValueList(String
, SplitTag
=DataType
.TAB_VALUE_SPLIT
, MaxSplit
= -1):
48 InSingleQuoteString
= False
49 InDoubleQuoteString
= False
51 for Index
in range(0, len(String
)):
55 # Found a splitter not in a string, split it
56 if (not InSingleQuoteString
or not InDoubleQuoteString
) and InParenthesis
== 0 and Char
== SplitTag
:
57 ValueList
.append(String
[Last
:Index
].strip())
59 if MaxSplit
> 0 and len(ValueList
) >= MaxSplit
:
62 if Char
== '\\' and (InSingleQuoteString
or InDoubleQuoteString
):
64 elif Char
== '"' and not InSingleQuoteString
:
65 if not InDoubleQuoteString
:
66 InDoubleQuoteString
= True
68 InDoubleQuoteString
= False
69 elif Char
== "'" and not InDoubleQuoteString
:
70 if not InSingleQuoteString
:
71 InSingleQuoteString
= True
73 InSingleQuoteString
= False
75 InParenthesis
= InParenthesis
+ 1
77 InParenthesis
= InParenthesis
- 1
81 if Last
< len(String
):
82 ValueList
.append(String
[Last
:].strip())
83 elif Last
== len(String
):
90 # Get a value list from a string with multiple values splited with SplitString
91 # The default SplitTag is DataType.TAB_VALUE_SPLIT
92 # 'AAA|BBB|CCC' -> ['AAA', 'BBB', 'CCC']
94 # @param String: The input string to be splitted
95 # @param SplitStr: The split key, default is DataType.TAB_VALUE_SPLIT
96 # @param MaxSplit: The max number of split values, default is -1
98 # @retval list() A list for splitted string
100 def GetSplitList(String
, SplitStr
=DataType
.TAB_VALUE_SPLIT
, MaxSplit
= -1):
101 return map(lambda l
: l
.strip(), String
.split(SplitStr
, MaxSplit
))
105 # Find a key's all arches in dict, add the new arch to the list
106 # If not exist any arch, set the arch directly
108 # @param Dict: The input value for Dict
109 # @param Key: The input value for Key
110 # @param Arch: The Arch to be added or merged
112 def MergeArches(Dict
, Key
, Arch
):
114 Dict
[Key
].append(Arch
)
116 Dict
[Key
] = Arch
.split()
120 # Parse a string with format "DEFINE <VarName> = <PATH>"
121 # Generate a map Defines[VarName] = PATH
122 # Return False if invalid format
124 # @param String: String with DEFINE statement
125 # @param Arch: Supportted Arch
126 # @param Defines: DEFINE statement to be parsed
128 # @retval 0 DEFINE statement found, and valid
129 # @retval 1 DEFINE statement found, but not valid
130 # @retval -1 DEFINE statement not found
132 def GenDefines(String
, Arch
, Defines
):
133 if String
.find(DataType
.TAB_DEFINE
+ ' ') > -1:
134 List
= String
.replace(DataType
.TAB_DEFINE
+ ' ', '').split(DataType
.TAB_EQUAL_SPLIT
)
136 Defines
[(CleanString(List
[0]), Arch
)] = CleanString(List
[1])
145 # Parse a string with format "!include <Filename>"
146 # Return the file path
147 # Return False if invalid format or NOT FOUND
149 # @param String: String with INCLUDE statement
150 # @param IncludeFiles: INCLUDE statement to be parsed
151 # @param Arch: Supportted Arch
156 def GenInclude(String
, IncludeFiles
, Arch
):
157 if String
.upper().find(DataType
.TAB_INCLUDE
.upper() + ' ') > -1:
158 IncludeFile
= CleanString(String
[String
.upper().find(DataType
.TAB_INCLUDE
.upper() + ' ') + len(DataType
.TAB_INCLUDE
+ ' ') : ])
159 MergeArches(IncludeFiles
, IncludeFile
, Arch
)
164 ## GetLibraryClassesWithModuleType
166 # Get Library Class definition when no module type defined
168 # @param Lines: The content to be parsed
169 # @param Key: Reserved
170 # @param KeyValues: To store data after parsing
171 # @param CommentCharacter: Comment char, used to ignore comment content
173 # @retval True Get library classes successfully
175 def GetLibraryClassesWithModuleType(Lines
, Key
, KeyValues
, CommentCharacter
):
176 newKey
= SplitModuleType(Key
)
177 Lines
= Lines
.split(DataType
.TAB_SECTION_END
, 1)[1]
178 LineList
= Lines
.splitlines()
179 for Line
in LineList
:
180 Line
= CleanString(Line
, CommentCharacter
)
181 if Line
!= '' and Line
[0] != CommentCharacter
:
182 KeyValues
.append([CleanString(Line
, CommentCharacter
), newKey
[1]])
190 # @param Lines: The content to be parsed
191 # @param Key: Reserved
192 # @param KeyValues: To store data after parsing
193 # @param CommentCharacter: Comment char, used to ignore comment content
195 # @retval True Get Dynamic Pcds successfully
197 def GetDynamics(Lines
, Key
, KeyValues
, CommentCharacter
):
199 # Get SkuId Name List
201 SkuIdNameList
= SplitModuleType(Key
)
203 Lines
= Lines
.split(DataType
.TAB_SECTION_END
, 1)[1]
204 LineList
= Lines
.splitlines()
205 for Line
in LineList
:
206 Line
= CleanString(Line
, CommentCharacter
)
207 if Line
!= '' and Line
[0] != CommentCharacter
:
208 KeyValues
.append([CleanString(Line
, CommentCharacter
), SkuIdNameList
[1]])
214 # Split ModuleType out of section defien to get key
215 # [LibraryClass.Arch.ModuleType|ModuleType|ModuleType] -> [ 'LibraryClass.Arch', ['ModuleType', 'ModuleType', 'ModuleType'] ]
217 # @param Key: String to be parsed
219 # @retval ReturnValue A list for module types
221 def SplitModuleType(Key
):
222 KeyList
= Key
.split(DataType
.TAB_SPLIT
)
228 # Fill in for moduletype
232 KeyValue
= KeyList
[0]
234 KeyValue
= KeyValue
+ DataType
.TAB_SPLIT
+ KeyList
[1]
235 ReturnValue
.append(KeyValue
)
236 ReturnValue
.append(GetSplitValueList(KeyList
[2]))
240 ## Replace macro in strings list
242 # This method replace macros used in a given string list. The macros are
243 # given in a dictionary.
245 # @param StringList StringList to be processed
246 # @param MacroDefinitions The macro definitions in the form of dictionary
247 # @param SelfReplacement To decide whether replace un-defined macro to ''
249 # @retval NewList A new string list whose macros are replaced
251 def ReplaceMacros(StringList
, MacroDefinitions
={}, SelfReplacement
=False):
253 for String
in StringList
:
254 if type(String
) == type(''):
255 NewList
.append(ReplaceMacro(String
, MacroDefinitions
, SelfReplacement
))
257 NewList
.append(String
)
261 ## Replace macro in string
263 # This method replace macros used in given string. The macros are given in a
266 # @param String String to be processed
267 # @param MacroDefinitions The macro definitions in the form of dictionary
268 # @param SelfReplacement To decide whether replace un-defined macro to ''
270 # @retval string The string whose macros are replaced
272 def ReplaceMacro(String
, MacroDefinitions
={}, SelfReplacement
=False, RaiseError
=False):
274 while String
and MacroDefinitions
:
275 MacroUsed
= GlobalData
.gMacroRefPattern
.findall(String
)
276 # no macro found in String, stop replacing
277 if len(MacroUsed
) == 0:
280 for Macro
in MacroUsed
:
281 if Macro
not in MacroDefinitions
:
283 raise SymbolNotFound("%s not defined" % Macro
)
285 String
= String
.replace("$(%s)" % Macro
, '')
287 if "$(%s)" % Macro
not in MacroDefinitions
[Macro
]:
288 String
= String
.replace("$(%s)" % Macro
, MacroDefinitions
[Macro
])
289 # in case there's macro not defined
290 if String
== LastString
:
298 # Create a normal path
299 # And replace DFEINE in the path
301 # @param Path: The input value for Path to be converted
302 # @param Defines: A set for DEFINE statement
304 # @retval Path Formatted path
306 def NormPath(Path
, Defines
={}):
307 IsRelativePath
= False
310 IsRelativePath
= True
312 # Replace with Define
315 Path
= ReplaceMacro(Path
, Defines
)
317 # To local path format
319 Path
= os
.path
.normpath(Path
)
320 if Path
.startswith(GlobalData
.gWorkspace
) and not Path
.startswith(GlobalData
.gBuildDirectory
) and not os
.path
.exists(Path
):
321 Path
= Path
[len (GlobalData
.gWorkspace
):]
322 if Path
[0] == os
.path
.sep
:
324 Path
= mws
.join(GlobalData
.gWorkspace
, Path
)
326 if IsRelativePath
and Path
[0] != '.':
327 Path
= os
.path
.join('.', Path
)
333 # Remove comments in a string
336 # @param Line: The string to be cleaned
337 # @param CommentCharacter: Comment char, used to ignore comment content, default is DataType.TAB_COMMENT_SPLIT
339 # @retval Path Formatted path
341 def CleanString(Line
, CommentCharacter
=DataType
.TAB_COMMENT_SPLIT
, AllowCppStyleComment
=False, BuildOption
=False):
347 # Replace Edk's comment character
349 if AllowCppStyleComment
:
350 Line
= Line
.replace(DataType
.TAB_COMMENT_EDK_SPLIT
, CommentCharacter
)
352 # remove comments, but we should escape comment character in string
354 InDoubleQuoteString
= False
355 InSingleQuoteString
= False
356 CommentInString
= False
357 for Index
in range(0, len(Line
)):
358 if Line
[Index
] == '"' and not InSingleQuoteString
:
359 InDoubleQuoteString
= not InDoubleQuoteString
360 elif Line
[Index
] == "'" and not InDoubleQuoteString
:
361 InSingleQuoteString
= not InSingleQuoteString
362 elif Line
[Index
] == CommentCharacter
and (InSingleQuoteString
or InDoubleQuoteString
):
363 CommentInString
= True
364 elif Line
[Index
] == CommentCharacter
and not (InSingleQuoteString
or InDoubleQuoteString
):
365 Line
= Line
[0: Index
]
368 if CommentInString
and BuildOption
:
369 Line
= Line
.replace('"', '')
370 ChIndex
= Line
.find('#')
372 if GlobalData
.gIsWindows
:
373 if ChIndex
== 0 or Line
[ChIndex
- 1] != '^':
374 Line
= Line
[0:ChIndex
] + '^' + Line
[ChIndex
:]
375 ChIndex
= Line
.find('#', ChIndex
+ 2)
377 ChIndex
= Line
.find('#', ChIndex
+ 1)
379 if ChIndex
== 0 or Line
[ChIndex
- 1] != '\\':
380 Line
= Line
[0:ChIndex
] + '\\' + Line
[ChIndex
:]
381 ChIndex
= Line
.find('#', ChIndex
+ 2)
383 ChIndex
= Line
.find('#', ChIndex
+ 1)
385 # remove whitespace again
393 # Split statement with comments in a string
396 # @param Line: The string to be cleaned
397 # @param CommentCharacter: Comment char, used to ignore comment content, default is DataType.TAB_COMMENT_SPLIT
399 # @retval Path Formatted path
401 def CleanString2(Line
, CommentCharacter
=DataType
.TAB_COMMENT_SPLIT
, AllowCppStyleComment
=False):
407 # Replace Edk's comment character
409 if AllowCppStyleComment
:
410 Line
= Line
.replace(DataType
.TAB_COMMENT_EDK_SPLIT
, CommentCharacter
)
412 # separate comments and statements, but we should escape comment character in string
414 InDoubleQuoteString
= False
415 InSingleQuoteString
= False
416 CommentInString
= False
418 for Index
in range(0, len(Line
)):
419 if Line
[Index
] == '"' and not InSingleQuoteString
:
420 InDoubleQuoteString
= not InDoubleQuoteString
421 elif Line
[Index
] == "'" and not InDoubleQuoteString
:
422 InSingleQuoteString
= not InSingleQuoteString
423 elif Line
[Index
] == CommentCharacter
and (InDoubleQuoteString
or InSingleQuoteString
):
424 CommentInString
= True
425 elif Line
[Index
] == CommentCharacter
and not (InDoubleQuoteString
or InSingleQuoteString
):
426 Comment
= Line
[Index
:].strip()
427 Line
= Line
[0:Index
].strip()
432 ## GetMultipleValuesOfKeyFromLines
434 # Parse multiple strings to clean comment and spaces
435 # The result is saved to KeyValues
437 # @param Lines: The content to be parsed
438 # @param Key: Reserved
439 # @param KeyValues: To store data after parsing
440 # @param CommentCharacter: Comment char, used to ignore comment content
442 # @retval True Successfully executed
444 def GetMultipleValuesOfKeyFromLines(Lines
, Key
, KeyValues
, CommentCharacter
):
445 Lines
= Lines
.split(DataType
.TAB_SECTION_END
, 1)[1]
446 LineList
= Lines
.split('\n')
447 for Line
in LineList
:
448 Line
= CleanString(Line
, CommentCharacter
)
449 if Line
!= '' and Line
[0] != CommentCharacter
:
456 # Parse a DEFINE statement to get defined value
459 # @param String: The content to be parsed
460 # @param Key: The key of DEFINE statement
461 # @param CommentCharacter: Comment char, used to ignore comment content
463 # @retval string The defined value
465 def GetDefineValue(String
, Key
, CommentCharacter
):
466 String
= CleanString(String
)
467 return String
[String
.find(Key
+ ' ') + len(Key
+ ' ') : ]
471 # Get a Hex Version Value
473 # @param VerString: The version string to be parsed
476 # @retval: If VerString is incorrectly formatted, return "None" which will break the build.
477 # If VerString is correctly formatted, return a Hex value of the Version Number (0xmmmmnnnn)
478 # where mmmm is the major number and nnnn is the adjusted minor number.
480 def GetHexVerValue(VerString
):
481 VerString
= CleanString(VerString
)
483 if gHumanReadableVerPatt
.match(VerString
):
484 ValueList
= VerString
.split('.')
489 DeciValue
= (int(Major
) << 16) + int(Minor
);
490 return "0x%08x" % DeciValue
491 elif gHexVerPatt
.match(VerString
):
497 ## GetSingleValueOfKeyFromLines
499 # Parse multiple strings as below to get value of each definition line
502 # The result is saved to Dictionary
504 # @param Lines: The content to be parsed
505 # @param Dictionary: To store data after parsing
506 # @param CommentCharacter: Comment char, be used to ignore comment content
507 # @param KeySplitCharacter: Key split char, between key name and key value. Key1 = Value1, '=' is the key split char
508 # @param ValueSplitFlag: Value split flag, be used to decide if has multiple values
509 # @param ValueSplitCharacter: Value split char, be used to split multiple values. Key1 = Value1|Value2, '|' is the value split char
511 # @retval True Successfully executed
513 def GetSingleValueOfKeyFromLines(Lines
, Dictionary
, CommentCharacter
, KeySplitCharacter
, ValueSplitFlag
, ValueSplitCharacter
):
514 Lines
= Lines
.split('\n')
522 # Handle DEFINE and SPEC
524 if Line
.find(DataType
.TAB_INF_DEFINES_DEFINE
+ ' ') > -1:
525 if '' in DefineValues
:
526 DefineValues
.remove('')
527 DefineValues
.append(GetDefineValue(Line
, DataType
.TAB_INF_DEFINES_DEFINE
, CommentCharacter
))
529 if Line
.find(DataType
.TAB_INF_DEFINES_SPEC
+ ' ') > -1:
531 SpecValues
.remove('')
532 SpecValues
.append(GetDefineValue(Line
, DataType
.TAB_INF_DEFINES_SPEC
, CommentCharacter
))
538 LineList
= Line
.split(KeySplitCharacter
, 1)
539 if len(LineList
) >= 2:
540 Key
= LineList
[0].split()
541 if len(Key
) == 1 and Key
[0][0] != CommentCharacter
:
543 # Remove comments and white spaces
545 LineList
[1] = CleanString(LineList
[1], CommentCharacter
)
547 Value
= map(string
.strip
, LineList
[1].split(ValueSplitCharacter
))
549 Value
= CleanString(LineList
[1], CommentCharacter
).splitlines()
551 if Key
[0] in Dictionary
:
552 if Key
[0] not in Keys
:
553 Dictionary
[Key
[0]] = Value
556 Dictionary
[Key
[0]].extend(Value
)
558 Dictionary
[DataType
.TAB_INF_DEFINES_MACRO
][Key
[0]] = Value
[0]
560 if DefineValues
== []:
564 Dictionary
[DataType
.TAB_INF_DEFINES_DEFINE
] = DefineValues
565 Dictionary
[DataType
.TAB_INF_DEFINES_SPEC
] = SpecValues
569 ## The content to be parsed
571 # Do pre-check for a file before it is parsed
575 # @param FileName: Used for error report
576 # @param FileContent: File content to be parsed
577 # @param SupSectionTag: Used for error report
579 def PreCheck(FileName
, FileContent
, SupSectionTag
):
583 for Line
in FileContent
.splitlines():
588 Line
= CleanString(Line
)
591 # Remove commented line
593 if Line
.find(DataType
.TAB_COMMA_SPLIT
) == 0:
598 if Line
.find('$') > -1:
599 if Line
.find('$(') < 0 or Line
.find(')') < 0:
600 EdkLogger
.error("Parser", FORMAT_INVALID
, Line
=LineNo
, File
=FileName
, RaiseError
=EdkLogger
.IsRaiseError
)
605 if Line
.find('[') > -1 or Line
.find(']') > -1:
607 # Only get one '[' or one ']'
609 if not (Line
.find('[') > -1 and Line
.find(']') > -1):
610 EdkLogger
.error("Parser", FORMAT_INVALID
, Line
=LineNo
, File
=FileName
, RaiseError
=EdkLogger
.IsRaiseError
)
613 # Regenerate FileContent
615 NewFileContent
= NewFileContent
+ Line
+ '\r\n'
618 EdkLogger
.error("Parser", FORMAT_INVALID
, Line
=LineNo
, File
=FileName
, RaiseError
=EdkLogger
.IsRaiseError
)
620 return NewFileContent
624 # Check if the Filename is including ExtName
625 # Return True if it exists
626 # Raise a error message if it not exists
628 # @param CheckFilename: Name of the file to be checked
629 # @param ExtName: Ext name of the file to be checked
630 # @param ContainerFilename: The container file which describes the file to be checked, used for error report
631 # @param SectionName: Used for error report
632 # @param Line: The line in container file which defines the file to be checked
634 # @retval True The file type is correct
636 def CheckFileType(CheckFilename
, ExtName
, ContainerFilename
, SectionName
, Line
, LineNo
= -1):
637 if CheckFilename
!= '' and CheckFilename
is not None:
638 (Root
, Ext
) = os
.path
.splitext(CheckFilename
)
639 if Ext
.upper() != ExtName
.upper():
640 ContainerFile
= open(ContainerFilename
, 'r').read()
642 LineNo
= GetLineNo(ContainerFile
, Line
)
643 ErrorMsg
= "Invalid %s. '%s' is found, but '%s' file is needed" % (SectionName
, CheckFilename
, ExtName
)
644 EdkLogger
.error("Parser", PARSER_ERROR
, ErrorMsg
, Line
=LineNo
,
645 File
=ContainerFilename
, RaiseError
=EdkLogger
.IsRaiseError
)
651 # Check if the file exists
652 # Return True if it exists
653 # Raise a error message if it not exists
655 # @param CheckFilename: Name of the file to be checked
656 # @param WorkspaceDir: Current workspace dir
657 # @param ContainerFilename: The container file which describes the file to be checked, used for error report
658 # @param SectionName: Used for error report
659 # @param Line: The line in container file which defines the file to be checked
661 # @retval The file full path if the file exists
663 def CheckFileExist(WorkspaceDir
, CheckFilename
, ContainerFilename
, SectionName
, Line
, LineNo
= -1):
665 if CheckFilename
!= '' and CheckFilename
is not None:
666 CheckFile
= WorkspaceFile(WorkspaceDir
, CheckFilename
)
667 if not os
.path
.isfile(CheckFile
):
668 ContainerFile
= open(ContainerFilename
, 'r').read()
670 LineNo
= GetLineNo(ContainerFile
, Line
)
671 ErrorMsg
= "Can't find file '%s' defined in section '%s'" % (CheckFile
, SectionName
)
672 EdkLogger
.error("Parser", PARSER_ERROR
, ErrorMsg
,
673 File
=ContainerFilename
, Line
=LineNo
, RaiseError
=EdkLogger
.IsRaiseError
)
679 # Find the index of a line in a file
681 # @param FileContent: Search scope
682 # @param Line: Search key
684 # @retval int Index of the line
685 # @retval -1 The line is not found
687 def GetLineNo(FileContent
, Line
, IsIgnoreComment
=True):
688 LineList
= FileContent
.splitlines()
689 for Index
in range(len(LineList
)):
690 if LineList
[Index
].find(Line
) > -1:
692 # Ignore statement in comment
695 if LineList
[Index
].strip()[0] == DataType
.TAB_COMMENT_SPLIT
:
703 # Raise a parser error
705 # @param Line: String which has error
706 # @param Section: Used for error report
707 # @param File: File which has the string
708 # @param Format: Correct format
710 def RaiseParserError(Line
, Section
, File
, Format
='', LineNo
= -1):
712 LineNo
= GetLineNo(open(os
.path
.normpath(File
), 'r').read(), Line
)
713 ErrorMsg
= "Invalid statement '%s' is found in section '%s'" % (Line
, Section
)
715 Format
= "Correct format is " + Format
716 EdkLogger
.error("Parser", PARSER_ERROR
, ErrorMsg
, File
=File
, Line
=LineNo
, ExtraData
=Format
, RaiseError
=EdkLogger
.IsRaiseError
)
720 # Return a full path with workspace dir
722 # @param WorkspaceDir: Workspace dir
723 # @param Filename: Relative file name
725 # @retval string A full path
727 def WorkspaceFile(WorkspaceDir
, Filename
):
728 return mws
.join(NormPath(WorkspaceDir
), NormPath(Filename
))
732 # Revmove '"' which startswith and endswith string
734 # @param String: The string need to be splited
736 # @retval String: The string after removed '""'
738 def SplitString(String
):
739 if String
.startswith('\"'):
741 if String
.endswith('\"'):
746 ## Convert To Sql String
748 # 1. Replace "'" with "''" in each item of StringList
750 # @param StringList: A list for strings to be converted
752 def ConvertToSqlString(StringList
):
753 return map(lambda s
: s
.replace("'", "''") , StringList
)
755 ## Convert To Sql String
757 # 1. Replace "'" with "''" in the String
759 # @param String: A String to be converted
761 def ConvertToSqlString2(String
):
762 return String
.replace("'", "''")
765 # Remove comment block
767 def RemoveBlockComment(Lines
):
768 IsFindBlockComment
= False
769 IsFindBlockCode
= False
776 # Remove comment block
778 if Line
.find(DataType
.TAB_COMMENT_EDK_START
) > -1:
779 ReservedLine
= GetSplitList(Line
, DataType
.TAB_COMMENT_EDK_START
, 1)[0]
780 IsFindBlockComment
= True
781 if Line
.find(DataType
.TAB_COMMENT_EDK_END
) > -1:
782 Line
= ReservedLine
+ GetSplitList(Line
, DataType
.TAB_COMMENT_EDK_END
, 1)[1]
784 IsFindBlockComment
= False
785 if IsFindBlockComment
:
789 NewLines
.append(Line
)
793 # Get String of a List
795 def GetStringOfList(List
, Split
=' '):
796 if type(List
) != type([]):
800 Str
= Str
+ Item
+ Split
805 # Get HelpTextList from HelpTextClassList
807 def GetHelpTextList(HelpTextClassList
):
809 if HelpTextClassList
:
810 for HelpText
in HelpTextClassList
:
811 if HelpText
.String
.endswith('\n'):
812 HelpText
.String
= HelpText
.String
[0: len(HelpText
.String
) - len('\n')]
813 List
.extend(HelpText
.String
.split('\n'))
817 def StringToArray(String
):
818 if isinstance(String
, unicode):
819 if len(unicode) == 0:
821 return "{%s,0x00,0x00}" % ",".join(["0x%02x,0x00" % ord(C
) for C
in String
])
822 elif String
.startswith('L"'):
823 if String
== "L\"\"":
826 return "{%s,0x00,0x00}" % ",".join(["0x%02x,0x00" % ord(C
) for C
in String
[2:-1]])
827 elif String
.startswith('"'):
831 StringLen
= len(String
[1:-1])
833 return "{%s,0x00}" % ",".join(["0x%02x" % ord(C
) for C
in String
[1:-1]])
835 return "{%s,0x00,0x00}" % ",".join(["0x%02x" % ord(C
) for C
in String
[1:-1]])
836 elif String
.startswith('{'):
837 StringLen
= len(String
.split(","))
839 return "{%s,0x00}" % ",".join([ C
.strip() for C
in String
[1:-1].split(',')])
841 return "{%s}" % ",".join([ C
.strip() for C
in String
[1:-1].split(',')])
844 if len(String
.split()) % 2:
845 return '{%s,0}' % ','.join(String
.split())
847 return '{%s,0,0}' % ','.join(String
.split())
849 def StringArrayLength(String
):
850 if isinstance(String
, unicode):
851 return (len(String
) + 1) * 2 + 1;
852 elif String
.startswith('L"'):
853 return (len(String
) - 3 + 1) * 2
854 elif String
.startswith('"'):
855 return (len(String
) - 2 + 1)
857 return len(String
.split()) + 1
859 def RemoveDupOption(OptionString
, Which
="/I", Against
=None):
860 OptionList
= OptionString
.split()
864 for Index
in range(len(OptionList
)):
865 Opt
= OptionList
[Index
]
866 if not Opt
.startswith(Which
):
868 if len(Opt
) > len(Which
):
869 Val
= Opt
[len(Which
):]
873 OptionList
[Index
] = ""
875 ValueList
.append(Val
)
876 return " ".join(OptionList
)
880 # This acts like the main() function for the script, unless it is 'import'ed into another
883 if __name__
== '__main__':