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