aboutsummaryrefslogtreecommitdiff
path: root/sgdfi/objects/object.py
blob: a20f7e575ff62da0f2b016e6c6fee90d7e8cd83c (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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
#!/usr/bin/env python3
#******************************************************************************
# Copyright (C) 2021 Thomas Touhey <thomas@touhey.fr>
# This file is part of the sgdfi project, which is MIT-licensed.
#******************************************************************************
""" Outils pour définir un objet avec nos propriétés. En grande partie
	tiré de thblog, moteur de blog statique par le même auteur. """

from enum import Enum as _Enum
from datetime import datetime as _datetime
from collections.abc import MutableSequence as _MutableSequence

from pytz import timezone as _timezone
from dateutil.parser import parse as _parsedate

__all__ = ['Object',
	'Property', 'TextProperty', 'BoolProperty', 'DateProperty',
	'ObjectProperty', 'DataProperty', 'EnumProperty']

_paristz = _timezone('Europe/Paris')

class _DummyPropertyData:
	__slots__ = ()

	def __init__(self, *args, **kwargs):
		raise NotImplementedError

class _Array(_MutableSequence):
	""" Un tableau d'objets pouvant être limité à certains types. """

	def __init__(self, types = ()):
		self._list  = []
		self._types = types

	def __repr__(self):
		return repr(self._list)

	def __iter__(self):
		return iter(self._list)

	def __len__(self):
		return len(self._list)

	def __getitem__(self, key):
		return self._list[key]

	def __setitem__(self, key, value):
		try:
			if self._list[key] is value:
				return
		except KeyError:
			pass

		self._assert_if_invalid_or_present(value)
		self._list[key] = value

	def __delitem__(self, key):
		del self._list[key]

	def _assert_if_invalid_or_present(self, value):
		if self._types:
			if all(not isinstance(value, t) for t in self._types):
				raise TypeError("element to add is of forbidden type "
					f"{type(value)}")

		if any(value is e or value == e for e in self._list):
			raise ValueError("element already inserted")

	def insert(self, index, value):
		self._assert_if_invalid_or_present(value)
		self._list.insert(index, value)

# ---
# Définition des propriétés.
# ---

class Property:
	""" Une propriété, pour usage par les objets définis dans sgdfi. """

	__slots__ = ('_doc',)

	def __init__(self, *_, doc: str = None):
		self._doc = doc

	def __repr__(self):
		def repr_iter():
			for key, value in self.__dict__.items():
				if key.startswith('__'):
					continue
				if value is None:
					continue

				key = key[1:] if key.startswith('_') else key
				yield f"{key} = {repr(value)}"

		return f"{self.__class__.__name__}({', '.join(repr_iter())})"

	def value(self, value = None):
		""" Normalize une valeur, ou lève une exception si la valeur
			donnée n'a pas pu être être interprétée pour la propriété
			courante.

			Cette méthode doit être définie par les classes filles. """

		raise NotImplementedError

	def doc(self) -> str:
		""" Retourne la docstring pour la propriété courante. """

		return self._doc


class TextProperty(Property):
	""" Une propriété contenant du texte arbitraire.

		:param lines: Nombre maximal de lignes autorisées dans le texte ;
		              0 indique un nombre infini.
		:type lines: int
		:param maxchars: Nombre maximal de caractères autorisés dans le texte ;
		                 0 indique un nombre infini. Les retours à la ligne
		                 comptent comme un caractère.
		:type maxchars: int
		:param not_empty: Selon si les textes vides sont interdits ou non.
		:type not_empty: bool """

	__slots__ = ('_lines', '_maxchars', '_not_empty')

	def __init__(self, *args, lines = 0, maxchars = 0,
		not_empty = False, **kwargs):
		super().__init__(*args, **kwargs)

		self._lines = lines
		self._maxchars = maxchars
		self._not_empty = not_empty

	def value(self, x):
		# First, we convert to boolean with the original type and check
		# if it evaluates to False; this checks for None values.
		#
		# Then, we convert to strings and check for empty strings.

		if x is None:
			if self._not_empty:
				raise ValueError("empty values aren't allowed")

			return None

		x = str(x)

		if self._not_empty and not x:
			raise ValueError("empty values aren't allowed")

		# We split lines and check for the related constraint.

		x = x.splitlines()
		if self._lines and len(x) > self._lines:
			raise ValueError(f"too many lines ({self._lines} allowed, "
				f"got {len(x)}")

		x = '\n'.join(x)

		# We check for the max number of characters.

		if self._maxchars and len(x) > self._maxchars:
			raise ValueError(f"too many characters ({self._maxchars} allowed, "
				f"got {len(x)}")

		return x


class BoolProperty(Property):
	""" Une propriété contenant un booléen. """

	__slots__ = ('_default',)

	def __init__(self, *args, default = False, **kwargs):
		super().__init__(*args, **kwargs)
		self._default = default

	def value(self, value = None):
		if value is None:
			return self._default
		else:
			return bool(value)


class DateProperty(Property):
	""" Une propriété contenant un timestamp basé sur un fuseau horaire
		donné ; par défaut, celui de Paris. """

	__slots__ = ('_tz',)

	def __init__(self, *args, timezone = _paristz, **kwargs):
		super().__init__(*args, **kwargs)
		self._tz = timezone

	def value(self, x = None):
		if x is None:
			return None

		if not isinstance(x, _datetime):
			try:
				return _parsedate(x, dayfirst = True)
			except:
				raise ValueError("invalid date")

		if x.tzinfo is None:
			x = x.replace(tzinfo = self._tz)

		return x


class ObjectProperty(Property):
	""" Une propriété contenant une instance d'une classe donnée. """

	__slots__ = ('_types')

	def __init__(self, *args, types = (), **kwargs):
		super().__init__(self, *args, **kwargs)
		self._types = types

	def value(self, value = None):
		if value is None:
			if self._types:
				return next(iter(self._types))()
			return None
		if all(not isinstance(value, cls) for cls in self._types):
			raise TypeError("expected an instance of one of: "
				+ ', '.join(cls.__name__ for cls in self._types))
		return value


class DataProperty(Property):
	""" Une propriété contenant une instance d'un objet instancié
		à l'aide d'une valeur donné (constructeur doté d'un paramètre
		positionnel unique). """

	__slots__ = ()
	cls = _DummyPropertyData

	def __init__(self, *args, **kwargs):
		super().__init__(*args, **kwargs)

	def value(self, value = None):
		if value is None:
			return None
		return type(self).cls(value)


class ArrayProperty(Property):
	""" Une propriété contenant un tableau dont les éléments sont des
		instances de classes données. """

	__slots__ = ('_types')

	def __init__(self, *args, types = (), **kwargs):
		super().__init__(*args, **kwargs)
		self._types = types

	def value(self, value = None):
		array = _Array(self._types)

		if value is not None:
			for element in value:
				array.append(element)

		return array


class EnumProperty(Property):
	""" Une propriété contenant une valeur d'une énumération. """

	__slots__ = ('_default',)
	_enum = _Enum

	def __init__(self, *args, default = None, **kwargs):
		super().__init__(*args, **kwargs)

		if default is not None:
			try:
				default = enum(default)
			except ValueError:
				raise ValueError("Default should be None or a "
					"valid enum value.") from None

		self._default = default

	def value(self, value = None):
		if value is None:
			return None

		return type(self)._enum(value)

# ---
# Object definition.
# ---

class _ObjectType(type):
	""" La métaclasse d'un objet de SGDFi. """

	__slots__ = ()

	def __new__(mcls, clsname, superclasses, attributedict):
		newattributedict = {}
		properties = {}

		# Get the properties.

		for key, prop in attributedict.items():
			if key.startswith('__') and key.endswith('__'):
				continue

			if key.startswith('_') or key.endswith('_'):
				raise ValueError(f"member {repr(key)} has an "
					"invalid name")
			if not all(char in 'abcdefghijklmnopqrstuvwxyz0123456789_'
				for char in key):
				raise ValueError(f"member {repr(key)} has an "
					"invalid name")

			try:
				key.index('__')
			except ValueError:
				pass
			else:
				raise ValueError(f"member {repr(key)} has an "
					 "invalid name") from None

			if not isinstance(prop, Property):
				raise TypeError(f"member {repr(key)} of {clsname} "
					"isn't an instance of Property")

			properties[key] = prop

		# Add the properties to the class.

		for key, prop in properties.items():
			def define_property(key, prop):
				""" This function is used to capture the value of key and
					prop, which could be a trap in a higher scope. """

				fget = lambda self: getattr(self, f"_{key}")
				fset = (lambda self, value: setattr(self, f"_{key}",
					prop.value(value)))
				fdel = lambda self: setattr(self, f"_{key}", prop.value(None))

				try:
					mdoc = prop.doc()
				except:
					mdoc = None

				return property(fget, fset, fdel, mdoc)

			newattributedict[key] = define_property(key, prop)

		# Add some special methods.

		def init_func(self, **kwargs):
			for key, prop in properties.items():
				setattr(self, f"_{key}", prop.value(None))

			for key, value in kwargs.items():
				try:
					prop = properties[key]
				except KeyError:
					raise TypeError("__init__() got an unexpected keyword "
						f"argument {repr(key)}") from None

				setattr(self, f"_{key}", prop.value(value))

		def repr_func(self):
			def repr_iter():
				for attribute in properties:
					yield f"{attribute} = {repr(getattr(self, attribute))}"

			return f"{self.__class__.__name__}({', '.join(repr_iter())})"

		newattributedict['__slots__'] = tuple(f"_{key}" for key in properties)
		newattributedict['__doc__'] = attributedict.get('__doc__', '')

		newattributedict['__properties__'] = properties

		newattributedict['__init__'] = init_func
		newattributedict['__repr__'] = repr_func

		# Done!

		return type.__new__(mcls, clsname, superclasses, newattributedict)

	def __repr__(self):
		def repr_iter():
			for key, value in self.__properties__.items():
				yield f"{key} = {repr(value)}"

		return f"Object({', '.join(repr_iter())})"

	def __setattr__(self, key, value):
		raise AttributeError("can't change properties after class definition")

	def __delattr__(self, key):
		raise AttributeError("can't change properties after class definition")

class Object(metaclass = _ObjectType):
	""" Un objet dans SGDFi ; sert de base à la plupart des
		représentations. """

	pass

# End of file.