]> git.proxmox.com Git - mirror_edk2.git/blame - BaseTools/Source/Python/Common/String.py
Check In tool source code based on Build tool project revision r1655.
[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
4# Copyright (c) 2007 ~ 2008, Intel Corporation\r
5# All rights reserved. This program and the accompanying materials\r
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
282 # remove comments\r
283 #\r
284 Line = Line.split(CommentCharacter, 1)[0];\r
285 #\r
286 # remove whitespace again\r
287 #\r
288 Line = Line.strip();\r
289\r
290 return Line\r
291\r
292## GetMultipleValuesOfKeyFromLines\r
293#\r
294# Parse multiple strings to clean comment and spaces\r
295# The result is saved to KeyValues\r
296#\r
297# @param Lines: The content to be parsed\r
298# @param Key: Reserved\r
299# @param KeyValues: To store data after parsing\r
300# @param CommentCharacter: Comment char, used to ignore comment content\r
301#\r
302# @retval True Successfully executed\r
303#\r
304def GetMultipleValuesOfKeyFromLines(Lines, Key, KeyValues, CommentCharacter):\r
305 Lines = Lines.split(DataType.TAB_SECTION_END, 1)[1]\r
306 LineList = Lines.split('\n')\r
307 for Line in LineList:\r
308 Line = CleanString(Line, CommentCharacter)\r
309 if Line != '' and Line[0] != CommentCharacter:\r
310 KeyValues += [Line]\r
311\r
312 return True\r
313\r
314## GetDefineValue\r
315#\r
316# Parse a DEFINE statement to get defined value\r
317# DEFINE Key Value\r
318#\r
319# @param String: The content to be parsed\r
320# @param Key: The key of DEFINE statement\r
321# @param CommentCharacter: Comment char, used to ignore comment content\r
322#\r
323# @retval string The defined value\r
324#\r
325def GetDefineValue(String, Key, CommentCharacter):\r
326 String = CleanString(String)\r
327 return String[String.find(Key + ' ') + len(Key + ' ') : ]\r
328\r
329## GetSingleValueOfKeyFromLines\r
330#\r
331# Parse multiple strings as below to get value of each definition line\r
332# Key1 = Value1\r
333# Key2 = Value2\r
334# The result is saved to Dictionary\r
335#\r
336# @param Lines: The content to be parsed\r
337# @param Dictionary: To store data after parsing\r
338# @param CommentCharacter: Comment char, be used to ignore comment content\r
339# @param KeySplitCharacter: Key split char, between key name and key value. Key1 = Value1, '=' is the key split char\r
340# @param ValueSplitFlag: Value split flag, be used to decide if has multiple values\r
341# @param ValueSplitCharacter: Value split char, be used to split multiple values. Key1 = Value1|Value2, '|' is the value split char\r
342#\r
343# @retval True Successfully executed\r
344#\r
345def GetSingleValueOfKeyFromLines(Lines, Dictionary, CommentCharacter, KeySplitCharacter, ValueSplitFlag, ValueSplitCharacter):\r
346 Lines = Lines.split('\n')\r
347 Keys = []\r
348 Value = ''\r
349 DefineValues = ['']\r
350 SpecValues = ['']\r
351\r
352 for Line in Lines:\r
353 #\r
354 # Handle DEFINE and SPEC\r
355 #\r
356 if Line.find(DataType.TAB_INF_DEFINES_DEFINE + ' ') > -1:\r
357 if '' in DefineValues:\r
358 DefineValues.remove('')\r
359 DefineValues.append(GetDefineValue(Line, DataType.TAB_INF_DEFINES_DEFINE, CommentCharacter))\r
360 continue\r
361 if Line.find(DataType.TAB_INF_DEFINES_SPEC + ' ') > -1:\r
362 if '' in SpecValues:\r
363 SpecValues.remove('')\r
364 SpecValues.append(GetDefineValue(Line, DataType.TAB_INF_DEFINES_SPEC, CommentCharacter))\r
365 continue\r
366\r
367 #\r
368 # Handle Others\r
369 #\r
370 LineList = Line.split(KeySplitCharacter, 1)\r
371 if len(LineList) >= 2:\r
372 Key = LineList[0].split()\r
373 if len(Key) == 1 and Key[0][0] != CommentCharacter:\r
374 #\r
375 # Remove comments and white spaces\r
376 #\r
377 LineList[1] = CleanString(LineList[1], CommentCharacter)\r
378 if ValueSplitFlag:\r
379 Value = map(string.strip, LineList[1].split(ValueSplitCharacter))\r
380 else:\r
381 Value = CleanString(LineList[1], CommentCharacter).splitlines()\r
382\r
383 if Key[0] in Dictionary:\r
384 if Key[0] not in Keys:\r
385 Dictionary[Key[0]] = Value\r
386 Keys.append(Key[0])\r
387 else:\r
388 Dictionary[Key[0]].extend(Value)\r
389 else:\r
390 Dictionary[DataType.TAB_INF_DEFINES_MACRO][Key[0]] = Value[0]\r
391\r
392 if DefineValues == []:\r
393 DefineValues = ['']\r
394 if SpecValues == []:\r
395 SpecValues = ['']\r
396 Dictionary[DataType.TAB_INF_DEFINES_DEFINE] = DefineValues\r
397 Dictionary[DataType.TAB_INF_DEFINES_SPEC] = SpecValues\r
398\r
399 return True\r
400\r
401## The content to be parsed\r
402#\r
403# Do pre-check for a file before it is parsed\r
404# Check $()\r
405# Check []\r
406#\r
407# @param FileName: Used for error report\r
408# @param FileContent: File content to be parsed\r
409# @param SupSectionTag: Used for error report\r
410#\r
411def PreCheck(FileName, FileContent, SupSectionTag):\r
412 LineNo = 0\r
413 IsFailed = False\r
414 NewFileContent = ''\r
415 for Line in FileContent.splitlines():\r
416 LineNo = LineNo + 1\r
417 #\r
418 # Clean current line\r
419 #\r
420 Line = CleanString(Line)\r
421\r
422 #\r
423 # Remove commented line\r
424 #\r
425 if Line.find(DataType.TAB_COMMA_SPLIT) == 0:\r
426 Line = ''\r
427 #\r
428 # Check $()\r
429 #\r
430 if Line.find('$') > -1:\r
431 if Line.find('$(') < 0 or Line.find(')') < 0:\r
432 EdkLogger.error("Parser", FORMAT_INVALID, Line=LineNo, File=FileName, RaiseError = EdkLogger.IsRaiseError)\r
433\r
434 #\r
435 # Check []\r
436 #\r
437 if Line.find('[') > -1 or Line.find(']') > -1:\r
438 #\r
439 # Only get one '[' or one ']'\r
440 #\r
441 if not (Line.find('[') > -1 and Line.find(']') > -1):\r
442 EdkLogger.error("Parser", FORMAT_INVALID, Line=LineNo, File=FileName, RaiseError = EdkLogger.IsRaiseError)\r
443\r
444 #\r
445 # Regenerate FileContent\r
446 #\r
447 NewFileContent = NewFileContent + Line + '\r\n'\r
448\r
449 if IsFailed:\r
450 EdkLogger.error("Parser", FORMAT_INVALID, Line=LineNo, File=FileName, RaiseError = EdkLogger.IsRaiseError)\r
451\r
452 return NewFileContent\r
453\r
454## CheckFileType\r
455#\r
456# Check if the Filename is including ExtName\r
457# Return True if it exists\r
458# Raise a error message if it not exists\r
459#\r
460# @param CheckFilename: Name of the file to be checked\r
461# @param ExtName: Ext name of the file to be checked\r
462# @param ContainerFilename: The container file which describes the file to be checked, used for error report\r
463# @param SectionName: Used for error report\r
464# @param Line: The line in container file which defines the file to be checked\r
465#\r
466# @retval True The file type is correct\r
467#\r
468def CheckFileType(CheckFilename, ExtName, ContainerFilename, SectionName, Line, LineNo = -1):\r
469 if CheckFilename != '' and CheckFilename != None:\r
470 (Root, Ext) = os.path.splitext(CheckFilename)\r
471 if Ext.upper() != ExtName.upper():\r
472 ContainerFile = open(ContainerFilename, 'r').read()\r
473 if LineNo == -1:\r
474 LineNo = GetLineNo(ContainerFile, Line)\r
475 ErrorMsg = "Invalid %s. '%s' is found, but '%s' file is needed" % (SectionName, CheckFilename, ExtName)\r
476 EdkLogger.error("Parser", PARSER_ERROR, ErrorMsg, Line=LineNo,\r
477 File=ContainerFilename, RaiseError = EdkLogger.IsRaiseError)\r
478\r
479 return True\r
480\r
481## CheckFileExist\r
482#\r
483# Check if the file exists\r
484# Return True if it exists\r
485# Raise a error message if it not exists\r
486#\r
487# @param CheckFilename: Name of the file to be checked\r
488# @param WorkspaceDir: Current workspace dir\r
489# @param ContainerFilename: The container file which describes the file to be checked, used for error report\r
490# @param SectionName: Used for error report\r
491# @param Line: The line in container file which defines the file to be checked\r
492#\r
493# @retval The file full path if the file exists\r
494#\r
495def CheckFileExist(WorkspaceDir, CheckFilename, ContainerFilename, SectionName, Line, LineNo = -1):\r
496 CheckFile = ''\r
497 if CheckFilename != '' and CheckFilename != None:\r
498 CheckFile = WorkspaceFile(WorkspaceDir, CheckFilename)\r
499 if not os.path.isfile(CheckFile):\r
500 ContainerFile = open(ContainerFilename, 'r').read()\r
501 if LineNo == -1:\r
502 LineNo = GetLineNo(ContainerFile, Line)\r
503 ErrorMsg = "Can't find file '%s' defined in section '%s'" % (CheckFile, SectionName)\r
504 EdkLogger.error("Parser", PARSER_ERROR, ErrorMsg,\r
505 File=ContainerFilename, Line = LineNo, RaiseError = EdkLogger.IsRaiseError)\r
506\r
507 return CheckFile\r
508\r
509## GetLineNo\r
510#\r
511# Find the index of a line in a file\r
512#\r
513# @param FileContent: Search scope\r
514# @param Line: Search key\r
515#\r
516# @retval int Index of the line\r
517# @retval -1 The line is not found\r
518#\r
519def GetLineNo(FileContent, Line, IsIgnoreComment = True):\r
520 LineList = FileContent.splitlines()\r
521 for Index in range(len(LineList)):\r
522 if LineList[Index].find(Line) > -1:\r
523 #\r
524 # Ignore statement in comment\r
525 #\r
526 if IsIgnoreComment:\r
527 if LineList[Index].strip()[0] == DataType.TAB_COMMENT_SPLIT:\r
528 continue\r
529 return Index + 1\r
530\r
531 return -1\r
532\r
533## RaiseParserError\r
534#\r
535# Raise a parser error\r
536#\r
537# @param Line: String which has error\r
538# @param Section: Used for error report\r
539# @param File: File which has the string\r
540# @param Format: Correct format\r
541#\r
542def RaiseParserError(Line, Section, File, Format = '', LineNo = -1):\r
543 if LineNo == -1:\r
544 LineNo = GetLineNo(open(os.path.normpath(File), 'r').read(), Line)\r
545 ErrorMsg = "Invalid statement '%s' is found in section '%s'" % (Line, Section)\r
546 if Format != '':\r
547 Format = "Correct format is " + Format\r
548 EdkLogger.error("Parser", PARSER_ERROR, ErrorMsg, File=File, Line=LineNo, ExtraData=Format, RaiseError = EdkLogger.IsRaiseError)\r
549\r
550## WorkspaceFile\r
551#\r
552# Return a full path with workspace dir\r
553#\r
554# @param WorkspaceDir: Workspace dir\r
555# @param Filename: Relative file name\r
556#\r
557# @retval string A full path\r
558#\r
559def WorkspaceFile(WorkspaceDir, Filename):\r
560 return os.path.join(NormPath(WorkspaceDir), NormPath(Filename))\r
561\r
562## Split string\r
563#\r
564# Revmove '"' which startswith and endswith string\r
565#\r
566# @param String: The string need to be splited\r
567#\r
568# @retval String: The string after removed '""'\r
569#\r
570def SplitString(String):\r
571 if String.startswith('\"'):\r
572 String = String[1:]\r
573 if String.endswith('\"'):\r
574 String = String[:-1]\r
575\r
576 return String\r
577\r
578## Convert To Sql String\r
579#\r
580# 1. Replace "'" with "''" in each item of StringList\r
581#\r
582# @param StringList: A list for strings to be converted\r
583#\r
584def ConvertToSqlString(StringList):\r
585 return map(lambda s: s.replace("'", "''") , StringList)\r
586\r
587## Convert To Sql String\r
588#\r
589# 1. Replace "'" with "''" in the String\r
590#\r
591# @param String: A String to be converted\r
592#\r
593def ConvertToSqlString2(String):\r
594 return String.replace("'", "''")\r
595\r
596#\r
597# Remove comment block\r
598#\r
599def RemoveBlockComment(Lines):\r
600 IsFindBlockComment = False\r
601 IsFindBlockCode = False\r
602 ReservedLine = ''\r
603 NewLines = []\r
604\r
605 for Line in Lines:\r
606 Line = Line.strip()\r
607 #\r
608 # Remove comment block\r
609 #\r
610 if Line.find(DataType.TAB_COMMENT_R8_START) > -1:\r
611 ReservedLine = GetSplitValueList(Line, DataType.TAB_COMMENT_R8_START, 1)[0]\r
612 IsFindBlockComment = True\r
613 if Line.find(DataType.TAB_COMMENT_R8_END) > -1:\r
614 Line = ReservedLine + GetSplitValueList(Line, DataType.TAB_COMMENT_R8_END, 1)[1]\r
615 ReservedLine = ''\r
616 IsFindBlockComment = False\r
617 if IsFindBlockComment:\r
618 NewLines.append('')\r
619 continue\r
620\r
621 NewLines.append(Line)\r
622 return NewLines\r
623\r
624#\r
625# Get String of a List\r
626#\r
627def GetStringOfList(List, Split = ' '):\r
628 if type(List) != type([]):\r
629 return List\r
630 Str = ''\r
631 for Item in List:\r
632 Str = Str + Item + Split\r
633\r
634 return Str.strip()\r
635\r
636#\r
637# Get HelpTextList from HelpTextClassList\r
638#\r
639def GetHelpTextList(HelpTextClassList):\r
640 List = []\r
641 if HelpTextClassList:\r
642 for HelpText in HelpTextClassList:\r
643 if HelpText.String.endswith('\n'):\r
644 HelpText.String = HelpText.String[0: len(HelpText.String) - len('\n')]\r
645 List.extend(HelpText.String.split('\n'))\r
646\r
647 return List\r
648\r
649def StringToArray(String):\r
650 if isinstance(String, unicode):\r
651 if len(unicode) ==0:\r
652 return "{0x00, 0x00}"\r
653 return "{%s, 0x00, 0x00}" % ", ".join(["0x%02x, 0x00" % ord(C) for C in String])\r
654 elif String.startswith('L"'):\r
655 if String == "L\"\"":\r
656 return "{0x00, 0x00}"\r
657 else:\r
658 return "{%s, 0x00, 0x00}" % ", ".join(["0x%02x, 0x00" % ord(C) for C in String[2:-1]])\r
659 elif String.startswith('"'):\r
660 if String == "\"\"":\r
661 return "{0x00}";\r
662 else:\r
663 return "{%s, 0x00}" % ", ".join(["0x%02x" % ord(C) for C in String[1:-1]])\r
664 else:\r
665 return '{%s, 0}' % ', '.join(String.split())\r
666\r
667def StringArrayLength(String):\r
668 if isinstance(String, unicode):\r
669 return (len(String) + 1) * 2 + 1;\r
670 elif String.startswith('L"'):\r
671 return (len(String) - 3 + 1) * 2\r
672 elif String.startswith('"'):\r
673 return (len(String) - 2 + 1)\r
674 else:\r
675 return len(String.split()) + 1\r
676 \r
677def RemoveDupOption(OptionString, Which="/I", Against=None):\r
678 OptionList = OptionString.split()\r
679 ValueList = []\r
680 if Against:\r
681 ValueList += Against\r
682 for Index in range(len(OptionList)):\r
683 Opt = OptionList[Index]\r
684 if not Opt.startswith(Which):\r
685 continue\r
686 if len(Opt) > len(Which):\r
687 Val = Opt[len(Which):]\r
688 else:\r
689 Val = ""\r
690 if Val in ValueList:\r
691 OptionList[Index] = ""\r
692 else:\r
693 ValueList.append(Val)\r
694 return " ".join(OptionList)\r
695\r
696##\r
697#\r
698# This acts like the main() function for the script, unless it is 'import'ed into another\r
699# script.\r
700#\r
701if __name__ == '__main__':\r
702 pass\r
703\r