How to use section method in storybook-root

Best JavaScript code snippet using storybook-root

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

InfGuidPpiProtocolSectionParser.py

Source:InfGuidPpiProtocolSectionParser.py Github

copy

Full Screen

1## @file2# This file contained the parser for [Guids], [Ppis], [Protocols] 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'''15InfGuidPpiProtocolSectionParser16'''17##18# Import Modules19#20import Logger.Log as Logger21from Logger import StringTable as ST22from Logger.ToolError import FORMAT_INVALID23from Parser.InfParserMisc import InfExpandMacro24from Library import DataType as DT25from Library import GlobalData26from Library.Parsing import MacroParser27from Library.Misc import GetSplitValueList28from Library.ParserValidate import IsValidIdString29from Library.ParserValidate import IsValidUserId30from Library.ParserValidate import IsValidArch31from Parser.InfParserMisc import InfParserSectionRoot32class InfGuidPpiProtocolSectionParser(InfParserSectionRoot):33 ## InfGuidParser34 #35 #36 def InfGuidParser(self, SectionString, InfSectionObject, FileName):37 #38 # Macro defined in this section 39 #40 SectionMacros = {}41 ValueList = []42 GuidList = []43 CommentsList = []44 CurrentLineVar = None45 #46 # Parse section content47 #48 for Line in SectionString:49 LineContent = Line[0]50 LineNo = Line[1]51 if LineContent.strip() == '':52 CommentsList = []53 continue54 if LineContent.strip().startswith(DT.TAB_COMMENT_SPLIT):55 CommentsList.append(Line)56 continue57 else:58 #59 # Encounter a GUID entry60 #61 if LineContent.find(DT.TAB_COMMENT_SPLIT) > -1:62 CommentsList.append((63 LineContent[LineContent.find(DT.TAB_COMMENT_SPLIT):],64 LineNo))65 LineContent = \66 LineContent[:LineContent.find(DT.TAB_COMMENT_SPLIT)]67 if LineContent != '':68 #69 # Find Macro70 #71 Name, Value = MacroParser((LineContent, LineNo),72 FileName,73 DT.MODEL_EFI_GUID,74 self.FileLocalMacros)75 if Name != None:76 SectionMacros[Name] = Value77 CommentsList = []78 ValueList = []79 continue80 TokenList = GetSplitValueList(LineContent, DT.TAB_VALUE_SPLIT, 1)81 ValueList[0:len(TokenList)] = TokenList82 #83 # Replace with Local section Macro and [Defines] section Macro.84 # 85 ValueList = [InfExpandMacro(Value, (FileName, LineContent, LineNo),86 self.FileLocalMacros, SectionMacros, True)87 for Value in ValueList]88 CurrentLineVar = (LineContent, LineNo, FileName)89 if len(ValueList) >= 1:90 GuidList.append((ValueList, CommentsList, CurrentLineVar))91 CommentsList = []92 ValueList = []93 continue94 #95 # Current section archs96 # 97 ArchList = []98 LineIndex = -199 for Item in self.LastSectionHeaderContent:100 LineIndex = Item[3]101 if Item[1] not in ArchList:102 ArchList.append(Item[1])103 if not InfSectionObject.SetGuid(GuidList, Arch=ArchList):104 Logger.Error('InfParser',105 FORMAT_INVALID,106 ST.ERR_INF_PARSER_MODULE_SECTION_TYPE_ERROR % ("[Guid]"),107 File=FileName,108 Line=LineIndex)109 ## InfPpiParser110 #111 #112 def InfPpiParser(self, SectionString, InfSectionObject, FileName):113 #114 # Macro defined in this section 115 #116 SectionMacros = {}117 ValueList = []118 PpiList = []119 CommentsList = []120 CurrentLineVar = None121 #122 # Parse section content123 #124 for Line in SectionString:125 LineContent = Line[0]126 LineNo = Line[1]127 if LineContent.strip() == '':128 CommentsList = []129 continue130 if LineContent.strip().startswith(DT.TAB_COMMENT_SPLIT):131 CommentsList.append(Line)132 continue133 else:134 #135 # Encounter a PPI entry136 #137 if LineContent.find(DT.TAB_COMMENT_SPLIT) > -1:138 CommentsList.append((139 LineContent[LineContent.find(DT.TAB_COMMENT_SPLIT):],140 LineNo))141 LineContent = \142 LineContent[:LineContent.find(DT.TAB_COMMENT_SPLIT)]143 if LineContent != '':144 #145 # Find Macro146 #147 Name, Value = MacroParser((LineContent, LineNo),148 FileName,149 DT.MODEL_EFI_PPI,150 self.FileLocalMacros)151 if Name != None:152 SectionMacros[Name] = Value153 ValueList = []154 CommentsList = []155 continue156 TokenList = GetSplitValueList(LineContent, DT.TAB_VALUE_SPLIT, 1)157 ValueList[0:len(TokenList)] = TokenList158 #159 # Replace with Local section Macro and [Defines] section Macro.160 # 161 ValueList = [InfExpandMacro(Value, (FileName, LineContent, LineNo), self.FileLocalMacros, SectionMacros)162 for Value in ValueList]163 CurrentLineVar = (LineContent, LineNo, FileName)164 if len(ValueList) >= 1:165 PpiList.append((ValueList, CommentsList, CurrentLineVar))166 ValueList = []167 CommentsList = []168 continue169 #170 # Current section archs171 # 172 ArchList = []173 LineIndex = -1174 for Item in self.LastSectionHeaderContent:175 LineIndex = Item[3]176 if Item[1] not in ArchList:177 ArchList.append(Item[1])178 if not InfSectionObject.SetPpi(PpiList, Arch=ArchList):179 Logger.Error('InfParser',180 FORMAT_INVALID,181 ST.ERR_INF_PARSER_MODULE_SECTION_TYPE_ERROR % ("[Ppis]"),182 File=FileName,183 Line=LineIndex)184 ## InfUserExtensionParser185 #186 # 187 def InfUserExtensionParser(self, SectionString, InfSectionObject, FileName):188 UserExtensionContent = ''189 #190 # Parse section content191 #192 for Line in SectionString:193 LineContent = Line[0]194 LineNo = Line[1]195 if LineContent.strip() == '':196 continue197 #198 # Replace with [Defines] section Macro199 #200 LineContent = InfExpandMacro(LineContent,201 (FileName, LineContent, LineNo),202 self.FileLocalMacros,203 None)204 UserExtensionContent += LineContent + DT.END_OF_LINE205 continue206 #207 # Current section UserId, IdString208 # 209 IdContentList = []210 LastItem = ''211 SectionLineNo = None212 for Item in self.LastSectionHeaderContent:213 UserId = Item[1]214 IdString = Item[2]215 Arch = Item[3]216 SectionLineNo = Item[4]217 if not IsValidArch(Arch):218 Logger.Error(219 'InfParser',220 FORMAT_INVALID,221 ST.ERR_INF_PARSER_DEFINE_FROMAT_INVALID % (Arch),222 File=GlobalData.gINF_MODULE_NAME,223 Line=SectionLineNo,224 ExtraData=None)225 if (UserId, IdString, Arch) not in IdContentList:226 #227 # To check the UserId and IdString valid or not.228 #229 if not IsValidUserId(UserId):230 Logger.Error('InfParser',231 FORMAT_INVALID,232 ST.ERR_INF_PARSER_UE_SECTION_USER_ID_ERROR % (Item[1]),233 File=GlobalData.gINF_MODULE_NAME,234 Line=SectionLineNo,235 ExtraData=None)236 if not IsValidIdString(IdString):237 Logger.Error('InfParser',238 FORMAT_INVALID,239 ST.ERR_INF_PARSER_UE_SECTION_ID_STRING_ERROR % (IdString),240 File=GlobalData.gINF_MODULE_NAME, Line=SectionLineNo,241 ExtraData=None)242 IdContentList.append((UserId, IdString, Arch))243 else:244 #245 # Each UserExtensions section header must have a unique set 246 # of UserId, IdString and Arch values.247 # This means that the same UserId can be used in more than one 248 # section header, provided the IdString or Arch values are 249 # different. The same IdString values can be used in more than 250 # one section header if the UserId or Arch values are 251 # different. The same UserId and the same IdString can be used 252 # in a section header if the Arch values are different in each 253 # of the section headers.254 #255 Logger.Error('InfParser',256 FORMAT_INVALID,257 ST.ERR_INF_PARSER_UE_SECTION_DUPLICATE_ERROR % (258 IdString),259 File=GlobalData.gINF_MODULE_NAME,260 Line=SectionLineNo,261 ExtraData=None)262 LastItem = Item263 if not InfSectionObject.SetUserExtension(UserExtensionContent,264 IdContent=IdContentList,265 LineNo=SectionLineNo):266 Logger.Error\267 ('InfParser', FORMAT_INVALID, \268 ST.ERR_INF_PARSER_MODULE_SECTION_TYPE_ERROR % ("[UserExtension]"), \269 File=FileName, Line=LastItem[4])270 def InfProtocolParser(self, SectionString, InfSectionObject, FileName):271 #272 # Macro defined in this section 273 #274 SectionMacros = {}275 ValueList = []276 ProtocolList = []277 CommentsList = []278 CurrentLineVar = None279 #280 # Parse section content281 #282 for Line in SectionString:283 LineContent = Line[0]284 LineNo = Line[1]285 if LineContent.strip() == '':286 CommentsList = []287 continue288 if LineContent.strip().startswith(DT.TAB_COMMENT_SPLIT):289 CommentsList.append(Line)290 continue291 else:292 #293 # Encounter a Protocol entry294 #295 if LineContent.find(DT.TAB_COMMENT_SPLIT) > -1:296 CommentsList.append((297 LineContent[LineContent.find(DT.TAB_COMMENT_SPLIT):],298 LineNo))299 LineContent = \300 LineContent[:LineContent.find(DT.TAB_COMMENT_SPLIT)]301 if LineContent != '':302 #303 # Find Macro304 #305 Name, Value = MacroParser((LineContent, LineNo),306 FileName,307 DT.MODEL_EFI_PROTOCOL,308 self.FileLocalMacros)309 if Name != None:310 SectionMacros[Name] = Value311 ValueList = []312 CommentsList = []313 continue314 TokenList = GetSplitValueList(LineContent, DT.TAB_VALUE_SPLIT, 1)315 ValueList[0:len(TokenList)] = TokenList316 #317 # Replace with Local section Macro and [Defines] section Macro.318 # 319 ValueList = [InfExpandMacro(Value, (FileName, LineContent, LineNo), self.FileLocalMacros, SectionMacros)320 for Value in ValueList]321 CurrentLineVar = (LineContent, LineNo, FileName)322 if len(ValueList) >= 1:323 ProtocolList.append((ValueList, CommentsList, CurrentLineVar))324 ValueList = []325 CommentsList = []326 continue327 #328 # Current section archs329 # 330 ArchList = []331 LineIndex = -1332 for Item in self.LastSectionHeaderContent:333 LineIndex = Item[3]334 if Item[1] not in ArchList:335 ArchList.append(Item[1])336 if not InfSectionObject.SetProtocol(ProtocolList, Arch=ArchList):337 Logger.Error\338 ('InfParser', FORMAT_INVALID, \339 ST.ERR_INF_PARSER_MODULE_SECTION_TYPE_ERROR % ("[Protocol]"), \...

