Advertisement
justin_hanekom

rm-unneeded-files.py

May 13th, 2019 (edited)
299
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.55 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3.  
  4. from __future__ import (
  5.     absolute_import, division, print_function, unicode_literals
  6. )
  7. from nine import (
  8.     IS_PYTHON2, basestring, chr, class_types, filter, integer_types,
  9.     implements_iterator, implements_to_string, implements_repr,
  10.     input, iterkeys, iteritems, itervalues, long, map,
  11.     native_str, nine, nimport, range, range_list, reraise, str, zip
  12. )
  13.  
  14. argparse = nimport('argparse')
  15. fnmatch = nimport('fnmatch')
  16. os = nimport('os')
  17. sys = nimport('sys')
  18. time = nimport('time')
  19.  
  20.  
  21. def run():
  22.     """Runs this program.
  23.  
  24.    The program removes unneeded files from a directory.
  25.    """
  26.     start_time = time.time()
  27.     options = parse_cmd_line()
  28.     rm_unneeded_files(options['directory'], options['verbose'])
  29.     if options['verbose']:
  30.         print('Done, in {} seconds!'.format(time.time() - start_time))
  31.  
  32.  
  33. def parse_cmd_line():
  34.     """Parses the command-line arguments.
  35.  
  36.    Arguments:
  37.        None
  38.  
  39.    Returns:
  40.        A dictionary with each of the supplied command-line arguments.
  41.    """
  42.     parser = argparse.ArgumentParser(
  43.         description=' '.join([
  44.             'Removes any unneeded files found',
  45.             'in the given directory or any subdirectory']))
  46.     parser.add_argument(
  47.         'directory',
  48.         help='specify the directory containing unneccessary files')
  49.     parser.add_argument(
  50.         '--verbose', '-v',
  51.         action='store_true',
  52.         default=False,
  53.         help='specify this to display verbose output')
  54.     # vars() turns Namespace into a regular dictionary
  55.     options = vars(parser.parse_args())
  56.     options['directory'] = chomp_sep(options['directory']) + os.sep
  57.     return options
  58.  
  59.  
  60. def chomp_sep(dir_name):
  61.     """Removes any trailing directory separator characters from the given
  62.    directory name.
  63.  
  64.    Arguments:
  65.        dir_name: the name that has to have any trailing slashes removed
  66.  
  67.    Returns:
  68.        The directory name with no trailing separator characters
  69.    """
  70.     while dir_name.endswith(os.sep):
  71.         dir_name = dir_name[:-1]
  72.     return dir_name
  73.  
  74.  
  75. def rm_unneeded_files(dir_name, verbose):
  76.     """Removes unneeded files under directory dir_name.
  77.  
  78.    Arguments:
  79.        dir_name:   the root directory under which to search for
  80.                    unneccessary files to delete
  81.        verbose:    whether to output text describing non-fatal events
  82.  
  83.    Returns:
  84.        None
  85.    """
  86.     _fnmatch = fnmatch.fnmatch
  87.     for tupl in os.walk(dir_name):
  88.         dir_name = tupl[0]  # (dir, subdirs, filenames)
  89.         for fname in tupl[2]:
  90.             if (_fnmatch(fname, '*~')
  91.                 or _fnmatch(fname, '*.#')
  92.                 or _fnmatch(fname, '#*#')
  93.                 or _fnmatch(fname, '*.sw?')
  94.                 or _fnmatch(fname, '*.autosave')
  95.                 or _fnmatch(fname, '*.DS_Store')
  96.                 or _fnmatch(fname, '*.lein_failures')
  97.                 or _fnmatch(fname, '*.lein-repl-history')
  98.                 or _fnmatch(fname, '*.lisp-temp')
  99.             ):
  100.                 dir_fname = os.path.join(dir_name, fname)
  101.                 try:
  102.                     os.remove(dir_fname)
  103.                     if verbose:
  104.                         print("Removed: '{}'".format(dir_fname))
  105.                 except OSError as err:
  106.                         print(
  107.                             "Unable to remove: '{}' => {}".format(
  108.                                 dir_fname,
  109.                                 err),
  110.                              file=sys.stderr)
  111.  
  112.  
  113. if __name__ == '__main__':
  114.     run()
  115.  
Tags: python
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement