def Inputs(filename, defines, ids_file, target_platform=None): grd = grd_reader.Parse( filename, debug=False, defines=defines, tags_to_ignore=set(['message']), first_ids_file=ids_file, target_platform=target_platform) files = set() for lang, ctx in grd.GetConfigurations(): grd.SetOutputLanguage(lang or grd.GetSourceLanguage()) grd.SetOutputContext(ctx) for node in grd.ActiveDescendants(): with node: if (node.name == 'structure' or node.name == 'skeleton' or (node.name == 'file' and node.parent and node.parent.name == 'translations')): files.add(grd.ToRealPath(node.GetInputPath())) # If it's a flattened node, grab inlined resources too. if node.name == 'structure' and node.attrs['flattenhtml'] == 'true': node.RunPreSubstitutionGatherer() files.update(node.GetHtmlResourceFilenames()) elif node.name == 'grit': first_ids_file = node.GetFirstIdsFile() if first_ids_file: files.add(first_ids_file) elif node.name == 'include': files.add(grd.ToRealPath(node.GetInputPath())) # If it's a flattened node, grab inlined resources too. if node.attrs['flattenhtml'] == 'true': files.update(node.GetHtmlResourceFilenames()) elif node.name == 'part': files.add(util.normpath(os.path.join(os.path.dirname(filename), node.GetInputPath()))) cwd = os.getcwd() return [os.path.relpath(f, cwd) for f in sorted(files)]
def testImgSrcsetIgnoresI18n(self): '''Tests that $i18n{...} strings are ignored when inlining. ''' src_html = ''' <html> <head></head> <body> <img srcset="$i18n{foo}"> </body> </html> ''' files = { 'index.html': src_html, } expected_inlined = src_html source_resources = set() tmp_dir = util.TempDir(files) for filename in files: source_resources.add(tmp_dir.GetPath(util.normpath(filename))) result = html_inline.DoInline(tmp_dir.GetPath('index.html'), None) resources = result.inlined_files resources.add(tmp_dir.GetPath('index.html')) self.failUnlessEqual(resources, source_resources) self.failUnlessEqual(expected_inlined, util.FixLineEnd(result.inlined_data, '\n')) tmp_dir.CleanUp()
def testGetPathNoBasedir(self): root = misc.GritNode() root.StartParsing(u'grit', None) root.HandleAttribute(u'latest_public_release', u'0') root.HandleAttribute(u'current_release', u'1') root.HandleAttribute(u'base_dir', r'..\resource') release = misc.ReleaseNode() release.StartParsing(u'release', root) release.HandleAttribute(u'seq', u'1') root.AddChild(release) includes = empty.IncludesNode() includes.StartParsing(u'includes', release) release.AddChild(includes) include_node = include.IncludeNode() include_node.StartParsing(u'include', includes) include_node.HandleAttribute(u'file', r'flugel\kugel.pdf') include_node.HandleAttribute(u'use_base_dir', u'false') includes.AddChild(include_node) root.EndParsing() last_dir = os.path.basename(os.getcwd()) expected_path = util.normpath( os.path.join(u'..', last_dir, u'flugel/kugel.pdf')) self.assertEqual(root.ToRealPath(include_node.GetInputPath()), expected_path)
def testInlineCSSImports(self): '''Tests that @import directives in inlined CSS files are inlined too. ''' files = { 'index.html': ''' <html> <head> <link rel="stylesheet" href="css/test.css"> </head> </html> ''', 'css/test.css': ''' @import url('test2.css'); blink { display: none; } ''', 'css/test2.css': ''' .image { background: url('../images/test.png'); } '''.strip(), 'images/test.png': 'PNG DATA' } expected_inlined = ''' <html> <head> <style> .image { background: url('data:image/png;base64,UE5HIERBVEE='); } blink { display: none; } </style> </head> </html> ''' source_resources = set() tmp_dir = util.TempDir(files) for filename in files: source_resources.add(tmp_dir.GetPath(util.normpath(filename))) result = html_inline.DoInline(tmp_dir.GetPath('index.html'), None) resources = result.inlined_files resources.add(tmp_dir.GetPath('index.html')) self.failUnlessEqual(resources, source_resources) self.failUnlessEqual(expected_inlined, util.FixLineEnd(result.inlined_data, '\n')) tmp_dir.CleanUp()
def testRcIncludeStructure(self): root = util.ParseGrdForUnittest(''' <structures> <structure type="tr_html" name="IDR_HTML" file="bingo.html"/> <structure type="tr_html" name="IDR_HTML2" file="bingo2.html"/> </structures>''', base_dir='/temp') # We do not run gatherers as it is not needed and wouldn't find the file buf = StringIO.StringIO() build.RcBuilder.ProcessNode(root, DummyOutput('rc_all', 'en'), buf) output = util.StripBlankLinesAndComments(buf.getvalue()) expected = (_PREAMBLE + u'IDR_HTML HTML "%s"\n' u'IDR_HTML2 HTML "%s"' % (util.normpath('/temp/bingo.html').replace('\\', '\\\\'), util.normpath('/temp/bingo2.html').replace('\\', '\\\\'))) # hackety hack to work on win32&lin output = re.sub('"[c-zC-Z]:', '"', output) self.assertEqual(expected, output)
def testRcIncludeStructure(self): root = grd_reader.Parse(StringIO.StringIO(''' <structures> <structure type="tr_html" name="IDR_HTML" file="bingo.html"/> <structure type="tr_html" name="IDR_HTML2" file="bingo2.html"/> </structures>'''), flexible_root = True) util.FixRootForUnittest(root, '/temp') # We do not run gatherers as it is not needed and wouldn't find the file buf = StringIO.StringIO() build.RcBuilder.ProcessNode(root, DummyOutput('rc_all', 'en'), buf) output = buf.getvalue() expected = (u'IDR_HTML HTML "%s"\n' u'IDR_HTML2 HTML "%s"' % (util.normpath('/temp/bingo.html').replace('\\', '\\\\'), util.normpath('/temp/bingo2.html').replace('\\', '\\\\'))) # hackety hack to work on win32&lin output = re.sub('"[c-zC-Z]:', '"', output) self.failUnless(output.strip() == expected)
def testRcIncludeStructure(self): root = util.ParseGrdForUnittest(''' <structures> <structure type="tr_html" name="IDR_HTML" file="bingo.html"/> <structure type="tr_html" name="IDR_HTML2" file="bingo2.html"/> </structures>''', base_dir = '/temp') # We do not run gatherers as it is not needed and wouldn't find the file buf = StringIO.StringIO() build.RcBuilder.ProcessNode(root, DummyOutput('rc_all', 'en'), buf) output = util.StripBlankLinesAndComments(buf.getvalue()) expected = (_PREAMBLE + u'IDR_HTML HTML "%s"\n' u'IDR_HTML2 HTML "%s"' % (util.normpath('/temp/bingo.html').replace('\\', '\\\\'), util.normpath('/temp/bingo2.html').replace('\\', '\\\\'))) # hackety hack to work on win32&lin output = re.sub('"[c-zC-Z]:', '"', output) self.assertEqual(expected, output)
def ToRealPath(self, path_from_basedir): """Returns a real path (which can be absolute or relative to the current working directory), given a path that is relative to the base directory set for the GRIT input file. Args: path_from_basedir: '..' Return: 'resource' """ return util.normpath(os.path.join(self.GetRoot().GetBaseDir(), os.path.expandvars(path_from_basedir)))
def testOutputs(self): grd = self.__ParseAndroidXml([ '--languages', 'en-US,ru,id', '--rc-dir', 'rc/dir', '--header-dir', 'header/dir', '--xtb-dir', 'xtb/dir', '--xml-dir', 'xml/dir' ]) outputs = grd.GetChildrenOfType(node_io.OutputNode) self.assertEqual(len(outputs), 7) header_outputs = [x for x in outputs if x.GetType() == 'rc_header'] rc_outputs = [x for x in outputs if x.GetType() == 'rc_all'] xml_outputs = [x for x in outputs if x.GetType() == 'android'] self.assertEqual(len(header_outputs), 1) self.assertEqual(len(rc_outputs), 3) self.assertEqual(len(xml_outputs), 3) # The header node should have an "<emit>" child and the proper filename. self.assertTrue(header_outputs[0].GetChildrenOfType(node_io.EmitNode)) self.assertEqual(util.normpath(header_outputs[0].GetFilename()), util.normpath('header/dir/chrome_android_strings.h')) id_rc = [x for x in rc_outputs if x.GetLanguage() == 'id'] id_xml = [x for x in xml_outputs if x.GetLanguage() == 'id'] self.assertTrue(id_rc) self.assertTrue(id_xml) self.assertEqual(util.normpath(id_rc[0].GetFilename()), util.normpath('rc/dir/chrome_android_strings_id.rc')) self.assertEqual(util.normpath(id_xml[0].GetFilename()), util.normpath('xml/dir/values-in/strings.xml')) us_rc = [x for x in rc_outputs if x.GetLanguage() == 'en-US'] us_xml = [x for x in xml_outputs if x.GetLanguage() == 'en-US'] self.assertTrue(us_rc) self.assertTrue(us_xml) self.assertEqual( util.normpath(us_rc[0].GetFilename()), util.normpath('rc/dir/chrome_android_strings_en-US.rc')) self.assertEqual(util.normpath(us_xml[0].GetFilename()), util.normpath('xml/dir/values-en-rUS/strings.xml'))
def testOutputs(self): grd = self.__ParseAndroidXml(['--languages', 'en-US,ru,id', '--rc-dir', 'rc/dir', '--header-dir', 'header/dir', '--xtb-dir', 'xtb/dir', '--xml-dir', 'xml/dir']) outputs = grd.GetChildrenOfType(io.OutputNode) self.assertEqual(len(outputs), 7) header_outputs = filter(lambda x: x.GetType() == 'rc_header', outputs) rc_outputs = filter(lambda x: x.GetType() == 'rc_all', outputs) xml_outputs = filter(lambda x: x.GetType() == 'android', outputs) self.assertEqual(len(header_outputs), 1) self.assertEqual(len(rc_outputs), 3) self.assertEqual(len(xml_outputs), 3) # The header node should have an "<emit>" child and the proper filename. self.assertTrue(header_outputs[0].GetChildrenOfType(io.EmitNode)) self.assertEqual(util.normpath(header_outputs[0].GetFilename()), util.normpath('header/dir/chrome_android_strings.h')) id_rc = filter(lambda x: x.GetLanguage() == 'id', rc_outputs) id_xml = filter(lambda x: x.GetLanguage() == 'id', xml_outputs) self.assertTrue(id_rc) self.assertTrue(id_xml) self.assertEqual(util.normpath(id_rc[0].GetFilename()), util.normpath('rc/dir/chrome_android_strings_id.rc')) self.assertEqual(util.normpath(id_xml[0].GetFilename()), util.normpath('xml/dir/values-in/strings.xml')) us_rc = filter(lambda x: x.GetLanguage() == 'en-US', rc_outputs) us_xml = filter(lambda x: x.GetLanguage() == 'en-US', xml_outputs) self.assertTrue(us_rc) self.assertTrue(us_xml) self.assertEqual(util.normpath(us_rc[0].GetFilename()), util.normpath('rc/dir/chrome_android_strings_en-US.rc')) self.assertEqual(util.normpath(us_xml[0].GetFilename()), util.normpath('xml/dir/values-en-rUS/strings.xml'))
def ToRealPath(self, path_from_basedir): '''Returns a real path (which can be absolute or relative to the current working directory), given a path that is relative to the base directory set for the GRIT input file. Args: path_from_basedir: '..' Return: 'resource' ''' return util.normpath( os.path.join(self.GetRoot().GetBaseDir(), path_from_basedir))
def _CountResourceUsage(grd, seen_files): tag_name_to_count = {tag: set() for tag in TAGS_OF_INTEREST} # Pass '_chromium', but '_google_chrome' would produce the same result. root = grd_reader.Parse(grd, defines={'_chromium': True}) seen_files.add(grd) # Count all descendant tags, regardless of whether they're active. for node in root.Preorder(): if node.name in TAGS_OF_INTEREST: tag_name_to_count[node.name].add(node.attrs['name']) elif node.name == 'part': part_path = os.path.join(os.path.dirname(grd), node.GetInputPath()) seen_files.add(util.normpath(part_path)) return {k: len(v) for k, v in tag_name_to_count.items() if v}
def testGetPath(self): root = misc.GritNode() root.StartParsing(u'grit', None) root.HandleAttribute(u'latest_public_release', u'0') root.HandleAttribute(u'current_release', u'1') root.HandleAttribute(u'base_dir', ur'..\resource') release = misc.ReleaseNode() release.StartParsing(u'release', root) release.HandleAttribute(u'seq', u'1') root.AddChild(release) includes = empty.IncludesNode() includes.StartParsing(u'includes', release) release.AddChild(includes) include_node = include.IncludeNode() include_node.StartParsing(u'include', includes) include_node.HandleAttribute(u'file', ur'flugel\kugel.pdf') includes.AddChild(include_node) root.EndParsing() self.assertEqual(root.ToRealPath(include_node.GetInputPath()), util.normpath( os.path.join(ur'../resource', ur'flugel/kugel.pdf')))
def Inputs(filename, defines, ids_file, target_platform=None, exclude_grit_source=False): grd = grd_reader.Parse(filename, debug=False, defines=defines, tags_to_ignore=set(['message']), first_ids_file=ids_file, target_platform=target_platform) files = set() for lang, ctx, fallback in grd.GetConfigurations(): # TODO(tdanderson): Refactor all places which perform the action of setting # output attributes on the root. See crbug.com/503637. grd.SetOutputLanguage(lang or grd.GetSourceLanguage()) grd.SetOutputContext(ctx) grd.SetFallbackToDefaultLayout(fallback) for node in grd.ActiveDescendants(): with node: if (node.name == 'structure' or node.name == 'skeleton' or (node.name == 'file' and node.parent and node.parent.name == 'translations')): path = node.GetInputPath() if path is not None: files.add(grd.ToRealPath(path)) # If it's a flattened node, grab inlined resources too. if node.name == 'structure' and node.attrs[ 'flattenhtml'] == 'true': node.RunPreSubstitutionGatherer() files.update(node.GetHtmlResourceFilenames()) elif node.name == 'grit': first_ids_file = node.GetFirstIdsFile() if first_ids_file and not exclude_grit_source: files.add(first_ids_file) elif node.name == 'include': files.add(grd.ToRealPath(node.GetInputPath())) # If it's a flattened node, grab inlined resources too. if node.attrs['flattenhtml'] == 'true': files.update(node.GetHtmlResourceFilenames()) elif node.name == 'part': files.add( util.normpath( os.path.join(os.path.dirname(filename), node.GetInputPath()))) cwd = os.getcwd() return [os.path.relpath(f, cwd) for f in sorted(files)]
def GetInputPath(self): # Do not mess with absolute paths, that would make them invalid. if os.path.isabs(os.path.expandvars(self.attrs['file'])): return self.attrs['file'] # We have no control over code that calls ToRealPath later, so convert # the path to be relative against our basedir. if self.attrs.get('use_base_dir', 'true') != 'true': # Normalize the directory path to use the appropriate OS separator. # GetBaseDir() may return paths\like\this or paths/like/this, since it is # read from the base_dir attribute in the grd file. norm_base_dir = util.normpath(self.GetRoot().GetBaseDir()) return os.path.relpath(self.attrs['file'], norm_base_dir) return self.attrs['file']
def Inputs(filename, defines, ids_file, target_platform=None): grd = grd_reader.Parse( filename, debug=False, defines=defines, tags_to_ignore=set(["message"]), first_ids_file=ids_file, target_platform=target_platform, ) files = set() for lang, ctx, fallback in grd.GetConfigurations(): # TODO(tdanderson): Refactor all places which perform the action of setting # output attributes on the root. See crbug.com/503637. grd.SetOutputLanguage(lang or grd.GetSourceLanguage()) grd.SetOutputContext(ctx) grd.SetFallbackToDefaultLayout(fallback) for node in grd.ActiveDescendants(): with node: if ( node.name == "structure" or node.name == "skeleton" or (node.name == "file" and node.parent and node.parent.name == "translations") ): path = node.GetInputPath() if path is not None: files.add(grd.ToRealPath(path)) # If it's a flattened node, grab inlined resources too. if node.name == "structure" and node.attrs["flattenhtml"] == "true": node.RunPreSubstitutionGatherer() files.update(node.GetHtmlResourceFilenames()) elif node.name == "grit": first_ids_file = node.GetFirstIdsFile() if first_ids_file: files.add(first_ids_file) elif node.name == "include": files.add(grd.ToRealPath(node.GetInputPath())) # If it's a flattened node, grab inlined resources too. if node.attrs["flattenhtml"] == "true": files.update(node.GetHtmlResourceFilenames()) elif node.name == "part": files.add(util.normpath(os.path.join(os.path.dirname(filename), node.GetInputPath()))) cwd = os.getcwd() return [os.path.relpath(f, cwd) for f in sorted(files)]
def testGetPath(self): root = misc.GritNode() root.StartParsing(u'grit', None) root.HandleAttribute(u'latest_public_release', u'0') root.HandleAttribute(u'current_release', u'1') root.HandleAttribute(u'base_dir', r'..\resource') translations = empty.TranslationsNode() translations.StartParsing(u'translations', root) root.AddChild(translations) file_node = node_io.FileNode() file_node.StartParsing(u'file', translations) file_node.HandleAttribute(u'path', r'flugel\kugel.pdf') translations.AddChild(file_node) root.EndParsing() self.failUnless( root.ToRealPath(file_node.GetInputPath()) == util.normpath( os.path.join(r'../resource', r'flugel/kugel.pdf')))
def testRcIncludeFile(self): root = grd_reader.Parse(StringIO.StringIO(''' <includes> <include type="TXT" name="TEXT_ONE" file="bingo.txt"/> <include type="TXT" name="TEXT_TWO" file="bingo2.txt" filenameonly="true" /> </includes>'''), flexible_root = True) util.FixRootForUnittest(root, '/temp') buf = StringIO.StringIO() build.RcBuilder.ProcessNode(root, DummyOutput('rc_all', 'en'), buf) output = buf.getvalue() expected = (u'TEXT_ONE TXT "%s"\n' u'TEXT_TWO TXT "%s"' % (util.normpath('/temp/bingo.txt').replace('\\', '\\\\'), 'bingo2.txt')) # hackety hack to work on win32&lin output = re.sub('"[c-zC-Z]:', '"', output) self.failUnless(output.strip() == expected)
def testRcIncludeFile(self): root = util.ParseGrdForUnittest(''' <includes> <include type="TXT" name="TEXT_ONE" file="bingo.txt"/> <include type="TXT" name="TEXT_TWO" file="bingo2.txt" filenameonly="true" /> </includes>''', base_dir = '/temp') buf = StringIO.StringIO() build.RcBuilder.ProcessNode(root, DummyOutput('rc_all', 'en'), buf) output = util.StripBlankLinesAndComments(buf.getvalue()) expected = (_PREAMBLE + u'TEXT_ONE TXT "%s"\n' u'TEXT_TWO TXT "%s"' % (util.normpath('/temp/bingo.txt').replace('\\', '\\\\'), 'bingo2.txt')) # hackety hack to work on win32&lin output = re.sub('"[c-zC-Z]:', '"', output) self.assertEqual(expected, output)
def testGetPath(self): root = misc.GritNode() root.StartParsing(u'grit', None) root.HandleAttribute(u'latest_public_release', u'0') root.HandleAttribute(u'current_release', u'1') root.HandleAttribute(u'base_dir', ur'..\resource') translations = empty.TranslationsNode() translations.StartParsing(u'translations', root) root.AddChild(translations) file_node = io.FileNode() file_node.StartParsing(u'file', translations) file_node.HandleAttribute(u'path', ur'flugel\kugel.pdf') translations.AddChild(file_node) root.EndParsing() self.failUnless(root.ToRealPath(file_node.GetInputPath()) == util.normpath( os.path.join(ur'../resource', ur'flugel/kugel.pdf')))
def testRcIncludeFile(self): root = util.ParseGrdForUnittest(''' <includes> <include type="TXT" name="TEXT_ONE" file="bingo.txt"/> <include type="TXT" name="TEXT_TWO" file="bingo2.txt" filenameonly="true" /> </includes>''', base_dir='/temp') buf = StringIO.StringIO() build.RcBuilder.ProcessNode(root, DummyOutput('rc_all', 'en'), buf) output = util.StripBlankLinesAndComments(buf.getvalue()) expected = (_PREAMBLE + u'TEXT_ONE TXT "%s"\n' u'TEXT_TWO TXT "%s"' % (util.normpath('/temp/bingo.txt').replace( '\\', '\\\\'), 'bingo2.txt')) # hackety hack to work on win32&lin output = re.sub('"[c-zC-Z]:', '"', output) self.assertEqual(expected, output)
def testGetPath(self): root = misc.GritNode() root.StartParsing(u"grit", None) root.HandleAttribute(u"latest_public_release", u"0") root.HandleAttribute(u"current_release", u"1") root.HandleAttribute(u"base_dir", ur"..\resource") translations = empty.TranslationsNode() translations.StartParsing(u"translations", root) root.AddChild(translations) file_node = io.FileNode() file_node.StartParsing(u"file", translations) file_node.HandleAttribute(u"path", ur"flugel\kugel.pdf") translations.AddChild(file_node) root.EndParsing() self.failUnless( root.ToRealPath(file_node.GetInputPath()) == util.normpath(os.path.join(ur"../resource", ur"flugel/kugel.pdf")) )
def Inputs(filename, defines, ids_file, target_platform): grd = grd_reader.Parse(filename, debug=False, defines=defines, tags_to_ignore=set(['message']), first_ids_file=ids_file, target_platform=target_platform) files = set() for lang, ctx in grd.GetConfigurations(): grd.SetOutputLanguage(lang or grd.GetSourceLanguage()) grd.SetOutputContext(ctx) for node in grd.ActiveDescendants(): with node: if (node.name == 'structure' or node.name == 'skeleton' or (node.name == 'file' and node.parent and node.parent.name == 'translations')): files.add(grd.ToRealPath(node.GetInputPath())) # If it's a flattened node, grab inlined resources too. if node.name == 'structure' and node.attrs[ 'flattenhtml'] == 'true': node.RunPreSubstitutionGatherer() files.update(node.GetHtmlResourceFilenames()) elif node.name == 'grit': first_ids_file = node.GetFirstIdsFile() if first_ids_file: files.add(first_ids_file) elif node.name == 'include': files.add(grd.ToRealPath(node.GetInputPath())) # If it's a flattened node, grab inlined resources too. if node.attrs['flattenhtml'] == 'true': files.update(node.GetHtmlResourceFilenames()) elif node.name == 'part': files.add( util.normpath( os.path.join(os.path.dirname(filename), node.GetInputPath()))) cwd = os.getcwd() return [os.path.relpath(f, cwd) for f in sorted(files)]
def Parse(filename_or_stream, dir=None, stop_after=None, first_ids_file=None, debug=False, defines=None, tags_to_ignore=None, target_platform=None): '''Parses a GRD file into a tree of nodes (from grit.node). If filename_or_stream is a stream, 'dir' should point to the directory notionally containing the stream (this feature is only used in unit tests). If 'stop_after' is provided, the parsing will stop once the first node with this name has been fully parsed (including all its contents). If 'debug' is true, lots of information about the parsing events will be printed out during parsing of the file. If 'first_ids_file' is non-empty, it is used to override the setting for the first_ids_file attribute of the <grit> root node. Note that the first_ids_file parameter should be relative to the cwd, even though the first_ids_file attribute of the <grit> node is relative to the grd file. If 'target_platform' is set, this is used to determine the target platform of builds, instead of using |sys.platform|. Args: filename_or_stream: './bla.xml' dir: None (if filename_or_stream is a filename) or '.' stop_after: 'inputs' first_ids_file: 'GRIT_DIR/../gritsettings/resource_ids' debug: False defines: dictionary of defines, like {'chromeos': '1'} target_platform: None or the value that would be returned by sys.platform on your target platform. Return: Subclass of grit.node.base.Node Throws: grit.exception.Parsing ''' if dir is None and isinstance(filename_or_stream, types.StringType): dir = util.dirname(filename_or_stream) handler = GrdContentHandler(stop_after=stop_after, debug=debug, dir=dir, defines=defines, tags_to_ignore=tags_to_ignore, target_platform=target_platform) try: xml.sax.parse(filename_or_stream, handler) except StopParsingException: assert stop_after pass except: if not debug: print "parse exception: run GRIT with the -x flag to debug .grd problems" raise if handler.root.name != 'grit': raise exception.MissingElement("root tag must be <grit>") if hasattr(handler.root, 'SetOwnDir'): # Fix up the base_dir so it is relative to the input file. assert dir is not None handler.root.SetOwnDir(dir) if isinstance(handler.root, misc.GritNode): if first_ids_file: # Make the path to the first_ids_file relative to the grd file, # unless it begins with GRIT_DIR. GRIT_DIR_PREFIX = 'GRIT_DIR' if not (first_ids_file.startswith(GRIT_DIR_PREFIX) and first_ids_file[len(GRIT_DIR_PREFIX)] in ['/', '\\']): rel_dir = os.path.relpath(os.getcwd(), dir) first_ids_file = util.normpath(os.path.join(rel_dir, first_ids_file)) handler.root.attrs['first_ids_file'] = first_ids_file # Assign first ids to the nodes that don't have them. handler.root.AssignFirstIds(filename_or_stream, defines) return handler.root
def Parse(filename_or_stream, dir=None, stop_after=None, first_ids_file=None, debug=False, defines=None, tags_to_ignore=None, target_platform=None, predetermined_ids_file=None): '''Parses a GRD file into a tree of nodes (from grit.node). If filename_or_stream is a stream, 'dir' should point to the directory notionally containing the stream (this feature is only used in unit tests). If 'stop_after' is provided, the parsing will stop once the first node with this name has been fully parsed (including all its contents). If 'debug' is true, lots of information about the parsing events will be printed out during parsing of the file. If 'first_ids_file' is non-empty, it is used to override the setting for the first_ids_file attribute of the <grit> root node. Note that the first_ids_file parameter should be relative to the cwd, even though the first_ids_file attribute of the <grit> node is relative to the grd file. If 'target_platform' is set, this is used to determine the target platform of builds, instead of using |sys.platform|. Args: filename_or_stream: './bla.xml' dir: None (if filename_or_stream is a filename) or '.' stop_after: 'inputs' first_ids_file: 'GRIT_DIR/../gritsettings/resource_ids' debug: False defines: dictionary of defines, like {'chromeos': '1'} target_platform: None or the value that would be returned by sys.platform on your target platform. predetermined_ids_file: File path to a file containing a pre-determined mapping from resource names to resource ids which will be used to assign resource ids to those resources. Return: Subclass of grit.node.base.Node Throws: grit.exception.Parsing ''' if isinstance(filename_or_stream, six.string_types): source = filename_or_stream if dir is None: dir = util.dirname(filename_or_stream) else: source = None handler = GrdContentHandler(stop_after=stop_after, debug=debug, dir=dir, defines=defines, tags_to_ignore=tags_to_ignore, target_platform=target_platform, source=source) try: xml.sax.parse(filename_or_stream, handler) except StopParsingException: assert stop_after pass except: if not debug: print( "parse exception: run GRIT with the -x flag to debug .grd problems" ) raise if handler.root.name != 'grit': raise exception.MissingElement("root tag must be <grit>") if hasattr(handler.root, 'SetOwnDir'): # Fix up the base_dir so it is relative to the input file. assert dir is not None handler.root.SetOwnDir(dir) if isinstance(handler.root, misc.GritNode): handler.root.SetPredeterminedIdsFile(predetermined_ids_file) if first_ids_file: # Make the path to the first_ids_file relative to the grd file, # unless it begins with GRIT_DIR. GRIT_DIR_PREFIX = 'GRIT_DIR' if not (first_ids_file.startswith(GRIT_DIR_PREFIX) and first_ids_file[len(GRIT_DIR_PREFIX)] in ['/', '\\']): rel_dir = os.path.relpath(os.getcwd(), dir) first_ids_file = util.normpath( os.path.join(rel_dir, first_ids_file)) handler.root.attrs['first_ids_file'] = first_ids_file # Assign first ids to the nodes that don't have them. handler.root.AssignFirstIds(filename_or_stream, defines) return handler.root
def testInlineIgnoresPolymerBindings(self): '''Tests that polymer bindings are ignored when inlining. ''' files = { 'index.html': ''' <html> <head> <link rel="stylesheet" href="test.css"> </head> <body> <iron-icon src="[[icon]]"></iron-icon><!-- Should be ignored. --> <iron-icon src="{{src}}"></iron-icon><!-- Also ignored. --> <!-- [[image]] should be ignored. --> <div style="background: url([[image]]), url('test.png');"> </div> <div style="background: url('test.png'), url([[image]]);"> </div> </body> </html> ''', 'test.css': ''' .image { background: url('test.png'); background-image: url([[ignoreMe]]); background-image: image-set(url({{alsoMe}}), 1x); background-image: image-set( url({{ignore}}) 1x, url('test.png') 2x); } ''', 'test.png': 'PNG DATA' } expected_inlined = ''' <html> <head> <style> .image { background: url('data:image/png;base64,UE5HIERBVEE='); background-image: url([[ignoreMe]]); background-image: image-set(url({{alsoMe}}), 1x); background-image: image-set( url({{ignore}}) 1x, url('data:image/png;base64,UE5HIERBVEE=') 2x); } </style> </head> <body> <iron-icon src="[[icon]]"></iron-icon><!-- Should be ignored. --> <iron-icon src="{{src}}"></iron-icon><!-- Also ignored. --> <!-- [[image]] should be ignored. --> <div style="background: url([[image]]), url('data:image/png;base64,UE5HIERBVEE=');"> </div> <div style="background: url('data:image/png;base64,UE5HIERBVEE='), url([[image]]);"> </div> </body> </html> ''' source_resources = set() tmp_dir = util.TempDir(files) for filename in files: source_resources.add(tmp_dir.GetPath(util.normpath(filename))) result = html_inline.DoInline(tmp_dir.GetPath('index.html'), None) resources = result.inlined_files resources.add(tmp_dir.GetPath('index.html')) self.failUnlessEqual(resources, source_resources) self.failUnlessEqual(expected_inlined, util.FixLineEnd(result.inlined_data, '\n')) tmp_dir.CleanUp()