Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ license_file = apache-2.0.LICENSE
name = commoncode
author = nexB. Inc. and others
author_email = info@aboutcode.org
description = commoncode
description = commoncode
long_description = file:README.rst
url = https://github.com/nexB/commoncode
classifiers =
Expand All @@ -16,7 +16,7 @@ classifiers =
Programming Language :: Python :: 3
Topic :: Software Development
Topic :: Utilities
keywords =
keywords =

[options]
package_dir=
Expand All @@ -33,7 +33,8 @@ install_requires =
requests >= 2.7.0, < 3.0.0
intbitset >= 2.3.0, < 3.0
saneyaml
setup_requires = setuptools_scm >= 4
typing >=3.6, < 3.7
setup_requires = setuptools_scm[toml] >= 4

[options.packages.find]
where=src
Expand Down
16 changes: 10 additions & 6 deletions src/commoncode/filetype.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,20 +45,24 @@ def is_link(location):
return location and os.path.islink(location)


def is_file(location):
def is_file(location, allow_symlinks=False):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What about using the same name as in the standard lib?
https://docs.python.org/3/library/os.html?highlight=link#os.link
https://docs.python.org/3/library/os.html?highlight=link#follow-symlinks

If follow_symlinks is False, and the last element of the path to operate on is a symbolic link, the function will operate on the symbolic link itself rather than the file pointed to by the link. (For POSIX systems, Python will call the l... variant of the function.)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's a good idea, I'll change it.

"""
Return True if `location` is a file.
"""
return (location and os.path.isfile(location)
and not is_link(location) and not is_broken_link(location))
_is_file = location and os.path.isfile(location)
if allow_symlinks:
return _is_file
return _is_file and not is_link(location) and not is_broken_link(location)


def is_dir(location):
def is_dir(location, allow_symlinks=False):
"""
Return True if `location` is a directory.
"""
return (location and os.path.isdir(location) and not is_file(location)
and not is_link(location) and not is_broken_link(location))
_is_dir = location and os.path.isdir(location) and not is_file(location)
if allow_symlinks:
return _is_dir
return _is_dir and not is_link(location) and not is_broken_link(location)


def is_regular(location):
Expand Down
36 changes: 22 additions & 14 deletions src/commoncode/fileutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ def prepare_path(pth):
if not isinstance(pth, bytes):
pth = fsencode(pth)
return pth
else:
else:
if not isinstance(pth, compat.unicode):
return fsdecode(pth)
return pth
Expand Down Expand Up @@ -365,16 +365,19 @@ def ignore_nothing(_):
return False


def walk(location, ignored=None):
def walk(location, ignored=None, allow_symlinks=False):
"""
Walk location returning the same tuples as os.walk but with a different
behavior:
- always walk top-down, breadth-first.
- always ignore and never follow symlinks,
- always ignore and never follow symlinks (unless `allow_symlinks` is True),
- always ignore special files (FIFOs, etc.)
- optionally ignore files and directories by invoking the `ignored`
callable on files and directories returning True if it should be ignored.
- location is a directory or a file: for a file, the file is returned.

If `allow_symlinks` is True, then symlinks will not be ignored and be
collected like regular files and directories
"""
if on_linux and py2:
location = fsencode(location)
Expand All @@ -387,33 +390,38 @@ def walk(location, ignored=None):
logger_debug('walk: ignored:', location, is_ignored)
return

if filetype.is_file(location) :
if filetype.is_file(location, allow_symlinks=allow_symlinks) :
yield parent_directory(location), [], [file_name(location)]

elif filetype.is_dir(location):
elif filetype.is_dir(location, allow_symlinks=allow_symlinks):
dirs = []
files = []
# TODO: consider using scandir
for name in os.listdir(location):
loc = os.path.join(location, name)
if filetype.is_special(loc) or (ignored and ignored(loc)):
if TRACE:
ign = ignored and ignored(loc)
logger_debug('walk: ignored:', loc, ign)
continue
if (allow_symlinks
and filetype.is_link(loc)
and not filetype.is_broken_link(location)):
pass
else:
if TRACE:
ign = ignored and ignored(loc)
logger_debug('walk: ignored:', loc, ign)
continue
# special files and symlinks are always ignored
if filetype.is_dir(loc):
if filetype.is_dir(loc, allow_symlinks=allow_symlinks):
dirs.append(name)
elif filetype.is_file(loc):
elif filetype.is_file(loc, allow_symlinks=allow_symlinks):
files.append(name)
yield location, dirs, files

for dr in dirs:
for tripple in walk(os.path.join(location, dr), ignored):
for tripple in walk(os.path.join(location, dr), ignored, allow_symlinks=allow_symlinks):
yield tripple


def resource_iter(location, ignored=ignore_nothing, with_dirs=True):
def resource_iter(location, ignored=ignore_nothing, with_dirs=True, allow_symlinks=False):
"""
Return an iterable of paths at `location` recursively.

Expand All @@ -424,7 +432,7 @@ def resource_iter(location, ignored=ignore_nothing, with_dirs=True):
"""
if on_linux and py2:
location = fsencode(location)
for top, dirs, files in walk(location, ignored):
for top, dirs, files in walk(location, ignored, allow_symlinks=allow_symlinks):
if with_dirs:
for d in dirs:
yield os.path.join(top, d)
Expand Down
Empty file.
22 changes: 22 additions & 0 deletions tests/commoncode/test_filetype.py
Original file line number Diff line number Diff line change
Expand Up @@ -209,3 +209,25 @@ def test_get_file_count(self):
for test_file, count in tests:
result = filetype.get_file_count(os.path.join(test_dir, test_file))
assert count == result


def SymlinkTest(FileBasedTesting):
test_data_dir = os.path.join(os.path.dirname(__file__), 'data')

@skipIf(on_windows, 'os.symlink does not work on Windows')
def test_is_file(self):
test_file = self.get_test_loc('symlink/test', copy=True)
temp_dir = fileutils.get_temp_dir()
test_link = join(temp_dir, 'test-link')
os.symlink(test_file, test_link)
assert filetype.is_file(test_link, allow_symlinks=True)
assert not filetype.is_file(test_link, allow_symlinks=False)

@skipIf(on_windows, 'os.symlink does not work on Windows')
def test_is_dir(self):
test_dir = self.get_test_loc('symlink', copy=True)
temp_dir = fileutils.get_temp_dir()
test_link = join(temp_dir, 'test-dir-link')
os.symlink(test_dir, test_link)
assert filetype.is_dir(test_link, allow_symlinks=True)
assert not filetype.is_dir(test_link, allow_symlinks=False)
14 changes: 14 additions & 0 deletions tests/commoncode/test_fileutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -384,6 +384,20 @@ def test_os_walk_can_walk_non_utf8_path_from_unicode_path(self):
_dirpath, _dirnames, filenames = result
assert 18 == len(filenames)

@skipIf(on_windows, 'os.symlink does not work on Windows')
def test_walk_on_symlinks(self):
test_dir = self.get_test_loc('symlink', copy=True)
temp_dir = fileutils.get_temp_dir()
test_link = join(temp_dir, 'test-dir-link')
os.symlink(test_dir, test_link)
results = list(fileutils.walk(test_link, allow_symlinks=True))
assert len(results) == 1
top, dirs, files = results[0]
top = os.path.basename(top)
assert 'test-dir-link' == top
assert [] == dirs
assert ['test'] == files


class TestFileUtilsIter(FileBasedTesting):
test_data_dir = os.path.join(os.path.dirname(__file__), 'data')
Expand Down