-
Notifications
You must be signed in to change notification settings - Fork 0
/
optimize.py
65 lines (49 loc) · 1.9 KB
/
optimize.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
###
#
# Version: 1.0.0
# Date: 2020-11-25
# Author: Yves Vindevogel (vindevoy)
#
# Purpose;
# Note: This dates back to 2018 or 2019, but was released on Github on 2020-11-25
###
SOURCE_FILE = './Dockerfile'
BUILD_FILE = './Dockerfile.build'
NO_INDENT_SPACES = 0
EXTRA_INDENT_SPACES = 4
RUN_INDENT_SPACES = 4
def optimize():
optimized = ''
command = ''
previous_command = ''
next_line_continued = False
next_command_continued = False
src = open(SOURCE_FILE, 'r')
for line in src.readlines():
line = line.strip()
if len(line) > 0 and line[0:1] != '#':
if next_line_continued:
extra_spaces = NO_INDENT_SPACES if next_command_continued else EXTRA_INDENT_SPACES
optimized += '\n' + (' ' * (len(command) + extra_spaces + 1)) + '{0}'.format(line)
else:
command = line.split()[0].upper()
if command == 'RUN':
if previous_command != 'RUN':
optimized += '\nRUN set -x'
# 4 is the length of the RUN command and a blank, nothing to do with the indent spaces
optimized += ' && \\ \n{0}{1}'.format(' ' * RUN_INDENT_SPACES, line[RUN_INDENT_SPACES:].strip())
else:
if previous_command == 'RUN':
optimized += '\n'
if previous_command != command and previous_command != '':
optimized += '\n'
optimized += '{0} {1}\n'.format(command.upper(), line[len(command) + 1:].strip())
previous_command = command
next_line_continued = line.endswith('\\')
next_command_continued = line.replace(' ', '').endswith('&&\\')
src.close()
build = open(BUILD_FILE, 'w+')
build.write(optimized)
build.close()
if __name__ == '__main__':
optimize()