Source

flaggie / lib / flaggie / makeconf.py

Full commit
  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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
#!/usr/bin/python
#	vim:fileencoding=utf-8
# (C) 2010 Michał Górny <gentoo@mgorny.alt.pl>
# Released under the terms of the 2-clause BSD license.

import codecs, os.path, re, string

from .packagefile import PackageFileSet

wsregex = re.compile('(?u)(\s+)')

class MakeConfVariable(object):
	class FlattenedToken(PackageFileSet.PackageFile.PackageEntry):
		class MakeConfFlag(PackageFileSet.PackageFile.PackageEntry.PackageFlag):
			def __init__(self, s, lta = []):
				PackageFileSet.PackageFile.PackageEntry.PackageFlag.__init__( \
					self, s + ''.join([f.toString() for t, f in lta]))

				self._origs = s
				self._partialflags = lta
				self._removed = False

			@property
			def modified(self):
				return self._origs is None

			@modified.setter
			def modified(self, val):
				if val:
					self._origs = None
					for t, pf in self._partialflags:
						t.modified = True
						pf.modified = True
				else:
					raise NotImplementedError('Disable modified for MakeConfFlag is not supported.')

			@property
			def removed(self):
				return self._removed

			@removed.setter
			def removed(self, val):
				# This also cleans up partial flags.
				self.modified = True
				self._removed = val

			@property
			def modifier(self):
				return self._modifier

			@modifier.setter
			def modifier(self, val):
				self._modifier = val
				self.modified = True

			def toString(self, raw = False):
				if self.removed:
					return ''
				elif not self.modified and raw:
					return self._origs
				else:
					return PackageFileSet.PackageFile.PackageEntry.PackageFlag.toString(self)

		class ExpandedFlag(MakeConfFlag):
			def __init__(self, s, use_expanded_from, lta = []):
				self.prefix = '%s_' % use_expanded_from
				MakeConfVariable.FlattenedToken.MakeConfFlag.__init__(self, s, lta)

			@property
			def removed(self):
				return self.modifier == '-'

			@removed.setter
			def removed(self, val):
				self.modifier = '-' if val else ''

			def toString(self, raw = False):
				ret = MakeConfVariable.FlattenedToken.MakeConfFlag.toString(self, raw)
				if raw:
					ret = ret.replace(self.prefix, '', 1)
				elif not ret:
					ret = PackageFileSet.PackageFile.PackageEntry.PackageFlag.toString(self)
				return ret

		class Whitespace(object):
			def __init__(self, s):
				self.s = s

			def toString(self, raw = False):
				return self.s

			@property
			def modified(self):
				return False

		class PartialFlag(Whitespace):
			@property
			def modified(self):
				return not self.s

			@modified.setter
			def modified(self, val):
				if val:
					self.s = ''
				else:
					raise NotImplementedError('Disabling modified for PartialFlag is not supported.')

		def __init__(self, token):
			self.use_expanded = False
			self._token = token
			token.flags = []

		@property
		def data(self):
			return self._token.data

		@property
		def modified(self):
			return self._token.modified

		@modified.setter
		def modified(self, val):
			self._token.modified = val

		@property
		def flags(self):
			return self._token.flags

		def toString(self):
			return self._token.toString()

		def append(self, flag):
			nonempty = bool(self.flags)

			if nonempty and isinstance(self._token, MakeConf.MakeConfFile.UnquotedWord):
				self._token.quoted = True

			if not isinstance(flag, self.MakeConfFlag):
				if self.use_expanded:
					flag = self.ExpandedFlag(flag, self.use_expanded)
				else:
					flag = self.MakeConfFlag(flag)
				if nonempty:
					self.flags.append(self.Whitespace(' '))

			self.flags.append(flag)
			self.modified = True
			return flag

		def __iter__(self):
			""" Iterate over all flags in the entry. """
			for f in reversed(self.flags):
				if isinstance(f, self.MakeConfFlag):
					yield f

		def __delitem__(self, flag):
			""" Remove all occurences of a flag. """
			for f in self.flags:
				if isinstance(f, self.MakeConfFlag) and flag == f.name:
					f.removed = True
					self.modified = True

	def __init__(self, key, tokens):
		def flattentokens(l):
			out = []
			for t in l:
				if isinstance(t, MakeConfVariable):
					out.extend(flattentokens(t._tokens))
				else:
					out.append(self.FlattenedToken(t))
			return out

		self._key = key
		self._tokens = tokens
		self._flattokens = flattentokens(tokens)
		self._parsed = False
		self._useexpanded = {}

	def parseflags(self):
		if self._parsed:
			return
		ftokens = self._flattokens

		fti = iter(ftokens)
		for t in fti:
			nt = None
			while True:
				if nt:
					sl = nsl
					nt = None
				else:
					sl = wsregex.split(t.data)
					# 'flag1 flag2' -> flag1, ' ', flag2
					# ' flag1 flag2' -> '', ' ', flag1, ' ', flag2
					# 'flag1 flag2 ' -> flag1, ' ', flag2, ' ', ''
					# ' ' -> '', ' ', ''
					# '' -> ''

				lta = []
				if sl[-1]:
					while True:
						try:
							nt = next(fti)
						except StopIteration:
							nt = None
							break
						else:
							nsl = wsregex.split(nt.data)
							if len(nsl) == 1 and not nsl[0]:
								pass
							elif not nsl[0]: # the whitespace we were hoping for
								break
							else:
								pf = self.FlattenedToken.PartialFlag(nsl[0])
								nt.flags.append(pf)
								lta.append((nt, pf))
								if len(nsl) != 1:
									nsl[0] = ''
									break

				lasti = len(sl) - 1
				for i, e in enumerate(sl):
					if i%2 == 0:
						if e:
							strippedtoken = e.lstrip('+-')
							if t.use_expanded:
								flagname = '%s_%s' % (t.use_expanded, e)
								if lta and i == lasti:
									flag = self.FlattenedToken.ExpandedFlag(
										flagname, t.use_expanded, lta)
								else:
									flag = self.FlattenedToken.ExpandedFlag(
										flagname, t.use_expanded)
								self._useexpanded[t.use_expanded].discard(flag.name)
							elif [x for x in self._useexpanded if strippedtoken.startswith(x)]:
								# inactive due to USE_EXPAND
								flag = self.FlattenedToken.PartialFlag(e)
							elif lta and i == lasti:
								flag = self.FlattenedToken.MakeConfFlag(e, lta)
							else:
								flag = self.FlattenedToken.MakeConfFlag(e)
							t.flags.append(flag)
					else:
						t.flags.append(self.FlattenedToken.Whitespace(e))

				if nt:
					t = nt
				else:
					break

		# Add disabled USE_EXPAND flags.
		for t in reversed(self._flattokens):
			if t.use_expanded in self._useexpanded:
				for f in self._useexpanded.pop(t.use_expanded):
					t.append('-%s' % f)
				t.modified = False

		self._parsed = True

	def add_expand(self, var, flagcache):
		if self._parsed:
			raise NotImplementedError('Appending to a parsed variable not supported')

		key = var._key.lower()
		values = [f for f in flagcache.glob if f.startswith(key)]
		self._useexpanded[key] = set(values)

		newtokens = []
		for t in var._flattokens:
			t.use_expanded = key
			newtokens.append(t)
		newtokens.append(self.FlattenedToken(MakeConf.MakeConfFile.Whitespace(' ')))
		newtokens.extend(self._flattokens)
		self._flattokens = newtokens

	def __iter__(self):
		self.parseflags()

		for t in reversed(self._flattokens):
			yield t

	def __repr__(self):
		return 'MakeConfVariable(%s, %s)' % (self._key, self._tokens)