Full Screen

Full Screen

EfiSection.py

Source:EfiSection.py Github

copy

Full Screen

1## @file2# process rule section generation3#4# Copyright (c) 2007, Intel Corporation. All rights reserved.<BR>5#6# This program and the accompanying materials7# are licensed and made available under the terms and conditions of the BSD License8# which accompanies this distribution. The full text of the license may be found at9# 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##15# Import Modules16#17from struct import *18import Section19from GenFdsGlobalVariable import GenFdsGlobalVariable20import subprocess21from Ffs import Ffs22import os23from CommonDataClass.FdfClass import EfiSectionClassObject24import shutil25from Common import EdkLogger26from Common.BuildToolError import *27from Common.Misc import PeImageClass28## generate rule section29#30#31class EfiSection (EfiSectionClassObject):32 ## The constructor33 #34 # @param self The object pointer35 #36 def __init__(self):37 EfiSectionClassObject.__init__(self)38 ## GenSection() method39 #40 # Generate rule section41 #42 # @param self The object pointer43 # @param OutputPath Where to place output file44 # @param ModuleName Which module this section belongs to45 # @param SecNum Index of section46 # @param KeyStringList Filter for inputs of section generation47 # @param FfsInf FfsInfStatement object that contains this section data48 # @param Dict dictionary contains macro and its value49 # @retval tuple (Generated file name list, section alignment)50 #51 def GenSection(self, OutputPath, ModuleName, SecNum, KeyStringList, FfsInf = None, Dict = {}) :52 53 if self.FileName != None and self.FileName.startswith('PCD('):54 self.FileName = GenFdsGlobalVariable.GetPcdValue(self.FileName)55 """Prepare the parameter of GenSection"""56 if FfsInf != None :57 InfFileName = FfsInf.InfFileName58 SectionType = FfsInf.__ExtendMacro__(self.SectionType)59 Filename = FfsInf.__ExtendMacro__(self.FileName)60 BuildNum = FfsInf.__ExtendMacro__(self.BuildNum)61 StringData = FfsInf.__ExtendMacro__(self.StringData)62 NoStrip = True63 if FfsInf.ModuleType in ('SEC', 'PEI_CORE', 'PEIM') and SectionType in ('TE', 'PE32'):64 if FfsInf.KeepReloc != None:65 NoStrip = FfsInf.KeepReloc66 elif FfsInf.KeepRelocFromRule != None:67 NoStrip = FfsInf.KeepRelocFromRule68 elif self.KeepReloc != None:69 NoStrip = self.KeepReloc70 elif FfsInf.ShadowFromInfFile != None:71 NoStrip = FfsInf.ShadowFromInfFile72 else:73 EdkLogger.error("GenFds", GENFDS_ERROR, "Module %s apply rule for None!" %ModuleName)74 """If the file name was pointed out, add it in FileList"""75 FileList = []76 if Filename != None:77 Filename = GenFdsGlobalVariable.MacroExtend(Filename, Dict)78 # check if the path is absolute or relative79 if os.path.isabs(Filename):80 Filename = os.path.normpath(Filename)81 else:82 Filename = os.path.normpath(os.path.join(FfsInf.EfiOutputPath, Filename))83 if not self.Optional:84 FileList.append(Filename)85 elif os.path.exists(Filename):86 FileList.append(Filename)87 else:88 FileList, IsSect = Section.Section.GetFileList(FfsInf, self.FileType, self.FileExtension, Dict)89 if IsSect :90 return FileList, self.Alignment91 Index = 092 """ If Section type is 'VERSION'"""93 OutputFileList = []94 if SectionType == 'VERSION':95 InfOverrideVerString = False96 if FfsInf.Version != None:97 #StringData = FfsInf.Version98 BuildNum = FfsInf.Version99 InfOverrideVerString = True100 if InfOverrideVerString:101 #VerTuple = ('-n', '"' + StringData + '"')102 if BuildNum != None and BuildNum != '':103 BuildNumTuple = ('-j', BuildNum)104 else:105 BuildNumTuple = tuple()106 Num = SecNum107 OutputFile = os.path.join( OutputPath, ModuleName + 'SEC' + str(Num) + Ffs.SectionSuffix.get(SectionType))108 GenFdsGlobalVariable.GenerateSection(OutputFile, [], 'EFI_SECTION_VERSION',109 #Ui=StringData, 110 Ver=BuildNum)111 OutputFileList.append(OutputFile)112 elif FileList != []:113 for File in FileList:114 Index = Index + 1115 Num = '%s.%d' %(SecNum , Index)116 OutputFile = os.path.join(OutputPath, ModuleName + 'SEC' + Num + Ffs.SectionSuffix.get(SectionType))117 f = open(File, 'r')118 VerString = f.read()119 f.close()120 BuildNum = VerString121 if BuildNum != None and BuildNum != '':122 BuildNumTuple = ('-j', BuildNum)123 GenFdsGlobalVariable.GenerateSection(OutputFile, [], 'EFI_SECTION_VERSION',124 #Ui=VerString, 125 Ver=BuildNum)126 OutputFileList.append(OutputFile)127 else:128 BuildNum = StringData129 if BuildNum != None and BuildNum != '':130 BuildNumTuple = ('-j', BuildNum)131 else:132 BuildNumTuple = tuple()133 BuildNumString = ' ' + ' '.join(BuildNumTuple)134 #if VerString == '' and 135 if BuildNumString == '':136 if self.Optional == True :137 GenFdsGlobalVariable.VerboseLogger( "Optional Section don't exist!")138 return [], None139 else:140 EdkLogger.error("GenFds", GENFDS_ERROR, "File: %s miss Version Section value" %InfFileName)141 Num = SecNum142 OutputFile = os.path.join( OutputPath, ModuleName + 'SEC' + str(Num) + Ffs.SectionSuffix.get(SectionType))143 GenFdsGlobalVariable.GenerateSection(OutputFile, [], 'EFI_SECTION_VERSION',144 #Ui=VerString, 145 Ver=BuildNum)146 OutputFileList.append(OutputFile)147 #148 # If Section Type is 'UI'149 #150 elif SectionType == 'UI':151 InfOverrideUiString = False152 if FfsInf.Ui != None:153 StringData = FfsInf.Ui154 InfOverrideUiString = True155 if InfOverrideUiString:156 Num = SecNum157 OutputFile = os.path.join( OutputPath, ModuleName + 'SEC' + str(Num) + Ffs.SectionSuffix.get(SectionType))158 GenFdsGlobalVariable.GenerateSection(OutputFile, [], 'EFI_SECTION_USER_INTERFACE',159 Ui=StringData)160 OutputFileList.append(OutputFile)161 elif FileList != []:162 for File in FileList:163 Index = Index + 1164 Num = '%s.%d' %(SecNum , Index)165 OutputFile = os.path.join(OutputPath, ModuleName + 'SEC' + Num + Ffs.SectionSuffix.get(SectionType))166 f = open(File, 'r')167 UiString = f.read()168 f.close()169 GenFdsGlobalVariable.GenerateSection(OutputFile, [], 'EFI_SECTION_USER_INTERFACE',170 Ui=UiString)171 OutputFileList.append(OutputFile)172 else:173 if StringData != None and len(StringData) > 0:174 UiTuple = ('-n', '"' + StringData + '"')175 else:176 UiTuple = tuple()177 if self.Optional == True :178 GenFdsGlobalVariable.VerboseLogger( "Optional Section don't exist!")179 return '', None180 else:181 EdkLogger.error("GenFds", GENFDS_ERROR, "File: %s miss UI Section value" %InfFileName)182 Num = SecNum183 OutputFile = os.path.join( OutputPath, ModuleName + 'SEC' + str(Num) + Ffs.SectionSuffix.get(SectionType))184 GenFdsGlobalVariable.GenerateSection(OutputFile, [], 'EFI_SECTION_USER_INTERFACE',185 Ui=StringData)186 OutputFileList.append(OutputFile)187 else:188 """If File List is empty"""189 if FileList == [] :190 if self.Optional == True:191 GenFdsGlobalVariable.VerboseLogger( "Optional Section don't exist!")192 return [], None193 else:194 EdkLogger.error("GenFds", GENFDS_ERROR, "Output file for %s section could not be found for %s" % (SectionType, InfFileName))195 else:196 """Convert the File to Section file one by one """197 for File in FileList:198 """ Copy Map file to FFS output path """199 Index = Index + 1200 Num = '%s.%d' %(SecNum , Index)201 OutputFile = os.path.join( OutputPath, ModuleName + 'SEC' + Num + Ffs.SectionSuffix.get(SectionType))202 File = GenFdsGlobalVariable.MacroExtend(File, Dict)203 204 #Get PE Section alignment when align is set to AUTO205 if self.Alignment == 'Auto' and (SectionType == 'PE32' or SectionType == 'TE'):206 ImageObj = PeImageClass (File)207 if ImageObj.SectionAlignment < 0x400:208 self.Alignment = str (ImageObj.SectionAlignment)209 else:210 self.Alignment = str (ImageObj.SectionAlignment / 0x400) + 'K'211 if File[(len(File)-4):] == '.efi':212 MapFile = File.replace('.efi', '.map')213 if os.path.exists(MapFile):214 CopyMapFile = os.path.join(OutputPath, ModuleName + '.map')215 if not os.path.exists(CopyMapFile) or \216 (os.path.getmtime(MapFile) > os.path.getmtime(CopyMapFile)):217 shutil.copyfile(MapFile, CopyMapFile)218 if not NoStrip:219 FileBeforeStrip = os.path.join(OutputPath, ModuleName + '.efi')220 if not os.path.exists(FileBeforeStrip) or \221 (os.path.getmtime(File) > os.path.getmtime(FileBeforeStrip)):222 shutil.copyfile(File, FileBeforeStrip)223 StrippedFile = os.path.join(OutputPath, ModuleName + '.stripped')224 GenFdsGlobalVariable.GenerateFirmwareImage(225 StrippedFile,226 [File],227 Strip=True228 )229 File = StrippedFile230 231 """For TE Section call GenFw to generate TE image"""232 if SectionType == 'TE':233 TeFile = os.path.join( OutputPath, ModuleName + 'Te.raw')234 GenFdsGlobalVariable.GenerateFirmwareImage(235 TeFile,236 [File],237 Type='te'238 )239 File = TeFile240 """Call GenSection"""241 GenFdsGlobalVariable.GenerateSection(OutputFile,242 [File],243 Section.Section.SectionType.get (SectionType)244 )245 OutputFileList.append(OutputFile)...

Full Screen

Full Screen

GenDecFile.py

Source:GenDecFile.py Github

copy

Full Screen

1## @file GenDecFile.py2#3# This file contained the logical of transfer package object to DEC files.4#5# Copyright (c) 2011, Intel Corporation. All rights reserved.<BR>6#7# This program and the accompanying materials are licensed and made available 8# under the terms and conditions of the BSD License which accompanies this 9# distribution. The full text of the license may be found at 10# http://opensource.org/licenses/bsd-license.php11#12# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,13# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.14#15'''16GenDEC17'''18from Library.Parsing import GenSection19from Library.CommentGenerating import GenHeaderCommentSection20from Library.CommentGenerating import GenGenericCommentF21from Library.CommentGenerating import GenDecTailComment22from Library.CommentGenerating import _GetHelpStr23from Library.Misc import GuidStringToGuidStructureString24from Library.Misc import SaveFileOnChange25from Library.Misc import ConvertPath26from Library.DataType import TAB_SPACE_SPLIT27from Library.DataType import TAB_COMMA_SPLIT28from Library.DataType import TAB_ARCH_COMMON29from Library.DataType import TAB_DEC_DEFINES_DEC_SPECIFICATION30from Library.DataType import TAB_DEC_DEFINES_PACKAGE_NAME31from Library.DataType import TAB_DEC_DEFINES_PACKAGE_GUID32from Library.DataType import TAB_DEC_DEFINES_PACKAGE_VERSION33def GenPcd(Package, Content):34 #35 # generate [Pcd] section36 # <TokenSpcCName>.<TokenCName>|<Value>|<DatumType>|<Token> 37 #38 ValidUsageDict = {}39 for Pcd in Package.GetPcdList():40 #41 # Generate generic comment42 #43 HelpTextList = Pcd.GetHelpTextList()44 HelpStr = _GetHelpStr(HelpTextList)45 CommentStr = GenGenericCommentF(HelpStr, 2)46 PcdErrList = Pcd.GetPcdErrorsList()47 if PcdErrList:48 CommentStr += GenPcdErrComment(PcdErrList[0])49 Statement = CommentStr50 CName = Pcd.GetCName()51 TokenSpaceGuidCName = Pcd.GetTokenSpaceGuidCName()52 DefaultValue = Pcd.GetDefaultValue()53 DatumType = Pcd.GetDatumType()54 Token = Pcd.GetToken()55 ValidUsage = Pcd.GetValidUsage()56 if ValidUsage == 'FeaturePcd':57 ValidUsage = 'PcdsFeatureFlag'58 elif ValidUsage == 'PatchPcd':59 ValidUsage = 'PcdsPatchableInModule'60 elif ValidUsage == 'FixedPcd':61 ValidUsage = 'PcdsFixedAtBuild'62 elif ValidUsage == 'Pcd':63 ValidUsage = 'PcdsDynamic'64 elif ValidUsage == 'PcdEx':65 ValidUsage = 'PcdsDynamicEx'66 67 if ValidUsage in ValidUsageDict:68 NewSectionDict = ValidUsageDict[ValidUsage]69 else:70 NewSectionDict = {}71 ValidUsageDict[ValidUsage] = NewSectionDict72 Statement += TokenSpaceGuidCName + '.' + CName73 Statement += '|' + DefaultValue74 Statement += '|' + DatumType75 Statement += '|' + Token76 #77 # generate tail comment78 #79 if Pcd.GetSupModuleList():80 Statement += GenDecTailComment(Pcd.GetSupModuleList())81 ArchList = Pcd.GetSupArchList()82 ArchList.sort()83 SortedArch = ' '.join(ArchList)84 if SortedArch in NewSectionDict:85 NewSectionDict[SortedArch] = \86 NewSectionDict[SortedArch] + [Statement]87 else:88 NewSectionDict[SortedArch] = [Statement] 89 90 for ValidUsage in ValidUsageDict:91 Content += GenSection(ValidUsage, ValidUsageDict[ValidUsage])92 93 return Content94def GenGuidProtocolPpi(Package, Content):95 #96 # generate [Guids] section97 #98 NewSectionDict = {}99 for Guid in Package.GetGuidList():100 #101 # Generate generic comment102 #103 HelpTextList = Guid.GetHelpTextList()104 HelpStr = _GetHelpStr(HelpTextList)105 CommentStr = GenGenericCommentF(HelpStr, 2)106 Statement = CommentStr107 CName = Guid.GetCName()108 Value = GuidStringToGuidStructureString(Guid.GetGuid())109 Statement += CName + ' = ' + Value110 #111 # generate tail comment112 #113 if Guid.GetSupModuleList():114 Statement += GenDecTailComment(Guid.GetSupModuleList()) 115 ArchList = Guid.GetSupArchList()116 ArchList.sort()117 SortedArch = ' '.join(ArchList)118 if SortedArch in NewSectionDict:119 NewSectionDict[SortedArch] = \120 NewSectionDict[SortedArch] + [Statement]121 else:122 NewSectionDict[SortedArch] = [Statement] 123 Content += GenSection('Guids', NewSectionDict) 124 125 #126 # generate [Protocols] section127 #128 NewSectionDict = {}129 for Protocol in Package.GetProtocolList():130 #131 # Generate generic comment132 #133 HelpTextList = Protocol.GetHelpTextList()134 HelpStr = _GetHelpStr(HelpTextList)135 CommentStr = GenGenericCommentF(HelpStr, 2) 136 Statement = CommentStr 137 CName = Protocol.GetCName()138 Value = GuidStringToGuidStructureString(Protocol.GetGuid())139 Statement += CName + ' = ' + Value140 #141 # generate tail comment142 #143 if Protocol.GetSupModuleList():144 Statement += GenDecTailComment(Protocol.GetSupModuleList())145 ArchList = Protocol.GetSupArchList()146 ArchList.sort()147 SortedArch = ' '.join(ArchList)148 if SortedArch in NewSectionDict:149 NewSectionDict[SortedArch] = \150 NewSectionDict[SortedArch] + [Statement]151 else:152 NewSectionDict[SortedArch] = [Statement] 153 Content += GenSection('Protocols', NewSectionDict) 154 #155 # generate [Ppis] section156 #157 NewSectionDict = {}158 for Ppi in Package.GetPpiList():159 #160 # Generate generic comment161 #162 HelpTextList = Ppi.GetHelpTextList()163 HelpStr = _GetHelpStr(HelpTextList)164 CommentStr = GenGenericCommentF(HelpStr, 2)165 Statement = CommentStr166 CName = Ppi.GetCName()167 Value = GuidStringToGuidStructureString(Ppi.GetGuid())168 Statement += CName + ' = ' + Value169 #170 # generate tail comment171 #172 if Ppi.GetSupModuleList():173 Statement += GenDecTailComment(Ppi.GetSupModuleList())174 ArchList = Ppi.GetSupArchList()175 ArchList.sort()176 SortedArch = ' '.join(ArchList)177 if SortedArch in NewSectionDict:178 NewSectionDict[SortedArch] = \179 NewSectionDict[SortedArch] + [Statement]180 else:181 NewSectionDict[SortedArch] = [Statement] 182 Content += GenSection('Ppis', NewSectionDict)183 184 return Content185## Transfer Package Object to Dec files186#187# Transfer all contents of a standard Package Object to a Dec file 188#189# @param Package: A Package 190#191def PackageToDec(Package):192 #193 # Init global information for the file194 #195 ContainerFile = Package.GetFullPath()196 197 Content = ''198 #199 # generate header comment section200 #201 Content += GenHeaderCommentSection(Package.GetAbstract(), \202 Package.GetDescription(), \203 Package.GetCopyright(), \204 Package.GetLicense())205 206 #207 # for each section, maintain a dict, sorted arch will be its key, 208 #statement list will be its data209 # { 'Arch1 Arch2 Arch3': [statement1, statement2],210 # 'Arch1' : [statement1, statement3] 211 # }212 #213 214 #215 # generate [Defines] section 216 #217 NewSectionDict = {TAB_ARCH_COMMON : []}218 SpecialItemList = []219 220 Statement = '%s = %s' % (TAB_DEC_DEFINES_DEC_SPECIFICATION, '0x00010017')221 SpecialItemList.append(Statement)222 223 BaseName = Package.GetBaseName()224 if BaseName.startswith('.') or BaseName.startswith('-'):225 BaseName = '_' + BaseName226 Statement = '%s = %s' % (TAB_DEC_DEFINES_PACKAGE_NAME, BaseName)227 SpecialItemList.append(Statement)228 Statement = '%s = %s' % (TAB_DEC_DEFINES_PACKAGE_VERSION, Package.GetVersion())229 SpecialItemList.append(Statement)230 Statement = '%s = %s' % (TAB_DEC_DEFINES_PACKAGE_GUID, Package.GetGuid())231 SpecialItemList.append(Statement) 232 for SortedArch in NewSectionDict:233 NewSectionDict[SortedArch] = \234 NewSectionDict[SortedArch] + SpecialItemList235 Content += GenSection('Defines', NewSectionDict)236 #237 # generate [Includes] section238 #239 NewSectionDict = {}240 IncludeArchList = Package.GetIncludeArchList()241 if IncludeArchList: 242 for Path, ArchList in IncludeArchList:243 Statement = Path244 ArchList.sort()245 SortedArch = ' '.join(ArchList)246 if SortedArch in NewSectionDict:247 NewSectionDict[SortedArch] = \248 NewSectionDict[SortedArch] + [ConvertPath(Statement)]249 else:250 NewSectionDict[SortedArch] = [ConvertPath(Statement)]251 Content += GenSection('Includes', NewSectionDict) 252 Content = GenGuidProtocolPpi(Package, Content)253 #254 # generate [LibraryClasses] section255 #256 NewSectionDict = {}257 for LibraryClass in Package.GetLibraryClassList():258 #259 # Generate generic comment260 #261 HelpTextList = LibraryClass.GetHelpTextList()262 HelpStr = _GetHelpStr(HelpTextList)263 if HelpStr:264 HelpStr = '@libraryclass ' + HelpStr265 CommentStr = GenGenericCommentF(HelpStr, 2)266 Statement = CommentStr267 Name = LibraryClass.GetLibraryClass()268 IncludeHeader = LibraryClass.GetIncludeHeader()269 Statement += Name + '|' + ConvertPath(IncludeHeader)270 #271 # generate tail comment272 #273 if LibraryClass.GetSupModuleList():274 Statement += \275 GenDecTailComment(LibraryClass.GetSupModuleList())276 ArchList = LibraryClass.GetSupArchList()277 ArchList.sort()278 SortedArch = ' '.join(ArchList)279 if SortedArch in NewSectionDict:280 NewSectionDict[SortedArch] = \281 NewSectionDict[SortedArch] + [Statement]282 else:283 NewSectionDict[SortedArch] = [Statement] 284 Content += GenSection('LibraryClasses', NewSectionDict)285 Content = GenPcd(Package, Content)286 287 #288 # generate [UserExtensions] section289 #290 NewSectionDict = {}291 for UserExtension in Package.GetUserExtensionList():292 Statement = UserExtension.GetStatement()293 if not Statement:294 continue295 296 SectionList = []297 SectionName = 'UserExtensions'298 UserId = UserExtension.GetUserID()299 if UserId:300 if '.' in UserId:301 UserId = '"' + UserId + '"'302 SectionName += '.' + UserId303 if UserExtension.GetIdentifier():304 SectionName += '.' + '"' + UserExtension.GetIdentifier() + '"'305 if not UserExtension.GetSupArchList():306 SectionList.append(SectionName)307 else:308 for Arch in UserExtension.GetSupArchList():309 SectionList.append(SectionName + '.' + Arch)310 SectionName = ', '.join(SectionList)311 SectionName = ''.join(['[', SectionName, ']\n'])312 Content += '\n\n' + SectionName + Statement313 SaveFileOnChange(ContainerFile, Content, False)314 return ContainerFile315## GenPcdErrComment316#317# @param PcdErrObject: PcdErrorObject318# 319# @retval CommentStr: Generated comment lines, with prefix "#"320# 321def GenPcdErrComment (PcdErrObject):322 EndOfLine = "\n" 323 ValidValueRange = PcdErrObject.GetValidValueRange()324 if ValidValueRange:325 CommentStr = "# @ValidRange " + ValidValueRange + EndOfLine326 327 ValidValue = PcdErrObject.GetValidValue()328 if ValidValue:329 ValidValueList = \330 [Value for Value in ValidValue.split(TAB_SPACE_SPLIT) if Value]331 CommentStr = \332 "# @ValidList " + TAB_COMMA_SPLIT.join(ValidValueList) + EndOfLine333 334 Expression = PcdErrObject.GetExpression()335 if Expression:336 CommentStr = "# @Expression " + Expression + EndOfLine337 ...

Full Screen

Full Screen

InfBinarySectionTest.py

Source:InfBinarySectionTest.py Github

copy

Full Screen

1## @file2# This file contain unit test for Test [Binary] section part of InfParser 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.13import os14#import Object.Parser.InfObject as InfObject15from Object.Parser.InfCommonObject import CurrentLine16from Object.Parser.InfCommonObject import InfLineCommentObject17from Object.Parser.InfBinaryObject import InfBinariesObject18import Logger.Log as Logger19import Library.GlobalData as Global20##21# Test Common binary item22#23#-------------start of common binary item test input--------------------------#24#25# Only has 1 element, binary item Type26#27SectionStringsCommonItem1 = \28"""29GUID30"""31#32# Have 2 elements, binary item Type and FileName33#34SectionStringsCommonItem2 = \35"""36GUID | Test/Test.guid37"""38#39# Have 3 elements, Type | FileName | Target | Family | TagName | FeatureFlagExp40#41SectionStringsCommonItem3 = \42"""43GUID | Test/Test.guid | DEBUG44"""45#46# Have 3 elements, Type | FileName | Target 47# Target with MACRO defined in [Define] section48#49SectionStringsCommonItem4 = \50"""51GUID | Test/Test.guid | $(TARGET)52"""53#54# Have 3 elements, Type | FileName | Target 55# FileName with MACRO defined in [Binary] section56#57SectionStringsCommonItem5 = \58"""59DEFINE BINARY_FILE_PATH = Test60GUID | $(BINARY_FILE_PATH)/Test.guid | $(TARGET)61"""62#63# Have 4 elements, Type | FileName | Target | Family64#65SectionStringsCommonItem6 = \66"""67GUID | Test/Test.guid | DEBUG | *68"""69#70# Have 4 elements, Type | FileName | Target | Family71#72SectionStringsCommonItem7 = \73"""74GUID | Test/Test.guid | DEBUG | MSFT75"""76#77# Have 5 elements, Type | FileName | Target | Family | TagName78#79SectionStringsCommonItem8 = \80"""81GUID | Test/Test.guid | DEBUG | MSFT | TEST82"""83#84# Have 6 elements, Type | FileName | Target | Family | TagName | FFE85#86SectionStringsCommonItem9 = \87"""88GUID | Test/Test.guid | DEBUG | MSFT | TEST | TRUE89"""90#91# Have 7 elements, Type | FileName | Target | Family | TagName | FFE | Overflow92# Test wrong format93#94SectionStringsCommonItem10 = \95"""96GUID | Test/Test.guid | DEBUG | MSFT | TEST | TRUE | OVERFLOW97"""98#-------------end of common binary item test input----------------------------#99#-------------start of VER type binary item test input------------------------#100#101# Has 1 element, error format 102#103SectionStringsVerItem1 = \104"""105VER106"""107#108# Have 5 elements, error format(Maximum elements amount is 4)109#110SectionStringsVerItem2 = \111"""112VER | Test/Test.ver | * | TRUE | OverFlow113"""114#115# Have 2 elements, Type | FileName116#117SectionStringsVerItem3 = \118"""119VER | Test/Test.ver120"""121#122# Have 3 elements, Type | FileName | Target123#124SectionStringsVerItem4 = \125"""126VER | Test/Test.ver | DEBUG127"""128#129# Have 4 elements, Type | FileName | Target | FeatureFlagExp130#131SectionStringsVerItem5 = \132"""133VER | Test/Test.ver | DEBUG | TRUE134"""135#136# Exist 2 VER items, both opened.137#138SectionStringsVerItem6 = \139"""140VER | Test/Test.ver | * | TRUE141VER | Test/Test2.ver | * | TRUE142"""143#144# Exist 2 VER items, only 1 opened.145#146SectionStringsVerItem7 = \147"""148VER | Test/Test.ver | * | TRUE149VER | Test/Test2.ver | * | FALSE150"""151#-------------end of VER type binary item test input--------------------------#152#-------------start of UI type binary item test input-------------------------#153#154# Test only one UI section can exist155#156SectionStringsUiItem1 = \157"""158UI | Test/Test.ui | * | TRUE159UI | Test/Test2.ui | * | TRUE160"""161SectionStringsUiItem2 = \162"""163UI | Test/Test.ui | * | TRUE164SEC_UI | Test/Test2.ui | * | TRUE165"""166SectionStringsUiItem3 = \167"""168UI | Test/Test.ui | * | TRUE169UI | Test/Test2.ui | * | FALSE170"""171#172# Has 1 element, error format 173#174SectionStringsUiItem4 = \175"""176UI177"""178#179# Have 5 elements, error format(Maximum elements amount is 4)180#181SectionStringsUiItem5 = \182"""183UI | Test/Test.ui | * | TRUE | OverFlow184"""185#186# Have 2 elements, Type | FileName187#188SectionStringsUiItem6 = \189"""190UI | Test/Test.ui191"""192#193# Have 3 elements, Type | FileName | Target194#195SectionStringsUiItem7 = \196"""197UI | Test/Test.ui | DEBUG198"""199#200# Have 4 elements, Type | FileName | Target | FeatureFlagExp201#202SectionStringsUiItem8 = \203"""204UI | Test/Test.ui | DEBUG | TRUE205"""206#---------------end of UI type binary item test input-------------------------#207gFileName = "BinarySectionTest.inf"208##209# Construct SectionString for call section parser usage.210#211def StringToSectionString(String):212 Lines = String.split('\n')213 LineNo = 0214 SectionString = []215 for Line in Lines:216 if Line.strip() == '':217 continue218 SectionString.append((Line, LineNo, ''))219 LineNo = LineNo + 1220 221 return SectionString222def PrepareTest(String):223 SectionString = StringToSectionString(String)224 ItemList = []225 for Item in SectionString:226 ValueList = Item[0].split('|')227 for count in range(len(ValueList)):228 ValueList[count] = ValueList[count].strip()229 if len(ValueList) >= 2:230 #231 # Create a temp file for test.232 #233 FileName = os.path.normpath(os.path.realpath(ValueList[1].strip()))234 try:235 TempFile = open (FileName, "w") 236 TempFile.close()237 except:238 print "File Create Error"239 CurrentLine = CurrentLine()240 CurrentLine.SetFileName("Test")241 CurrentLine.SetLineString(Item[0])242 CurrentLine.SetLineNo(Item[1])243 InfLineCommentObject = InfLineCommentObject()244 245 ItemList.append((ValueList, InfLineCommentObject, CurrentLine))246 247 return ItemList248if __name__ == '__main__':249 Logger.Initialize()250 251 InfBinariesInstance = InfBinariesObject()252 ArchList = ['COMMON']253 Global.gINF_MODULE_DIR = os.getcwd()254 255 AllPassedFlag = True256 257 #258 # For All Ui test259 #260 UiStringList = [ 261 SectionStringsUiItem1,262 SectionStringsUiItem2,263 SectionStringsUiItem3,264 SectionStringsUiItem4,265 SectionStringsUiItem5,266 SectionStringsUiItem6,267 SectionStringsUiItem7,268 SectionStringsUiItem8 269 ]270 271 for Item in UiStringList: 272 Ui = PrepareTest(Item)273 if Item == SectionStringsUiItem4 or Item == SectionStringsUiItem5:274 try:275 InfBinariesInstance.SetBinary(Ui = Ui, ArchList = ArchList)276 except Logger.FatalError:277 pass278 else:279 try: 280 InfBinariesInstance.SetBinary(Ui = Ui, ArchList = ArchList)281 except:282 AllPassedFlag = False 283 284 #285 # For All Ver Test286 #287 VerStringList = [288 SectionStringsVerItem1,289 SectionStringsVerItem2,290 SectionStringsVerItem3,291 SectionStringsVerItem4,292 SectionStringsVerItem5,293 SectionStringsVerItem6,294 SectionStringsVerItem7295 ]296 for Item in VerStringList: 297 Ver = PrepareTest(Item)298 if Item == SectionStringsVerItem1 or \299 Item == SectionStringsVerItem2:300 301 try:302 InfBinariesInstance.SetBinary(Ver = Ver, ArchList = ArchList)303 except:304 pass305 306 else:307 try:308 InfBinariesInstance.SetBinary(Ver = Ver, ArchList = ArchList)309 except:310 AllPassedFlag = False 311 312 #313 # For All Common Test314 # 315 CommonStringList = [316 SectionStringsCommonItem1,317 SectionStringsCommonItem2,318 SectionStringsCommonItem3,319 SectionStringsCommonItem4,320 SectionStringsCommonItem5,321 SectionStringsCommonItem6,322 SectionStringsCommonItem7,323 SectionStringsCommonItem8,324 SectionStringsCommonItem9,325 SectionStringsCommonItem10326 ]327 for Item in CommonStringList: 328 CommonBin = PrepareTest(Item)329 if Item == SectionStringsCommonItem10 or \330 Item == SectionStringsCommonItem1:331 332 try:333 InfBinariesInstance.SetBinary(CommonBinary = CommonBin, ArchList = ArchList)334 except:335 pass336 337 else:338 try:339 InfBinariesInstance.SetBinary(Ver = Ver, ArchList = ArchList)340 except:341 print "Test Failed!"342 AllPassedFlag = False343 344 if AllPassedFlag :345 print 'All tests passed...'346 else:...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1import React from 'react';2import { storiesOf } from '@storybook/react';3import { withRootDecorator } from 'storybook-root-decorator';4import { withInfo } from '@storybook/addon-info';5import { withKnobs } from '@storybook/addon-knobs/react';6import { withOptions } from '@storybook/addon-options';7import { withViewport } from '@storybook/addon-viewport';8import { withA11y } from '@storybook/addon-a11y';9import { withConsole } from '@storybook/addon-console';10import { withPropsTable } from 'storybook-addon-react-docgen';11import { withTests } from '@storybook/addon-jest';12import { withPerformance } from 'storybook-addon-performance';13import { withBackgrounds } from '@storybook/addon-backgrounds';14const options = {

Full Screen

Using AI Code Generation

copy

Full Screen

1import React from 'react';2import { storiesOf } from '@storybook/react';3import { action } from '@storybook/addon-actions';4import { linkTo } from '@storybook/addon-links';5import { withInfo } from '@storybook/addon-info';6import { withKnobs, text, boolean, number } from '@storybook/addon-knobs';7import { withNotes } from '@storybook/addon-notes';8import { withReadme } from 'storybook-readme';9import { withOptions } from '@storybook/addon-options';10import { withViewport } from '@storybook/addon-viewport';11import { withBackgrounds } from '@storybook/addon-backgrounds';12import Button from './Button';13const stories = storiesOf('Button', module);14stories.addDecorator(withKnobs);15stories.add('with text', () => <Button onClick={action('clicked')}>{text('Label', 'Hello Button')}</Button>);16stories.add('with some emoji', () => (17 <Button onClick={action('clicked')} disabled={boolean('Disabled', false)}>18));19stories.add('with some emoji and background', () => (20 <Button onClick={action('clicked')} disabled={boolean('Disabled', false)}>21));22stories.add('with some emoji and background', () => (23 <Button onClick={action('clicked')} disabled={boolean('Disabled', false)}>24));25stories.add('with some emoji and background', () => (26 <Button onClick={action('clicked')} disabled={boolean('Disabled', false)}>27));28stories.add('with some emoji and background', () => (29 <Button onClick={action('clicked')} disabled={boolean('Disabled', false)}>30));31stories.add('with some emoji and background', () =>

Full Screen

Using AI Code Generation

copy

Full Screen

1import { section } from 'storybook-root-decorator';2section('My Section');3section('My Section', 'My Subsection');4section('My Section', 'My Subsection', 'My Subsubsection');5section('My Section', 'My Subsection', 'My Subsubsection', 'My Subsubsubsection');6section('My Section', 'My Subsection', 'My Subsubsection', 'My Subsubsubsection', 'My Subsubsubsubsection');7section('My Section', 'My Subsection', 'My Subsubsection', 'My Subsubsubsection', 'My Subsubsubsubsection', 'My Subsubsubsubsubsection');8section('My Section', 'My Subsection', 'My Subsubsection', 'My Subsubsubsection', 'My Subsubsubsubsection', 'My Subsubsubsubsubsection', 'My Subsubsubsubsubsubsection');9section('My Section', 'My Subsection', 'My Subsubsection', 'My Subsubsubsection', 'My Subsubsubsubsection', 'My Subsubsubsubsubsection', 'My Subsubsubsubsubsubsection', 'My Subsubsubsubsubsubsubsection');10section('My Section', 'My Subsection', 'My Subsubsection', 'My Subsubsubsection', 'My Subsubsubsubsection', 'My Subsubsubsubsubsection', 'My Subsubsubsubsubsubsection', 'My Subsubsubsubsubsubsubsection', 'My Subsubsubsubsubsubsubsubsection');11section('My Section', 'My Subsection', 'My Subsubsection', 'My Subsubsubsection', 'My Subsubsubsubsection', 'My Subsubsubsubsubsection', 'My Subsubsubsubsubsubsection', 'My Subsubsubsubsubsubsubsection', 'My Subsubsubsubsubsub

Full Screen

Using AI Code Generation

copy

Full Screen

1import { storiesOf } from '@storybook/react';2import { withRootDecorator } from 'storybook-root-decorator';3const stories = storiesOf('Test', module);4stories.add('Test', () => <div>Test</div>);5stories.section('Section 1').add('Test', () => <div>Test</div>);6stories.section('Section 2').add('Test', () => <div>Test</div>);7import { configure } from '@storybook/react';8import { withRootDecorator } from 'storybook-root-decorator';9configure(() => {10 require('../test.js');11}, module);12const path = require('path');13module.exports = ({ config }) => {14 ...(config.resolve.modules || []),15 path.resolve(__dirname, '../'),16 ];17 return config;18};19import 'storybook-root-decorator/register';

Full Screen

Using AI Code Generation

copy

Full Screen

1import { section } from "storybook-root-decorator";2export default {3 decorators: [section("section1")],4};5export const test = () => <div>test</div>;6import { section } from "storybook-root-decorator";7export default {8 decorators: [section("section1")],9};10export const test2 = () => <div>test2</div>;11import { section } from "storybook-root-decorator";12export default {13 decorators: [section("section2")],14};15export const test3 = () => <div>test3</div>;16import { section } from "storybook-root-decorator";17export default {18 decorators: [section("section2")],19};20export const test4 = () => <div>test4</div>;21import { section } from "storybook-root-decorator";22export default {23 decorators: [section("section2")],24};25export const test5 = () => <div>test5</div>;26import { section } from "storybook-root-decorator";27export default {28 decorators: [section("section3")],29};30export const test6 = () => <div>test6</div>;31import

Full Screen

Using AI Code Generation

copy

Full Screen

1import { section } from 'storybook-root'2import { section } from 'storybook-root'3import { section } from 'storybook-root'4import { section } from 'storybook-root'5import { section } from 'storybook-root'6import { section } from 'storybook-root'7import { section } from 'storybook-root'8import { section } from 'storybook-root'9import { section } from 'storybook-root'10import { section } from 'storybook-root'11import { section } from 'storybook-root'12import { section } from 'storybook-root'13import { section } from 'storybook-root'14import { section } from 'storybook-root'15import { section } from 'storybook-root'

Full Screen

Using AI Code Generation

copy

Full Screen

1import { withRoot } from 'storybook-root-decorator';2export default {3 parameters: {4 root: {5 },6 },7};8import React from 'react';9import MyComponent from '../MyComponent';10export const MyComponentStory = () => <MyComponent />;11import React from 'react';12import MyComponent from '../MyComponent';13export const MyComponentStory = () => <MyComponent />;14import React from 'react';15import MyComponent from '../MyComponent';16export const MyComponentStory = () => <MyComponent />;17import React from 'react';18import MyComponent from '../MyComponent';19export const MyComponentStory = () => <MyComponent />;20import React from 'react';21import MyComponent from '../MyComponent';22export const MyComponentStory = () => <MyComponent />;23import React from 'react';24import MyComponent from '../MyComponent';25export const MyComponentStory = () => <MyComponent />;26import React from 'react';27import MyComponent from '../MyComponent';28export const MyComponentStory = () => <MyComponent />;29import React from 'react';30import MyComponent from '../MyComponent';31export const MyComponentStory = () => <MyComponent />;32import React from 'react';33import MyComponent from '../MyComponent';34export const MyComponentStory = () => <MyComponent />;35import React from 'react';36import MyComponent from '../MyComponent';37export const MyComponentStory = () => <MyComponent />;38import React from 'react';39import MyComponent from '../MyComponent';40export const MyComponentStory = () => <MyComponent />;

Full Screen

Using AI Code Generation

copy

Full Screen

1import { section } from 'storybook-root';2import { storiesOf } from '@storybook/react';3import Button from './Button';4const stories = storiesOf('Button', module);5 .add('default', () => <Button>Default</Button>)6 .add('primary', () => <Button primary>Primary</Button>)7 .add('secondary', () => <Button secondary>Secondary</Button>)8 .add('disabled', () => <Button disabled>Disabled</Button>)9 .add('primary disabled', () => (10 .add('secondary disabled', () => (11 .add('with icon', () => <Button icon="check">With Icon</Button>)12 .add('with icon and text', () => (13 .add('with icon and text', () => (14 .add('with icon and text', () => (15 ));16section('Button', stories);17import { storiesOf } from '@storybook/react';18import { Button } from 'storybook-root';19const stories = storiesOf('Button', module);20 .add('default', () => <Button>Default</Button>)21 .add('primary', () => <Button primary>Primary</Button>)22 .add('secondary', () => <Button secondary>Secondary</Button>)23 .add('disabled', () => <Button disabled>Disabled</Button>)24 .add('primary disabled', () => (25 .add('secondary disabled', () => (26 .add('with icon', () => <Button icon="check">With Icon</Button>)27 .add('with icon and text', () => (28 .add('with icon and text', () => (

Full Screen

Using AI Code Generation

copy

Full Screen

1import { section } from 'storybook-root'2const { story, storiesOf } = section('test')3story('test', () => {4})5storiesOf('test', () => {6})7import { story } from 'storybook-root'8story('test', () => {9})

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 storybook-root 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