nb_black icon indicating copy to clipboard operation
nb_black copied to clipboard

cannot parse `ls ./`

Open manycoding opened this issue 5 years ago • 3 comments

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.

manycoding avatar Oct 01 '19 17:10 manycoding

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.

michaelaye avatar Oct 01 '19 18:10 michaelaye

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).

hanfried avatar Oct 02 '19 06:10 hanfried

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.

erdmann avatar Dec 04 '19 07:12 erdmann