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