|
| 1 | +#!/usr/bin/env python3 |
| 2 | +import argparse |
| 3 | +import json |
| 4 | +import sys |
| 5 | + |
| 6 | + |
| 7 | +plugin = { |
| 8 | + "name": "Calculator", |
| 9 | + "directives": [ |
| 10 | + { |
| 11 | + "name": "calc", |
| 12 | + "doc": "An example directive for running Python expressions.", |
| 13 | + "body": { |
| 14 | + "type": "string", |
| 15 | + "doc": "The expression to compute", |
| 16 | + }, |
| 17 | + } |
| 18 | + ], |
| 19 | +} |
| 20 | + |
| 21 | + |
| 22 | +def declare_result(content): |
| 23 | + """Declare result as JSON to stdout |
| 24 | +
|
| 25 | + :param content: content to declare as the result |
| 26 | + """ |
| 27 | + |
| 28 | + # Format result and write to stdout |
| 29 | + json.dump(content, sys.stdout, indent=2) |
| 30 | + # Successfully exit |
| 31 | + raise SystemExit(0) |
| 32 | + |
| 33 | + |
| 34 | +def run_directive(name, data): |
| 35 | + """Execute a directive with the given name and data |
| 36 | +
|
| 37 | + :param name: name of the directive to run |
| 38 | + :param data: data of the directive to run |
| 39 | + """ |
| 40 | + assert name == "calc" |
| 41 | + |
| 42 | + # Run user program |
| 43 | + result = eval(data["body"], {**globals(), **vars(__import__("math"))}) |
| 44 | + result = {"type": "code", "value": str(result)} |
| 45 | + return [result] |
| 46 | + |
| 47 | + |
| 48 | +if __name__ == "__main__": |
| 49 | + parser = argparse.ArgumentParser() |
| 50 | + group = parser.add_mutually_exclusive_group() |
| 51 | + group.add_argument("--role") |
| 52 | + group.add_argument("--directive") |
| 53 | + group.add_argument("--transform") |
| 54 | + args = parser.parse_args() |
| 55 | + |
| 56 | + if args.directive: |
| 57 | + data = json.load(sys.stdin) |
| 58 | + declare_result(run_directive(args.directive, data)) |
| 59 | + elif args.transform: |
| 60 | + raise NotImplementedError |
| 61 | + elif args.role: |
| 62 | + raise NotImplementedError |
| 63 | + else: |
| 64 | + declare_result(plugin) |
0 commit comments