Commit 57d56130 authored by Guido Trotter's avatar Guido Trotter
Browse files

ListVisibleFiles: do optional sorting


Signed-off-by: default avatarGuido Trotter <ultrotter@google.com>
Reviewed-by: default avatarMichael Hanselmann <hansmi@google.com>
parent ca9ec5aa
......@@ -1715,11 +1715,13 @@ def OwnIpAddress(address):
source=constants.LOCALHOST_IP_ADDRESS)
def ListVisibleFiles(path):
def ListVisibleFiles(path, sort=True):
"""Returns a list of visible files in a directory.
@type path: str
@param path: the directory to enumerate
@type sort: boolean
@param sort: whether to provide a sorted output
@rtype: list
@return: the list of all files not starting with a dot
@raise ProgrammerError: if L{path} is not an absolue and normalized path
......@@ -1729,7 +1731,8 @@ def ListVisibleFiles(path):
raise errors.ProgrammerError("Path passed to ListVisibleFiles is not"
" absolute/normalized: '%s'" % path)
files = [i for i in os.listdir(path) if not i.startswith(".")]
files.sort()
if sort:
files.sort()
return files
......
......@@ -1334,22 +1334,15 @@ class TestListVisibleFiles(unittest.TestCase):
def tearDown(self):
shutil.rmtree(self.path)
def _test(self, files, expected):
# Sort a copy
expected = expected[:]
expected.sort()
def _CreateFiles(self, files):
for name in files:
f = open(os.path.join(self.path, name), 'w')
try:
f.write("Test\n")
finally:
f.close()
utils.WriteFile(os.path.join(self.path, name), data="test")
def _test(self, files, expected):
self._CreateFiles(files)
found = ListVisibleFiles(self.path)
found.sort()
self.assertEqual(found, expected)
# by default ListVisibleFiles sorts its output
self.assertEqual(found, sorted(expected))
def testAllVisible(self):
files = ["a", "b", "c"]
......@@ -1366,6 +1359,20 @@ class TestListVisibleFiles(unittest.TestCase):
expected = ["a", "b"]
self._test(files, expected)
def testForceSort(self):
files = ["c", "b", "a"]
self._CreateFiles(files)
found = ListVisibleFiles(self.path, sort=True)
self.assertEqual(found, sorted(files))
def testForceNonSort(self):
files = ["c", "b", "a"]
self._CreateFiles(files)
found = ListVisibleFiles(self.path, sort=False)
# We can't actually check that they weren't sorted, because they might come
# out sorted by chance
self.assertEqual(set(found), set(files))
def testNonAbsolutePath(self):
self.failUnlessRaises(errors.ProgrammerError, ListVisibleFiles, "abc")
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment