Exemple #1
0
    def get_source(self, environment: jinja2.Environment, template: str):
        template = pathlib.Path(template)
        if not template.is_absolute():
            try:
                base, template = next(
                    yield_all_versions(template, *self.search_paths))
            except StopIteration:
                raise jinja2.TemplateNotFound(template.name) from None
        try:
            with template.open('r', encoding=self.encoding) as f:
                contents = f.read()
        except (FileNotFoundError, IsADirectoryError):
            raise jinja2.TemplateNotFound(template.name)

        mtime = template.stat().st_mtime

        def has_changed():
            """Checks whether the template loaded via
            :class:`OverridableFileSystemLoader` has changed.

            This function won't detect new versions of the template in other
            search paths with higher precedence or new deletion markers in other
            search paths. We would additionally need a list of all parent
            directories in the other search paths and check all of them."""
            try:
                return template.stat().st_mtime == mtime
            except OSError:
                return False

        return contents, str(template), has_changed
Exemple #2
0
    def get_source(self, environment, template):
        if not os.path.isabs(template):
            raise jinja2.TemplateNotFound(template)

        template_file = jinja2.utils.open_if_exists(template)
        if template_file is None:
            raise jinja2.TemplateNotFound(template)
        try:
            contents = template_file.read().decode(self.encoding)
        except Exception as exc:
            msg = ("Error reading file {template}: {exc}".format(
                template=template, exc=str(exc)))
            raise RuntimeError(msg)
        finally:
            template_file.close()

        mtime = os.path.getmtime(template)

        def uptodate():
            try:
                return os.path.getmtime(template) == mtime
            except OSError:
                return False

        return contents, template, uptodate
Exemple #3
0
 def get_source(self, environment, template):
   try:
     prefix, name = template.split(self.delimiter, 1)
     # logging.info("Trying => %s %s" % (prefix, name))
     loader = self.mapping[prefix]
   except (ValueError, KeyError):
     raise jinja2.TemplateNotFound(template)
   try:
     return loader.get_source(environment, name)
   except jinja2.TemplateNotFound:
     # re-raise the exception with the correct fileame here.
     # (the one that includes the prefix)
     raise jinja2.TemplateNotFound(template)
Exemple #4
0
        def get_source(self, environment, template):
            # We make the template path absolute, so that we can later resolve
            # relative includes, even if the current working directory has
            # changed in the meantime. This also makes caching easier because we
            # will always use the same path for the same file (unless symbolic
            # links are involved).
            template = os.path.abspath(template)
            # We treat the template name as a file path.
            file_version = version_for_file_path(template)
            try:
                with open(template, 'rb') as file_descriptor:
                    file_contents = file_descriptor.read().decode(
                        self._encoding)
            except (FileNotFoundError, IsADirectoryError):
                raise jinja2.TemplateNotFound(template)

            if self._cache_enabled:

                def up_to_date():
                    current_file_version = version_for_file_path(template)
                    return current_file_version == file_version
            else:

                def up_to_date():
                    return False

            return file_contents, template, up_to_date
Exemple #5
0
class TestCLI(unittest.TestCase):
    def setUp(self):
        self.silencer = patch('sys.stdout')
        self.silencer.start()

    def tearDown(self):
        self.silencer.stop()

    @patch('dayone_export.cli.dayone_export', return_value="")
    def test_tag_splitter_protects_any(self, mock_doe):
        dayone_export.cli.run(['--tags', 'any', FAKE_JOURNAL])
        expected = 'any'
        actual = mock_doe.call_args[1]['tags']
        self.assertEqual(expected, actual)

    @patch('dayone_export.cli.dayone_export', return_value="")
    def test_tag_splitter(self, mock_doe):
        dayone_export.cli.run(['--tags', 'a, b', FAKE_JOURNAL])
        expected = ['a', 'b']
        actual = mock_doe.call_args[1]['tags']
        self.assertEqual(expected, actual)

    def test_invalid_package(self):
        actual = dayone_export.cli.run(['.'])
        expected = 'Not a valid Day One package'
        self.assertTrue(actual.startswith(expected), actual)

    @patch('dayone_export.jinja2.Template.render',
           side_effect=jinja2.TemplateNotFound('msg'))
    def test_template_not_found(self, mock_doe):
        actual = dayone_export.cli.run([FAKE_JOURNAL])
        expected = "Template not found"
        self.assertTrue(actual.startswith(expected), actual)
Exemple #6
0
 def get_source(self, environment, path):
     if not os.path.exists(path):
         raise jinja2.TemplateNotFound(path)
     mtime = os.path.getmtime(path)
     with open(path) as f:
         source = f.read()
     return source, path, lambda: mtime == os.path.getmtime(path)
Exemple #7
0
 def get_source(self, environment, template):
     
     for path in self.paths:
         for directory, directories, filenames in os.walk(path):
             
             # filter out directories that contain toaster content
             for dir in directories:
                 if os.path.relpath(dir).startswith(('_', '.')):
                     directories.remove(dir)
         
             # if the current directory contains toast content then skip it, too
             if os.path.relpath(directory).startswith('_') and os.path.relpath(directory) != '_layouts':
                 continue
             
             if os.path.isfile(os.path.join(directory, template)):
                 
                 mtime = os.path.getmtime(os.path.join(directory, template))
                 
                 def uptodate():
                     return os.path.getmtime(os.path.join(directory, template)) == mtime
                 
                 with file(os.path.join(directory, template)) as stream:
                     content = stream.read().decode('utf-8')
                 
                 return content, os.path.join(directory, template), uptodate
             
         raise jinja2.TemplateNotFound(template)
Exemple #8
0
    def get_source(self, environment, template):  # noqa: U100
        if template not in self.files:
            raise jinja2.TemplateNotFound(template)

        source = Path(template).read_text()
        mtime = os.path.getmtime(template)

        return source, template, lambda: mtime == os.path.getmtime(template)
 def get_source(self, unused_environment, template):
     for dir_name in self._dir_names:
         filename = AbstractFileSystem.normpath(
             os.path.join(dir_name, template))
         if self._fs.isfile(filename):
             return self._fs.get(filename).read().decode(
                 'utf-8'), filename, True
     raise jinja2.TemplateNotFound(template)
Exemple #10
0
 def get_source(self, environment, template):
     path = os.path.join(self.path, template)
     if not os.path.exists(path):
         raise jinja2.TemplateNotFound(template)
     mtime = os.path.getmtime(path)
     with open(path) as f:
         source = self.preprocess(f.read())
     return source, path, lambda: mtime == os.path.getmtime(path)
Exemple #11
0
 def load(self, environment, name, globals=None):
     loader, local_name = self.get_loader(name)
     try:
         return loader.load(environment, local_name, globals)
     except jinja2.TemplateNotFound:
         # re-raise the exception with the correct filename here.
         # (the one that includes the prefix)
         raise jinja2.TemplateNotFound(name)
Exemple #12
0
 def get_source(self, environment, template):
     loader, name = self.get_loader(template)
     try:
         return loader.get_source(environment, name)
     except jinja2.TemplateNotFound:
         # re-raise the exception with the correct filename here.
         # (the one that includes the prefix)
         raise jinja2.TemplateNotFound(template)
Exemple #13
0
 def get_source(self, environment, template):
     path = os.path.realpath(os.path.join(TEMPLATES_PATH, template))
     if not os.path.exists(path):
         raise jinja2.TemplateNotFound(template)
     mtime = os.path.getmtime(path)
     with file(path) as f:
         source = f.read().decode('utf-8')
     return source, path, lambda: mtime == os.path.getmtime(path)
Exemple #14
0
 def string_load(name):
     """
     Allow specifying a string instead of template to be able
     to return expanded config/specs/...
     """
     if name.startswith(('{{', '{%')):
         return name
     raise jinja2.TemplateNotFound(name)
Exemple #15
0
	def get_source(self, environment, template):
		template_path = find.data_file(template, os.R_OK)
		if template_path is None:
			raise jinja2.TemplateNotFound(template)
		mtime = os.path.getmtime(template_path)
		with codecs.open(template_path, 'r', encoding='utf-8') as file_h:
			source = file_h.read()
		return source, template_path, lambda: mtime == os.path.getmtime(template_path)
Exemple #16
0
 def get_source(self, environment, template):
     path = self.mewlosite.resolve(template)
     if not os.path.exists(path):
         raise jinja2.TemplateNotFound(template)
     mtime = os.path.getmtime(path)
     with file(path) as f:
         source = f.read().decode('utf-8')
     return source, path, lambda: mtime == os.path.getmtime(path)
Exemple #17
0
 def get_source(self, environment, template):
     path = self.path / template
     if not path.exists():
         raise jinja2.TemplateNotFound(template)
     mtime = os.path.getmtime(path)
     with path.open() as f:
         source = f.read()
     return self._replace_inline_syntax(
         source), None, lambda: mtime == os.path.getmtime(path)
Exemple #18
0
 def get_source(self, environment, template):
     path = self.path + template
     page = get_contents_of_url(path)
     if not page:
         raise jinja2.TemplateNotFound(template)
     #mtime = os.path.getmtime(path)
     #with file(path) as f:
     source = page.decode('utf-8')
     return source, path, lambda: False  #lambda: mtime == os.path.getmtime(path)
Exemple #19
0
    def get_source(self, environment, template):
        frame_response = getattr(flask.g, 'frame_response', None)

        if template != 'frame.html' or frame_response is None:
            raise jinja2.TemplateNotFound(template)

        path = ':frame-templates:%s' % template
        source = _process_frame_html(flask.g.frame_response['frame_html'])
        return source, path, lambda: False
Exemple #20
0
 def get_source(self, environment, template):
     path = template
     if not os.path.exists(path):
         raise jinja2.TemplateNotFound(template)
     mtime = os.path.getmtime(path)
     with open(path, 'r', encoding='utf-8') as f:
         source = "{% extends 'base.html' %}{% block content %}" + f.read(
         ) + "{% endblock %}"
     return source, path, lambda: mtime == os.path.getmtime(path)
Exemple #21
0
 def get_source(self, _env, template):
     path = os.path.join(self._subdir, template)
     try:
         source = utils.read_file(path)
     except OSError:
         raise jinja2.TemplateNotFound(template)
     # Currently we don't implement auto-reloading, so we always return True
     # for up-to-date.
     return source, path, lambda: True
Exemple #22
0
 def get_source(self, environment, template):
     path = os.path.join(self.path, template.lstrip('/'))
     try:
         source = CloudStorage.read(path)
     except cloudstorage.NotFoundError:
         raise jinja2.TemplateNotFound(template)
     # TODO(jeremydw): Make this function properly.
     source = source.decode('utf-8')
     return source, path, lambda: True
Exemple #23
0
    def get_source(self, environment, template):
        path = os.path.abspath(os.path.relpath(template, self.path))
        self.logger.debug('Rendering %s', path)

        if not os.path.exists(path):
            raise jinja2.TemplateNotFound(template)
        mtime = os.path.getmtime(path)
        with file(path) as f:
            source = f.read().decode('utf-8')
        return source, path, lambda: mtime == os.path.getmtime(path)
Exemple #24
0
    def get_source(self, environment, template):
        response = requests.get(template, verify=self.verify_ssl, timeout=60)

        if response.ok:
            template_source = response.text

        else:
            raise jinja2.TemplateNotFound(template)

        return template_source, None, lambda: False
Exemple #25
0
 def get_source(
     self,
     environment: jinja2.Environment,
     template: str,
 ) -> Tuple[str, Optional[str], Callable[[], bool]]:
     try:
         _, resource = _get_resource(template, resources.read_text)
     except FileNotFoundError:
         raise jinja2.TemplateNotFound(template) from None
     return (resource, None, lambda: False)
Exemple #26
0
  def get_source(self, environment, template):
    try:
      fullpath = '{}/{}'.format(self.basedir, template)
      with self.zipf.open(fullpath) as fileobj:
        source = fileobj.read()
    except IOError:
      raise jinja2.TemplateNotFound(template,
                                    message='Fullpath: {}'.format(fullpath))

    return (source, None, lambda: False)
Exemple #27
0
    def get_source(self, environment, template):
        filename = os.path.join(self.cwd, template)

        try:
            with open(filename, 'r') as f:
                contents = f.read()
        except IOError:
            raise jinja2.TemplateNotFound(filename)

        return contents, filename, lambda: False
Exemple #28
0
 def get_source(self, environment, template):
     if not os.path.exists(self.path):
         raise jinja2.TemplateNotFound(template)
     mtime = os.path.getmtime(self.path)
     try:
         with open(self.path, "r") as fp:
             source = fp.read()
     except:
         print("Error reading file \"" + self.path + "\"")
     return source, self.path, lambda: mtime == os.path.getmtime(self.path)
Exemple #29
0
 def get_source(self, environment, template):
     for template_file in self.files:
         if os.path.basename(template_file) == template:
             with open(template_file) as f:
                 contents = f.read().decode('utf-8')
             mtime = os.path.getmtime(template_file)
             return (contents, template_file,
                     lambda: mtime == os.path.getmtime(template_file))
     else:
         raise jinja2.TemplateNotFound(template)
Exemple #30
0
    def get_source(self, environment, template):
        if not os.path.isabs(template):
            raise jinja2.TemplateNotFound(template)

        f = jinja2.utils.open_if_exists(template)
        if f is None:
            raise jinja2.TemplateNotFound(template)
        try:
            contents = f.read().decode(self.encoding)
        finally:
            f.close()

        mtime = os.path.getmtime(template)

        def uptodate():
            try:
                return os.path.getmtime(template) == mtime
            except OSError:
                return False
        return contents, template, uptodate