Skaruts

coding_placer.py

Aug 9th, 2017
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.27 KB | None | 0 0
  1. #!/usr/local/bin/python
  2. # -*- coding:latin-1 -*-
  3.  
  4. # Inserts the above encoding lines in every file it finds within the current directory
  5. # and its subdirectories. Tries to find similarities, in case the lines are already
  6. # there, but spelled incorrectly or not as per PEP...something.
  7.  
  8. import time
  9. import os
  10. import subprocess
  11. from difflib import SequenceMatcher
  12.  
  13. correct_lines   = [ "#!/usr/local/bin/python",  "# -*- coding:latin-1 -*-" ]
  14.  
  15. # similarity thresholds to test the existing first two lines. If values are below 60%, then
  16. # the assumption is the existing lines are not encoding lines, and new ones get prepended.
  17. replace_thres   = 75    # similarity >= 75%, replace line.
  18. warning_thres   = 70    # >= 70 < 75, replace but warn user of low similarity.
  19. noreplace_thres = 60    # >= 60 < 70, querry the user.
  20.  
  21. def cls():                      subprocess.call( 'cls', shell=True, cwd='./' )
  22. def similar( a, b ):            return SequenceMatcher( None, a, b ).ratio()
  23. def concat( a, b ): return ''.join( [ a, b ] )
  24.  
  25. def check_for_replace( a, b ):
  26.     percent = similar( a, b )*100
  27.     if   percent == 100:             return ( -1, -1, percent )     # ignore, it's fine
  28.     elif percent >= replace_thres:   return (  1,  0, percent )     # replace, no warning
  29.     elif percent >= warning_thres:   return (  1,  1, percent )     # replace, w/ warning
  30.     elif percent >  noreplace_thres: return (  1,  0, percent )  \
  31.                                         if ask_user( a, b ) else ( 0, 0, percent )
  32.     else:                           return (  0,  0, percent )
  33.  
  34. def ask_user( a, b ):
  35.     inpt = ''
  36.     while inpt.lower() not in ( 'y', 'n' ):
  37.         inpt = raw_input( 'Found %s. Replace the string? (y/n) ' % ( b ) )
  38.     return inpt in 'y'
  39.  
  40. def prepend( fpath ):
  41.     with open( fpath, 'r' ) as f:
  42.         writen_something = False
  43.         lines = list( f.read().split('\n') )
  44.         tmp_lines_copy = lines
  45.         for i, c in enumerate( correct_lines ):
  46.             replace, warn, percent = check_for_replace( c, tmp_lines_copy[i] )
  47.             if replace == -1:   # ignore, already correct in the file
  48.                 continue
  49.             elif replace == 1# replace
  50.                 if warn == 1:
  51.                     print "- WARNING: string '%s' only %.1f similar..." % ( lines[i], percent ),
  52.                 lines[i] = c
  53.                 writen_something = True
  54.             else:               # prepend
  55.                 lines.insert( i, c )
  56.                 writen_something = True
  57.         if writen_something:
  58.             # add a blank line after the second one, to keep things neet
  59.             if len( lines[2] ):
  60.                 lines[1] = concat( lines[1], '\n' )
  61.             # a little quick hack to not add an extra \n at the end
  62.             if not len( lines[-1] ):
  63.                 del lines[-1]
  64.             with open( fpath, 'w' ) as fout:
  65.                 for l in lines:
  66.                     fout.write( concat( l, '\n' ) )
  67.             return True
  68.         return False
  69.  
  70. def main():
  71.     start = time.time()
  72.     num_files = sum( [ len( files ) for r, d, files in os.walk(".\\") ] )
  73.     cls()
  74.     print "\n\t%d .py files found.\n\n" % ( num_files )
  75.     for directory, d, files in os.walk('.\\'):
  76.         # os.walk gives me paths w/ backslashes, so I use them for consistency
  77.         for f in files:
  78.             if f.endswith('.py'):
  79.                 if not directory.endswith('\\'):
  80.                     fpath = concat( concat( directory, '\\' ), f )
  81.                 else:
  82.                     fpath = concat( directory, f )
  83.  
  84.                 print " %s" % ( fpath ),
  85.                 if prepend( fpath ):
  86.                     print "Done."
  87.                 else:
  88.                     print "is fine."
  89.     end = time.time()
  90.     print "\n\t %d files in %.3f seconds." % ( num_files, end-start )
  91.  
  92.  
  93. if __name__ == "__main__":
  94.     main()
Advertisement
Add Comment
Please, Sign In to add comment