Created
October 15, 2021 18:57
-
-
Save particledecay/877773577afe5566ed64cebe42b7ea79 to your computer and use it in GitHub Desktop.
yq
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python | |
| import json | |
| import yaml | |
| def yaml_to_json(data): | |
| yaml_data = yaml.safe_load(data) | |
| json_data = json.dumps(yaml_data) | |
| return json_data | |
| if __name__ == "__main__": | |
| import logging | |
| import os | |
| import subprocess | |
| import sys | |
| logging.basicConfig(format="%(message)s") | |
| logger = logging.getLogger(__name__) | |
| def fail(err): | |
| logger.error(err) | |
| sys.exit(1) | |
| data = None | |
| cmd = ['jq'] | |
| args = [] | |
| # figure out where we're getting the YAML from | |
| try: | |
| if len(sys.argv) > 2: | |
| filename = sys.argv[-1] | |
| if not os.path.isfile(filename): | |
| fail(f"{filename} not found") | |
| data = open(filename).read() | |
| args = sys.argv[1:-1] | |
| elif len(sys.argv) == 2: | |
| unknown_arg = sys.argv[-1] | |
| if not os.path.isfile(unknown_arg): | |
| data = sys.stdin.read() | |
| args = sys.argv[1:] | |
| else: | |
| data = open(unknown_arg).read() | |
| args = sys.argv[1:-1] | |
| else: | |
| data = sys.stdin.read() | |
| args = sys.argv[1:] | |
| except UnicodeDecodeError as e: | |
| fail(e) | |
| # prepare any args | |
| if args: | |
| args[-1] = repr(args[-1]) | |
| cmd.extend(args) | |
| # convert to JSON | |
| try: | |
| converted = yaml_to_json(data) | |
| # print(converted) | |
| except (json.JSONDecodeError, yaml.YAMLError) as e: | |
| fail(e) | |
| # call out to `jq` | |
| try: | |
| jq = subprocess.Popen(' '.join(cmd), stdin=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) | |
| jq.communicate(input=converted.encode())[0] | |
| except subprocess.SubprocessError as e: | |
| fail(e) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Clever hack.