jupyter_core icon indicating copy to clipboard operation
jupyter_core copied to clipboard

paths.is_hidden() Reports invalid input as hidden

Open matyanwek opened this issue 6 months ago • 1 comments

A bug in a previous version of Jupyter led to errors when trying to rename a file. After a bit of digging, I think I've tracked down the root cause to line 497 of jupyter_core/paths.py, where the assignment inside_root = abs_path[len(abs_root) :] assumes that the abs_path will have abs_root as a prefix. In some cases, the abs_path could get trimmed down to exactly the file extension, like in this case:

is_hidden("filename.ipynb", "/home/aa")

where filename is exactly the same length as /home/aa. The resulting trimmed file extension .ipynb looks like a hidden file when checked.

A simple way to fix this would be to check that abs_root is a prefix of abs_path before trimming:

if abs_path.startswith(abs_root):
    inside_root = abs_path[len(abs_root):]
else:
    inside_root = abs_path

I'd also propose to fix the check on abs_root on line 495, since the call to os.path.normpath() on line 487 ensures it will never be an empty string:

    abs_path = os.path.normpath(abs_path)
    if abs_root == "":
        abs_root = abs_path.split(os.sep, 1)[0] + os.sep
    else:
        abs_root = os.path.normpath(abs_root)

matyanwek avatar Apr 29 '25 06:04 matyanwek

Perhaps this is a bug in argument validation, because the code assumes (and specifies in the docstring) rather than asserts that abs_path is a sub-path of abs_root and both are absolute. It would also be correct to add the following argument validation checks:

abs_path_p = Path(abs_path)
abs_root_p = Path(abs_root)
if not abs_path_p.is_absolute():
    raise ValueError(f"{abs_path=} is not absolute")
if not abs_root_p.is_absolute():
    raise ValueError(f"{abs_root=} is not absolute")
if not abs_path_p.is_relative_to(abs_root_p):
    raise ValueError(f"{abs_path=} is not a subpath of {abs_root=}")

which would appropriately raise an error for the given arguments.

ensures it will never be an empty string:

A valid abs_root can never be an empty string, since an empty string is not an absolute path. This would also be solved by the above argument validation.

minrk avatar Apr 29 '25 11:04 minrk