我们从Python开源项目中,提取了以下25个代码示例,用于说明如何使用docutils.utils.relative_path()。
def stylesheet_call(self, path): """Return code to reference or embed stylesheet file `path`""" if self.settings.embed_stylesheet: try: content = io.FileInput(source_path=path, encoding='utf-8').read() self.settings.record_dependencies.add(path) except IOError, err: msg = u"Cannot embed stylesheet '%s': %s." % ( path, SafeString(err.strerror)) self.document.reporter.error(msg) return '<--- %s --->\n' % msg return self.embedded_stylesheet % content # else link to style file: if self.settings.stylesheet_path: # adapt path relative to output (cf. config.html#stylesheet-path) path = utils.relative_path(self.settings._destination, path) return self.stylesheet_link % self.encode(path)
def stylesheet_call(self, path): """Return code to reference or embed stylesheet file `path`""" if self.settings.embed_stylesheet: try: content = io.FileInput(source_path=path, encoding='utf-8').read() self.settings.record_dependencies.add(path) except IOError as err: msg = "Cannot embed stylesheet '%s': %s." % ( path, SafeString(err.strerror)) self.document.reporter.error(msg) return '<--- %s --->\n' % msg return self.embedded_stylesheet % content # else link to style file: if self.settings.stylesheet_path: # adapt path relative to output (cf. config.html#stylesheet-path) path = utils.relative_path(self.settings._destination, path) return self.stylesheet_link % self.encode(path)
def open_file(self, path): """Open a file and register it as a dependency.""" path = os.path.normpath(path) path = utils.relative_path(None, path) path = nodes.reprunicode(path) self.state.document.settings.record_dependencies.add(path) return open(path, 'r')
def generate_footer(self): # @@@ Text is hard-coded for now. # Should be made dynamic (language-dependent). # @@@ Use timestamp from the `SOURCE_DATE_EPOCH`_ environment variable # for the datestamp? # See https://sourceforge.net/p/docutils/patches/132/ # and https://reproducible-builds.org/specs/source-date-epoch/ settings = self.document.settings if settings.generator or settings.datestamp or settings.source_link \ or settings.source_url: text = [] if settings.source_link and settings._source \ or settings.source_url: if settings.source_url: source = settings.source_url else: source = utils.relative_path(settings._destination, settings._source) text.extend([ nodes.reference('', 'View document source', refuri=source), nodes.Text('.\n')]) if settings.datestamp: datestamp = time.strftime(settings.datestamp, time.gmtime()) text.append(nodes.Text('Generated on: ' + datestamp + '.\n')) if settings.generator: text.extend([ nodes.Text('Generated by '), nodes.reference('', 'Docutils', refuri= 'http://docutils.sourceforge.net/'), nodes.Text(' from '), nodes.reference('', 'reStructuredText', refuri='http://' 'docutils.sourceforge.net/rst.html'), nodes.Text(' source.\n')]) return [nodes.paragraph('', '', *text)] else: return None
def stylesheet_call(self, path): """Return code to reference or embed stylesheet file `path`""" # is it a package (no extension or *.sty) or "normal" tex code: (base, ext) = os.path.splitext(path) is_package = ext in ['.sty', ''] # Embed content of style file: if self.settings.embed_stylesheet: if is_package: path = base + '.sty' # ensure extension try: content = io.FileInput(source_path=path, encoding='utf-8').read() self.settings.record_dependencies.add(path) except IOError, err: msg = u"Cannot embed stylesheet '%s':\n %s." % ( path, SafeString(err.strerror)) self.document.reporter.error(msg) return '% ' + msg.replace('\n', '\n% ') if is_package: content = '\n'.join([r'\makeatletter', content, r'\makeatother']) return '%% embedded stylesheet: %s\n%s' % (path, content) # Link to style file: if is_package: path = base # drop extension cmd = r'\usepackage{%s}' else: cmd = r'\input{%s}' if self.settings.stylesheet_path: # adapt path relative to output (cf. config.html#stylesheet-path) path = utils.relative_path(self.settings._destination, path) return cmd % path
def generate_footer(self): # @@@ Text is hard-coded for now. # Should be made dynamic (language-dependent). settings = self.document.settings if settings.generator or settings.datestamp or settings.source_link \ or settings.source_url: text = [] if settings.source_link and settings._source \ or settings.source_url: if settings.source_url: source = settings.source_url else: source = utils.relative_path(settings._destination, settings._source) text.extend([ nodes.reference('', 'View document source', refuri=source), nodes.Text('.\n')]) if settings.datestamp: datestamp = time.strftime(settings.datestamp, time.gmtime()) text.append(nodes.Text('Generated on: ' + datestamp + '.\n')) if settings.generator: text.extend([ nodes.Text('Generated by '), nodes.reference('', 'Docutils', refuri= 'http://docutils.sourceforge.net/'), nodes.Text(' from '), nodes.reference('', 'reStructuredText', refuri='http://' 'docutils.sourceforge.net/rst.html'), nodes.Text(' source.\n')]) return [nodes.paragraph('', '', *text)] else: return None
def process_dependencies(self, docname, doctree): """Process docutils-generated dependency info.""" cwd = getcwd() frompath = path.join(path.normpath(self.srcdir), 'dummy') deps = doctree.settings.record_dependencies if not deps: return for dep in deps.list: # the dependency path is relative to the working dir, so get # one relative to the srcdir if isinstance(dep, bytes): dep = dep.decode(fs_encoding) relpath = relative_path(frompath, path.normpath(path.join(cwd, dep))) self.dependencies.setdefault(docname, set()).add(relpath)
def copy_static_entry(source, targetdir, builder, context={}, exclude_matchers=(), level=0): """Copy a HTML builder static_path entry from source to targetdir. Handles all possible cases of files, directories and subdirectories. """ if exclude_matchers: relpath = relative_path(path.join(builder.srcdir, 'dummy'), source) for matcher in exclude_matchers: if matcher(relpath): return if path.isfile(source): target = path.join(targetdir, path.basename(source)) if source.lower().endswith('_t') and builder.templates: # templated! fsrc = open(source, 'r', encoding='utf-8') fdst = open(target[:-2], 'w', encoding='utf-8') fdst.write(builder.templates.render_string(fsrc.read(), context)) fsrc.close() fdst.close() else: copyfile(source, target) elif path.isdir(source): if not path.isdir(targetdir): os.mkdir(targetdir) for entry in os.listdir(source): if entry.startswith('.'): continue newtarget = targetdir if path.isdir(path.join(source, entry)): newtarget = path.join(targetdir, entry) copy_static_entry(path.join(source, entry), newtarget, builder, context, level=level+1, exclude_matchers=exclude_matchers)
def stylesheet_call(self, path): """Return code to reference or embed stylesheet file `path`""" # is it a package (no extension or *.sty) or "normal" tex code: (base, ext) = os.path.splitext(path) is_package = ext in ['.sty', ''] # Embed content of style file: if self.settings.embed_stylesheet: if is_package: path = base + '.sty' # ensure extension try: content = io.FileInput(source_path=path, encoding='utf-8').read() self.settings.record_dependencies.add(path) except IOError as err: msg = "Cannot embed stylesheet '%s':\n %s." % ( path, SafeString(err.strerror)) self.document.reporter.error(msg) return '% ' + msg.replace('\n', '\n% ') if is_package: content = '\n'.join([r'\makeatletter', content, r'\makeatother']) return '%% embedded stylesheet: %s\n%s' % (path, content) # Link to style file: if is_package: path = base # drop extension cmd = r'\usepackage{%s}' else: cmd = r'\input{%s}' if self.settings.stylesheet_path: # adapt path relative to output (cf. config.html#stylesheet-path) path = utils.relative_path(self.settings._destination, path) return cmd % path
def script_call(self, path): path = utils.relative_path(self.settings._destination, path) return self.mathjax_script % self.encode(path)
def run(self): """Most of this method is from ``docutils.parser.rst.Directive``. docutils version: 0.12 """ if not self.state.document.settings.file_insertion_enabled: raise self.warning('"%s" directive disabled.' % self.name) source = self.state_machine.input_lines.source( self.lineno - self.state_machine.input_offset - 1) source_dir = os.path.dirname(os.path.abspath(source)) path = rst.directives.path(self.arguments[0]) path = os.path.normpath(os.path.join(source_dir, path)) path = utils.relative_path(None, path) path = nodes.reprunicode(path) # get options (currently not use directive-specific options) encoding = self.options.get( 'encoding', self.state.document.settings.input_encoding) e_handler = self.state.document.settings.input_encoding_error_handler tab_width = self.options.get( 'tab-width', self.state.document.settings.tab_width) # open the inclding file try: self.state.document.settings.record_dependencies.add(path) include_file = io.FileInput(source_path=path, encoding=encoding, error_handler=e_handler) except UnicodeEncodeError as error: raise self.severe('Problems with "%s" directive path:\n' 'Cannot encode input file path "%s" ' '(wrong locale?).' % (self.name, SafeString(path))) except IOError as error: raise self.severe('Problems with "%s" directive path:\n%s.' % (self.name, ErrorString(error))) # read from the file try: rawtext = include_file.read() except UnicodeError as error: raise self.severe('Problem with "%s" directive:\n%s' % (self.name, ErrorString(error))) config = self.state.document.settings.env.config converter = M2R(no_underscore_emphasis=config.no_underscore_emphasis) include_lines = statemachine.string2lines(converter(rawtext), tab_width, convert_whitespace=True) self.state_machine.insert_input(include_lines, path) return []
def process_images(self, docname, doctree): """Process and rewrite image URIs.""" for node in doctree.traverse(nodes.image): # Map the mimetype to the corresponding image. The writer may # choose the best image from these candidates. The special key * is # set if there is only single candidate to be used by a writer. # The special key ? is set for nonlocal URIs. node['candidates'] = candidates = {} imguri = node['uri'] if imguri.find('://') != -1: self.warn_node('nonlocal image URI found: %s' % imguri, node) candidates['?'] = imguri continue rel_imgpath, full_imgpath = self.relfn2path(imguri, docname) # set imgpath as default URI node['uri'] = rel_imgpath if rel_imgpath.endswith(os.extsep + '*'): for filename in glob(full_imgpath): new_imgpath = relative_path(path.join(self.srcdir, 'dummy'), filename) if filename.lower().endswith('.pdf'): candidates['application/pdf'] = new_imgpath elif filename.lower().endswith('.svg'): candidates['image/svg+xml'] = new_imgpath else: try: f = open(filename, 'rb') try: imgtype = imghdr.what(f) finally: f.close() except (OSError, IOError) as err: self.warn_node('image file %s not readable: %s' % (filename, err), node) if imgtype: candidates['image/' + imgtype] = new_imgpath else: candidates['*'] = rel_imgpath # map image paths to unique image names (so that they can be put # into a single directory) for imgpath in itervalues(candidates): self.dependencies.setdefault(docname, set()).add(imgpath) if not os.access(path.join(self.srcdir, imgpath), os.R_OK): self.warn_node('image file not readable: %s' % imgpath, node) continue self.images.add_file(docname, imgpath)