aboutsummaryrefslogtreecommitdiff
path: root/tools/make.py
blob: a7ea6e8956407e6d386588e9e1b6037b8bc36bb4 (plain)
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
#!/usr/bin/env python3
""" This tool is responsable for actually building the library.
	It takes the configuration from the file generated by 'configure.py',
	which contains the modules to build and the build tools configuration,
	finds out what is left to do, what has been updated (to re-build),
	and finishes the job.

	It is possible to make several times out of a single configuration,
	and this is cool when you are just programming in one or more modules.
"""

import os, traceback
from shutil import rmtree, copyfile

import yaml
from Internals import *
#*****************************************************************************#
# Parse arguments                                                             #
#*****************************************************************************#
argparser = CarrotArgumentParser(loc['desc']['make'])

# Set up the arguments.
argparser.add_argument('-c', '--config', dest='config',
	default='.config.yml', help='the build configuration path')
argparser.add_argument('-C', '--cache', dest='cache',
	default='.cache.yml', help='the make cache')

argparser.add_argument('-i', '/I', '--include',
	dest='incdir', default='include',
	help='the generated include directory')
argparser.add_argument('-O', '--obj', dest='objdir', default='obj',
	help='the generated objects directory')

argparser.add_argument('command', help='the command to execute')
#*****************************************************************************#
#  Commands                                                                   #
#*****************************************************************************#
def clean(args):
	""" Clean the project (remove generated files in order to
		force rebuild). """
	# Remove the caches.
	try: os.remove('.makeinc-cache')
	except FileNotFoundError: pass

	# Remove the include folder.
	try: rmtree('include')
	except FileNotFoundError: pass

	# Remove the objects folder.
	try: rmtree('obj')
	except FileNotFoundError: pass

def mrproper(args):
	""" Clean the project for distribution (remove generated files and
		configurations). """

	# Clean generated files.
	clean(args)

	# Remove the configuration.
	try: os.remove('.config.yml')
	except FileNotFoundError: pass
	try: os.remove('build.yml')
	except FileNotFoundError: pass

def build(args):
	""" Build the project with the current configuration. """
	args.config = yaml.load(open(args.config).read())

	# Open the main configuration
	root = os.path.join(os.path.dirname(__file__), '..')
	globalconfig = yaml.load(open(os.path.join(root, "config.yml")).read())
	if 'arch' in globalconfig and not args.arch in globalconfig['arch']:
		print("Unsupported arch for libcarrot")
		exit(0)
	mroot = os.path.normpath(os.path.join(root, globalconfig['modules']))

	# Setup the tools.
	tools.setup(args.config['tools'])

	# Gather the modules.
	ret, modules = gather_modules(mroot, args.config['modules'],
		os.path.getmtime(os.path.join(root, "build.yml")))
	if ret: return ret

	# Make the include folder.
	incdirs = []; bitdirs = []
	for name, module in map(lambda x:(x, modules[x]), sorted(modules)):
		i, b = module.getpath('include'), module.getpath('bits')
		if os.path.isdir(i): incdirs.append(i)
		if os.path.isdir(b): bitdirs.append(b)
	ret = tools.suph(args.incdir, incdirs, bitdirs)
	if ret: exit(ret)

	# Get the maximum header modification time.
	# TODO: only check the things for what is actually included in the
	# source file!
	incmtimes = {}
	for root, _, nms in os.walk(args.incdir):
		for nm in nms:
			nm = os.path.join(root, nm)[len(os.path.join(args.incdir, '')):]
			incmtimes[nm] = os.path.getmtime(os.path.join(args.incdir, nm))
	incmtime = max(incmtimes.values())

	# Make the objects.
	objs = []
	for name, module in map(lambda x:(x, modules[x]), sorted(modules)):
		objdir = os.path.join(args.objdir,
			name.split('/')[0], name.split('/')[1])

		# C files
		for source in module.getfiles('src', tools.get('cc_ext')):
			objpath = os.path.join(objdir, source + '.' + tools.get('obj_ext'))
			objs.append(objpath)

			incdirs = []
			if not os.path.exists(objpath): objmtime = -1
			else: objmtime = os.path.getmtime(objpath)
			depmtime = os.path.getmtime(module.getpath('src', source))
			depmtime = max(depmtime, incmtime)

			if objmtime < depmtime:
				# Make the object directory.
				try: os.makedirs(os.path.dirname(objpath))
				except FileExistsError: True

				# Do the command.
				print('[%s] CC %s'%(name, source))
				srcfile = module.getpath('src', source)
				if tools.cc(objpath, srcfile, [args.incdir]):
					exit(1)

		# C++ files
		for source in module.getfiles('src', tools.get('cxx_ext')):
			objpath = os.path.join(objdir, source + '.' + tools.get('obj_ext'))
			objs.append(objpath)

			incdirs = []
			if not os.path.exists(objpath): objmtime = -1
			else: objmtime = os.path.getmtime(objpath)
			depmtime = os.path.getmtime(module.getpath('src', source))
			depmtime = max(depmtime, incmtime)

			if objmtime < depmtime:
				# Make the object directory.
				try: os.makedirs(os.path.dirname(objpath))
				except FileExistsError: True

				# Do the command.
				print('[%s] CXX %s'%(name, source))
				srcfile = module.getpath('src', source)
				if tools.cxx(objpath, srcfile, [args.incdir]):
					exit(1)

		# Assembly with C preprocessor
		for source in module.getfiles('src', tools.get('asmc_ext')):
			objpath = os.path.join(objdir, source + '.' + tools.get('obj_ext'))
			objs.append(objpath)

			incdirs = []
			if not os.path.exists(objpath): objmtime = -1
			else: objmtime = os.path.getmtime(objpath)
			depmtime = os.path.getmtime(module.getpath('src', source))
			depmtime = max(depmtime, incmtime)

			if objmtime < depmtime:
				# Make the object directory.
				try: os.makedirs(os.path.dirname(objpath))
				except FileExistsError: True

				# Do the command.
				print('[%s] ASMC %s'%(name, source))
				srcfile = module.getpath('src', source)
				if tools.asmc(objpath, srcfile, [args.incdir]):
					exit(1)

		# Assembly
		for source in module.getfiles('src', tools.get('asm_ext')):
			objpath = os.path.join(objdir, source + '.' + tools.get('obj_ext'))
			objs.append(objpath)

			if not os.path.exists(objpath): objmtime = -1
			else: objmtime = os.path.getmtime(objpath)
			if objmtime < os.path.getmtime(module.getpath('src', source)):
				# Make the object directory.
				try: os.makedirs(os.path.dirname(objpath))
				except FileExistsError: True

				# Do the command.
				print('[%s] ASM %s'%(name, source))
				if tools.asm(objpath, module.getpath('src', source)):
					exit(1)

	# Make something out of those objects.
	libs = {}
	for name, module in map(lambda x:(x, modules[x]), sorted(modules)):
		objdir = os.path.join('obj',
			name.split('/')[0], name.split('/')[1], '')
		objs = []
		for rt, _, nms in os.walk(objdir):
			for nm in nms:
				objs.append(os.path.join(rt, nm)[len(objdir):])
		objp = list(map(lambda x:os.path.join(objdir, x), objs))

		if module.out[:3] == 'lib':
			lib = module.out[3:]
			if not lib in libs: libs[lib] = []
			libs[lib] += objp
		elif module.out[:3] in ['obj', 'crt']:
			for obj in objs:
				copyfile(os.path.join(objdir, obj),
					os.path.join('obj', obj.split('.')[0] + '.o'))

	# Make the libraries.
	for name in libs:
		libname = 'lib%s.%s'%(name, tools.get('lib_ext'))
		try:
			mtim = os.path.getmtime(os.path.join('obj', libname))
			maxm = max(map(lambda x: os.path.getmtime(x), libs[lib]))
			if mtim > maxm: continue
		except: pass

		print('AR %s'%libname)
		if tools.pack(os.path.join('obj', libname), libs[lib]):
			exit(1)

def install(args):
	pass

	#TODO:
	#try:
	# (installing things)
	#except PermissionError:
	# (check if has admin privileges using `os.getgid() == 0` on Unix
	#  or `win32com.shell.IsUserAnAdmin()` on Windows)
	# (if not, try sudoing the same command)
#*****************************************************************************#
# Main interface.                                                             #
#*****************************************************************************#
def main():
	""" Main function, checks the command and runs the appropriate
		function. """

	# Parse the arguments, get the configuration.
	args = argparser.parse_args()

	# Make the command.
	args.command = args.command.lower()
	if   args.command in ['all', 'build']:
		build(args)
	elif args.command in ['clean']:
		clean(args)
	elif args.command in ['mrproper']:
		mrproper(args)
	elif args.command in ['re', 'rebuild']:
		clean(args)
		build(args)
	else:
		raise InvalidCommandException(args.command)

if __name__ == "__main__":
	do_main(main)

# End of file.