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