/Tools/scripts/pathfix.py

http://unladen-swallow.googlecode.com/ · Python · 149 lines · 112 code · 12 blank · 25 comment · 39 complexity · 2688586f0f6fa8c679c1d7479bcd2def MD5 · raw file

  1. #! /usr/bin/env python
  2. # Change the #! line occurring in Python scripts. The new interpreter
  3. # pathname must be given with a -i option.
  4. #
  5. # Command line arguments are files or directories to be processed.
  6. # Directories are searched recursively for files whose name looks
  7. # like a python module.
  8. # Symbolic links are always ignored (except as explicit directory
  9. # arguments). Of course, the original file is kept as a back-up
  10. # (with a "~" attached to its name).
  11. #
  12. # Undoubtedly you can do this using find and sed or perl, but this is
  13. # a nice example of Python code that recurses down a directory tree
  14. # and uses regular expressions. Also note several subtleties like
  15. # preserving the file's mode and avoiding to even write a temp file
  16. # when no changes are needed for a file.
  17. #
  18. # NB: by changing only the function fixfile() you can turn this
  19. # into a program for a different change to Python programs...
  20. import sys
  21. import re
  22. import os
  23. from stat import *
  24. import getopt
  25. err = sys.stderr.write
  26. dbg = err
  27. rep = sys.stdout.write
  28. new_interpreter = None
  29. def main():
  30. global new_interpreter
  31. usage = ('usage: %s -i /interpreter file-or-directory ...\n' %
  32. sys.argv[0])
  33. try:
  34. opts, args = getopt.getopt(sys.argv[1:], 'i:')
  35. except getopt.error, msg:
  36. err(msg + '\n')
  37. err(usage)
  38. sys.exit(2)
  39. for o, a in opts:
  40. if o == '-i':
  41. new_interpreter = a
  42. if not new_interpreter or new_interpreter[0] != '/' or not args:
  43. err('-i option or file-or-directory missing\n')
  44. err(usage)
  45. sys.exit(2)
  46. bad = 0
  47. for arg in args:
  48. if os.path.isdir(arg):
  49. if recursedown(arg): bad = 1
  50. elif os.path.islink(arg):
  51. err(arg + ': will not process symbolic links\n')
  52. bad = 1
  53. else:
  54. if fix(arg): bad = 1
  55. sys.exit(bad)
  56. ispythonprog = re.compile('^[a-zA-Z0-9_]+\.py$')
  57. def ispython(name):
  58. return ispythonprog.match(name) >= 0
  59. def recursedown(dirname):
  60. dbg('recursedown(%r)\n' % (dirname,))
  61. bad = 0
  62. try:
  63. names = os.listdir(dirname)
  64. except os.error, msg:
  65. err('%s: cannot list directory: %r\n' % (dirname, msg))
  66. return 1
  67. names.sort()
  68. subdirs = []
  69. for name in names:
  70. if name in (os.curdir, os.pardir): continue
  71. fullname = os.path.join(dirname, name)
  72. if os.path.islink(fullname): pass
  73. elif os.path.isdir(fullname):
  74. subdirs.append(fullname)
  75. elif ispython(name):
  76. if fix(fullname): bad = 1
  77. for fullname in subdirs:
  78. if recursedown(fullname): bad = 1
  79. return bad
  80. def fix(filename):
  81. ## dbg('fix(%r)\n' % (filename,))
  82. try:
  83. f = open(filename, 'r')
  84. except IOError, msg:
  85. err('%s: cannot open: %r\n' % (filename, msg))
  86. return 1
  87. line = f.readline()
  88. fixed = fixline(line)
  89. if line == fixed:
  90. rep(filename+': no change\n')
  91. f.close()
  92. return
  93. head, tail = os.path.split(filename)
  94. tempname = os.path.join(head, '@' + tail)
  95. try:
  96. g = open(tempname, 'w')
  97. except IOError, msg:
  98. f.close()
  99. err('%s: cannot create: %r\n' % (tempname, msg))
  100. return 1
  101. rep(filename + ': updating\n')
  102. g.write(fixed)
  103. BUFSIZE = 8*1024
  104. while 1:
  105. buf = f.read(BUFSIZE)
  106. if not buf: break
  107. g.write(buf)
  108. g.close()
  109. f.close()
  110. # Finishing touch -- move files
  111. # First copy the file's mode to the temp file
  112. try:
  113. statbuf = os.stat(filename)
  114. os.chmod(tempname, statbuf[ST_MODE] & 07777)
  115. except os.error, msg:
  116. err('%s: warning: chmod failed (%r)\n' % (tempname, msg))
  117. # Then make a backup of the original file as filename~
  118. try:
  119. os.rename(filename, filename + '~')
  120. except os.error, msg:
  121. err('%s: warning: backup failed (%r)\n' % (filename, msg))
  122. # Now move the temp file to the original file
  123. try:
  124. os.rename(tempname, filename)
  125. except os.error, msg:
  126. err('%s: rename failed (%r)\n' % (filename, msg))
  127. return 1
  128. # Return succes
  129. return 0
  130. def fixline(line):
  131. if not line.startswith('#!'):
  132. return line
  133. if "python" not in line:
  134. return line
  135. return '#! %s\n' % new_interpreter
  136. if __name__ == '__main__':
  137. main()