mirror of
https://github.com/pre-commit/pre-commit-hooks.git
synced 2026-04-09 21:04:17 +00:00
Add error handling
This commit is contained in:
parent
3df7b7ac8e
commit
405a904906
1 changed files with 33 additions and 25 deletions
|
|
@ -8,34 +8,42 @@ from pre_commit_hooks.util_string_fixer import fix_strings_in_file_contents
|
||||||
|
|
||||||
|
|
||||||
def fix_strings(filename: str) -> int:
|
def fix_strings(filename: str) -> int:
|
||||||
with open(filename) as f:
|
if not filename.endswith('.ipynb'):
|
||||||
notebook_contents = json.load(f)
|
print(f'{filename}: not a Jupyter notebook file')
|
||||||
|
return 1
|
||||||
|
|
||||||
cells = notebook_contents['cells']
|
try:
|
||||||
return_value = 0
|
with open(filename) as f:
|
||||||
for cell in cells:
|
notebook_contents = json.load(f)
|
||||||
if cell.get('cell_type') == 'code' and 'source' in cell:
|
except json.JSONDecodeError as exc:
|
||||||
# Each element in cell['source'] is a string that ends with \n,
|
print(f'{filename}: Failed to load')
|
||||||
# except for the last element, which is why we don't join by \n
|
return 1
|
||||||
source_in_1_line = ''.join(cell['source'])
|
else:
|
||||||
fixed = fix_strings_in_file_contents(source_in_1_line)
|
cells = notebook_contents['cells']
|
||||||
if fixed != source_in_1_line:
|
return_value = 0
|
||||||
fixed_lines = fixed.split('\n')
|
for cell in cells:
|
||||||
cell['source'] = (
|
if cell.get('cell_type') == 'code' and 'source' in cell:
|
||||||
[_ + '\n' for _ in fixed_lines[:-1]]
|
# Each element in cell['source'] is a string that ends with \n,
|
||||||
+ [fixed_lines[-1]]
|
# except for the last element, which is why we don't join by \n
|
||||||
)
|
source_in_1_line = ''.join(cell['source'])
|
||||||
return_value = 1
|
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:
|
if return_value == 1:
|
||||||
notebook_contents['cells'] = cells
|
notebook_contents['cells'] = cells
|
||||||
with open(filename, 'w') as f:
|
with open(filename, 'w') as f:
|
||||||
json.dump(notebook_contents, f, indent=1)
|
json.dump(notebook_contents, f, indent=1)
|
||||||
# Jupyter notebooks (.ipynb) always ends with a new line
|
# Jupyter notebooks (.ipynb) always ends with a new line
|
||||||
# but json.dump does not.
|
# but json.dump does not.
|
||||||
f.write("\n")
|
f.write("\n")
|
||||||
|
|
||||||
return return_value
|
return return_value
|
||||||
|
|
||||||
|
|
||||||
def main(argv: Sequence[str] | None = None) -> int:
|
def main(argv: Sequence[str] | None = None) -> int:
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue