noahmorrison / chevron

A Python implementation of mustache
MIT License
505 stars 55 forks source link

DATA parameter should directly support stdin #77

Open kriswuollett opened 4 years ago

kriswuollett commented 4 years ago

The chevron (v0.13.1) program currently only supports standard files for the -d (DATA) parameter. It should support the commonly used convention of the dash, -, to represent stdin. The current workaround for me is to use the filename /dev/stdin on Linux, but would guess that some platforms may not support that. Example use case is piping in output from yq or jq that merges multiple data sources without creating temporary files.

tekknolagi commented 3 years ago

It's not clear which of the parameters (--data, --template) should get stdin when passing -, I think. This is a fairly trivial patch (below), but this reads from stdin for both params (which seems broken):

diff --git a/chevron/main.py b/chevron/main.py
index 83bfa93..4e4fdff 100755
--- a/chevron/main.py
+++ b/chevron/main.py
@@ -18,7 +18,9 @@ except (ValueError, SystemError):  # python 2

 def main(template, data=None, **kwargs):
     with io.open(template, 'r', encoding='utf-8') as template_file:
-        if data is not None:
+        if data == "-":
+            data = json.load(sys.stdin)
+        elif data is not None:
             with io.open(data, 'r', encoding='utf-8') as data_file:
                 data = json.load(data_file)
         else:
@@ -39,6 +41,9 @@ def cli_main():
     import os

     def is_file_or_pipe(arg):
+        if arg == "-":
+            # Special case for passing stdin as `-`
+            return arg
         if not os.path.exists(arg) or os.path.isdir(arg):
             parser.error('The file {0} does not exist!'.format(arg))
         else: