Skip to content

Instantly share code, notes, and snippets.

@marcbln
Forked from dokterbob/copywriter.py
Last active October 27, 2017 11:59
Show Gist options
  • Save marcbln/77458ebec1f2eeed2d456be104722e2f to your computer and use it in GitHub Desktop.
Save marcbln/77458ebec1f2eeed2d456be104722e2f to your computer and use it in GitHub Desktop.
Script for automatically prepending copyright notice to a file
#!/usr/bin/env python
#
# original: https://gist.github.com/dokterbob/880378
# 10/2017 updated to work with php files
#
# usage:
# find src/ -name "*.php" -exec shell/copywriter.py some_docheader.txt {} \;
import sys
from optparse import OptionParser
def main():
parser = OptionParser(usage="usage: %prog [options] <notice_filename> <code_filename>")
(options, args) = parser.parse_args()
if len(args) != 2:
parser.error('incorrect number of arguments')
notice_filename = args[0]
filename = args[1]
notice_file = open(notice_filename)
notice = notice_file.read()
notice_file.close()
code_file = open(filename, 'r+')
code = code_file.read()
if notice in code[:len(notice*2)]:
print 'Copyright notice already in file %s' % filename
sys.exit(0)
print 'Prepending copyright notice to beginning of %s' % filename
code_file.seek(0)
# check for shebang
split_first_line = code.split('\n', 1)
first_line = split_first_line[0]
if first_line[:2] == '#!':
print 'Shebang found, preserving'
code = split_first_line[1]
code_file.write(first_line+'\n')
# check for <?
split_first_line = code.split('\n', 1)
first_line = split_first_line[0]
if first_line[:2] == '<?':
print 'php opening tag found, preserving'
code = split_first_line[1]
code_file.write(first_line+'\n')
code_file.write(notice)
code_file.write(code)
code_file.close()
sys.exit(0)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment