Commits

Anton Shestakov committed d5c2742

Moved from getopt to optparse, removed --quiet option, code cleanup.

Comments (0)

Files changed (1)

-#!/usr/bin/env python
+#!/usr/bin/env python2
 # -*- coding: UTF-8 -*-
 
 import os
 import sys
-import getopt
-
 import libtorrent as lt
 
+from optparse import OptionParser
 
-dry_run = False
-verbose = 1
-source_file = None
-dirty_directory = None
 
 header_printed = False
 
-def show_usage():
-    print("""Remove files bigger than declared in .torrent file.
-Usage: %s -s TORRENT_FILE -d DIRECTORY [-n]
 
- -s, --source=TORRENT_FILE
- -t, --torrent=TORRENT_FILE  Get file information from TORRENT_FILE
-
- -d, --directory=DIRECTORY   Clean DIRECTORY from bad files
-    
- -n, --dry-run               Don't delete anything, just print what will be done
- 
- -q, --quiet                 Print only errors
-
- -v, --verbose               Print information about every file in TORRENT_FILE
-    """ % os.path.split(sys.argv[0])[1])
-
-
-def info(message, level):
+def info(message, important=False):
     global header_printed
 
-    if level > verbose:
+    if not important:
         return
 
     if not header_printed:
-        print('%s %27s %19s %20s' 
-            % ('OPERATION', 'FILE', 'SIZE DECLARED', 'SIZE FOUND'))
+        print(('%s %27s %19s %20s' 
+            % ('OPERATION', 'FILE', 'SIZE DECLARED', 'SIZE FOUND')))
         header_printed = True
         
     print(message)
 
 
 def main():
-    global source_file, dirty_directory, dry_run, verbose
+    parser = OptionParser(
+        usage='%prog -s TORRENT_FILE -d DIRECTORY [options]',
+        description='Remove files bigger than declared in .torrent file.')
     
-    try:
-        opts, args = getopt.getopt(sys.argv[1:], 's:t:d:nqv', 
-            ['source=', 'torrent=', 'directory=', 'dry-run', 'quiet', 'verbose'])
-    except getopt.GetoptError as err:
-        print(err)
-        show_usage()
-        sys.exit(2)
-        
-    for o, a in opts:
-        if o in ('-s', '--source', '-t', '--torrent'):
-            source_file = a
-        elif o in ('-d', '--directory'):
-            dirty_directory = a
-        elif o in ('-n', '--dry-run'):
-            dry_run = True
-        elif o in ('-q', '--quiet'):
-            verbose = 0
-        elif o in ('-v', '--verbose'):
-            verbose = 2
-        
-    if source_file is not None and dirty_directory is not None:
-        clean()
+    parser.add_option('-s', '--source', '-t', '--torrent', dest='source_file',
+                metavar='TORRENT_FILE', help='get file information from TORRENT_FILE')
+    parser.add_option('-d', '--directory', dest='dirty_directory',
+                metavar='DIRECTORY', help='clean DIRECTORY from bad files')
+    parser.add_option('-n', '--dry-run', dest='dry_run', default=False,
+                action='store_true', help='do not perform actions, just print info')
+    parser.add_option('-v', '--verbose', dest='verbose', default=False,
+                action='store_true', help='print information about every file in TORRENT_FILE')
+    
+    options, args = parser.parse_args()
+    
+    if all([options.source_file, options.dirty_directory]):
+        clean(options)
     else:
-        show_usage()
+        parser.print_help()
+        parser.exit()
 
 
-def clean():
-    with open(source_file) as torrent_src:
+def clean(options):
+    with open(options.source_file, 'rb') as torrent_src:
         bulk = lt.bdecode(torrent_src.read())
 
     try:
         src_sizes = bulk['info']['files']
     except TypeError as error:
-        print('Invalid .torrent format. Couldn\'t get files list.')
+        print("Invalid .torrent format. Couldn't get files list.")
         sys.exit(4)
     
     for src_file in src_sizes:
         filename = os.path.join(*src_file['path'])
-        real_path = os.path.join(dirty_directory, filename)
+        real_path = os.path.join(options.dirty_directory, filename)
 
         try:
             real_size = os.stat(real_path).st_size
             real_size = None
             
         op = 'N/A'
-        level = 2
+        important = False
         
         if real_size is None:
             comp = ''
         elif src_file['length'] < real_size:
             op = 'unlink'
             comp = '<'
-            level = 1
+            important = True
         elif src_file['length'] > real_size:
             comp = '>'
         else:
             comp = '='
             
         info('%6s %30s: %12d bytes %1s %12d bytes' % (
-            op, filename, src_file['length'], comp, real_size), level)
+            op, filename, src_file['length'], comp, real_size), 
+            options.verbose or important)
             
-        if op == 'unlink' and not dry_run:
+        if op == 'unlink' and not options.dry_run:
             try:
                 os.unlink(real_path)
             except OSError as error:
                 print(error)
-    return 0
 
 
 if __name__ == '__main__':