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