aboutsummaryrefslogtreecommitdiff
path: root/tools/Internals/module.py
blob: e44185fc5e862c2038a3158bcff6ba47a0c33185 (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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
#!/usr/bin/env python3
""" The main thing about libcarrot's organization, if you haven't understood
	yet, is that it works using modules. This is the main management file
	for modules: module object, finding modules out of user configuration
	options, and gather modules out of a list.

	The used configuration formats are in `FORMATS.md`.
"""

import os, sys
import yaml

from time import time
from .exceptions import *

class SourceModule:
	""" The source module class.
		Extracts data from the filesystem, and offer utilities to interact
		with its elements easily.
	"""

	def __init__(self, root, name, platform = None, mtim = None):
		""" Initialize the class, gather the information from the platform
			then the module configuration, and deduce module properties
			out of it.

			`root` is the module root (e.g. `./arch/casiowin/fxlib`).
			`name` is the module name, e.g. `casiowin/fxlib`.
			`mtim` is the reference modification time for the user config.
			`platform` is the platform containing the module.
		"""

		# Open the module configuration.
		mconfigpath = os.path.join(root, 'info.yml')
		try:
			mconfig = yaml.load(open(mconfigpath))
		except (NotADirectoryError, FileNotFoundError):
			Raise(ModuleNotFoundException(name))

		# Check the difference to the reference time.
		if mtim != None:
			if os.path.getmtime(mconfigpath) > mtim:
				Raise(UpdatedModuleException(name))

		# Check the magic.
		if 'magic' in mconfig and mconfig['magic'] != 'potatosdk-1.0':
			Raise(PlatformNotFoundException(name))

		# Keep the arguments.
		self.root = root
		self.name = name
		self.__root = root
		self.mtim = os.path.getmtime(mconfigpath)

		# Get the usual things.
		self.description = mconfig['description']
		self.out = mconfig['out'] if 'out' in mconfig else 'libc'
		self.deps = mconfig['deps'] if 'deps' in mconfig else []
		self.conflicts = mconfig['conflicts'] if 'conflicts' in mconfig else []

		# Get the requirements.
		self.compilers = []
		self.arch = []
		if 'requires' in mconfig:
			r = mconfig['requires']
			if 'compiler' in r:
				self.compilers = r['compiler']
			if 'arch' in r:
				self.arch = r['arch']
		if not self.arch and platform.arch:
			self.arch = platform.arch

		self.roles = {}
		rpath = os.path.join(root, 'roles.yml')
		try:
			with open(rpath) as f:
				raw = yaml.load(f.read())
				self.roles = self.__go_through_dirs(raw)
		except (IsADirectoryError, FileNotFoundError):
			pass

	def __go_through_dirs(self, roles, prefix=()):
		""" Read a roles file. """

		elements = {}
		for key, element in roles.items():
			key = prefix + (key,)
			if type(element) == dict:
				elements.update(self.__go_through_dirs(element, key))
			else:
				elements[key] = element
		return elements

	def getpath(self, *elements):
		""" Get the complete path within a directory. """

		# Get the root, adjust the elements if necessary.
		rt = self.__root
		if elements and elements[0] == 'obj':
			rt = self.__objroot
			elements = elements[1:]

		# Join it all and send it back!
		return os.path.join(rt, *elements)

	def getfiles(self, *path, ext=[], full=False):
		""" Get the list of files in a directory. """

		# Get the root.
		root = os.path.join(self.getpath(*path), '')

		# Get the source files.
		files = []
		for r, _, filenames in os.walk(root):
			if not full:
				r = r[len(root):]

			for name in filenames:
				pos = name.find('.')
				if   pos <  0 and not None in ext:
					continue
				elif pos >= 0 and not name[pos + 1:].lower() in ext:
					continue
				files.append(os.path.join(r, name))

		return files

class SourcePlatform:
	""" The source platform class.
		Extracts data from the filesystem, and offer utilities to interact
		with its element easily.
	"""

	def __init__(self, root, name, glob = None, mtim = None):
		""" Initialize the class, gather the information from the platform
			configuration, and deduce properties out of it.

			`root` is the platform root (generally `./arch/casiowin`).
			`name` is the platform name, e.g. `casiowin`.
			`mtim` is the reference modification time for the user config.
		"""

		# Check that it is a platform, load the configuration.
		pconfigpath = os.path.join(root, 'info.yml')
		try:
			pconfig = yaml.load(open(pconfigpath))
		except (NotADirectoryError, FileNotFoundError):
			Raise(PlatformNotFoundException(name))

		# Check the difference to the reference time.
		if mtim != None:
			if os.path.getmtime(pconfigpath) > mtim:
				Raise(UpdatedPlatformException(name))

		# Check the magic.
		if 'magic' in pconfig and pconfig['magic'] != 'potatosdk-1.0':
			Raise(PlatformNotFoundException(name))

		# Keep the arguments.
		self.__root = root
		self.__name = name
		self.__mtim = mtim

		# Get the properties.
		self.description = pconfig['description']
		self.defaults = pconfig['default'] if 'default' in pconfig else []
		self.arch = []
		if 'requires' in pconfig:
			r = pconfig['requires']
			if 'arch' in r:
				self.arch = r['arch']

		# Loaded modules.
		self.__loaded = {}

	def getmodule(self, name):
		""" Load a submodule, e.g. "fxlib" for the "casiowin/fxlib" module. """

		if name in self.__loaded:
			return self.__loaded[name]
		module = SourceModule(os.path.join(self.__root, name),
			'%s/%s'%(self.__name, name), self, self.__mtim)
		self.__loaded[name] = module
		return module

	def getallmodules(self):
		""" Load all of the submodules. """

		modules = {}
		for name in os.listdir(self.__root):
			try: module = self.getmodule(name)
			except ModuleNotFoundException: continue
			modules[name] = module
		return modules

class SourceGlobal:
	""" The global source class.
		Extracts data from the filesystem. """

	def __init__(self, root, mtim = None):
		""" Initialize the class, gather the information about the source,
			and deduce properties out of it.

			`root` is the modules root (generally `./arch`).
			`mtim` is the reference modification time for the user config.
		"""

		# Open the global configuration.
		gconfigpath = os.path.join(root, 'info.yml')
		try:
			gconfig = yaml.load(open(gconfigpath))
		except (NotADirectoryError, FileNotFoundError):
			Raise(GlobalNotFoundException)

		# Check the difference to the reference time.
		if mtim != None:
			if os.path.getmtime(gconfigpath) > mtim:
				Raise(UpdatedGlobalException)

		# Check the magic.
		if 'magic' in gconfig and gconfig['magic'] != 'potatosdk-1.0':
			Raise(GlobalNotFoundException)

		# Keep the arguments.
		self.__root = root
		self.__mtim = mtim

		# Get the properties.
		self.version = gconfig['version']
		self.description = gconfig['description']
		self.arch = gconfig['arch']

		# Loaded platforms.
		self.__loaded = {}

	def getplatform(self, name):
		""" Get a platform using its name, e.g. "casiowin". """

		if name in self.__loaded:
			return self.__loaded[name]

		platform = SourcePlatform(os.path.join(self.__root, name),
			name, self, self.__mtim)
		self.__loaded[name] = platform
		return platform

	def getallplatforms(self):
		""" Get all of the existing platforms. """

		platforms = {}
		for name in os.listdir(self.__root):
			try: platform = self.getplatform(name)
			except PlatformNotFoundException: continue
			platforms[name] = platform
		return platforms

	def getmodule(self, name):
		""" Get a module. """

		platform_name, module_name = name.split('/')
		platform = self.getplatform(platform_name)
		return platform.getmodule(module_name)

	def getmodules(self, names):
		""" Get a list of modules. """

		modules = {}
		for name in names:
			modules[name] = self.getmodule(name)
		return modules

	def getallmodules(self):
		""" Get all of the existing modules. """

		modules = {}
		for platform_name, platform in self.getallplatforms().items():
			for module_name, module in platform.getallmodules().items():
				modules['%s/%s'%(platform_name, module_name)] = module
		return modules

	def findmodules(self, arch, platform = None,
			compiler = ('GNU', 'GCC'), languages = ['c', 'c++'],
			addition = []):
		""" Find modules corresponding to a query, based on:
			- `arch`:      the architecture for which to build;
			- `platform`:  the platform for which to build;
			- `compiler`:  the C/C++ compiler with and for which to build;
			- `languages`: the programming languages for which to
			               offer support;
			- `addition`:  the additional modules to include. """

		modules = {}

		# In 'hand-written' information files, the user ain't using the
		# '!!python/tuple' trick, so we're just going to use a list instead
		# of a tuple.
		compiler = list(compiler)

		# Get the language defaults for the platforms.
		# 'dp' means 'default platforms', 'pn' means 'platform name'.
		default = {'c': [], 'c++': []}
		dp = ['all']
		if platform:
			dp.append(platform)
		for pn in dp:
			p = self.getplatform(pn)
			if p.arch and not arch in p.arch:
				Raise(UnsupportedArchForPlatformException(arch, pn))
			if 'c' in p.defaults:
				default['c']   += p.defaults['c']
				default['c++'] += p.defaults['c']
			if 'c++' in p.defaults:
				default['c++'] += p.defaults['c++']

		# Gather the additional modules.
		for name in set(addition):
			module = self.getmodule(name)
			if module.arch and not arch in module.arch:
				Raise(UnsupportedArchForModuleException(name, arch))
				continue
			if module.compiler and not compiler in module.compiler:
				Raise(UnsupportedCompilerForModuleException(name, compiler))
				continue
			modules[name] = module

		# Gather the defaults for the languages.
		# 'dm' means 'default modules', 'ldm' means 'language default modules'.
		dm = []
		for ldm in map(lambda x:default[x], languages):
			dm.extend(ldm)
		for name in dm:
			module = self.getmodule(name)
			if module.arch and not arch in module.arch:
				continue
			if module.compilers and not compiler in module.compilers:
				continue
			modules[name] = module

		# Gather the dependencies.
		# 'newdeps' is a list of tuples, where the first element of each tuple
		# is the name of the module to gather, and the second is modules from
		# which the dependency comes from (for logging).
		newdeps = []
		blacklist = []
		while True:
			# Get the previous dependencies.
			for dep in newdeps:
				name = dep[0]
				try:
					module = self.getmodule(name)
				except (PlatformNotFoundException, ModuleNotFoundException):
					Raise(UnresolvedDependencyException(name, dep[1]))
					blacklist.append(name)
					continue

				if   module.arch and not arch in module.arch:
					blacklist.append(name)
				elif module.compiler and not compiler in module.compiler:
					blacklist.append(name)
				else:
					modules[name] = module
			newdeps = []

			# Check the dependencies.
			for name, module in modules.items():
				for dep in module.deps:
					if not dep in modules and not dep in blacklist:
						try: ndep = next(i for i in newdeps if i[0] == dep)
						except: newdeps.append([dep, [name]])
						else: ndep[1].append(name)

			# No dependency? Good!
			if not newdeps:
				break

		# TODO: check conflicts.
		# We're done!
		return modules

# End of file.