Advertisement
justin_hanekom

rm-unneeded-files.py

May 13th, 2019
285
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.71 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3.  
  4. # File: rm-unneeded-files.py
  5. # Copyright (c) 2018-2019 Justin Hanekom <justin_hanekom@yahoo.com>
  6. # Licensed under the MIT License
  7.  
  8. # Permission is hereby granted, free of charge, to any person obtaining
  9. # a copy of this software and associated documentation files
  10. # (the "Software"), to deal in the Software without restriction,
  11. # including without limitation the rights to use, copy, modify, merge,
  12. # publish, distribute, sublicense, and/or sell copies of the Software,
  13. # and to permit persons to whom the Software is furnished to do so,
  14. # subject to the following conditions:
  15. #
  16. # The above copyright notice and this permission notice shall be
  17. # included in all copies or substantial portions of the Software.
  18. #
  19. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  20. # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  21. # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  22. # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  23. # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  24. # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  25. # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  26.  
  27. from __future__ import (
  28.     absolute_import, division, print_function, unicode_literals
  29. )
  30. from nine import (
  31.     IS_PYTHON2, basestring, chr, class_types, filter, integer_types,
  32.     implements_iterator, implements_to_string, implements_repr,
  33.     input, iterkeys, iteritems, itervalues, long, map,
  34.     native_str, nine, nimport, range, range_list, reraise, str, zip
  35. )
  36.  
  37. argparse = nimport('argparse')
  38. fnmatch = nimport('fnmatch')
  39. os = nimport('os')
  40. sys = nimport('sys')
  41. time = nimport('time')
  42.  
  43.  
  44. def run():
  45.     """Runs this program.
  46.  
  47.    The program removes unneeded files from a directory.
  48.    """
  49.     start_time = time.time()
  50.     options = parse_cmd_line()
  51.     rm_unneeded_files(options['directory'], options['verbose'])
  52.     if options['verbose']:
  53.         print('Done, in {} seconds!'.format(time.time() - start_time))
  54.  
  55.  
  56. def parse_cmd_line():
  57.     """Parses the command-line arguments.
  58.  
  59.    Arguments:
  60.        None
  61.  
  62.    Returns:
  63.        A dictionary with each of the supplied command-line arguments.
  64.    """
  65.     parser = argparse.ArgumentParser(
  66.         description=' '.join([
  67.             'Removes any unneeded files found',
  68.             'in the given directory or any subdirectory']))
  69.     parser.add_argument(
  70.         'directory',
  71.         help='specify the directory containing unneccessary files')
  72.     parser.add_argument(
  73.         '--verbose', '-v',
  74.         action='store_true',
  75.         default=False,
  76.         help='specify this to display verbose output')
  77.     # vars() turns Namespace into a regular dictionary
  78.     options = vars(parser.parse_args())
  79.     options['directory'] = chomp_sep(options['directory']) + os.sep
  80.     return options
  81.  
  82.  
  83. def chomp_sep(dir_name):
  84.     """Removes any trailing directory separator characters from the given
  85.    directory name.
  86.  
  87.    Arguments:
  88.        dir_name: the name that has to have any trailing slashes removed
  89.  
  90.    Returns:
  91.        The directory name with no trailing separator characters
  92.    """
  93.     while dir_name.endswith(os.sep):
  94.         dir_name = dir_name[:-1]
  95.     return dir_name
  96.  
  97.  
  98. def rm_unneeded_files(dir_name, verbose):
  99.     """Removes unneeded files under directory dir_name.
  100.  
  101.    Arguments:
  102.        dir_name:   the root directory under which to search for
  103.                    unneccessary files to delete
  104.        verbose:    whether to output text describing non-fatal events
  105.  
  106.    Returns:
  107.        None
  108.    """
  109.     _fnmatch = fnmatch.fnmatch
  110.     for tupl in os.walk(dir_name):
  111.         dir_name = tupl[0]  # (dir, subdirs, filenames)
  112.         for fname in tupl[2]:
  113.             if (_fnmatch(fname, '*~')
  114.                 or _fnmatch(fname, '*.#')
  115.                 or _fnmatch(fname, '#*#')
  116.                 or _fnmatch(fname, '*.sw?')
  117.                 or _fnmatch(fname, '*.autosave')
  118.                 or _fnmatch(fname, '*.DS_Store')
  119.                 or _fnmatch(fname, '*.lein_failures')
  120.                 or _fnmatch(fname, '*.lein-repl-history')
  121.                 or _fnmatch(fname, '*.lisp-temp')
  122.             ):
  123.                 dir_fname = os.path.join(dir_name, fname)
  124.                 try:
  125.                     os.remove(dir_fname)
  126.                     if verbose:
  127.                         print("Removed: '{}'".format(dir_fname))
  128.                 except OSError as err:
  129.                         print(
  130.                             "Unable to remove: '{}' => {}".format(
  131.                                 dir_fname,
  132.                                 err),
  133.                              file=sys.stderr)
  134.  
  135.  
  136. if __name__ == '__main__':
  137.     run()
  138.  
  139. # vim: set filetype=python smartindent autoindent smarttab expandtab tabstop=4 softtabstop=4 shiftwidth=4 autoread
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement