home *** CD-ROM | disk | FTP | other *** search
/ Clickx 115 / Clickx 115.iso / software / tools / windows / tails-i386-0.16.iso / live / filesystem.squashfs / usr / bin / pyclean < prev    next >
Encoding:
Text File  |  2012-05-04  |  4.5 KB  |  135 lines

  1. #! /usr/bin/python
  2. # -*- coding: UTF-8 -*-
  3. # vim: et ts=4 sw=4
  4.  
  5. # Copyright ┬⌐ 2010 Piotr O┼╝arowski <piotr@debian.org>
  6. #
  7. # Permission is hereby granted, free of charge, to any person obtaining a copy
  8. # of this software and associated documentation files (the "Software"), to deal
  9. # in the Software without restriction, including without limitation the rights
  10. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. # copies of the Software, and to permit persons to whom the Software is
  12. # furnished to do so, subject to the following conditions:
  13. #
  14. # The above copyright notice and this permission notice shall be included in
  15. # all copies or substantial portions of the Software.
  16. #
  17. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  23. # THE SOFTWARE.
  24.  
  25. import logging
  26. import optparse
  27. import sys
  28. from os import environ, remove, walk
  29. from os.path import exists, isdir, isfile, join
  30. from subprocess import Popen, PIPE
  31.  
  32.  
  33. # initialize script
  34. logging.basicConfig(format='%(levelname).1s: %(module)s:%(lineno)d: '
  35.                            '%(message)s')
  36. log = logging.getLogger(__name__)
  37.  
  38. """TODO: move it to manpage
  39. Examples:
  40.     pyclean -p python-mako # all .py[co] files from the package
  41.     pyclean /usr/lib/python2.6/dist-packages # python2.6
  42. """
  43.  
  44.  
  45. def destroyer():  # ;-)
  46.     """Removes every .py[co] file associated to received .py file."""
  47.  
  48.     def find_files_to_remove(pyfile):
  49.         for filename in ("%sc" % pyfile, "%so" % pyfile):
  50.             if exists(filename):
  51.                 yield filename
  52.  
  53.     counter = 0
  54.     try:
  55.         while True:
  56.             pyfile = (yield)
  57.             for filename in find_files_to_remove(pyfile):
  58.                 try:
  59.                     log.debug('removing %s', filename)
  60.                     remove(filename)
  61.                     counter += 1
  62.                 except (IOError, OSError), e:
  63.                     log.error('cannot remove %s', filename)
  64.                     log.debug(e)
  65.     except GeneratorExit:
  66.         log.info("removed files: %s", counter)
  67.  
  68.  
  69. def get_files(items):
  70.     for item in items:
  71.         if isfile(item) and item.endswith('.py'):
  72.             yield item
  73.         elif isdir(item):
  74.             for root, dirs, files in walk(item):
  75.                 #for fn in glob1(root, '*.py'):
  76.                 #    yield join(root, fn)
  77.                 for fn in files:
  78.                     if fn.endswith('.py'):
  79.                         yield join(root, fn)
  80.  
  81.  
  82. def get_package_files(package_name):
  83.     process = Popen("/usr/bin/dpkg -L %s" % package_name,\
  84.                     shell=True, stdout=PIPE)
  85.     stdout, stderr = process.communicate()
  86.     if process.returncode != 0:
  87.         log.error('cannot get content of %s', package_name)
  88.         sys.exit(2)
  89.     for line in stdout.split('\n'):
  90.         if line.endswith('.py'):
  91.             yield line
  92.  
  93.  
  94. def main():
  95.     usage = '%prog [-p PACKAGE | DIR_OR_FILE]'
  96.     parser = optparse.OptionParser(usage, version='%prog 0.9')
  97.     parser.add_option('-v', '--verbose', action='store_true', dest='verbose',
  98.         help='turn verbose more one')
  99.     parser.add_option('-q', '--quiet', action='store_false', dest='verbose',
  100.         default=False, help='be quiet')
  101.     parser.add_option('-p', '--package',
  102.         help='specify Debian package name to clean')
  103.  
  104.     (options, args) = parser.parse_args()
  105.  
  106.     if options.verbose or environ.get('PYCLEAN_DEBUG') == '1':
  107.         log.setLevel(logging.DEBUG)
  108.         log.debug('argv: %s', sys.argv)
  109.         log.debug('options: %s', options)
  110.         log.debug('args: %s', args)
  111.     else:
  112.         log.setLevel(logging.WARNING)
  113.  
  114.     d = destroyer()
  115.     d.next()  # initialize coroutine
  116.  
  117.     if options.package and args:
  118.         parser.error('only one action is allowed at the same time ('
  119.                      'cleaning directory or a package)')
  120.  
  121.     if options.package:
  122.         log.info('cleaning package %s', options.package)
  123.         for filename in get_package_files(options.package):
  124.             d.send(filename)
  125.     elif args:
  126.         log.info('cleaning directories: %s', args)
  127.         for filename in get_files(args):
  128.             d.send(filename)
  129.     else:
  130.         parser.print_usage()
  131.         sys.exit(1)
  132.  
  133. if __name__ == '__main__':
  134.     main()
  135.