#!/usr/bin/python
import sys
import os
import tempfile
import subprocess
import time
########################################
#### Subroutines #######################
########################################
# callback for filter below
def isNonTrivial(fileName):
# If the fileName starts with a dot, it doesn't count
if fileName[0:1] == '.':
return False
else:
return True
# function which sets the finder label for OS X files
def finderLabelFiles(files, labelNum):
# Write the list of files to label to a temp file
(tmpFH, tmpPath) = tempfile.mkstemp('.txt')
os.write(tmpFH, "\n".join(files))
os.close(tmpFH)
# Open a pipe to and from the applescript interpreter
asInterpreter = subprocess.Popen(
"/usr/bin/osascript",
shell=True,
stdin=subprocess.PIPE,
stdout=sys.stdout)
# The script we'll send it
script = [
'tell application "Finder"',
'set fileList to (POSIX file "%s")' % (tmpPath),
'set labelColor to %i' % (labelNum),
'try',
'set fh to open for access fileList',
'repeat with thisFile in (read fh using delimiter (ASCII character 10))',
'set label index of item (thisFile as POSIX file) to labelColor',
'end repeat',
'close access fh',
'on error',
'try',
'close access fh',
'end try',
'end try',
'end tell'
]
asInterpreter.stdin.write("\n".join(script))
asInterpreter.stdin.close()
asInterpreter.wait()
os.unlink(tmpPath)
########################################
#### Main ##############################
########################################
# Sanity-Check Arguments
if (not (len(sys.argv) > 1 and map(os.path.isdir, sys.argv[1:]).count(False) < 1)):
print "Usage: %s directory_to_search [...]" % (sys.argv[0])
exit()
# For each directory specified on the command line
for searchDirectory in sys.argv[1:]:
# Init
emptyDirs = []
reportFile = os.path.join(searchDirectory, "Empty Folders Report.txt")
# Main Loop: os.walk returns this tuple for each subdir
for thisPath, thisPathDirs, thisPathFiles in os.walk(searchDirectory):
# Does this directory have subdirectories?
if len(thisPathDirs) == 0:
# Does this directory have files?
if len(thisPathFiles) == 0:
emptyDirs.append(thisPath)
else:
# Are the files all trivial?
filteredFiles = filter(isNonTrivial, thisPathFiles)
if len(filteredFiles) == 0:
emptyDirs.append(thisPath)
# Were there actually were any empty directories?
if len(emptyDirs) > 0:
# Write our report
try:
report = open(reportFile, 'w')
report.write("# Empty Folders in %s on %s:\n" % ( searchDirectory, time.asctime() ) )
report.write("\n".join(emptyDirs))
report.close()
except:
print "Couldn't write report for %s (%s)" % (searchDirectory, reportFile)
raise
# Set the finder labels for the empty dirs
finderLabelFiles(emptyDirs, 1)
else:
print 'No empty directories were found in "%s"' % (searchDirectory)
exit()