def CreateInputSource(obj, uri=None): """ Convenience function for creating an InputSource. obj - a string, Unicode object (only if you really know what you're doing), file-like object (stream), file path or URI. You can also pass an InputSource object, in which case the return value is just the same object, possibly with the URI modified uri - optional override URI. The base URI for the IS will be set to this value Returns an InputSource which can be passed to 4Suite APIs. """ #do the imports within the function: a tad bit less efficient, but #avoid circular crap from Ft.Xml import InputSource factory = InputSource.DefaultFactory from Ft.Lib import Uri, Uuid from Ft.Xml.Lib.XmlString import IsXml if isinstance(obj, InputSource.InputSource): isrc = obj elif hasattr(obj, 'read'): #Create dummy Uri to use as base dummy_uri = 'urn:uuid:' + Uuid.UuidAsString(Uuid.GenerateUuid()) isrc = factory.fromStream(obj, dummy_uri) elif IsXml(obj): dummy_uri = 'urn:uuid:' + Uuid.UuidAsString(Uuid.GenerateUuid()) isrc = factory.fromString(obj, dummy_uri) elif Uri.IsAbsolute(obj): #or not os.path.isfile(obj): isrc = factory.fromUri(obj) else: isrc = factory.fromUri(Uri.OsPathToUri(obj)) if uri: isrc.uri = uri return isrc
def pushdom(source, xpatterns, prefixes=None, validate=False): parser = Sax.CreateParser() if validate: parser.setFeature(xml.sax.handler.feature_validation, True) else: parser.setFeature(xml.sax.handler.feature_external_pes, False) parser.setFeature(Sax.FEATURE_GENERATOR, True) def handle_chunk(docfrag): parser.setProperty(Sax.PROPERTY_YIELD_RESULT, docfrag) handler = sax2dom_chunker(xpatterns=xpatterns, nss=prefixes, chunk_consumer=handle_chunk) parser.setContentHandler(handler) if isinstance(source, InputSource.InputSource): pass elif hasattr(source, 'read'): #Create dummy Uri to use as base dummy_uri = 'urn:uuid:' + Uuid.UuidAsString(Uuid.GenerateUuid()) source = InputSource.DefaultFactory.fromStream(source, dummy_uri) elif IsXml(source): #Create dummy Uri to use as base dummy_uri = 'urn:uuid:' + Uuid.UuidAsString(Uuid.GenerateUuid()) source = InputSource.DefaultFactory.fromString(source, dummy_uri) elif Uri.IsAbsolute(source): #or not os.path.isfile(source): source = InputSource.DefaultFactory.fromUri(source) else: source = InputSource.DefaultFactory.fromUri(Uri.OsPathToUri(source)) return parser.parse(source)
def _parseTr9401(self, data): """ Parse a TR9401 Catalog, as specified in <http://www.oasis-open.org/specs/a401.htm>. Partially implemented. """ prefer_public = True base = self.uri for cmd in TR9401.findall(data): token = cmd[0].upper() if token == 'PUBLIC': if len(cmd) == 3: self.publicIds[cmd[1]] = (Uri.Absolutize(cmd[2], base), prefer_public) elif token == 'SYSTEM': if len(cmd) == 3: self.systemIds[cmd[1]] = Uri.Absolutize(cmd[2], base) elif token == 'BASE': base = cmd[1] elif token[:8] == 'OVERRIDE': prefer_public = token[8:].strip() == 'YES' elif token == 'DELEGATE': if len(cmd) == 3: self.publicDelegates[cmd[1]] = Uri.Absolutize(cmd[2], base) elif token == 'CATALOG': if len(cmd) == 2: catalog = Catalog(Uri.Absolutize(cmd[1], base), self.quiet) self.catalogs.append(catalog) return
def Test(tester): tester.startGroup("instantiation of runNode") base = Uri.OsPathToUri(__file__, attemptAbsolute=True) src_uri = Uri.Absolutize('addr_book1.xml', base) sty_uri = Uri.Absolutize('addr_book1.xsl', base) tester.startTest("without whitespace preservation") p = Processor.Processor() node = Domlette.NonvalidatingReader.parseUri(src_uri) isrc = InputSource.DefaultFactory.fromUri(sty_uri) p.appendStylesheet(isrc) res = p.runNode(node, src_uri, ignorePis=True, preserveSrc=False) tester.compare(expected, res, func=TreeCompare.TreeCompare) tester.testDone() tester.startTest("with whitespace preservation") p = Processor.Processor() node = Domlette.NonvalidatingReader.parseUri(src_uri) isrc = InputSource.DefaultFactory.fromUri(sty_uri) p.appendStylesheet(isrc) res = p.runNode(node, src_uri, ignorePis=True, preserveSrc=True) tester.compare(expected, res, func=TreeCompare.TreeCompare) tester.testDone() tester.groupDone() return
def GetDefaultCatalog(basename='default.cat'): """ Load the default catalog file(s). """ quiet = 'XML_DEBUG_CATALOG' not in os.environ uris = [] # original 4Suite XML Catalog support if 'XML_CATALOGS' in os.environ: # os.pathsep seperated list of pathnames for path in os.environ['XML_CATALOGS'].split(os.pathsep): uris.append(Uri.OsPathToUri(path)) # libxml2 XML Catalog support if 'XML_CATALOG_FILES' in os.environ: # whitespace-separated list of pathnames or URLs (ick!) for path in os.environ['XML_CATALOG_FILES'].split(): # if its already not already an URL, make it one if not Uri.IsAbsolute(path): uris.append(Uri.OsPathToUri(path)) else: uris.append(path) # add the default 4Suite catalog pathname = os.path.join(GetConfigVar('DATADIR'), basename) if GetConfigVar('RESOURCEBUNDLE'): resource = ImportUtil.OsPathToResource(pathname) uri = Uri.ResourceToUri('Ft.Xml', resource) else: uri = Uri.OsPathToUri(pathname) uris.append(uri) if not quiet: prefix = "Catalog URIs:" for uri in uris: sys.stderr.write('%s %s\n' % (prefix, uri)) prefix = " "*len(prefix) catalog = None for uri in uris: if not quiet: sys.stderr.write('Reading %s\n' % uri) sys.stderr.flush() try: # FIXME: Use dict merging rather than this inefficient cascading if catalog is None: if not quiet: sys.stderr.write('Creating catalog from %s\n' % uri) sys.stderr.flush() catalog = Catalog(uri, quiet) else: if not quiet: sys.stderr.write('Appending %s\n' % uri) sys.stderr.flush() catalog.catalogs.append(Catalog(uri, quiet)) except UriException, e: #warnings.warn("Catalog resource (%s) disabled: %s" % (uri, # e.message), # FtWarning) pass
def finalize_options(self): self.set_undefined_options('build_docs', ('build_dir', 'build_dir')) self.set_undefined_options('install', ('install_docs', 'install_dir'), ('skip_build', 'skip_build'), ('force', 'force')) self.documents = self.get_documents() resourcebundle = GetConfigVar('RESOURCEBUNDLE') if resourcebundle is None: # building 4Suite itself; use different (hard-wired) directories base_uri = Uri.OsPathToUri(os.path.join('Ft', 'Data')) else: datadir = GetConfigVar('DATADIR') datadir = os.path.join(datadir, 'Data', 'Stylesheets') if resourcebundle: resource = ImportUtil.OsPathToResource(datadir) base_uri = Uri.ResourceToUri('Ft.Lib', resource) else: base_uri = Uri.OsPathToUri(datadir) defaults = self.get_default_stylesheets() for name in defaults: attr = name + '_xslt' value = getattr(self, attr) if value is None: value = base_uri + '/' + defaults[name] else: pathname = util.convert_path(value) value = Uri.OsPathToUri(pathname) setattr(self, attr, value) self._xslt_processor = None self._stylesheets = {} return
def _AttachStylesheetToProcessor(stylesheet, processor): from Ft.Lib import Uri, Uuid from Ft.Xml import InputSource from Ft.Xml.Catalog import IsXml if isinstance(stylesheet, InputSource.InputSource): processor.appendStylesheet(stylesheet) #elif stylesheet.find(XSL_NAMESPACE) > 0 and IsXml(stylesheet): #Note: this would break in pathological cases such as a user #passing in a stylesheet string with only an XInclude to the actual XSLT elif IsXml(stylesheet): #Create dummy Uri to use as base dummy_uri = 'urn:uuid:' + Uuid.UuidAsString(Uuid.GenerateUuid()) processor.appendStylesheet( InputSource.DefaultFactory.fromString(stylesheet, dummy_uri)) elif hasattr(stylesheet, 'read'): #Create dummy Uri to use as base dummy_uri = 'urn:uuid:' + Uuid.UuidAsString(Uuid.GenerateUuid()) processor.appendStylesheet( InputSource.DefaultFactory.fromStream(stylesheet, dummy_uri)) elif Uri.IsAbsolute(stylesheet): # or not os.path.isfile(stylesheet): processor.appendStylesheet( InputSource.DefaultFactory.fromUri(stylesheet)) else: processor.appendStylesheet( InputSource.DefaultFactory.fromUri(Uri.OsPathToUri(stylesheet))) return
def Test(tester): base = Uri.OsPathToUri(__file__, attemptAbsolute=True) tester.startGroup('Simple XLinks') from Ft.Xml.XLink.Processor import Processor tester.startTest('Process w/xlink:show="embed"') uri1 = Uri.Absolutize('addr_book1.xml', base) isrc = InputSource.DefaultFactory.fromUri(uri1) p = Processor() doc = p.run(isrc) stream = cStringIO.StringIO() Print(doc, stream) actual = stream.getvalue() tester.compare(EXPECTED_1, actual, func=TreeCompare.TreeCompare) tester.testDone() tester.startTest('Process w/xlink:show="replace"') uri3 = Uri.Absolutize('addr_book3.xml', base) isrc = InputSource.DefaultFactory.fromUri(uri3) p = Processor() doc = p.run(isrc) stream = cStringIO.StringIO() Print(doc, stream) actual = stream.getvalue() tester.compare(EXPECTED_2, actual, func=TreeCompare.TreeCompare) tester.testDone() return tester.groupDone()
def find_css_uris(uri): """Find all the CSS dependencies (@import directives).""" uris = [uri] stream = Uri.UrlOpen(uri) for line in Uri.UrlOpen(uri).readlines(): match = re.match(r"\s*@import\s+url\s*\((.*)\)", line) if match: next_uri = Uri.BaseJoin(uri, eval(match.group(1))) uris.extend(find_css_uris(next_uri)) return uris
def get(self, fn): if fn.startswith('pkg://'): package, sep, path = fn[6:].partition('#') if pkg_resources.resource_exists(package, path): return self.xslt_factory.fromString(pkg_resources.resource_string(package, path)) path = Uri.OsPathToUri(os.path.join(self.tdir, fn)) try: xslt = self.xslt_factory.fromUri(path) except UriException, e: xslt = self.xslt_factory.fromString( fn, Uri.OsPathToUri(os.path.abspath('.')) )
def resolve(self, uri, base=None): scheme = Uri.GetScheme(uri) if not scheme: if base: scheme = Uri.GetScheme(base) if not scheme: #Another option is to fall back to Base class behavior raise Uri.UriException(Uri.UriException.SCHEME_REQUIRED, base=base, ref=uri) func = self.handlers.get(scheme) if not func: func = self.handlers.get(None) if not func: return Uri.UriResolverBase.resolve(self, uri, base) return func(uri, base)
def __init__(self,iptFile,ctFile,truncTime): # Read epidemic and truncate to truncTime self.infectives = [] self.labels = [] epiFile = open(iptFile,'r') for line in epiFile: toks = line.split() label = atoi(toks[0]) I = atof(toks[1]) N = atof(toks[2]) R = atof(toks[3]) if N <= truncTime: # Take individuals who have been notified by truncTime if R > truncTime: # If R > truncTime, set R = truncTime R = truncTime self.infectives.append(Infective(label,I,N,R)) self.labels.append(label) epiFile.close() # Read in XML conFile = Uri.OsPathToUri(ctFile) xmlSrc = DefaultFactory.fromUri(conFile,stripElements=[(EMPTY_NAMESPACE,'*',1)]) self.doc = NonvalidatingReader.parse(xmlSrc) # Remove from the contact DOM any contact info # for individuals that are not present in labels self.labels = set(self.labels) for contact in self.doc.documentElement.xpath(u'tc:contact',explicitNss={u'tc':u'tracedcontacts'}): contactLabel = atoi(contact.getAttributeNS(None,u'id')) if contactLabel not in self.labels: self.doc.documentElement.removeChild(contact)
def copy_uri(self, uri, filename): """ Copies the contents of the resource given by 'uri' to 'filename'. """ source = Uri.UrlOpen(uri) try: source_mtime = source.headers.getdate_tz('last-modified') source_mtime = rfc822.mktime_tz(source_mtime) try: target_mtime = os.path.getmtime(filename) except OSError: target_mtime = -1 if not (self.force or source_mtime > target_mtime): self.announce("not copying %s (output up-to-date)" % uri, 1) return filename, False self.announce("copying %s -> %s" % (uri, filename), 2) if not self.dry_run: f = open(filename, 'wb') try: f.write(source.read()) finally: f.close() finally: source.close() return filename, True
def _compile_xsl(XSLT_FILE, XSLT_COMPILED_FILE): """ compiling docbook stylesheet reference: http://155.210.85.193:8010/ccia/nodes/2005-03-18/compileXslt?xslt=/akara/akara.xslt """ from Ft.Xml.Xslt.Processor import Processor from Ft.Xml.Xslt import Stylesheet from Ft.Xml import InputSource from Ft.Lib import Uri # New docbook processor db_processor = Processor() # Docbook Stylesheet my_sheet_uri = Uri.OsPathToUri(XSLT_FILE, 1) sty_isrc = InputSource.DefaultFactory.fromUri(my_sheet_uri) # Append Stylesheet db_processor.appendStylesheet(sty_isrc) # Pickled stylesheet will be self.abs_db_compiled_xsl file db_root = db_processor.stylesheet.root fw = file(XSLT_COMPILED_FILE, 'wb') cPickle.dump(db_root, fw) # , protocol=2) fw.close()
def Test(tester): tester.startGroup('Exercise namespace nodes') isrc = InputSource.DefaultFactory.fromString(SRC_1, Uri.OsPathToUri(os.getcwd())) doc = NonvalidatingReader.parse(isrc) con = Context.Context(doc, 1, 1) EXPR = '//namespace::node()' expr = Compile(EXPR) #expr is <AbbreviatedAbsoluteLocationPath: /descendant-or-self::node()/namespace::node()> #expr._rel is <Step: namespace::node()> #expr._step is <Step: descendant-or-self::node()> tester.startTest(EXPR) actual = expr.evaluate(con) tester.compare(7, len(actual)) tester.testDone() EXPR = '//node()/namespace::node()' expr = Compile(EXPR) tester.startTest(EXPR) EXPECTED = [] actual = expr.evaluate(con) tester.compare(7, len(actual)) tester.testDone() EXPR = '//*/namespace::node()' expr = Compile(EXPR) tester.startTest(EXPR) EXPECTED = [] actual = expr.evaluate(con) tester.compare(7, len(actual)) tester.testDone() EXPR = '/*/*/namespace::node()' expr = Compile(EXPR) tester.startTest(EXPR) EXPECTED = [] actual = expr.evaluate(con) tester.compare(6, len(actual)) tester.testDone() EXPR = '/*/namespace::node()|/*/*/namespace::node()' expr = Compile(EXPR) tester.startTest(EXPR) EXPECTED = [] actual = expr.evaluate(con) tester.compare(7, len(actual)) tester.testDone() EXPR = '//*' expr = Compile(EXPR) #expr is <AbbreviatedAbsoluteLocationPath: /descendant-or-self::node()/child::*> tester.startTest(EXPR) EXPECTED = [] actual = expr.evaluate(con) tester.compare(4, len(actual)) tester.testDone() return tester.groupDone()
def SourceArgToUri(arg, resolver=Uri.BASIC_RESOLVER): """ Some command-line scripts take an argument that is supposed to be either "-" (denoting standard input) or a URI reference that can be resolved against the URI equivalent of the current working directory. This function processes such an argument, given as a string, and returns an appropriate URI. Since users tend to expect local OS paths to work as URIs, this function will accept and use an OS path argument if does appear to point to an existing local file, even though this could interfere with catalog-based resolution. Raises a ValueError if arg is neither a local file nor a valid URI reference nor "-". The resolver object must support a normalize() method that can resolve a URI reference against a base URI, returning a URI. """ if not isinstance(resolver, Uri.UriResolverBase): msg = 'It appears there is a bug in this command-line' \ ' script. A %s was passed as URI resolver to a function that' \ ' requires an instance of Ft.Lib.Uri.UriResolverBase (or' \ ' a subclass thereof).' raise TypeError(msg % type(resolver)) if not isinstance(arg, str) and not isinstance(arg, unicode): msg = 'It appears there is a bug in this command-line' \ ' script. A %s was passed as an argument needing to be' \ ' converted to a URI. A string must be provided instead.' raise TypeError(msg % type(arg)) if arg == '-': return Uri.OsPathToUri('unknown-STDIN', attemptAbsolute=True) elif arg: if os.path.isfile(arg): return Uri.OsPathToUri(arg, attemptAbsolute=True) elif not Uri.MatchesUriRefSyntax(arg): raise ValueError("'%s' is not a valid URI reference." % arg) elif Uri.IsAbsolute(arg): return arg base = Uri.OsPathToUri(os.getcwd(), attemptAbsolute=True) if base[-1] != '/': base += '/' return resolver.normalize(arg, base)
def startDocument(self): url = self._locator.getSystemId() self._bases = [url] self._scheme = Uri.GetScheme(url) self._elements = [ ("http://www.w3.org/2001/XInclude", "include"), ] if xslt: self._elements.extend(self.XSLT_INCLUDES)
def ResolvePath(context, base, rel): """ Resolves a Posix-style path, such as the path portion of a URL, against a base. Similar to f:resolve-url, but allows the base to be just a path, not necessarily a full URL. """ base = Conversions.StringValue(base) rel = Conversions.StringValue(rel) return Uri.BaseJoin(base, rel)
def instantiate(self, context, processor): context.processorNss = self.namespaces context.currentInstruction = self # this uses attributes directly from self self._output_parameters.avtParse(self, context) href = self._href.evaluate(context) if Uri.IsAbsolute(href): uri = href else: try: uri = Uri.Absolutize(href, Uri.OsPathToUri(processor.writer.getStream().name)) except Exception, e: raise XsltRuntimeException( ExsltError.NO_EXSLTDOCUMENT_BASE_URI, context.currentInstruction, href)
def Test(tester): tester.startGroup('EXSLT exsl:document and indent') fname = tempfile.mktemp() furi = Uri.OsPathToUri(fname) source = test_harness.FileInfo(string="<dummy/>") sheet = test_harness.FileInfo(string=SHEET_1 % (furi, "no")) test_harness.XsltTest(tester, source, [sheet], EXPECTED, title='run transform') tester.startTest("With indent='no'") tester.compare(True, os.path.exists(fname)) file = open(fname, 'r') fcontent = file.read() file.close() tester.compare(EXPECTED_FILE_1, fcontent) os.unlink(fname) tester.testDone() fname = tempfile.mktemp() furi = Uri.OsPathToUri(fname) source = test_harness.FileInfo(string="<dummy/>") sheet = test_harness.FileInfo(string=SHEET_1 % (furi, "yes")) test_harness.XsltTest(tester, source, [sheet], EXPECTED, title='run transform') tester.startTest("With indent='yes'") tester.compare(True, os.path.exists(fname)) file = open(fname, 'r') fcontent = file.read() file.close() tester.compare(EXPECTED_FILE_2, fcontent) os.unlink(fname) tester.testDone() tester.groupDone() return
def Parse(source): """ Convenience function for parsing XML. Use this function with a single argument, which must either be a string (not Unicode object), file-like object (stream), file path or URI. Returns a Domlette node. Only pass strings or streams to this function if the XML is self-contained XML (i.e. not requiring access to any other resource such as external entities or includes). If you get URI resolution errors, do not use this function: use the lower-level APIs instead. As an example, if you want such resolution to use the current working directory as a base, parse as follows for strings: from Ft.Xml.Domlette import NonvalidatingReader from Ft.Lib import Uri XML = "<!DOCTYPE a [ <!ENTITY b "b.xml"> ]><a>&b;</a>" base = Uri.OsPathToUri('') #Turn CWD into a file: URL doc = NonvalidatingReader.parseString(XML, base) # during parsing, the replacement text for &b; # will be obtained from b.xml in the CWD For streams, use "parseStream" rather than "parseString" in the above. """ #do the imports within the function: a tad bit less efficient, but #avoid circular crap from Ft.Xml.Domlette import NonvalidatingReader from Ft.Lib import Uri, Uuid from Ft.Xml.Lib.XmlString import IsXml if hasattr(source, 'read'): #Create dummy Uri to use as base dummy_uri = 'urn:uuid:' + Uuid.UuidAsString(Uuid.GenerateUuid()) return NonvalidatingReader.parseStream(source, dummy_uri) elif IsXml(source): dummy_uri = 'urn:uuid:' + Uuid.UuidAsString(Uuid.GenerateUuid()) return NonvalidatingReader.parseString(source, dummy_uri) elif Uri.IsAbsolute(source): #or not os.path.isfile(source): return NonvalidatingReader.parseUri(source) else: return NonvalidatingReader.parseUri(Uri.OsPathToUri(source))
def Test(tester): source = test_harness.FileInfo(string=source_1) sheet = test_harness.FileInfo(string=sheet_1) test_harness.XsltTest(tester, source, [sheet], expected_1) #Test again with a specfied baseUri uri = Uri.OsPathToUri(os.path.abspath(__file__)) source = test_harness.FileInfo(string=source_1) sheet = test_harness.FileInfo(string=sheet_1, baseUri=uri) test_harness.XsltTest(tester, source, [sheet], expected_1) return
def secureFilePathresolve(self, uri, base=None): if base: uri = self.normalize(uri, base) path = Uri.UriToOsPath(uri) for prefix in self.path: if os.path.abspath(path).startswith(os.path.abspath(prefix)): if fileCache:#todo: this only works if secure file access is on return StringIO.StringIO(fileCache.getValue(path)) else: return SiteUriResolver._resolveFile(path) raise UriException(UriException.RESOURCE_ERROR, uri, 'Unauthorized')
def Transform(source, stylesheet, params=None, output=None): """ Convenience function for applying an XSLT transform. Returns a string. source - XML source document in the form of a a string (not Unicode object), file-like object (stream), file path, URI or Ft.Xml.InputSource.InputSource instance. If string or stream it must be self-contained XML (i.e. not requiring access to any other resource such as external entities or includes) stylesheet - XSLT document in the form of a string, stream, URL, file path or Ft.Xml.InputSource.InputSource instance params - optional dictionary of stylesheet parameters, the keys of which may be given as unicode objects if they have no namespace, or as (uri, localname) tuples if they do. output - optional file-like object to which output is written (incrementally, as processed) """ #do the imports within the function: a tad bit less efficient, but #avoid circular crap from Ft.Xml.Xslt import Processor from Ft.Xml import InputSource from Ft.Lib import Uri, Uuid from Ft.Xml.Lib.XmlString import IsXml params = params or {} processor = Processor.Processor() _AttachStylesheetToProcessor(stylesheet, processor) if isinstance(source, InputSource.InputSource): pass elif hasattr(source, 'read'): #Create dummy Uri to use as base dummy_uri = 'urn:uuid:' + Uuid.UuidAsString(Uuid.GenerateUuid()) source = InputSource.DefaultFactory.fromStream(source, dummy_uri) elif IsXml(source): dummy_uri = 'urn:uuid:' + Uuid.UuidAsString(Uuid.GenerateUuid()) source = InputSource.DefaultFactory.fromString(source, dummy_uri) elif Uri.IsAbsolute(source): # or not os.path.isfile(source): source = InputSource.DefaultFactory.fromUri(source) else: source = InputSource.DefaultFactory.fromUri(Uri.OsPathToUri(source)) return processor.run(source, topLevelParams=params, outputStream=output)
def render_documents(self): extras = {} for document in self.documents: # Find the stylesheet to render this document stylesheet = self.get_stylesheet_obj(document.stylesheet) filename = self.get_output_filename(document) destdir = os.path.dirname(filename) self.mkpath(destdir) try: target_mtime = os.path.getmtime(filename) except OSError: target_mtime = -1 document.uri = Uri.OsPathToUri(document.source) document_mtime = self.get_modification_time(document.uri) source_mtime = max(document_mtime, stylesheet.mtime) if document_mtime is None: self.announce('skipping %s (not documented)' % filename, 3) elif self.force or source_mtime > target_mtime: self.announce( "rendering %s -> %s" % (document.source, filename), 2) try: self.render_document(document, stylesheet, filename) except (KeyboardInterrupt, SystemExit): # Let "exitting" exceptions propagate through. raise except Exception, exc: if DEBUG: raise raise DistutilsFileError("could not render %s (%s)" % (document.source, exc)) else: self.announce('not rendering %s (up-to-date)' % filename, 1) # Copy any extra files for the stylesheet to destdir. # 'extra_outputs' is a list of URIs. for uri in stylesheet.extra_outputs: pathname = Uri.Relativize(uri, stylesheet.uri) target = os.path.join(destdir, *pathname.split('/')) if target not in extras: extras[target] = True self.copy_uri(uri, target)
def FileExists(context, uri): path = StringValue(uri) if path.startswith('file:'): path = Uri.UriToOsPath(path) #todo: security hole return Xbool(os.path.exists(path)) else: if path.startswith('path:'): path = path[len('path:'):] for prefix in InputSource.DefaultFactory.resolver.path: if os.path.exists(os.path.join(prefix.strip(), path)): return XTrue return XFalse
def ResolveUrl(context, base, rel): """ Returns the relative URL ref given in the second argument resolved against the base given in the first argument. In case of URI processing error an empty string is returned """ base = Conversions.StringValue(base) rel = Conversions.StringValue(rel) try: return Uri.Absolutize(rel, base) except Uri.UriException: return u''
def _orig_resolve(self, uri, baseUri=None): """ This function takes a URI or a URI reference plus a base URI, produces a normalized URI using the normalize function if a base URI was given, then attempts to obtain access to an entity representing the resource identified by the resulting URI, returning the entity as a stream (a Python file-like object). Raises a UriException if the URI scheme is unsupported or if a stream could not be obtained for any reason. """ if baseUri is not None: uri = self.normalize(uri, baseUri) scheme = Uri.GetScheme(uri) else: scheme = Uri.GetScheme(uri) # since we didn't use normalize(), we need to verify here if scheme not in Uri.DEFAULT_URI_SCHEMES: if scheme is None: raise ValueError('When the URI to resolve is a relative ' 'reference, it must be accompanied by a base URI.') else: raise UriException(UriException.UNSUPPORTED_SCHEME, scheme=scheme, resolver=self.__class__.__name__) # Bypass urllib for opening local files. This means we don't get all # the extra metadata that urllib adds to the stream (Last-modified, # Content-Length, a poorly guessed Content-Type, and the URI), but # we also avoid its potentially time-consuming socket.gethostbyname() # calls, which aren't even warranted and are part of urllib's dubious # interpretation of RFC 1738. if scheme == 'file': path = Uri.UriToOsPath(uri, attemptAbsolute=False) try: stream = file(path, 'rb') except IOError, e: raise UriException(UriException.RESOURCE_ERROR, loc='%s (%s)' % (uri, path), uri=uri, msg=str(e))
def build_dom_and_apply_style_sheet(self, xsl, file): #doc = xml.dom.minidom.Document() doc = implementation.createRootNode('file:///article.xml') self.app.ann_frame.build_xml(doc) xsltproc = Processor() xsltproc.appendStylesheet(DefaultFactory.fromUri(Uri.OsPathToUri(xsl))) output = xsltproc.runNode(doc, 'file:///article.xml') outFile = open(file, 'w') outFile.write(output) outFile.close()
def startElementNS(self, expandedName, tagName, attrs): # Update xml:base stack xml_base = ("http://www.w3.org/XML/1998/namespace", "base") baseUri = attrs.get(xml_base, self._bases[-1]) self._bases.append(baseUri) if expandedName in self._elements: try: href = attrs[(None, 'href')] except KeyError: # XInclude same document reference, nothing to do return # Ignore XInclude's with parse='text' if attrs.get((None, 'parse'), 'xml') == 'text': return # Only follow inclusions that have the same scheme as the # initial document. fullurl = Uri.BaseJoin(baseUri, href) if Uri.GetScheme(fullurl) == self._scheme: callback(fullurl)