class FakeVariable(MakeConfVariable):
	def __init__(self, key):
		MakeConfVariable.__init__(self, key,
			(MakeConf.MakeConfFile.DoubleQuotedString(''),))

class NewVariable(FakeVariable):
	def __init__(self, key):
		FakeVariable.__init__(self, key)

	@property
	def key(self):
		return self._key

class MakeConf(object):
	class NewMakeConfFile(PackageFileSet.PackageFile):
		class Token(object):
			def __init__(self, s = ''):
				self._modified = False
				self.s = s

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

			def __eq__(self, other):
				return self.s == other

			def __iadd__(self, s):
				self.s += s
				return self

			@property
			def modified(self):
				return self._modified

			@modified.setter
			def modified(self, val):
				self._modified = val

			@property
			def data(self):
				if self.modified:
					hadremovedflag = False
					ret = ''
					fi = iter(self.flags)
					for f in fi:
						while f is not None:
							nf = None
							if isinstance(f, MakeConfVariable.FlattenedToken.MakeConfFlag) and \
									f.removed:
								hadremovedflag = not hadremovedflag
							else:
								if isinstance(f, MakeConfVariable.FlattenedToken.Whitespace):
									if not hadremovedflag:
										try:
											nf = next(fi)
										except StopIteration:
											pass
										else:
											# Drop whitespace before the flag.
											if isinstance(f, MakeConfVariable.FlattenedToken.MakeConfFlag) and \
													nf.removed:
												# Reverse to not drop whitespace after it.
												hadremovedflag = True
												f = nf
												continue
									else:
										# Drop whitespace after the flag.
										hadremovedflag = False
										f = nf
										continue

								ret += f.toString(True)
								hadremovedflag = False
							f = nf

					return ret
				else:
					return self.s

			def toString(self):
				return self.data

			def __repr__(self):
				return '%s(%s)' % (self.__class__.__name__, self.toString())

		class Whitespace(Token):
			def hasNL(self):
				return '\n' in self.data

		class UnquotedWord(Token):
			quoted = False

			def toString(self):
				if self.quoted:
					return '"%s"' % self.data
				else:
					return self.data

		class VariableRef(UnquotedWord):
			def toString(self):
				return '$%s' % self.s

			@property
			def data(self):
				ret = self.s
				if ret.startswith('{') and ret.endswith('}'):
					return ret[1:-1]
				return ret

		class QuotedString(Token):
			def toString(self):
				raise NotImplementedError('QuotedString.toString() needs to be overriden')

		class SingleQuotedString(QuotedString):
			def toString(self):
				return "'%s'" % self.data

		class DoubleQuotedString(QuotedString):
			lquo = True
			rquo = True

			def toString(self):
				out = ''
				if self.lquo:
					out += '"'
				out += self.data
				if self.rquo:
					out += '"'

				return out

		class DoubleQuotedVariableRef(VariableRef, DoubleQuotedString):
			@property
			def data(self):
				return self.s

		class DoubleQuotedBracedVariableRef(DoubleQuotedVariableRef):
			def toString(self):
				return '${%s}' % self.data

		@property
		def data(self):
			data = ''
			for l in self:
				data += l.toString()
			return data

		def __init__(self, path):
			list.__init__(self)
			self.path = path
			# not used in MakeConfFile
			self._modified = False
			self.trailing_whitespace = []

	class MakeConfFile(NewMakeConfFile):
		def __init__(self, path, basedir = None):
			MakeConf.NewMakeConfFile.__init__(self, path)

			def newtoken(kind, oldtoken = None):
				if isinstance(oldtoken, kind):
					return oldtoken

				token = kind()
				self.append(token)
				return token

			token = None
			if basedir:
				path = os.path.join(basedir, path)
			f = codecs.open(path, 'r', 'utf8')
			for l in f:
				if not isinstance(token, self.QuotedString) and l.startswith('#'):
					token = newtoken(self.Whitespace, token)
					token += l
					continue

				ci = iter(l)
				for c in ci:
					if c == '\\':
						if not isinstance(token, self.QuotedString):
							token = newtoken(self.UnquotedWord, token)
						try:
							token += c + next(ci)
						except StopIteration:
							token += c
					elif not isinstance(token, self.QuotedString):
						if c in string.whitespace:
							token = newtoken(self.Whitespace, token)
							token += c
						elif c == "'":
							token = newtoken(self.SingleQuotedString)
						elif c == '"':
							token = newtoken(self.DoubleQuotedString)
						elif c == '$':
							token = newtoken(self.VariableRef, token)
						else:
							token = newtoken(self.UnquotedWord, token)
							token += c
							if c == '=':
								token = None
					elif isinstance(token, self.SingleQuotedString) and c == "'":
						token = None
					elif isinstance(token, self.DoubleQuotedString) and c == '"':
						if isinstance(token, self.DoubleQuotedVariableRef):
							tmp = newtoken(self.DoubleQuotedString)
							tmp.lquo = False
						token = None
					elif isinstance(token, self.DoubleQuotedBracedVariableRef) and c == '}':
						token = newtoken(self.DoubleQuotedString)
						token.lquo = False
					elif isinstance(token, self.DoubleQuotedVariableRef) and c in string.whitespace:
						token = newtoken(self.DoubleQuotedString)
						token.lquo = False
						token += c
					elif c == '$':
						try:
							n = next(ci)
						except StopIteration:
							token += c
						else:
							if n in string.whitespace:
								token += c + n
							else:
								token.rquo = False
								if n == '{':
									token = newtoken(self.DoubleQuotedBracedVariableRef)
								else:
									token = newtoken(self.DoubleQuotedVariableRef)
									token += n
					else:
						token += c

			f.close()

	def __init__(self, paths, dbapi, caches = None):
		self.files = {}
		self.variables = {}
		self.newvars = []
		self.masterfile = None

		try:
			flagcache = caches['use']
			use_expand_vars = frozenset(flagcache.use_expand_vars)
		except (KeyError, TypeError):
			flagcache = None
			use_expand_vars = frozenset()

		for path in paths:
			if os.path.exists(path):
				mf = self.MakeConfFile(path)
				self.files[path] = mf
				self.parse(mf, path)
				self.masterfile = mf

		if not self.masterfile:
			path = paths[0]
			mf = self.NewMakeConfFile(path)
			self.files[path] = mf
			self.masterfile = mf

		for key in use_expand_vars:
			if key in self.variables:
				self.variables['USE'].add_expand(self.variables[key],
						flagcache)

	def parse(self, mf, path):
		# 1) group tokens in lines
		lines = []
		words = []
		tokens = []
		for t in mf:
			if isinstance(t, self.MakeConfFile.Whitespace):
				if tokens:
					words.append(tokens)
					tokens = []
				if t.hasNL():
					if words:
						lines.append(words)
						words = []
			else:
				tokens.append(t)
		else:
			if tokens:
				words.append(tokens)
			if words:
				lines.append(words)

		def join(words):
			return ''.join([t.data for t in words])

		# 2) now go for it
		for l in lines:
			joined = join(l[0])
			if joined == 'source':
				fn = join(l[1])
				if fn not in self.files:
					self.files[fn] = self.MakeConfFile(fn, path)
				self.parse(self.files[fn], fn)
				continue
			elif joined == 'export':
				assignm = l[1]
			else:
				assignm = l[0]
			
			for i, t in enumerate(assignm):
				if isinstance(t, self.MakeConfFile.UnquotedWord) and t.data.endswith('='):
					key = join(assignm[:i+1])[:-1]
					val = []

					for t in assignm[i+1:]:
						if isinstance(t, self.MakeConfFile.VariableRef):
							try:
								val.append(self.variables[t.data])
							except KeyError:
								pass
						else:
							val.append(t)

					self.variables[key] = MakeConfVariable(key, val)
					break

	def __getitem__(self, k):
		if k == 'env': # env not supported as a global var
			return FakeVariable('DUMMY_%s' % k.upper())

		kmap = {
			'use': 'USE',
			'kw': 'ACCEPT_KEYWORDS',
			'lic': 'ACCEPT_LICENSE'
		}
		varname = kmap[k]

		if varname not in self.variables:
			nv = NewVariable(varname)
			self.newvars.append(nv)
			self.variables[varname] = nv

		return self.variables[varname]

	def write(self):
		for nv in self.newvars:
			for t in nv:
				if t.modified:
					nl = self.MakeConfFile.Whitespace('\n')
					out = []
					if self.masterfile:
						lt = self.masterfile[-1]
						if not isinstance(lt, self.MakeConfFile.Whitespace) or not lt.hasNL():
							out.append(nl)

					out.append(self.MakeConfFile.UnquotedWord('%s=' % nv.key))
					out.extend(list(nv))
					out.append(nl)

					self.masterfile.extend(out)
					break

		for f in self.files.values():
			f.write()