2012
03.18
03.18
In Programming ,Python
I have on more than one occasion been given a homogenous folder of code with sources and headers mixed together, and needed to break them up into more library-friendly include and src folders. Instead of manually sorting them, I wrote this little python script:
#!/usr/bin/python
import os
import sys
import shutil
if len( sys.argv ) < 3:
sys.stderr.write( 'Usage: ' + sys.argv[0] + ' [inputDir] [outputDir]\n' )
else:
rootPath = sys.argv[1];
outDir = sys.argv[2];
headers = []
sources = []
unknown = []
for root, dirs, files in os.walk( rootPath ):
for filename in files:
if filename.endswith( '.h' ):
headers.append( [ root, filename ] )
elif filename.endswith( '.cpp' ) or filename.endswith( '.c' ):
sources.append( [ root, filename ] )
else:
unknown.append( [ root, filename ] )
def getTargetPath( root, folder, filename ):
newRoot = root.replace( rootPath, '' )
if newRoot.startswith( '/' ):
newRoot = newRoot[1:]
targetDir = os.path.join( outDir, folder, newRoot )
if not os.path.exists( targetDir ):
os.makedirs( targetDir )
return os.path.join( targetDir, filename )
for file in headers:
fromPath = os.path.join( file[0], file[1] )
toPath = getTargetPath( file[0], 'include', file[1] )
shutil.copyfile( fromPath, toPath )
for file in sources:
fromPath = os.path.join( file[0], file[1] )
toPath = getTargetPath( file[0], 'src', file[1] )
shutil.copyfile( fromPath, toPath )
for file in unknown:
fromPath = os.path.join( file[0], file[1] )
toPath = getTargetPath( file[0], 'unknown', file[1] )
shutil.copyfile( fromPath, toPath )
The results would be something like this:
Input: /aardvark.h /stuff.h /stuff.cpp /main.cpp /widgets/doodad.h /widgets/doodad.cpp
Output: /include/aardvark.h /include/stuff.h /include/widgets/doodad.h /src/stuff.cpp /src/main.cpp /src/widgets/doodad.cpp










