Skip to content

Instantly share code, notes, and snippets.

@Kaylebor
Last active April 4, 2018 07:49
Show Gist options
  • Save Kaylebor/2773c096d9e59d646759fa4698a02eaf to your computer and use it in GitHub Desktop.
Save Kaylebor/2773c096d9e59d646759fa4698a02eaf to your computer and use it in GitHub Desktop.
project-import-scan.py
#!/usr/bin/env python
import csv
import re
import os
topdir=r'folderToScan'
output=r'outputFile.csv'
exten='.extension'
def parsesource(firstfolder,filepath,filename,sourcefile):
with open(output, 'a', newline='') as resultstable:
comment=False
for line in sourcefile:
if line.startswith(r'/*') or line.startswith(r'//'):
comment=True
continue
elif line.endswith(r'*/'):
comment=False
continue
row=[firstfolder,filepath,filename]
if line.startswith(r'import ') and not comment:
importcontentcomponents=line.split(' ')
del importcontentcomponents[0]
importcontentcomponents[-1]=importcontentcomponents[-1].split(';')[0]
importcontent=' '.join(importcontentcomponents)
importcontentcomponents=importcontent.split('.')
while (len(importcontentcomponents)>3):
del importcontentcomponents[-1]
importpackage='.'.join(importcontentcomponents)
row.append(importpackage)
row.append(importcontent)
csv.writer(resultstable, delimiter=' ', quotechar='"', quoting=csv.QUOTE_ALL).writerow(row)
if os.path.isfile(output):
os.remove(output)
with open(output, 'a', newline='') as resultstable:
row=['Parent package','File path','File name','Import package','Import value']
csv.writer(resultstable, delimiter=' ', quotechar='"', quoting=csv.QUOTE_ALL).writerow(row)
for dirpath, dirnames, files in os.walk(topdir):
for name in files:
if name.lower().endswith(exten):
with open(os.path.join(dirpath, name), 'r') as sourcefile:
topdircomponents=[key.strip() for key in topdir.split('\\')]
dirpathcomponents=[key.strip() for key in dirpath.split('\\')]
relativepathcomponents=[key for key in dirpathcomponents if key not in topdircomponents]
relativepath='\\'.join(relativepathcomponents)
parsesource(relativepathcomponents[0], relativepath+'\\'+name,name,sourcefile)
print("Done")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment