From 405a904906f66c3aed505b19b2c6a2e91618d7a1 Mon Sep 17 00:00:00 2001 From: cyyc1 <114281716+cyyc1@users.noreply.github.com> Date: Thu, 6 Oct 2022 01:21:45 -0700 Subject: [PATCH] Add error handling --- .../string_fixer_for_jupyter_notebooks.py | 58 +++++++++++-------- 1 file changed, 33 insertions(+), 25 deletions(-) diff --git a/pre_commit_hooks/string_fixer_for_jupyter_notebooks.py b/pre_commit_hooks/string_fixer_for_jupyter_notebooks.py index 78854fd..ab4be97 100644 --- a/pre_commit_hooks/string_fixer_for_jupyter_notebooks.py +++ b/pre_commit_hooks/string_fixer_for_jupyter_notebooks.py @@ -8,34 +8,42 @@ from pre_commit_hooks.util_string_fixer import fix_strings_in_file_contents def fix_strings(filename: str) -> int: - with open(filename) as f: - notebook_contents = json.load(f) + if not filename.endswith('.ipynb'): + print(f'{filename}: not a Jupyter notebook file') + return 1 - cells = notebook_contents['cells'] - return_value = 0 - for cell in cells: - if cell.get('cell_type') == 'code' and 'source' in cell: - # Each element in cell['source'] is a string that ends with \n, - # except for the last element, which is why we don't join by \n - source_in_1_line = ''.join(cell['source']) - fixed = fix_strings_in_file_contents(source_in_1_line) - if fixed != source_in_1_line: - fixed_lines = fixed.split('\n') - cell['source'] = ( - [_ + '\n' for _ in fixed_lines[:-1]] - + [fixed_lines[-1]] - ) - return_value = 1 + try: + with open(filename) as f: + notebook_contents = json.load(f) + except json.JSONDecodeError as exc: + print(f'{filename}: Failed to load') + return 1 + else: + cells = notebook_contents['cells'] + return_value = 0 + for cell in cells: + if cell.get('cell_type') == 'code' and 'source' in cell: + # Each element in cell['source'] is a string that ends with \n, + # except for the last element, which is why we don't join by \n + source_in_1_line = ''.join(cell['source']) + fixed = fix_strings_in_file_contents(source_in_1_line) + if fixed != source_in_1_line: + fixed_lines = fixed.split('\n') + cell['source'] = ( + [_ + '\n' for _ in fixed_lines[:-1]] + + [fixed_lines[-1]] + ) + return_value = 1 - if return_value == 1: - notebook_contents['cells'] = cells - with open(filename, 'w') as f: - json.dump(notebook_contents, f, indent=1) - # Jupyter notebooks (.ipynb) always ends with a new line - # but json.dump does not. - f.write("\n") + if return_value == 1: + notebook_contents['cells'] = cells + with open(filename, 'w') as f: + json.dump(notebook_contents, f, indent=1) + # Jupyter notebooks (.ipynb) always ends with a new line + # but json.dump does not. + f.write("\n") - return return_value + return return_value def main(argv: Sequence[str] | None = None) -> int: