]>
git.proxmox.com Git - mirror_edk2.git/blob - BaseTools/Source/Python/Common/String.py
6c9671d5142235f24688e4f745349e2d4d63fdd1
2 # This file is used to define common string related functions used in parsing process
4 # Copyright (c) 2007 - 2015, 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
28 gHexVerPatt
= re
.compile('0x[a-f0-9]{4}[a-f0-9]{4}$', re
.IGNORECASE
)
29 gHumanReadableVerPatt
= re
.compile(r
'([1-9][0-9]*|0)\.[0-9]{1,2}$')
33 # Get a value list from a string with multiple values splited with SplitTag
34 # The default SplitTag is DataType.TAB_VALUE_SPLIT
35 # 'AAA|BBB|CCC' -> ['AAA', 'BBB', 'CCC']
37 # @param String: The input string to be splitted
38 # @param SplitTag: The split key, default is DataType.TAB_VALUE_SPLIT
39 # @param MaxSplit: The max number of split values, default is -1
41 # @retval list() A list for splitted string
43 def GetSplitValueList(String
, SplitTag
=DataType
.TAB_VALUE_SPLIT
, MaxSplit
= -1):
48 for Index
in range(0, len(String
)):
52 # Found a splitter not in a string, split it
53 if not InString
and Char
== SplitTag
:
54 ValueList
.append(String
[Last
:Index
].strip())
56 if MaxSplit
> 0 and len(ValueList
) >= MaxSplit
:
59 if Char
== '\\' and InString
:
69 if Last
< len(String
):
70 ValueList
.append(String
[Last
:].strip())
71 elif Last
== len(String
):
78 # Get a value list from a string with multiple values splited with SplitString
79 # The default SplitTag is DataType.TAB_VALUE_SPLIT
80 # 'AAA|BBB|CCC' -> ['AAA', 'BBB', 'CCC']
82 # @param String: The input string to be splitted
83 # @param SplitStr: The split key, default is DataType.TAB_VALUE_SPLIT
84 # @param MaxSplit: The max number of split values, default is -1
86 # @retval list() A list for splitted string
88 def GetSplitList(String
, SplitStr
=DataType
.TAB_VALUE_SPLIT
, MaxSplit
= -1):
89 return map(lambda l
: l
.strip(), String
.split(SplitStr
, MaxSplit
))
93 # Find a key's all arches in dict, add the new arch to the list
94 # If not exist any arch, set the arch directly
96 # @param Dict: The input value for Dict
97 # @param Key: The input value for Key
98 # @param Arch: The Arch to be added or merged
100 def MergeArches(Dict
, Key
, Arch
):
101 if Key
in Dict
.keys():
102 Dict
[Key
].append(Arch
)
104 Dict
[Key
] = Arch
.split()
108 # Parse a string with format "DEFINE <VarName> = <PATH>"
109 # Generate a map Defines[VarName] = PATH
110 # Return False if invalid format
112 # @param String: String with DEFINE statement
113 # @param Arch: Supportted Arch
114 # @param Defines: DEFINE statement to be parsed
116 # @retval 0 DEFINE statement found, and valid
117 # @retval 1 DEFINE statement found, but not valid
118 # @retval -1 DEFINE statement not found
120 def GenDefines(String
, Arch
, Defines
):
121 if String
.find(DataType
.TAB_DEFINE
+ ' ') > -1:
122 List
= String
.replace(DataType
.TAB_DEFINE
+ ' ', '').split(DataType
.TAB_EQUAL_SPLIT
)
124 Defines
[(CleanString(List
[0]), Arch
)] = CleanString(List
[1])
133 # Parse a string with format "!include <Filename>"
134 # Return the file path
135 # Return False if invalid format or NOT FOUND
137 # @param String: String with INCLUDE statement
138 # @param IncludeFiles: INCLUDE statement to be parsed
139 # @param Arch: Supportted Arch
144 def GenInclude(String
, IncludeFiles
, Arch
):
145 if String
.upper().find(DataType
.TAB_INCLUDE
.upper() + ' ') > -1:
146 IncludeFile
= CleanString(String
[String
.upper().find(DataType
.TAB_INCLUDE
.upper() + ' ') + len(DataType
.TAB_INCLUDE
+ ' ') : ])
147 MergeArches(IncludeFiles
, IncludeFile
, Arch
)
152 ## GetLibraryClassesWithModuleType
154 # Get Library Class definition when no module type defined
156 # @param Lines: The content to be parsed
157 # @param Key: Reserved
158 # @param KeyValues: To store data after parsing
159 # @param CommentCharacter: Comment char, used to ignore comment content
161 # @retval True Get library classes successfully
163 def GetLibraryClassesWithModuleType(Lines
, Key
, KeyValues
, CommentCharacter
):
164 newKey
= SplitModuleType(Key
)
165 Lines
= Lines
.split(DataType
.TAB_SECTION_END
, 1)[1]
166 LineList
= Lines
.splitlines()
167 for Line
in LineList
:
168 Line
= CleanString(Line
, CommentCharacter
)
169 if Line
!= '' and Line
[0] != CommentCharacter
:
170 KeyValues
.append([CleanString(Line
, CommentCharacter
), newKey
[1]])
178 # @param Lines: The content to be parsed
179 # @param Key: Reserved
180 # @param KeyValues: To store data after parsing
181 # @param CommentCharacter: Comment char, used to ignore comment content
183 # @retval True Get Dynamic Pcds successfully
185 def GetDynamics(Lines
, Key
, KeyValues
, CommentCharacter
):
187 # Get SkuId Name List
189 SkuIdNameList
= SplitModuleType(Key
)
191 Lines
= Lines
.split(DataType
.TAB_SECTION_END
, 1)[1]
192 LineList
= Lines
.splitlines()
193 for Line
in LineList
:
194 Line
= CleanString(Line
, CommentCharacter
)
195 if Line
!= '' and Line
[0] != CommentCharacter
:
196 KeyValues
.append([CleanString(Line
, CommentCharacter
), SkuIdNameList
[1]])
202 # Split ModuleType out of section defien to get key
203 # [LibraryClass.Arch.ModuleType|ModuleType|ModuleType] -> [ 'LibraryClass.Arch', ['ModuleType', 'ModuleType', 'ModuleType'] ]
205 # @param Key: String to be parsed
207 # @retval ReturnValue A list for module types
209 def SplitModuleType(Key
):
210 KeyList
= Key
.split(DataType
.TAB_SPLIT
)
216 # Fill in for moduletype
220 KeyValue
= KeyList
[0]
222 KeyValue
= KeyValue
+ DataType
.TAB_SPLIT
+ KeyList
[1]
223 ReturnValue
.append(KeyValue
)
224 ReturnValue
.append(GetSplitValueList(KeyList
[2]))
228 ## Replace macro in strings list
230 # This method replace macros used in a given string list. The macros are
231 # given in a dictionary.
233 # @param StringList StringList to be processed
234 # @param MacroDefinitions The macro definitions in the form of dictionary
235 # @param SelfReplacement To decide whether replace un-defined macro to ''
237 # @retval NewList A new string list whose macros are replaced
239 def ReplaceMacros(StringList
, MacroDefinitions
={}, SelfReplacement
=False):
241 for String
in StringList
:
242 if type(String
) == type(''):
243 NewList
.append(ReplaceMacro(String
, MacroDefinitions
, SelfReplacement
))
245 NewList
.append(String
)
249 ## Replace macro in string
251 # This method replace macros used in given string. The macros are given in a
254 # @param String String to be processed
255 # @param MacroDefinitions The macro definitions in the form of dictionary
256 # @param SelfReplacement To decide whether replace un-defined macro to ''
258 # @retval string The string whose macros are replaced
260 def ReplaceMacro(String
, MacroDefinitions
={}, SelfReplacement
=False, RaiseError
=False):
262 while String
and MacroDefinitions
:
263 MacroUsed
= GlobalData
.gMacroRefPattern
.findall(String
)
264 # no macro found in String, stop replacing
265 if len(MacroUsed
) == 0:
268 for Macro
in MacroUsed
:
269 if Macro
not in MacroDefinitions
:
271 raise SymbolNotFound("%s not defined" % Macro
)
273 String
= String
.replace("$(%s)" % Macro
, '')
275 if "$(%s)" % Macro
not in MacroDefinitions
[Macro
]:
276 String
= String
.replace("$(%s)" % Macro
, MacroDefinitions
[Macro
])
277 # in case there's macro not defined
278 if String
== LastString
:
286 # Create a normal path
287 # And replace DFEINE in the path
289 # @param Path: The input value for Path to be converted
290 # @param Defines: A set for DEFINE statement
292 # @retval Path Formatted path
294 def NormPath(Path
, Defines
={}):
295 IsRelativePath
= False
298 IsRelativePath
= True
300 # Replace with Define
303 Path
= ReplaceMacro(Path
, Defines
)
305 # To local path format
307 Path
= os
.path
.normpath(Path
)
309 if IsRelativePath
and Path
[0] != '.':
310 Path
= os
.path
.join('.', Path
)
316 # Remove comments in a string
319 # @param Line: The string to be cleaned
320 # @param CommentCharacter: Comment char, used to ignore comment content, default is DataType.TAB_COMMENT_SPLIT
322 # @retval Path Formatted path
324 def CleanString(Line
, CommentCharacter
=DataType
.TAB_COMMENT_SPLIT
, AllowCppStyleComment
=False, BuildOption
=False):
330 # Replace Edk's comment character
332 if AllowCppStyleComment
:
333 Line
= Line
.replace(DataType
.TAB_COMMENT_EDK_SPLIT
, CommentCharacter
)
335 # remove comments, but we should escape comment character in string
338 CommentInString
= False
339 for Index
in range(0, len(Line
)):
340 if Line
[Index
] == '"':
341 InString
= not InString
342 elif Line
[Index
] == CommentCharacter
and InString
:
343 CommentInString
= True
344 elif Line
[Index
] == CommentCharacter
and not InString
:
345 Line
= Line
[0: Index
]
348 if CommentInString
and BuildOption
:
349 Line
= Line
.replace('"', '')
350 ChIndex
= Line
.find('#')
352 if GlobalData
.gIsWindows
:
353 if ChIndex
== 0 or Line
[ChIndex
- 1] != '^':
354 Line
= Line
[0:ChIndex
] + '^' + Line
[ChIndex
:]
355 ChIndex
= Line
.find('#', ChIndex
+ 2)
357 ChIndex
= Line
.find('#', ChIndex
+ 1)
359 if ChIndex
== 0 or Line
[ChIndex
- 1] != '\\':
360 Line
= Line
[0:ChIndex
] + '\\' + Line
[ChIndex
:]
361 ChIndex
= Line
.find('#', ChIndex
+ 2)
363 ChIndex
= Line
.find('#', ChIndex
+ 1)
365 # remove whitespace again
373 # Split statement with comments in a string
376 # @param Line: The string to be cleaned
377 # @param CommentCharacter: Comment char, used to ignore comment content, default is DataType.TAB_COMMENT_SPLIT
379 # @retval Path Formatted path
381 def CleanString2(Line
, CommentCharacter
=DataType
.TAB_COMMENT_SPLIT
, AllowCppStyleComment
=False):
387 # Replace Edk's comment character
389 if AllowCppStyleComment
:
390 Line
= Line
.replace(DataType
.TAB_COMMENT_EDK_SPLIT
, CommentCharacter
)
392 # separate comments and statements, but we should escape comment character in string
395 CommentInString
= False
397 for Index
in range(0, len(Line
)):
398 if Line
[Index
] == '"':
399 InString
= not InString
400 elif Line
[Index
] == CommentCharacter
and InString
:
401 CommentInString
= True
402 elif Line
[Index
] == CommentCharacter
and not InString
:
403 Comment
= Line
[Index
:].strip()
404 Line
= Line
[0:Index
].strip()
409 ## GetMultipleValuesOfKeyFromLines
411 # Parse multiple strings to clean comment and spaces
412 # The result is saved to KeyValues
414 # @param Lines: The content to be parsed
415 # @param Key: Reserved
416 # @param KeyValues: To store data after parsing
417 # @param CommentCharacter: Comment char, used to ignore comment content
419 # @retval True Successfully executed
421 def GetMultipleValuesOfKeyFromLines(Lines
, Key
, KeyValues
, CommentCharacter
):
422 Lines
= Lines
.split(DataType
.TAB_SECTION_END
, 1)[1]
423 LineList
= Lines
.split('\n')
424 for Line
in LineList
:
425 Line
= CleanString(Line
, CommentCharacter
)
426 if Line
!= '' and Line
[0] != CommentCharacter
:
433 # Parse a DEFINE statement to get defined value
436 # @param String: The content to be parsed
437 # @param Key: The key of DEFINE statement
438 # @param CommentCharacter: Comment char, used to ignore comment content
440 # @retval string The defined value
442 def GetDefineValue(String
, Key
, CommentCharacter
):
443 String
= CleanString(String
)
444 return String
[String
.find(Key
+ ' ') + len(Key
+ ' ') : ]
448 # Get a Hex Version Value
450 # @param VerString: The version string to be parsed
453 # @retval: If VerString is incorrectly formatted, return "None" which will break the build.
454 # If VerString is correctly formatted, return a Hex value of the Version Number (0xmmmmnnnn)
455 # where mmmm is the major number and nnnn is the adjusted minor number.
457 def GetHexVerValue(VerString
):
458 VerString
= CleanString(VerString
)
460 if gHumanReadableVerPatt
.match(VerString
):
461 ValueList
= VerString
.split('.')
466 DeciValue
= (int(Major
) << 16) + int(Minor
);
467 return "0x%08x" % DeciValue
468 elif gHexVerPatt
.match(VerString
):
474 ## GetSingleValueOfKeyFromLines
476 # Parse multiple strings as below to get value of each definition line
479 # The result is saved to Dictionary
481 # @param Lines: The content to be parsed
482 # @param Dictionary: To store data after parsing
483 # @param CommentCharacter: Comment char, be used to ignore comment content
484 # @param KeySplitCharacter: Key split char, between key name and key value. Key1 = Value1, '=' is the key split char
485 # @param ValueSplitFlag: Value split flag, be used to decide if has multiple values
486 # @param ValueSplitCharacter: Value split char, be used to split multiple values. Key1 = Value1|Value2, '|' is the value split char
488 # @retval True Successfully executed
490 def GetSingleValueOfKeyFromLines(Lines
, Dictionary
, CommentCharacter
, KeySplitCharacter
, ValueSplitFlag
, ValueSplitCharacter
):
491 Lines
= Lines
.split('\n')
499 # Handle DEFINE and SPEC
501 if Line
.find(DataType
.TAB_INF_DEFINES_DEFINE
+ ' ') > -1:
502 if '' in DefineValues
:
503 DefineValues
.remove('')
504 DefineValues
.append(GetDefineValue(Line
, DataType
.TAB_INF_DEFINES_DEFINE
, CommentCharacter
))
506 if Line
.find(DataType
.TAB_INF_DEFINES_SPEC
+ ' ') > -1:
508 SpecValues
.remove('')
509 SpecValues
.append(GetDefineValue(Line
, DataType
.TAB_INF_DEFINES_SPEC
, CommentCharacter
))
515 LineList
= Line
.split(KeySplitCharacter
, 1)
516 if len(LineList
) >= 2:
517 Key
= LineList
[0].split()
518 if len(Key
) == 1 and Key
[0][0] != CommentCharacter
:
520 # Remove comments and white spaces
522 LineList
[1] = CleanString(LineList
[1], CommentCharacter
)
524 Value
= map(string
.strip
, LineList
[1].split(ValueSplitCharacter
))
526 Value
= CleanString(LineList
[1], CommentCharacter
).splitlines()
528 if Key
[0] in Dictionary
:
529 if Key
[0] not in Keys
:
530 Dictionary
[Key
[0]] = Value
533 Dictionary
[Key
[0]].extend(Value
)
535 Dictionary
[DataType
.TAB_INF_DEFINES_MACRO
][Key
[0]] = Value
[0]
537 if DefineValues
== []:
541 Dictionary
[DataType
.TAB_INF_DEFINES_DEFINE
] = DefineValues
542 Dictionary
[DataType
.TAB_INF_DEFINES_SPEC
] = SpecValues
546 ## The content to be parsed
548 # Do pre-check for a file before it is parsed
552 # @param FileName: Used for error report
553 # @param FileContent: File content to be parsed
554 # @param SupSectionTag: Used for error report
556 def PreCheck(FileName
, FileContent
, SupSectionTag
):
560 for Line
in FileContent
.splitlines():
565 Line
= CleanString(Line
)
568 # Remove commented line
570 if Line
.find(DataType
.TAB_COMMA_SPLIT
) == 0:
575 if Line
.find('$') > -1:
576 if Line
.find('$(') < 0 or Line
.find(')') < 0:
577 EdkLogger
.error("Parser", FORMAT_INVALID
, Line
=LineNo
, File
=FileName
, RaiseError
=EdkLogger
.IsRaiseError
)
582 if Line
.find('[') > -1 or Line
.find(']') > -1:
584 # Only get one '[' or one ']'
586 if not (Line
.find('[') > -1 and Line
.find(']') > -1):
587 EdkLogger
.error("Parser", FORMAT_INVALID
, Line
=LineNo
, File
=FileName
, RaiseError
=EdkLogger
.IsRaiseError
)
590 # Regenerate FileContent
592 NewFileContent
= NewFileContent
+ Line
+ '\r\n'
595 EdkLogger
.error("Parser", FORMAT_INVALID
, Line
=LineNo
, File
=FileName
, RaiseError
=EdkLogger
.IsRaiseError
)
597 return NewFileContent
601 # Check if the Filename is including ExtName
602 # Return True if it exists
603 # Raise a error message if it not exists
605 # @param CheckFilename: Name of the file to be checked
606 # @param ExtName: Ext name of the file to be checked
607 # @param ContainerFilename: The container file which describes the file to be checked, used for error report
608 # @param SectionName: Used for error report
609 # @param Line: The line in container file which defines the file to be checked
611 # @retval True The file type is correct
613 def CheckFileType(CheckFilename
, ExtName
, ContainerFilename
, SectionName
, Line
, LineNo
= -1):
614 if CheckFilename
!= '' and CheckFilename
!= None:
615 (Root
, Ext
) = os
.path
.splitext(CheckFilename
)
616 if Ext
.upper() != ExtName
.upper():
617 ContainerFile
= open(ContainerFilename
, 'r').read()
619 LineNo
= GetLineNo(ContainerFile
, Line
)
620 ErrorMsg
= "Invalid %s. '%s' is found, but '%s' file is needed" % (SectionName
, CheckFilename
, ExtName
)
621 EdkLogger
.error("Parser", PARSER_ERROR
, ErrorMsg
, Line
=LineNo
,
622 File
=ContainerFilename
, RaiseError
=EdkLogger
.IsRaiseError
)
628 # Check if the file exists
629 # Return True if it exists
630 # Raise a error message if it not exists
632 # @param CheckFilename: Name of the file to be checked
633 # @param WorkspaceDir: Current workspace dir
634 # @param ContainerFilename: The container file which describes the file to be checked, used for error report
635 # @param SectionName: Used for error report
636 # @param Line: The line in container file which defines the file to be checked
638 # @retval The file full path if the file exists
640 def CheckFileExist(WorkspaceDir
, CheckFilename
, ContainerFilename
, SectionName
, Line
, LineNo
= -1):
642 if CheckFilename
!= '' and CheckFilename
!= None:
643 CheckFile
= WorkspaceFile(WorkspaceDir
, CheckFilename
)
644 if not os
.path
.isfile(CheckFile
):
645 ContainerFile
= open(ContainerFilename
, 'r').read()
647 LineNo
= GetLineNo(ContainerFile
, Line
)
648 ErrorMsg
= "Can't find file '%s' defined in section '%s'" % (CheckFile
, SectionName
)
649 EdkLogger
.error("Parser", PARSER_ERROR
, ErrorMsg
,
650 File
=ContainerFilename
, Line
=LineNo
, RaiseError
=EdkLogger
.IsRaiseError
)
656 # Find the index of a line in a file
658 # @param FileContent: Search scope
659 # @param Line: Search key
661 # @retval int Index of the line
662 # @retval -1 The line is not found
664 def GetLineNo(FileContent
, Line
, IsIgnoreComment
=True):
665 LineList
= FileContent
.splitlines()
666 for Index
in range(len(LineList
)):
667 if LineList
[Index
].find(Line
) > -1:
669 # Ignore statement in comment
672 if LineList
[Index
].strip()[0] == DataType
.TAB_COMMENT_SPLIT
:
680 # Raise a parser error
682 # @param Line: String which has error
683 # @param Section: Used for error report
684 # @param File: File which has the string
685 # @param Format: Correct format
687 def RaiseParserError(Line
, Section
, File
, Format
='', LineNo
= -1):
689 LineNo
= GetLineNo(open(os
.path
.normpath(File
), 'r').read(), Line
)
690 ErrorMsg
= "Invalid statement '%s' is found in section '%s'" % (Line
, Section
)
692 Format
= "Correct format is " + Format
693 EdkLogger
.error("Parser", PARSER_ERROR
, ErrorMsg
, File
=File
, Line
=LineNo
, ExtraData
=Format
, RaiseError
=EdkLogger
.IsRaiseError
)
697 # Return a full path with workspace dir
699 # @param WorkspaceDir: Workspace dir
700 # @param Filename: Relative file name
702 # @retval string A full path
704 def WorkspaceFile(WorkspaceDir
, Filename
):
705 return os
.path
.join(NormPath(WorkspaceDir
), NormPath(Filename
))
709 # Revmove '"' which startswith and endswith string
711 # @param String: The string need to be splited
713 # @retval String: The string after removed '""'
715 def SplitString(String
):
716 if String
.startswith('\"'):
718 if String
.endswith('\"'):
723 ## Convert To Sql String
725 # 1. Replace "'" with "''" in each item of StringList
727 # @param StringList: A list for strings to be converted
729 def ConvertToSqlString(StringList
):
730 return map(lambda s
: s
.replace("'", "''") , StringList
)
732 ## Convert To Sql String
734 # 1. Replace "'" with "''" in the String
736 # @param String: A String to be converted
738 def ConvertToSqlString2(String
):
739 return String
.replace("'", "''")
742 # Remove comment block
744 def RemoveBlockComment(Lines
):
745 IsFindBlockComment
= False
746 IsFindBlockCode
= False
753 # Remove comment block
755 if Line
.find(DataType
.TAB_COMMENT_EDK_START
) > -1:
756 ReservedLine
= GetSplitList(Line
, DataType
.TAB_COMMENT_EDK_START
, 1)[0]
757 IsFindBlockComment
= True
758 if Line
.find(DataType
.TAB_COMMENT_EDK_END
) > -1:
759 Line
= ReservedLine
+ GetSplitList(Line
, DataType
.TAB_COMMENT_EDK_END
, 1)[1]
761 IsFindBlockComment
= False
762 if IsFindBlockComment
:
766 NewLines
.append(Line
)
770 # Get String of a List
772 def GetStringOfList(List
, Split
=' '):
773 if type(List
) != type([]):
777 Str
= Str
+ Item
+ Split
782 # Get HelpTextList from HelpTextClassList
784 def GetHelpTextList(HelpTextClassList
):
786 if HelpTextClassList
:
787 for HelpText
in HelpTextClassList
:
788 if HelpText
.String
.endswith('\n'):
789 HelpText
.String
= HelpText
.String
[0: len(HelpText
.String
) - len('\n')]
790 List
.extend(HelpText
.String
.split('\n'))
794 def StringToArray(String
):
795 if isinstance(String
, unicode):
796 if len(unicode) == 0:
797 return "{0x00, 0x00}"
798 return "{%s, 0x00, 0x00}" % ", ".join(["0x%02x, 0x00" % ord(C
) for C
in String
])
799 elif String
.startswith('L"'):
800 if String
== "L\"\"":
801 return "{0x00, 0x00}"
803 return "{%s, 0x00, 0x00}" % ", ".join(["0x%02x, 0x00" % ord(C
) for C
in String
[2:-1]])
804 elif String
.startswith('"'):
808 StringLen
= len(String
[1:-1])
810 return "{%s, 0x00}" % ", ".join(["0x%02x" % ord(C
) for C
in String
[1:-1]])
812 return "{%s, 0x00,0x00}" % ", ".join(["0x%02x" % ord(C
) for C
in String
[1:-1]])
813 elif String
.startswith('{'):
814 StringLen
= len(String
.split(","))
816 return "{%s, 0x00}" % ", ".join([ C
for C
in String
[1:-1].split(',')])
818 return "{%s}" % ", ".join([ C
for C
in String
[1:-1].split(',')])
821 if len(String
.split()) % 2:
822 return '{%s, 0}' % ', '.join(String
.split())
824 return '{%s, 0,0}' % ', '.join(String
.split())
826 def StringArrayLength(String
):
827 if isinstance(String
, unicode):
828 return (len(String
) + 1) * 2 + 1;
829 elif String
.startswith('L"'):
830 return (len(String
) - 3 + 1) * 2
831 elif String
.startswith('"'):
832 return (len(String
) - 2 + 1)
834 return len(String
.split()) + 1
836 def RemoveDupOption(OptionString
, Which
="/I", Against
=None):
837 OptionList
= OptionString
.split()
841 for Index
in range(len(OptionList
)):
842 Opt
= OptionList
[Index
]
843 if not Opt
.startswith(Which
):
845 if len(Opt
) > len(Which
):
846 Val
= Opt
[len(Which
):]
850 OptionList
[Index
] = ""
852 ValueList
.append(Val
)
853 return " ".join(OptionList
)
857 # This acts like the main() function for the script, unless it is 'import'ed into another
860 if __name__
== '__main__':