Skip to content

Instantly share code, notes, and snippets.

@csmoore
Last active September 8, 2017 15:51
Show Gist options
  • Save csmoore/b00156b06a85d5196f1ea213f27223b1 to your computer and use it in GitHub Desktop.
Save csmoore/b00156b06a85d5196f1ea213f27223b1 to your computer and use it in GitHub Desktop.
Recurse a supplied folder and add a file header to all files matching a pattern
#------------------------------------------------------------------------------
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#------------------------------------------------------------------------------
# Filename: AddHeaderToFiles.py
# Usage: python AddHeaderToFiles.py <Directory>
# Notes: This will modify files matching "patternsToMatch" list
# by adding the header below
#------------------------------------------------------------------------------
import fnmatch
import fileinput
import os
import sys
totalFilesModified = 0
#######################################################
# You may need to modify this section to match your needs:
patternsToMatch = [ '*.js' ]
skipIfFileStartsWith = ('//', '/*')
ignoreFolders = ['FolderToSkip']
headerToAdd = \
'///////////////////////////////////////////////////////////////////////////\n' + \
'// Copyright (c) {YEAR} {COMPANY/NAME} All Rights Reserved.\n' + \
'//\n' + \
'// Licensed under the Apache License Version 2.0 (the "License");\n' + \
'// you may not use this file except in compliance with the License.\n' + \
'// You may obtain a copy of the License at\n' + \
'//\n' + \
'// http://www.apache.org/licenses/LICENSE-2.0\n' + \
'//\n' + \
'// Unless required by applicable law or agreed to in writing, software\n' + \
'// distributed under the License is distributed on an "AS IS" BASIS,\n' + \
'// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n' + \
'// See the License for the specific language governing permissions and\n' + \
'// limitations under the License.\n' + \
'///////////////////////////////////////////////////////////////////////////\n\n'
# End Section to Modify
#######################################################
# Walk credit: Robin Parmar: http://code.activestate.com/recipes/527746-line-of-code-counter/
def Walk(root='.', recurse=True, pattern='*'):
"""
Generator for walking a directory tree.
Starts at specified root folder, returning files
that match our pattern. Optionally will also
recurse through sub-folders.
"""
global ignoreFolders
for path, directories, files in os.walk(root):
# filter directories named in ignoreFolders
directories[:] = [d for d in directories if d not in ignoreFolders]
for name in files:
if fnmatch.fnmatch(name, pattern):
fileName = os.path.join(path, name)
dirName = os.path.dirname(os.path.realpath(fileName))
print("Matching File in Dir: " + dirName + ", Name: " + name)
yield fileName
if not recurse:
break
def DoForEachMatchingFileInDirectory(root='', recurse=True, patterns = ["*.*"]):
# ex. patterns = ["*.txt",...]
for pattern in patterns:
for fspec in Walk(root, recurse, pattern):
AddHeaderToFile(fspec)
def AddHeaderToFile(fspec):
global totalFilesModified, headerToAdd
for line in fileinput.input([fspec], inplace=True):
if fileinput.isfirstline():
if not line.startswith(skipIfFileStartsWith):
totalFilesModified += 1
sys.stdout.write(headerToAdd)
sys.stdout.write(line)
def main():
global patternsToMatch, totalFilesModified
dirName=sys.argv[1]
numberOfArguments=len(sys.argv)
if numberOfArguments < 2:
print("directory name expected. Usage: python AddHeaderToFiles.py <Directory Name>")
sys.exit()
print "Modifying all matching files in folder: " + dirName
print "Matching patterns=" + str(patternsToMatch)
DoForEachMatchingFileInDirectory(dirName, True, patternsToMatch)
print "Total Files Modified: " + str(totalFilesModified)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment