From c1542b1a5ed286e8f8bc0507e899c1d2a5388e49 Mon Sep 17 00:00:00 2001 From: Roger Luethi Date: Fri, 6 Jun 2014 14:43:22 +0200 Subject: [PATCH] jsoncheck: split process_one_file from main blueprint modularize-doctest This patch moves most of the code from checkjson's main into a new function process_file. External users of the module will have their own filesystem walker, they just use the module to check/format a file of interest. Change-Id: I510b5d3d5ea20d2c0a694ef3401eb9fafc15bed4 --- os_doc_tools/jsoncheck.py | 29 ++++++++++++++++------------- 1 file changed, 16 insertions(+), 13 deletions(-) diff --git a/os_doc_tools/jsoncheck.py b/os_doc_tools/jsoncheck.py index 2f6af6bc..8d5f930d 100644 --- a/os_doc_tools/jsoncheck.py +++ b/os_doc_tools/jsoncheck.py @@ -95,6 +95,21 @@ def check_format(parsed, raw, path=None): raise FormattingException(errstr) +def process_file(path, format): + """Check syntax/formatting and fix formatting of a JSON file.""" + with open(path, 'r') as infile: + raw = infile.read() + try: + parsed = parse_json(raw) + except ParserException as err: + print("%s\n%s" % (path, err)) + else: + try: + check_format(parsed, raw, path if format else None) + except FormattingException as err: + print("%s\n%s" % (path, err)) + + def main(): parser = argparse.ArgumentParser(description="Validate and reformat JSON" "files.") @@ -104,19 +119,7 @@ def main(): args = parser.parse_args() for path in args.files: - with open(path, 'r') as infile: - raw = infile.read() - infile.close() - try: - parsed = parse_json(raw) - except ParserException as err: - print("%s\n%s" % (path, err)) - else: - try: - check_format(parsed, raw, path if args.format else None) - except FormattingException as err: - print("%s\n%s" % (path, err)) - + process_file(path, args.format) if __name__ == "__main__": sys.exit(main())