Skip to content

Commit

Permalink
Listing directory entries using execution contexts
Browse files Browse the repository at this point in the history
  • Loading branch information
xolox committed Mar 22, 2016
1 parent 9dd90fa commit 87fbdde
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 1 deletion.
2 changes: 1 addition & 1 deletion executor/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@
unicode = str

# Semi-standard module versioning.
__version__ = '9.2'
__version__ = '9.3'

# Initialize a logger.
logger = logging.getLogger(__name__)
Expand Down
16 changes: 16 additions & 0 deletions executor/contexts.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ def details_about_system(context):
# Standard library modules.
import logging
import multiprocessing
import os
import socket

# External dependencies.
Expand Down Expand Up @@ -308,6 +309,21 @@ def write_file(self, filename, contents):
"""
return self.execute('cat > %s' % quote(filename), shell=True, input=contents)

def list_entries(self, directory):
"""
List the entries in a directory.
:param directory: The pathname of the directory (a string).
:returns: A list of strings with the names of the directory entries.
This method uses ``find -mindepth 1 -maxdepth 1 -print0`` to list
directory entries instead of going for the more obvious choice ``ls
-A1`` because ``find`` enables more reliable parsing of command output
(with regards to whitespace).
"""
listing = self.capture('find', directory, '-mindepth', '1', '-maxdepth', '1', '-print0')
return [os.path.basename(fn) for fn in listing.split('\0') if fn]

def __enter__(self):
"""Initialize a new "undo stack" (refer to :func:`cleanup()`)."""
self.undo_stack.append([])
Expand Down
17 changes: 17 additions & 0 deletions executor/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -741,6 +741,23 @@ def check_context(self, context):
# Make sure the contents are correct.
actual_contents = context.read_file(random_file)
assert actual_contents == expected_contents
# Test context.list_entries() and make sure it doesn't mangle filenames
# containing whitespace.
nasty_filenames = [
'something-innocent',
'now with spaces',
'and\twith\ttabs',
'and\nfinally\nnewlines',
]
with TemporaryDirectory() as directory:
# Create files with nasty names :-).
for filename in nasty_filenames:
with open(os.path.join(directory, filename), 'w') as handle:
handle.write('\n')
# List the directory entries.
parsed_filenames = context.list_entries(directory)
# Make sure all filenames were parsed correctly.
assert sorted(nasty_filenames) == sorted(parsed_filenames)

def test_cli_usage(self):
"""Make sure the command line interface properly presents its usage message."""
Expand Down

0 comments on commit 87fbdde

Please sign in to comment.