How to use section method in Nose

Best Python code snippet using nose

setup.py

Source:setup.py Github

copy

Full Screen

...54 return self.__defOrder55 else: 56 return self.__def.keys()57 58 def add_section(self, section):59 """Add a configuration section / option group."""60 61 if self.__def.has_key(section):62 raise Exception("Section already exists: '%s'" % section)63 else:64 self.__def[section] = {}65 def add_def(self, section, var, type, desc, help = True, default = None, 66 req = True, validate = True, short = None):67 """ Add a variable definition.68 69 section - section name70 var - variable name71 type - valid hodlib.types72 desc - description of variable73 help - display help for this variable74 default - default value75 req - bool, requried?76 validate - bool, validate type value?77 short - short symbol (1 character),78 help - bool, display help?"""79 80 if self.__def.has_key(section):81 if not is_valid_type(type):82 raise Exception("Type (type) is invalid: %s.%s - '%s'" % (section, var, 83 type))84 if not isinstance(desc, str):85 raise Exception("Description (desc) must be a string: %s.%s - '%s'" % (86 section, var, desc))87 if not isinstance(req, bool):88 raise Exception("Required (req) must be a bool: %s.%s - '%s'" % (section, 89 var, 90 req))91 if not isinstance(validate, bool):92 raise Exception("Validate (validate) must be a bool: %s.%s - '%s'" % (93 section, var, validate))94 95 if self.__def[section].has_key(var):96 raise Exception("Variable name already defined: '%s'" % var)97 else:98 self.__def[section][var] = { 'type' : type,99 'desc' : desc,100 'help' : help,101 'default' : default,102 'req' : req,103 'validate' : validate,104 'short' : short } 105 else: 106 raise Exception("Section does not exist: '%s'" % section)107 108 def add_defs(self, defList, defOrder=None):109 """ Add a series of definitions.110 111 defList = { section0 : ((name0, 112 type0, 113 desc0, 114 help0,115 default0,116 req0, 117 validate0,118 short0),119 ....120 (nameN, 121 typeN, 122 descN,123 helpN, 124 defaultN, 125 reqN, 126 validateN,127 shortN)), 128 ....129 130 sectionN : ... }131 132 Where the short synmbol is optional and can only be one char."""133 134 for section in defList.keys():135 self.add_section(section)136 for defTuple in defList[section]:137 if isinstance(defTuple, tuple): 138 if len(defTuple) < 7:139 raise Exception(140 "section %s is missing an element: %s" % (141 section, pprint.pformat(defTuple)))142 else:143 raise Exception("section %s of defList is not a tuple" % 144 section)145 146 if len(defTuple) == 7:147 self.add_def(section, defTuple[0], defTuple[1], 148 defTuple[2], defTuple[3], defTuple[4], 149 defTuple[5], defTuple[6])...

Full Screen

Full Screen

ConfigParser.py

Source:ConfigParser.py Github

copy

Full Screen

...20 interpolation. Note that `__name__' is always an intrinsic default;21 its value is the section's name.22 sections()23 return all the configuration section names, sans DEFAULT24 has_section(section)25 return whether the given section exists26 has_option(section, option)27 return whether the given option exists in the given section28 options(section)29 return list of configuration options for the named section30 read(filenames)31 read and parse the list of named configuration files, given by32 name. A single filename is also allowed. Non-existing files33 are ignored. Return list of successfully read files.34 readfp(fp, filename=None)35 read and parse one configuration file, given as a file object.36 The filename defaults to fp.name; it is only used in error37 messages (if fp has no `name' attribute, the string `<???>' is used).38 get(section, option, raw=False, vars=None)39 return a string value for the named option. All % interpolations are40 expanded in the return values, based on the defaults passed into the41 constructor and the DEFAULT section. Additional substitutions may be42 provided using the `vars' argument, which must be a dictionary whose43 contents override any pre-existing defaults.44 getint(section, options)45 like get(), but convert value to an integer46 getfloat(section, options)47 like get(), but convert value to a float48 getboolean(section, options)49 like get(), but convert value to a boolean (currently case50 insensitively defined as 0, false, no, off for False, and 1, true,51 yes, on for True). Returns False or True.52 items(section, raw=False, vars=None)53 return a list of tuples with (name, value) for each option54 in the section.55 remove_section(section)56 remove the given file section and all its options57 remove_option(section, option)58 remove the given option from the given section59 set(section, option, value)60 set the given option61 write(fp)62 write the configuration state in .ini format63"""64try:65 from collections import OrderedDict as _default_dict66except ImportError:67 # fallback for setup.py which hasn't yet built _collections68 _default_dict = dict69import re70__all__ = ["NoSectionError", "DuplicateSectionError", "NoOptionError",71 "InterpolationError", "InterpolationDepthError",72 "InterpolationSyntaxError", "ParsingError",73 "MissingSectionHeaderError",74 "ConfigParser", "SafeConfigParser", "RawConfigParser",75 "DEFAULTSECT", "MAX_INTERPOLATION_DEPTH"]76DEFAULTSECT = "DEFAULT"77MAX_INTERPOLATION_DEPTH = 1078# exception classes79class Error(Exception):80 """Base class for ConfigParser exceptions."""81 def _get_message(self):82 """Getter for 'message'; needed only to override deprecation in83 BaseException."""84 return self.__message85 def _set_message(self, value):86 """Setter for 'message'; needed only to override deprecation in87 BaseException."""88 self.__message = value89 # BaseException.message has been deprecated since Python 2.6. To prevent90 # DeprecationWarning from popping up over this pre-existing attribute, use91 # a new property that takes lookup precedence.92 message = property(_get_message, _set_message)93 def __init__(self, msg=''):94 self.message = msg95 Exception.__init__(self, msg)96 def __repr__(self):97 return self.message98 __str__ = __repr__99class NoSectionError(Error):100 """Raised when no section matches a requested option."""101 def __init__(self, section):102 Error.__init__(self, 'No section: %r' % (section,))103 self.section = section104 self.args = (section, )105class DuplicateSectionError(Error):106 """Raised when a section is multiply-created."""107 def __init__(self, section):108 Error.__init__(self, "Section %r already exists" % section)109 self.section = section110 self.args = (section, )111class NoOptionError(Error):112 """A requested option was not found."""113 def __init__(self, option, section):114 Error.__init__(self, "No option %r in section: %r" %115 (option, section))116 self.option = option117 self.section = section118 self.args = (option, section)119class InterpolationError(Error):120 """Base class for interpolation-related exceptions."""121 def __init__(self, option, section, msg):122 Error.__init__(self, msg)123 self.option = option124 self.section = section125 self.args = (option, section, msg)126class InterpolationMissingOptionError(InterpolationError):127 """A string substitution required a setting which was not available."""128 def __init__(self, option, section, rawval, reference):129 msg = ("Bad value substitution:\n"130 "\tsection: [%s]\n"131 "\toption : %s\n"132 "\tkey : %s\n"133 "\trawval : %s\n"134 % (section, option, reference, rawval))135 InterpolationError.__init__(self, option, section, msg)136 self.reference = reference137 self.args = (option, section, rawval, reference)138class InterpolationSyntaxError(InterpolationError):139 """Raised when the source text into which substitutions are made140 does not conform to the required syntax."""141class InterpolationDepthError(InterpolationError):142 """Raised when substitutions are nested too deeply."""143 def __init__(self, option, section, rawval):144 msg = ("Value interpolation too deeply recursive:\n"145 "\tsection: [%s]\n"146 "\toption : %s\n"147 "\trawval : %s\n"148 % (section, option, rawval))149 InterpolationError.__init__(self, option, section, msg)150 self.args = (option, section, rawval)151class ParsingError(Error):152 """Raised when a configuration file does not follow legal syntax."""153 def __init__(self, filename):154 Error.__init__(self, 'File contains parsing errors: %s' % filename)155 self.filename = filename156 self.errors = []157 self.args = (filename, )158 def append(self, lineno, line):159 self.errors.append((lineno, line))160 self.message += '\n\t[line %2d]: %s' % (lineno, line)161class MissingSectionHeaderError(ParsingError):162 """Raised when a key-value pair is found before any section header."""163 def __init__(self, filename, lineno, line):164 Error.__init__(165 self,166 'File contains no section headers.\nfile: %s, line: %d\n%r' %167 (filename, lineno, line))168 self.filename = filename169 self.lineno = lineno170 self.line = line171 self.args = (filename, lineno, line)172class RawConfigParser:173 def __init__(self, defaults=None, dict_type=_default_dict,174 allow_no_value=False):175 self._dict = dict_type176 self._sections = self._dict()177 self._defaults = self._dict()178 if allow_no_value:179 self._optcre = self.OPTCRE_NV180 else:181 self._optcre = self.OPTCRE182 if defaults:183 for key, value in defaults.items():184 self._defaults[self.optionxform(key)] = value185 def defaults(self):186 return self._defaults187 def sections(self):188 """Return a list of section names, excluding [DEFAULT]"""189 # self._sections will never have [DEFAULT] in it190 return self._sections.keys()191 def add_section(self, section):192 """Create a new section in the configuration.193 Raise DuplicateSectionError if a section by the specified name194 already exists. Raise ValueError if name is DEFAULT or any of it's195 case-insensitive variants.196 """197 if section.lower() == "default":198 raise ValueError, 'Invalid section name: %s' % section199 if section in self._sections:200 raise DuplicateSectionError(section)201 self._sections[section] = self._dict()202 def has_section(self, section):203 """Indicate whether the named section is present in the configuration.204 The DEFAULT section is not acknowledged.205 """206 return section in self._sections207 def options(self, section):208 """Return a list of option names for the given section name."""209 try:210 opts = self._sections[section].copy()211 except KeyError:212 raise NoSectionError(section)213 opts.update(self._defaults)214 if '__name__' in opts:215 del opts['__name__']216 return opts.keys()217 def read(self, filenames):218 """Read and parse a filename or a list of filenames.219 Files that cannot be opened are silently ignored; this is220 designed so that you can specify a list of potential221 configuration file locations (e.g. current directory, user's222 home directory, systemwide directory), and all existing223 configuration files in the list will be read. A single224 filename may also be given.225 Return list of successfully read files.226 """227 if isinstance(filenames, basestring):228 filenames = [filenames]229 read_ok = []230 for filename in filenames:231 try:232 fp = open(filename)233 except IOError:234 continue235 self._read(fp, filename)236 fp.close()237 read_ok.append(filename)238 return read_ok239 def readfp(self, fp, filename=None):240 """Like read() but the argument must be a file-like object.241 The `fp' argument must have a `readline' method. Optional242 second argument is the `filename', which if not given, is243 taken from fp.name. If fp has no `name' attribute, `<???>' is244 used.245 """246 if filename is None:247 try:248 filename = fp.name249 except AttributeError:250 filename = '<???>'251 self._read(fp, filename)252 def get(self, section, option):253 opt = self.optionxform(option)254 if section not in self._sections:255 if section != DEFAULTSECT:256 raise NoSectionError(section)257 if opt in self._defaults:258 return self._defaults[opt]259 else:260 raise NoOptionError(option, section)261 elif opt in self._sections[section]:262 return self._sections[section][opt]263 elif opt in self._defaults:264 return self._defaults[opt]265 else:266 raise NoOptionError(option, section)267 def items(self, section):268 try:269 d2 = self._sections[section]270 except KeyError:271 if section != DEFAULTSECT:272 raise NoSectionError(section)273 d2 = self._dict()274 d = self._defaults.copy()275 d.update(d2)276 if "__name__" in d:277 del d["__name__"]278 return d.items()279 def _get(self, section, conv, option):280 return conv(self.get(section, option))281 def getint(self, section, option):282 return self._get(section, int, option)283 def getfloat(self, section, option):284 return self._get(section, float, option)285 _boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,286 '0': False, 'no': False, 'false': False, 'off': False}287 def getboolean(self, section, option):288 v = self.get(section, option)289 if v.lower() not in self._boolean_states:290 raise ValueError, 'Not a boolean: %s' % v291 return self._boolean_states[v.lower()]292 def optionxform(self, optionstr):293 return optionstr.lower()294 def has_option(self, section, option):295 """Check for the existence of a given option in a given section."""296 if not section or section == DEFAULTSECT:297 option = self.optionxform(option)298 return option in self._defaults299 elif section not in self._sections:300 return False301 else:302 option = self.optionxform(option)303 return (option in self._sections[section]304 or option in self._defaults)305 def set(self, section, option, value=None):306 """Set an option."""307 if not section or section == DEFAULTSECT:308 sectdict = self._defaults309 else:310 try:311 sectdict = self._sections[section]312 except KeyError:313 raise NoSectionError(section)314 sectdict[self.optionxform(option)] = value315 def write(self, fp):316 """Write an .ini-format representation of the configuration state."""317 if self._defaults:318 fp.write("[%s]\n" % DEFAULTSECT)319 for (key, value) in self._defaults.items():320 fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))321 fp.write("\n")322 for section in self._sections:323 fp.write("[%s]\n" % section)324 for (key, value) in self._sections[section].items():325 if key == "__name__":326 continue327 if (value is not None) or (self._optcre == self.OPTCRE):328 key = " = ".join((key, str(value).replace('\n', '\n\t')))329 fp.write("%s\n" % (key))330 fp.write("\n")331 def remove_option(self, section, option):332 """Remove an option."""333 if not section or section == DEFAULTSECT:334 sectdict = self._defaults335 else:336 try:337 sectdict = self._sections[section]338 except KeyError:339 raise NoSectionError(section)340 option = self.optionxform(option)341 existed = option in sectdict342 if existed:343 del sectdict[option]344 return existed345 def remove_section(self, section):346 """Remove a file section."""347 existed = section in self._sections348 if existed:349 del self._sections[section]350 return existed351 #352 # Regular expressions for parsing section headers and options.353 #354 SECTCRE = re.compile(355 r'\[' # [356 r'(?P<header>[^]]+)' # very permissive!357 r'\]' # ]358 )359 OPTCRE = re.compile(...

Full Screen

Full Screen

InfParser.py

Source:InfParser.py Github

copy

Full Screen

1## @file2# This file contained the parser for INF file3#4# Copyright (c) 2011, Intel Corporation. All rights reserved.<BR>5#6# This program and the accompanying materials are licensed and made available 7# under the terms and conditions of the BSD License which accompanies this 8# distribution. The full text of the license may be found at 9# http://opensource.org/licenses/bsd-license.php10#11# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,12# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.13#14'''15InfParser16'''17##18# Import Modules19#20import re21import os22from copy import deepcopy23from Library.String import GetSplitValueList24from Library.String import ConvertSpecialChar25from Library.Misc import ProcessLineExtender26from Library.Misc import ProcessEdkComment27from Library.Parsing import NormPath28from Library.ParserValidate import IsValidInfMoudleTypeList29from Library.ParserValidate import IsValidArch30from Library import DataType as DT31from Library import GlobalData32import Logger.Log as Logger33from Logger import StringTable as ST34from Logger.ToolError import FORMAT_INVALID35from Logger.ToolError import FILE_READ_FAILURE36from Logger.ToolError import PARSER_ERROR37from Object.Parser.InfCommonObject import InfSectionCommonDef38from Parser.InfSectionParser import InfSectionParser39from Parser.InfParserMisc import gINF_SECTION_DEF40from Parser.InfParserMisc import IsBinaryInf41## OpenInfFile42#43#44def OpenInfFile(Filename):45 FileLinesList = []46 47 try:48 FInputfile = open(Filename, "rb", 0)49 try:50 FileLinesList = FInputfile.readlines()51 except BaseException:52 Logger.Error("InfParser", 53 FILE_READ_FAILURE, 54 ST.ERR_FILE_OPEN_FAILURE,55 File=Filename)56 finally:57 FInputfile.close()58 except BaseException:59 Logger.Error("InfParser", 60 FILE_READ_FAILURE, 61 ST.ERR_FILE_OPEN_FAILURE,62 File=Filename)63 64 return FileLinesList65## InfParser66#67# This class defined the structure used in InfParser object68#69# @param InfObject: Inherited from InfSectionParser class70# @param Filename: Input value for Filename of INF file, default is 71# None72# @param WorkspaceDir: Input value for current workspace directory, 73# default is None74#75class InfParser(InfSectionParser):76 def __init__(self, Filename = None, WorkspaceDir = None):77 78 #79 # Call parent class construct function80 #81 super(InfParser, self).__init__()82 83 self.WorkspaceDir = WorkspaceDir84 self.SupArchList = DT.ARCH_LIST85 self.EventList = []86 self.HobList = []87 self.BootModeList = []88 #89 # Load Inf file if filename is not None90 #91 if Filename != None:92 self.ParseInfFile(Filename)93 ## Parse INF file94 #95 # Parse the file if it exists96 #97 # @param Filename: Input value for filename of INF file98 #99 def ParseInfFile(self, Filename):100 101 Filename = NormPath(Filename)102 (Path, Name) = os.path.split(Filename)103 self.FullPath = Filename104 self.RelaPath = Path105 self.FileName = Name106 GlobalData.gINF_MODULE_DIR = Path107 GlobalData.gINF_MODULE_NAME = self.FullPath108 GlobalData.gIS_BINARY_INF = False109 #110 # Initialize common data111 #112 LineNo = 0113 CurrentSection = DT.MODEL_UNKNOWN 114 SectionLines = []115 116 #117 # Flags118 #119 HeaderCommentStart = False 120 HeaderCommentEnd = False121 122 #123 # While Section ends. parse whole section contents.124 #125 NewSectionStartFlag = False126 FirstSectionStartFlag = False127 128 #129 # Parse file content130 #131 CommentBlock = []132 133 #134 # Variables for Event/Hob/BootMode135 #136 self.EventList = []137 self.HobList = []138 self.BootModeList = []139 SectionType = ''140 141 FileLinesList = OpenInfFile (Filename)142 143 #144 # One INF file can only has one [Defines] section.145 #146 DefineSectionParsedFlag = False147 148 #149 # Convert special characters in lines to space character.150 #151 FileLinesList = ConvertSpecialChar(FileLinesList)152 153 #154 # Process Line Extender155 #156 FileLinesList = ProcessLineExtender(FileLinesList)157 158 #159 # Process EdkI INF style comment if found160 #161 OrigLines = [Line for Line in FileLinesList]162 FileLinesList, EdkCommentStartPos = ProcessEdkComment(FileLinesList)163 164 #165 # Judge whether the INF file is Binary INF or not166 #167 if IsBinaryInf(FileLinesList):168 GlobalData.gIS_BINARY_INF = True169 170 InfSectionCommonDefObj = None171 172 for Line in FileLinesList:173 LineNo = LineNo + 1174 Line = Line.strip()175 if (LineNo < len(FileLinesList) - 1):176 NextLine = FileLinesList[LineNo].strip()177 178 #179 # blank line180 #181 if (Line == '' or not Line) and LineNo == len(FileLinesList):182 LastSectionFalg = True183 #184 # check whether file header comment section started185 #186 if Line.startswith(DT.TAB_SPECIAL_COMMENT) and \187 (Line.find(DT.TAB_HEADER_COMMENT) > -1) and \188 not HeaderCommentStart:189 if CurrentSection != DT.MODEL_UNKNOWN:190 Logger.Error("Parser", 191 PARSER_ERROR, 192 ST.ERR_INF_PARSER_HEADER_FILE, 193 File=Filename, 194 Line=LineNo, 195 RaiseError = Logger.IS_RAISE_ERROR)196 else:197 CurrentSection = DT.MODEL_META_DATA_FILE_HEADER198 #199 # Append the first line to section lines.200 #201 SectionLines.append((Line, LineNo))202 HeaderCommentStart = True203 continue 204 205 #206 # Collect Header content.207 #208 if (Line.startswith(DT.TAB_COMMENT_SPLIT) and CurrentSection == DT.MODEL_META_DATA_FILE_HEADER) and\209 HeaderCommentStart and not Line.startswith(DT.TAB_SPECIAL_COMMENT) and not\210 HeaderCommentEnd and NextLine != '':211 SectionLines.append((Line, LineNo))212 continue213 #214 # Header content end215 #216 if (Line.startswith(DT.TAB_SPECIAL_COMMENT) or not Line.strip().startswith("#")) and HeaderCommentStart \217 and not HeaderCommentEnd:218 SectionLines.append((Line, LineNo))219 HeaderCommentStart = False220 #221 # Call Header comment parser.222 #223 self.InfHeaderParser(SectionLines, self.InfHeader, self.FileName)224 SectionLines = []225 HeaderCommentEnd = True 226 continue 227 228 #229 # Find a new section tab230 # Or at the last line of INF file, 231 # need to process the last section.232 #233 LastSectionFalg = False234 if LineNo == len(FileLinesList):235 LastSectionFalg = True236 237 if Line.startswith(DT.TAB_COMMENT_SPLIT) and not Line.startswith(DT.TAB_SPECIAL_COMMENT):238 SectionLines.append((Line, LineNo))239 if not LastSectionFalg:240 continue241 242 #243 # Encountered a section. start with '[' and end with ']'244 #245 if (Line.startswith(DT.TAB_SECTION_START) and \246 Line.find(DT.TAB_SECTION_END) > -1) or LastSectionFalg: 247 if not LastSectionFalg:248 #249 # check to prevent '#' inside section header250 #251 HeaderContent = Line[1:Line.find(DT.TAB_SECTION_END)]252 if HeaderContent.find(DT.TAB_COMMENT_SPLIT) != -1:253 Logger.Error("InfParser", 254 FORMAT_INVALID,255 ST.ERR_INF_PARSER_DEFINE_SECTION_HEADER_INVALID,256 File=self.FullPath,257 Line=LineNo, 258 ExtraData=Line) 259 260 #261 # Keep last time section header content for section parser262 # usage.263 #264 self.LastSectionHeaderContent = deepcopy(self.SectionHeaderContent)265 266 #267 # TailComments in section define.268 #269 TailComments = ''270 CommentIndex = Line.find(DT.TAB_COMMENT_SPLIT)271 if CommentIndex > -1:272 TailComments = Line[CommentIndex:]273 Line = Line[:CommentIndex]274 275 InfSectionCommonDefObj = InfSectionCommonDef()276 if TailComments != '':277 InfSectionCommonDefObj.SetTailComments(TailComments)278 if CommentBlock != '':279 InfSectionCommonDefObj.SetHeaderComments(CommentBlock)280 CommentBlock = []281 #282 # Call section parser before section header parer to avoid encounter EDKI INF file283 #284 if CurrentSection == DT.MODEL_META_DATA_DEFINE:285 DefineSectionParsedFlag = self._CallSectionParsers(CurrentSection, 286 DefineSectionParsedFlag, SectionLines, 287 InfSectionCommonDefObj, LineNo)288 #289 # Compare the new section name with current290 #291 self.SectionHeaderParser(Line, self.FileName, LineNo)292 293 self._CheckSectionHeaders(Line, LineNo)294 SectionType = _ConvertSecNameToType(self.SectionHeaderContent[0][0])295 296 if not FirstSectionStartFlag:297 CurrentSection = SectionType298 FirstSectionStartFlag = True299 else:300 NewSectionStartFlag = True301 else:302 SectionLines.append((Line, LineNo))303 continue304 305 if LastSectionFalg:306 SectionLines, CurrentSection = self._ProcessLastSection(SectionLines, Line, LineNo, CurrentSection)307 308 #309 # End of section content collect.310 # Parser the section content collected previously.311 # 312 if NewSectionStartFlag or LastSectionFalg:313 if CurrentSection != DT.MODEL_META_DATA_DEFINE or \314 (LastSectionFalg and CurrentSection == DT.MODEL_META_DATA_DEFINE): 315 DefineSectionParsedFlag = self._CallSectionParsers(CurrentSection, 316 DefineSectionParsedFlag, SectionLines, 317 InfSectionCommonDefObj, LineNo)318 319 CurrentSection = SectionType320 #321 # Clear section lines322 #323 SectionLines = [] 324 #325 # End of for326 #327 #328 # Found the first section, No file header.329 #330 if DefineSectionParsedFlag and not HeaderCommentEnd:331 Logger.Error("InfParser", 332 FORMAT_INVALID, 333 ST.ERR_INF_PARSER_HEADER_MISSGING, 334 File=self.FullPath)335 336 #337 # EDKII INF should not have EDKI style comment338 #339 if EdkCommentStartPos != -1:340 Logger.Error("InfParser", 341 FORMAT_INVALID, 342 ST.ERR_INF_PARSER_EDKI_COMMENT_IN_EDKII, 343 File=self.FullPath,344 Line=EdkCommentStartPos + 1,345 ExtraData=OrigLines[EdkCommentStartPos])346 347 #348 # extract [Event] [Hob] [BootMode] sections 349 # 350 self._ExtractEventHobBootMod(FileLinesList)351 352 ## _CheckSectionHeaders353 #354 #355 def _CheckSectionHeaders(self, Line, LineNo):356 if len(self.SectionHeaderContent) == 0:357 Logger.Error("InfParser", 358 FORMAT_INVALID,359 ST.ERR_INF_PARSER_DEFINE_SECTION_HEADER_INVALID,360 File=self.FullPath,361 Line=LineNo, ExtraData=Line)362 else:363 for SectionItem in self.SectionHeaderContent:364 ArchList = []365 #366 # Not cover Depex/UserExtension section header 367 # check.368 #369 if SectionItem[0].strip().upper() == DT.TAB_INF_FIXED_PCD.upper() or \370 SectionItem[0].strip().upper() == DT.TAB_INF_PATCH_PCD.upper() or \371 SectionItem[0].strip().upper() == DT.TAB_INF_PCD_EX.upper() or \372 SectionItem[0].strip().upper() == DT.TAB_INF_PCD.upper() or \373 SectionItem[0].strip().upper() == DT.TAB_INF_FEATURE_PCD.upper():374 ArchList = GetSplitValueList(SectionItem[1].strip(), ' ')375 else:376 ArchList = [SectionItem[1].strip()]377 378 for Arch in ArchList:379 if (not IsValidArch(Arch)) and \380 (SectionItem[0].strip().upper() != DT.TAB_DEPEX.upper()) and \381 (SectionItem[0].strip().upper() != DT.TAB_USER_EXTENSIONS.upper()) and \382 (SectionItem[0].strip().upper() != DT.TAB_COMMON_DEFINES.upper()):383 Logger.Error("InfParser", 384 FORMAT_INVALID,385 ST.ERR_INF_PARSER_DEFINE_FROMAT_INVALID%(SectionItem[1]), 386 File=self.FullPath,387 Line=LineNo, ExtraData=Line)388 #389 # Check if the ModuleType is valid390 #391 ChkModSectionList = ['LIBRARYCLASSES']392 if (self.SectionHeaderContent[0][0].upper() in ChkModSectionList):393 if SectionItem[2].strip().upper():394 MoudleTypeList = GetSplitValueList(395 SectionItem[2].strip().upper())396 if (not IsValidInfMoudleTypeList(MoudleTypeList)):397 Logger.Error("InfParser",398 FORMAT_INVALID,399 ST.ERR_INF_PARSER_DEFINE_FROMAT_INVALID%(SectionItem[2]),400 File=self.FullPath, Line=LineNo,401 ExtraData=Line)402 403 ## _CallSectionParsers404 #405 #406 def _CallSectionParsers(self, CurrentSection, DefineSectionParsedFlag, 407 SectionLines, InfSectionCommonDefObj, LineNo):408 if CurrentSection == DT.MODEL_META_DATA_DEFINE:409 if not DefineSectionParsedFlag:410 self.InfDefineParser(SectionLines,411 self.InfDefSection,412 self.FullPath,413 InfSectionCommonDefObj)414 DefineSectionParsedFlag = True415 else:416 Logger.Error("Parser", 417 PARSER_ERROR, 418 ST.ERR_INF_PARSER_MULTI_DEFINE_SECTION, 419 File=self.FullPath, 420 RaiseError = Logger.IS_RAISE_ERROR)421 422 elif CurrentSection == DT.MODEL_META_DATA_BUILD_OPTION:423 self.InfBuildOptionParser(SectionLines,424 self.InfBuildOptionSection,425 self.FullPath)426 427 elif CurrentSection == DT.MODEL_EFI_LIBRARY_CLASS:428 self.InfLibraryParser(SectionLines,429 self.InfLibraryClassSection,430 self.FullPath)431 432 elif CurrentSection == DT.MODEL_META_DATA_PACKAGE:433 self.InfPackageParser(SectionLines,434 self.InfPackageSection,435 self.FullPath)436 #437 # [Pcd] Sections, put it together438 #439 elif CurrentSection == DT.MODEL_PCD_FIXED_AT_BUILD or \440 CurrentSection == DT.MODEL_PCD_PATCHABLE_IN_MODULE or \441 CurrentSection == DT.MODEL_PCD_FEATURE_FLAG or \442 CurrentSection == DT.MODEL_PCD_DYNAMIC_EX or \443 CurrentSection == DT.MODEL_PCD_DYNAMIC:444 self.InfPcdParser(SectionLines,445 self.InfPcdSection,446 self.FullPath)447 448 elif CurrentSection == DT.MODEL_EFI_SOURCE_FILE:449 self.InfSourceParser(SectionLines,450 self.InfSourcesSection,451 self.FullPath)452 453 elif CurrentSection == DT.MODEL_META_DATA_USER_EXTENSION:454 self.InfUserExtensionParser(SectionLines,455 self.InfUserExtensionSection,456 self.FullPath)457 458 elif CurrentSection == DT.MODEL_EFI_PROTOCOL:459 self.InfProtocolParser(SectionLines,460 self.InfProtocolSection,461 self.FullPath)462 463 elif CurrentSection == DT.MODEL_EFI_PPI:464 self.InfPpiParser(SectionLines,465 self.InfPpiSection,466 self.FullPath)467 468 elif CurrentSection == DT.MODEL_EFI_GUID:469 self.InfGuidParser(SectionLines,470 self.InfGuidSection,471 self.FullPath)472 473 elif CurrentSection == DT.MODEL_EFI_DEPEX:474 self.InfDepexParser(SectionLines,475 self.InfDepexSection,476 self.FullPath)477 478 elif CurrentSection == DT.MODEL_EFI_BINARY_FILE:479 self.InfBinaryParser(SectionLines,480 self.InfBinariesSection,481 self.FullPath)482 #483 # Unknown section type found, raise error.484 #485 else:486 if len(self.SectionHeaderContent) >= 1:487 Logger.Error("Parser", 488 PARSER_ERROR, 489 ST.ERR_INF_PARSER_UNKNOWN_SECTION, 490 File=self.FullPath, Line=LineNo, 491 RaiseError = Logger.IS_RAISE_ERROR)492 else:493 Logger.Error("Parser", 494 PARSER_ERROR, 495 ST.ERR_INF_PARSER_NO_SECTION_ERROR, 496 File=self.FullPath, Line=LineNo, 497 RaiseError = Logger.IS_RAISE_ERROR)498 499 return DefineSectionParsedFlag 500 501 def _ExtractEventHobBootMod(self, FileLinesList):502 SpecialSectionStart = False503 CheckLocation = False504 GFindSpecialCommentRe = \505 re.compile(r"""#(?:\s*)\[(.*?)\](?:.*)""", re.DOTALL)506 GFindNewSectionRe2 = \507 re.compile(r"""#?(\s*)\[(.*?)\](.*)""", re.DOTALL)508 LineNum = 0509 Element = []510 for Line in FileLinesList:511 Line = Line.strip()512 LineNum += 1513 MatchObject = GFindSpecialCommentRe.search(Line)514 if MatchObject:515 SpecialSectionStart = True516 Element = []517 if MatchObject.group(1).upper().startswith("EVENT"):518 List = self.EventList519 elif MatchObject.group(1).upper().startswith("HOB"):520 List = self.HobList521 elif MatchObject.group(1).upper().startswith("BOOTMODE"):522 List = self.BootModeList523 else:524 SpecialSectionStart = False525 CheckLocation = False526 if SpecialSectionStart:527 Element.append([Line, LineNum])528 List.append(Element)529 else:530 #531 # if currently in special section, try to detect end of current section532 #533 MatchObject = GFindNewSectionRe2.search(Line)534 if SpecialSectionStart:535 if MatchObject:536 SpecialSectionStart = False537 CheckLocation = False538 Element = []539 elif not Line:540 SpecialSectionStart = False541 CheckLocation = True542 Element = [] 543 else:544 if not Line.startswith(DT.TAB_COMMENT_SPLIT):545 Logger.Warn("Parser", 546 ST.WARN_SPECIAL_SECTION_LOCATION_WRONG, 547 File=self.FullPath, Line=LineNum)548 SpecialSectionStart = False549 CheckLocation = False550 Element = []551 else:552 Element.append([Line, LineNum]) 553 else:554 if CheckLocation:555 if MatchObject:556 CheckLocation = False557 elif Line:558 Logger.Warn("Parser", 559 ST.WARN_SPECIAL_SECTION_LOCATION_WRONG, 560 File=self.FullPath, Line=LineNum) 561 CheckLocation = False562 563 if len(self.BootModeList) >= 1:564 self.InfSpecialCommentParser(self.BootModeList, 565 self.InfSpecialCommentSection, 566 self.FileName, 567 DT.TYPE_BOOTMODE_SECTION)568 569 if len(self.EventList) >= 1:570 self.InfSpecialCommentParser(self.EventList, 571 self.InfSpecialCommentSection,572 self.FileName, 573 DT.TYPE_EVENT_SECTION)574 575 if len(self.HobList) >= 1:576 self.InfSpecialCommentParser(self.HobList, 577 self.InfSpecialCommentSection, 578 self.FileName, 579 DT.TYPE_HOB_SECTION)580 ## _ProcessLastSection581 #582 #583 def _ProcessLastSection(self, SectionLines, Line, LineNo, CurrentSection):584 #585 # The last line is a section header. will discard it.586 #587 if not (Line.startswith(DT.TAB_SECTION_START) and Line.find(DT.TAB_SECTION_END) > -1): 588 SectionLines.append((Line, LineNo))589 590 if len(self.SectionHeaderContent) >= 1:591 TemSectionName = self.SectionHeaderContent[0][0].upper()592 if TemSectionName.upper() not in gINF_SECTION_DEF.keys():593 Logger.Error("InfParser", 594 FORMAT_INVALID, 595 ST.ERR_INF_PARSER_UNKNOWN_SECTION, 596 File=self.FullPath, 597 Line=LineNo, 598 ExtraData=Line,599 RaiseError = Logger.IS_RAISE_ERROR600 ) 601 else:602 CurrentSection = gINF_SECTION_DEF[TemSectionName]603 self.LastSectionHeaderContent = self.SectionHeaderContent604 605 return SectionLines, CurrentSection606## _ConvertSecNameToType607#608#609def _ConvertSecNameToType(SectionName): 610 SectionType = ''611 if SectionName.upper() not in gINF_SECTION_DEF.keys():612 SectionType = DT.MODEL_UNKNOWN 613 else:614 SectionType = gINF_SECTION_DEF[SectionName.upper()] 615 616 return SectionType ...

Full Screen

Full Screen

InfSectionParser.py

Source:InfSectionParser.py Github

copy

Full Screen

1## @file2# This file contained the parser for sections in INF file 3#4# Copyright (c) 2011, Intel Corporation. All rights reserved.<BR>5#6# This program and the accompanying materials are licensed and made available 7# under the terms and conditions of the BSD License which accompanies this 8# distribution. The full text of the license may be found at 9# http://opensource.org/licenses/bsd-license.php10#11# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,12# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.13#14'''15InfSectionParser16'''17##18# Import Modules19#20from copy import deepcopy21import re22from Library.String import GetSplitValueList23from Library.CommentParsing import ParseHeaderCommentSection24from Library.CommentParsing import ParseComment25from Library import DataType as DT26import Logger.Log as Logger27from Logger import StringTable as ST28from Logger.ToolError import FORMAT_INVALID29from Object.Parser.InfDefineObject import InfDefObject30from Object.Parser.InfBuildOptionObject import InfBuildOptionsObject31from Object.Parser.InfLibraryClassesObject import InfLibraryClassObject32from Object.Parser.InfPackagesObject import InfPackageObject33from Object.Parser.InfPcdObject import InfPcdObject34from Object.Parser.InfSoucesObject import InfSourcesObject35from Object.Parser.InfUserExtensionObject import InfUserExtensionObject36from Object.Parser.InfProtocolObject import InfProtocolObject37from Object.Parser.InfPpiObject import InfPpiObject38from Object.Parser.InfGuidObject import InfGuidObject39from Object.Parser.InfDepexObject import InfDepexObject40from Object.Parser.InfBinaryObject import InfBinariesObject41from Object.Parser.InfHeaderObject import InfHeaderObject42from Object.Parser.InfMisc import InfSpecialCommentObject43from Object.Parser.InfMisc import InfHobObject44from Object.Parser.InfMisc import InfBootModeObject45from Object.Parser.InfMisc import InfEventObject46from Parser.InfParserMisc import gINF_SECTION_DEF47from Parser.InfDefineSectionParser import InfDefinSectionParser48from Parser.InfBuildOptionSectionParser import InfBuildOptionSectionParser49from Parser.InfSourceSectionParser import InfSourceSectionParser50from Parser.InfLibrarySectionParser import InfLibrarySectionParser51from Parser.InfPackageSectionParser import InfPackageSectionParser52from Parser.InfGuidPpiProtocolSectionParser import InfGuidPpiProtocolSectionParser53from Parser.InfBinarySectionParser import InfBinarySectionParser54from Parser.InfPcdSectionParser import InfPcdSectionParser55from Parser.InfDepexSectionParser import InfDepexSectionParser56## GetSpecialStr257#58# GetSpecialStr259#60def GetSpecialStr2(ItemList, FileName, LineNo, SectionString):61 Str2 = ''62 #63 # S2 may be Platform or ModuleType64 #65 if len(ItemList) == 3:66 #67 # Except [LibraryClass], [Depex]68 # section can has more than 2 items in section header string,69 # others should report error.70 #71 if not (ItemList[0].upper() == DT.TAB_LIBRARY_CLASSES.upper() or \72 ItemList[0].upper() == DT.TAB_DEPEX.upper() or \73 ItemList[0].upper() == DT.TAB_USER_EXTENSIONS.upper()):74 if ItemList[2] != '':75 Logger.Error('Parser',76 FORMAT_INVALID,77 ST.ERR_INF_PARSER_SOURCE_SECTION_SECTIONNAME_INVALID % (SectionString),78 File=FileName,79 Line=LineNo,80 ExtraData=SectionString)81 Str2 = ItemList[2]82 elif len(ItemList) == 4:83 #84 # Except [UserExtension]85 # section can has 4 items in section header string,86 # others should report error.87 #88 if not ItemList[0].upper() == DT.TAB_USER_EXTENSIONS.upper() or ItemList[0].upper() == DT.TAB_DEPEX.upper():89 if ItemList[3] != '':90 Logger.Error('Parser', FORMAT_INVALID, ST.ERR_INF_PARSER_SOURCE_SECTION_SECTIONNAME_INVALID \91 % (SectionString), File=FileName, Line=LineNo, ExtraData=SectionString)92 93 if not ItemList[0].upper() == DT.TAB_USER_EXTENSIONS.upper():94 Str2 = ItemList[2] + ' | ' + ItemList[3]95 else:96 Str2 = ItemList[2]97 elif len(ItemList) > 4:98 Logger.Error('Parser', FORMAT_INVALID, ST.ERR_INF_PARSER_SOURCE_SECTION_SECTIONNAME_INVALID \99 % (SectionString), File=FileName, Line=LineNo, ExtraData=SectionString)100 return Str2101## ProcessUseExtHeader102# 103#104def ProcessUseExtHeader(ItemList):105 NewItemList = []106 AppendContent = ''107 CompleteFlag = False108 for Item in ItemList:109 if Item.startswith('\"') and not Item.endswith('\"'):110 AppendContent = Item111 CompleteFlag = True112 elif Item.endswith('\"') and not Item.startswith('\"'):113 #114 # Should not have an userId or IdString not starts with " before but ends with ".115 #116 if not CompleteFlag:117 return False, []118 AppendContent = AppendContent + "." + Item119 NewItemList.append(AppendContent)120 CompleteFlag = False121 AppendContent = ''122 elif Item.endswith('\"') and Item.startswith('\"'):123 #124 # Common item, not need to combine the information125 #126 NewItemList.append(Item)127 else:128 if not CompleteFlag:129 NewItemList.append(Item)130 else:131 AppendContent = AppendContent + "." + Item132 133 if len(NewItemList) > 4:134 return False, []135 136 return True, NewItemList137 138## GetArch139#140# GetArch141#142def GetArch(ItemList, ArchList, FileName, LineNo, SectionString):143 #144 # S1 is always Arch145 #146 if len(ItemList) > 1:147 Arch = ItemList[1]148 else:149 Arch = 'COMMON'150 ArchList.add(Arch)151 #152 # 'COMMON' must not be used with specific ARCHs at the same section153 #154 if 'COMMON' in ArchList and len(ArchList) > 1:155 Logger.Error('Parser',156 FORMAT_INVALID,157 ST.ERR_INF_PARSER_SECTION_ARCH_CONFLICT,158 File=FileName,159 Line=LineNo,160 ExtraData=SectionString)161 return Arch, ArchList162## InfSectionParser163#164# Inherit from object165#166class InfSectionParser(InfDefinSectionParser,167 InfBuildOptionSectionParser,168 InfSourceSectionParser,169 InfLibrarySectionParser,170 InfPackageSectionParser,171 InfGuidPpiProtocolSectionParser,172 InfBinarySectionParser,173 InfPcdSectionParser,174 InfDepexSectionParser):175 #176 # Parser objects used to implement singleton177 #178 MetaFiles = {}179 ## Factory method180 #181 # One file, one parser object. This factory method makes sure that there's182 # only one object constructed for one meta file.183 #184 # @param Class class object of real AutoGen class185 # (InfParser, DecParser or DscParser)186 # @param FilePath The path of meta file187 #188 def __new__(cls, FilePath, *args, **kwargs):189 if args:190 pass191 if kwargs:192 pass193 if FilePath in cls.MetaFiles:194 return cls.MetaFiles[FilePath]195 else:196 ParserObject = super(InfSectionParser, cls).__new__(cls)197 cls.MetaFiles[FilePath] = ParserObject198 return ParserObject199 def __init__(self):200 InfDefinSectionParser.__init__(self)201 InfBuildOptionSectionParser.__init__(self)202 InfSourceSectionParser.__init__(self)203 InfLibrarySectionParser.__init__(self)204 InfPackageSectionParser.__init__(self)205 InfGuidPpiProtocolSectionParser.__init__(self)206 InfBinarySectionParser.__init__(self)207 InfPcdSectionParser.__init__(self)208 InfDepexSectionParser.__init__(self)209 #210 # Initialize all objects that an INF file will generated.211 #212 self.InfDefSection = InfDefObject()213 self.InfBuildOptionSection = InfBuildOptionsObject()214 self.InfLibraryClassSection = InfLibraryClassObject()215 self.InfPackageSection = InfPackageObject()216 self.InfPcdSection = InfPcdObject(self.MetaFiles.keys()[0])217 self.InfSourcesSection = InfSourcesObject()218 self.InfUserExtensionSection = InfUserExtensionObject()219 self.InfProtocolSection = InfProtocolObject()220 self.InfPpiSection = InfPpiObject()221 self.InfGuidSection = InfGuidObject()222 self.InfDepexSection = InfDepexObject()223 self.InfPeiDepexSection = InfDepexObject()224 self.InfDxeDepexSection = InfDepexObject()225 self.InfSmmDepexSection = InfDepexObject()226 self.InfBinariesSection = InfBinariesObject()227 self.InfHeader = InfHeaderObject()228 self.InfSpecialCommentSection = InfSpecialCommentObject()229 #230 # A List for store define section content.231 # 232 self._PcdNameList = []233 self._SectionName = ''234 self._SectionType = 0235 self.RelaPath = ''236 self.FileName = ''237 #238 # File Header content parser239 # 240 def InfHeaderParser(self, Content, InfHeaderObject2, FileName):241 (Abstract, Description, Copyright, License) = ParseHeaderCommentSection(Content, FileName)242 #243 # Not process file name now, for later usage.244 #245 if self.FileName:246 pass247 #248 # Insert Abstract, Description, CopyRight, License into header object249 # 250 InfHeaderObject2.SetAbstract(Abstract)251 InfHeaderObject2.SetDescription(Description)252 InfHeaderObject2.SetCopyright(Copyright)253 InfHeaderObject2.SetLicense(License)254 ## Section header parser255 #256 # The section header is always in following format:257 #258 # [section_name.arch<.platform|module_type>]259 #260 # @param String A string contained the content need to be parsed. 261 #262 def SectionHeaderParser(self, SectionString, FileName, LineNo):263 _Scope = []264 _SectionName = ''265 ArchList = set()266 _ValueList = []267 _PcdNameList = [DT.TAB_INF_FIXED_PCD.upper(),268 DT.TAB_INF_FEATURE_PCD.upper(),269 DT.TAB_INF_PATCH_PCD.upper(),270 DT.TAB_INF_PCD.upper(),271 DT.TAB_INF_PCD_EX.upper()272 ]273 SectionString = SectionString.strip()274 for Item in GetSplitValueList(SectionString[1:-1], DT.TAB_COMMA_SPLIT):275 if Item == '':276 Logger.Error('Parser',277 FORMAT_INVALID,278 ST.ERR_INF_PARSER_MODULE_SECTION_TYPE_ERROR % (""),279 File=FileName,280 Line=LineNo,281 ExtraData=SectionString)282 ItemList = GetSplitValueList(Item, DT.TAB_SPLIT)283 #284 # different section should not mix in one section285 # Allow different PCD type sections mixed together286 # 287 if _SectionName.upper() not in _PcdNameList:288 if _SectionName != '' and _SectionName.upper() != ItemList[0].upper():289 Logger.Error('Parser',290 FORMAT_INVALID,291 ST.ERR_INF_PARSER_SECTION_NAME_DUPLICATE,292 File=FileName,293 Line=LineNo,294 ExtraData=SectionString)295 elif _PcdNameList[1] in [_SectionName.upper(), ItemList[0].upper()] and \296 (_SectionName.upper()!= ItemList[0].upper()):297 Logger.Error('Parser',298 FORMAT_INVALID,299 ST.ERR_INF_PARSER_MODULE_SECTION_TYPE_ERROR % (""),300 File=FileName,301 Line=LineNo,302 ExtraData=SectionString)303 _SectionName = ItemList[0]304 if _SectionName.upper() in gINF_SECTION_DEF:305 self._SectionType = gINF_SECTION_DEF[_SectionName.upper()]306 else:307 self._SectionType = DT.MODEL_UNKNOWN308 Logger.Error("Parser",309 FORMAT_INVALID,310 ST.ERR_INF_PARSER_UNKNOWN_SECTION,311 File=FileName,312 Line=LineNo,313 ExtraData=SectionString)314 #315 # Get Arch316 #317 Str1, ArchList = GetArch(ItemList, ArchList, FileName, LineNo, SectionString)318 #319 # For [Defines] section, do special check.320 # 321 if ItemList[0].upper() == DT.TAB_COMMON_DEFINES.upper():322 if len(ItemList) != 1:323 Logger.Error('Parser',324 FORMAT_INVALID,325 ST.ERR_INF_PARSER_DEFINE_FROMAT_INVALID % (SectionString),326 File=FileName, Line=LineNo, ExtraData=SectionString)327 #328 # For [UserExtension] section, do special check.329 # 330 if ItemList[0].upper() == DT.TAB_USER_EXTENSIONS.upper():331 332 RetValue = ProcessUseExtHeader(ItemList)333 334 if not RetValue[0]:335 Logger.Error('Parser',336 FORMAT_INVALID,337 ST.ERR_INF_PARSER_DEFINE_FROMAT_INVALID % (SectionString),338 File=FileName, Line=LineNo, ExtraData=SectionString)339 else:340 ItemList = RetValue[1] 341 342 if len(ItemList) == 3:343 ItemList.append('COMMON')344 345 Str1 = ItemList[1]346 #347 # For Library classes, need to check module type. 348 #349 if ItemList[0].upper() == DT.TAB_LIBRARY_CLASSES.upper() and len(ItemList) == 3:350 if ItemList[2] != '':351 ModuleTypeList = GetSplitValueList(ItemList[2], DT.TAB_VALUE_SPLIT)352 for Item in ModuleTypeList:353 if Item.strip() not in DT.MODULE_LIST:354 Logger.Error('Parser',355 FORMAT_INVALID,356 ST.ERR_INF_PARSER_DEFINE_MODULETYPE_INVALID % (Item),357 File=FileName,358 Line=LineNo,359 ExtraData=SectionString)360 #361 # GetSpecialStr2362 #363 Str2 = GetSpecialStr2(ItemList, FileName, LineNo, SectionString)364 _Scope.append([Str1, Str2])365 _NewValueList = []366 _AppendFlag = True367 if _SectionName.upper() in _PcdNameList:368 for ValueItem in _ValueList:369 if _SectionName.upper() == ValueItem[0].upper() and Str1.upper() not in ValueItem[1].split():370 ValueItem[1] = ValueItem[1] + " " + Str1371 _AppendFlag = False372 elif _SectionName.upper() == ValueItem[0].upper() and Str1.upper() in ValueItem[1].split():373 _AppendFlag = False374 _NewValueList.append(ValueItem)375 _ValueList = _NewValueList376 if _AppendFlag:377 if not ItemList[0].upper() == DT.TAB_USER_EXTENSIONS.upper():378 _ValueList.append([_SectionName, Str1, Str2, LineNo])379 else:380 if len(ItemList) == 4:381 _ValueList.append([_SectionName, Str1, Str2, ItemList[3], LineNo])382 self.SectionHeaderContent = deepcopy(_ValueList)383 ## GenSpecialSectionList384 #385 # @param SpecialSectionList: a list of list, of which item's format 386 # (Comment, LineNum)387 # @param ContainerFile: Input value for filename of Inf file388 # 389 def InfSpecialCommentParser (self, SpecialSectionList, InfSectionObject, ContainerFile, SectionType):390 ReFindSpecialCommentRe = re.compile(r"""#(?:\s*)\[(.*?)\](?:.*)""", re.DOTALL)391 ReFindHobArchRe = re.compile(r"""[Hh][Oo][Bb]\.([^,]*)""", re.DOTALL)392 if self.FileName:393 pass394 SpecialObjectList = []395 ArchList = []396 if SectionType == DT.TYPE_EVENT_SECTION:397 TokenDict = DT.EVENT_TOKENS398 elif SectionType == DT.TYPE_HOB_SECTION:399 TokenDict = DT.HOB_TOKENS400 else:401 TokenDict = DT.BOOTMODE_TOKENS402 for List in SpecialSectionList:403 #404 # Hob has Arch attribute, need to be handled specially here405 #406 if SectionType == DT.TYPE_HOB_SECTION:407 MatchObject = ReFindSpecialCommentRe.search(List[0][0])408 HobSectionStr = MatchObject.group(1)409 ArchList = []410 for Match in ReFindHobArchRe.finditer(HobSectionStr):411 Arch = Match.groups(1)[0].upper()412 ArchList.append(Arch)413 CommentSoFar = ''414 for Index in xrange(1, len(List)):415 Result = ParseComment(List[Index], DT.ALL_USAGE_TOKENS, TokenDict, [], False)416 Usage = Result[0]417 Type = Result[1]418 HelpText = Result[3]419 if Usage == DT.ITEM_UNDEFINED and Type == DT.ITEM_UNDEFINED:420 if HelpText is None:421 HelpText = ''422 if not HelpText.endswith('\n'):423 HelpText += '\n'424 CommentSoFar += HelpText425 else:426 if HelpText:427 CommentSoFar += HelpText428 if SectionType == DT.TYPE_EVENT_SECTION:429 SpecialObject = InfEventObject()430 SpecialObject.SetEventType(Type)431 SpecialObject.SetUsage(Usage)432 SpecialObject.SetHelpString(CommentSoFar)433 elif SectionType == DT.TYPE_HOB_SECTION:434 SpecialObject = InfHobObject()435 SpecialObject.SetHobType(Type)436 SpecialObject.SetUsage(Usage)437 SpecialObject.SetHelpString(CommentSoFar)438 if len(ArchList) >= 1:439 SpecialObject.SetSupArchList(ArchList)440 else:441 SpecialObject = InfBootModeObject()442 SpecialObject.SetSupportedBootModes(Type)443 SpecialObject.SetUsage(Usage)444 SpecialObject.SetHelpString(CommentSoFar)445 SpecialObjectList.append(SpecialObject)446 CommentSoFar = ''447 if not InfSectionObject.SetSpecialComments(SpecialObjectList,448 SectionType):449 Logger.Error('InfParser',450 FORMAT_INVALID,451 ST.ERR_INF_PARSER_MODULE_SECTION_TYPE_ERROR % (SectionType),452 ContainerFile...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Nose automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful