-
Notifications
You must be signed in to change notification settings - Fork 0
/
pruner.py
executable file
·84 lines (69 loc) · 2.37 KB
/
pruner.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#!/usr/bin/python
import os
import sys
import fileinput
import re
import subprocess
import configparser
import contextlib
import math
import FileUtils
import Recipe
class Pruner:
def __init__(self, path, recipe):
self.pathToFile = path
self.recipeToCompilePath = recipe
def removeUnusedIncludes(self):
for include in self.__generateIncludeList():
f = FileUtils.FileWithBackup(self.pathToFile)
f.deleteLine(include)
if not self.__canCompileToObjectCode():
f.restore()
def __canCompileToObjectCode(self):
return not subprocess.call(self.recipeToCompilePath,
stderr=open(os.devnull, 'wb'),
shell=True)
def __generateIncludeList(self):
includes = []
for line in FileUtils.readFile(self.pathToFile).split('\n'):
if re.match( r'^#include.*', line):
includes.append(line)
return includes
@contextlib.contextmanager
def changeWorkingDir(path):
startingDirectory = os.getcwd()
os.makedirs(path, exist_ok=True)
try:
os.chdir(path)
yield
finally:
os.chdir(startingDirectory)
def countFilesRecursively(path, filenameFilter=None):
if filenameFilter is None:
filenameFilter = ".*"
count = 0
for root, subdirs, files in os.walk(path):
for filename in files:
filenameFilterRegex = r"%s" % filenameFilter
if re.match(filenameFilterRegex, filename):
count += 1
return count
config = configparser.ConfigParser()
config.read('config.ini')
workingDirectory = config['DEFAULT']['WorkingDir']
processedFiles = 0
numberOfFiles = countFilesRecursively(workingDirectory, ".*\.cpp")
progressLineLength = 25
for root, subdirs, files in os.walk(workingDirectory):
if '.git' in subdirs:
subdirs.remove('.git')
for filename in files:
path = os.path.join(root, filename)
ext = os.path.splitext(filename)[-1].lower()
if(ext == '.cpp'):
p = Pruner(path, "g++ -c %s" % path)
p.removeUnusedIncludes()
processedFiles += 1
progress = math.floor(processedFiles / numberOfFiles * progressLineLength)
print('total:\t[%s%s]' % ('#'*progress, ' '*(progressLineLength - progress)), end='\r')
print('\nDONE!')