#! /opt/alt/python312/bin/python3.12
preserve_timestamps = False
global preserve_timestamps
usage = ('usage: %s -i /interpreter -p -n -k -a file-or-directory ...\n' %
opts, args = getopt.getopt(sys.argv[1:], 'i:a:kpn')
except getopt.error as msg:
new_interpreter = a.encode()
preserve_timestamps = True
err("-a option doesn't support whitespaces")
if not new_interpreter or not new_interpreter.startswith(b'/') or \
err('-i option or file-or-directory missing\n')
if recursedown(arg): bad = 1
elif os.path.islink(arg):
err(arg + ': will not process symbolic links\n')
return name.endswith('.py')
def recursedown(dirname):
dbg('recursedown(%r)\n' % (dirname,))
names = os.listdir(dirname)
err('%s: cannot list directory: %r\n' % (dirname, msg))
if name in (os.curdir, os.pardir): continue
fullname = os.path.join(dirname, name)
if os.path.islink(fullname): pass
elif os.path.isdir(fullname):
if fix(fullname): bad = 1
if recursedown(fullname): bad = 1
## dbg('fix(%r)\n' % (filename,))
err('%s: cannot open: %r\n' % (filename, msg))
rep(filename+': no change\n')
head, tail = os.path.split(filename)
tempname = os.path.join(head, '@' + tail)
err('%s: cannot create: %r\n' % (tempname, msg))
rep(filename + ': updating\n')
# Finishing touch -- move files
# First copy the file's mode to the temp file
statbuf = os.stat(filename)
os.chmod(tempname, statbuf[ST_MODE] & 0o7777)
err('%s: warning: chmod failed (%r)\n' % (tempname, msg))
# Then make a backup of the original file as filename~
os.rename(filename, filename + '~')
err('%s: warning: backup failed (%r)\n' % (filename, msg))
err('%s: warning: removing failed (%r)\n' % (filename, msg))
# Now move the temp file to the original file
os.rename(tempname, filename)
err('%s: rename failed (%r)\n' % (filename, msg))
os.utime(filename, (atime, mtime))
err('%s: reset of timestamp failed (%r)\n' % (filename, msg))
def parse_shebang(shebangline):
shebangline = shebangline.rstrip(b'\n')
start = shebangline.find(b' -')
return shebangline[start:]
def populate_flags(shebangline):
old_flags = parse_shebang(shebangline)
old_flags = old_flags[2:]
if not (old_flags or add_flags):
# On Linux, the entire string following the interpreter name
# is passed as a single argument to the interpreter.
# e.g. "#! /usr/bin/python3 -W Error -s" runs "/usr/bin/python3 "-W Error -s"
# so shebang should have single '-' where flags are given and
# flag might need argument for that reasons adding new flags is
# between '-' and original flags
# e.g. #! /usr/bin/python3 -sW Error
return b' -' + add_flags + old_flags
if not line.startswith(b'#!'):
if b"python" not in line:
flags = populate_flags(line)
return b'#! ' + new_interpreter + flags + b'\n'
if __name__ == '__main__':