-
-
Save scottyab/d721bec60e38901b2bcfa2b795a09bd0 to your computer and use it in GitHub Desktop.
Adds Copyright Notice to a bunch of Java and Kotlin files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/env python | |
# coding: utf-8 | |
"""This script reads all .java and .kt files from a directory tree and determines if | |
it's necessary to write a Copyright Notice in the beginning of each Java file. | |
It checks that by searching for the word "copyright" in the first few lines. | |
Warning: use it at your own risk. Better have a source control to rollback if | |
necessary. | |
""" | |
import fnmatch | |
import sys | |
import os | |
#: The copyright message to be included in the beginning of files if the word | |
#: "copyright" is not present in the first lines | |
COPYRIGHT_MESSAGE = "/*\n * Copyright (C) Help Scout - All Rights Reserved \n" \ | |
" * Unauthorized copying of this file, via any medium is strictly prohibited \n" \ | |
" * Proprietary and confidential \n" \ | |
" */\n" | |
#: Number of lines to look for the word "copyright" in the beginning of file, | |
#: to decide whether or not the copyright notice is presented | |
LINES_TO_LOOK = 10 | |
def is_valid_source_file(filename, extensions=['.java', '.kt']): | |
return any(filename.endswith(e) for e in extensions) | |
def locate(root=os.curdir): | |
'''Locate all files matching supplied filename pattern in and below | |
supplied root directory.''' | |
for path, dirs, files in os.walk(os.path.abspath(root)): | |
for filename in filter(is_valid_source_file, files): | |
yield os.path.join(path, filename) | |
if __name__ == "__main__": | |
# locate files in current directory or one specified in command line arg | |
root_dir = sys.argv[1] if len(sys.argv) == 2 else os.curdir | |
for filename in locate(root_dir): | |
with open(filename) as f: | |
all_lines = f.readlines() | |
# check Copyright notice in the starting of file | |
file_header = ''.join(all_lines[:LINES_TO_LOOK]) | |
if not 'copyright' in file_header.lower(): | |
print "Adding copyright notice:", filename | |
with open(filename, 'w') as f: | |
f.write(COPYRIGHT_MESSAGE) | |
for line in all_lines: | |
f.write(line) | |
print "Please compile your project to make sure I haven't break anything." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment