From 725b26565107a5cf84e3e9c027879ce118e9196f Mon Sep 17 00:00:00 2001 From: Lucas Schwiderski Date: Sun, 24 Mar 2019 14:37:15 +0100 Subject: [PATCH 1/2] Add exists_in_path jinja helper function The function is a wrapper around `shutil.which` that allows to check for an executable in the OS's PATH within templates. --- dotdrop/jhelpers.py | 6 ++++++ dotdrop/templategen.py | 1 + 2 files changed, 7 insertions(+) diff --git a/dotdrop/jhelpers.py b/dotdrop/jhelpers.py index 0bff618..99d5ddc 100644 --- a/dotdrop/jhelpers.py +++ b/dotdrop/jhelpers.py @@ -6,8 +6,14 @@ jinja2 helper methods """ import os +import shutil def exists(path): """return true when path exists""" return os.path.exists(os.path.expandvars(path)) + + +def exists_in_path(name, path=None): + """return true when executable exists in os path""" + return shutil.which(name, os.F_OK | os.X_OK, path) is not None diff --git a/dotdrop/templategen.py b/dotdrop/templategen.py index ae49f47..53b0bbc 100644 --- a/dotdrop/templategen.py +++ b/dotdrop/templategen.py @@ -49,6 +49,7 @@ class Templategen: self.env.globals['header'] = self._header # adding helper methods self.env.globals['exists'] = jhelpers.exists + self.env.globals['exists_in_path'] = jhelpers.exists_in_path def generate(self, src): """render template from path""" From 94174dac12e2716770913fb2400121c516f12a18 Mon Sep 17 00:00:00 2001 From: Lucas Schwiderski Date: Sun, 24 Mar 2019 14:38:27 +0100 Subject: [PATCH 2/2] Add test case for new jinja helper function --- tests-ng/jhelpers.sh | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/tests-ng/jhelpers.sh b/tests-ng/jhelpers.sh index afc2bcc..fbb5414 100755 --- a/tests-ng/jhelpers.sh +++ b/tests-ng/jhelpers.sh @@ -83,6 +83,19 @@ echo "{%@@ if exists('/dev/abcdef') @@%}" >> ${tmps}/dotfiles/abc echo "this should not exist" >> ${tmps}/dotfiles/abc echo "{%@@ endif @@%}" >> ${tmps}/dotfiles/abc +# test exists_in_path +cat >> ${tmps}/dotfiles/abc << _EOF +{%@@ if exists_in_path('cat') @@%} +this should exist too +{%@@ endif @@%} +_EOF + +cat >> ${tmps}/dotfiles/abc << _EOF +{%@@ if exists_in_path('a_name_that_is_unlikely_to_be_chosen_for_an_executable') @@%} +this should not exist either +{%@@ endif @@%} +_EOF + #cat ${tmps}/dotfiles/abc # install @@ -92,6 +105,8 @@ cd ${ddpath} | ${bin} install -f -c ${cfg} -p p1 -V grep '^this should exist' ${tmpd}/abc >/dev/null grep -v '^this should not exist' ${tmpd}/abc >/dev/null +grep '^this should exist too' ${tmpd}/abc >/dev/null +grep -v '^this should not exist either' ${tmpd}/abc >/dev/null #cat ${tmpd}/abc