dnanhkhoa / nb_black

A simple extension for Jupyter Notebook and Jupyter Lab to beautify Python code automatically using black.
MIT License
367 stars 41 forks source link

cannot parse `ls ./` #13

Open manycoding opened 4 years ago

manycoding commented 4 years ago

nb_black 1.0.6

listing a path ending with / results in an error ls ./

ERROR:root:Cannot parse: 1:4: ls ./ Traceback (most recent call last): File "/usr/local/lib/python3.6/dist-packages/lab_black.py", line 210, in format_cell formatted_code = _format_code(cell) File "/usr/local/lib/python3.6/dist-packages/lab_black.py", line 29, in _format_code return format_str(src_contents=code, mode=FileMode()) File "/usr/local/lib/python3.6/dist-packages/black.py", line 669, in format_str src_node = lib2to3_parse(src_contents.lstrip(), mode.target_versions) File "/usr/local/lib/python3.6/dist-packages/black.py", line 758, in lib2to3_parse raise exc from None black.InvalidInput: Cannot parse: 1:4: ls ./

And listing a path without / - ls /something/else formats the path, which shouldn't be the case.

michaelaye commented 4 years ago

Confirmed. That's a tough case, though, because formally speaking the jupyter syntax for these is !ls ./ and it's just a convenience that it keeps checking fitting bash commands for you. If you use !ls ./ in the full formal way, nb_black doesn't complain.

hanfried commented 4 years ago

We could use IPython's own logic to catch these cases:

In [10]: import IPython.core.magics.osm as osm

In [12]: list(osm.OSMagics.magics['line'].keys())
Out[12]: 
['alias',
 'unalias',
 'rehashx',
 'pwd',
 'cd',
 'env',
 'set_env',
 'pushd',
 'popd',
 'dirs',
 'dhist',
 'sc',
 'sx',
 'system',
 'bookmark',
 'pycat']

These are all defined magic aliases from the Operating System Magics class. Not sure, whether that would too much special casing, but adding something like if any(line.strip().startswith(alias) for alias in osm.OSMagics.magics['line'].keys()): line = line.replace('!' + line); ignore_for_black(line) should be doable with all the usual caveats (we have to make sure it's not part of a """ ... """ block etc).

erdmann commented 4 years ago

Note that !cd /some/directory and cd /some/directory are not semantically equivalent in Jupyter since the former doesn't change the cwd and the latter does. I think the more correct semantic equivalent of cd is %cd rather than !cd.