From 615fe2122217af0fb39ad92cbe06d178d39a407e Mon Sep 17 00:00:00 2001 From: Adar Nimrod <nimrod@shore.co.il> Date: Sun, 15 Aug 2021 10:50:26 +0300 Subject: [PATCH] Add the readfile function. --- README.rst | 1 + template/functions.py | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+) diff --git a/README.rst b/README.rst index 40472bb..3ad3ab6 100644 --- a/README.rst +++ b/README.rst @@ -117,6 +117,7 @@ Jinja functions - :code:`run`: Runs a command and returns the stdout, stderr and returncode using run_. This function replaces the :code:`run` filter. +- :code:`readfile`: Returns the contents of a file. Example usage can be seen in :code:`tests` and for specific filters in the docstrings in :code:`template/functions.py`. diff --git a/template/functions.py b/template/functions.py index c219b2e..3d31471 100644 --- a/template/functions.py +++ b/template/functions.py @@ -39,3 +39,21 @@ def run(*argv, **kwargs): proc["stdout"] = proc["stdout"].decode() proc["stderr"] = proc["stderr"].decode() return proc + + +def readfile(path): + """ + Opens a file, returns the contents. + + >>> readfile("/dev/null") + '' + >>> foo = "foo" + >>> with open("/tmp/foo", "w") as f: + ... f.write(foo) + 3 + >>> foo == readfile("/tmp/foo") + True + """ + + with open(path, "r") as f: # pylint: disable=invalid-name + return f.read() -- GitLab