aboutsummaryrefslogtreecommitdiff
blob: 55732c428e80f21b2874b6d6ff73ddb1220bdf6d (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
# R overlay -- simple dependency rules
# Copyright 2006-2012 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2

import re
import logging

from roverlay.depres import deprule

TMP_LOGGER = logging.getLogger ('simpledeps')

class SimpleIgnoreDependencyRule ( deprule.DependencyRule ):
	"""A dependency rule that represents an ignored package in portage."""

	def __init__ ( self, dep_str=None, priority=50 ):
		"""Initializes a SimpleIgnoreDependencyRule.

		arguments:
		* dep_str -- a dependency string that this rule is able to resolve
		* priority -- priority of this rule
		"""
		super ( SimpleIgnoreDependencyRule, self ) . __init__ ( priority )
		self.dep_alias = set ()

		self.logger = TMP_LOGGER.getChild ( 'IGNORE_DEPS' )

		if not dep_str is None:
			self.dep_alias.add ( dep_str )

	# --- end of __init__ (...) ---

	def add_resolved ( self, dep_str ):
		"""Adds an dependency string that should be matched by this rule.

		arguments:
		* dep_str --
		"""
		self.dep_alias.add ( dep_str )
	# --- end of add_resolved (...) ---

	def matches ( self, dep_env, lowercase=True ):
		"""Returns True if this rule matches the given DepEnv, else False.

		arguments:
		* dep_env --
		* lowercase -- if True: be case-insensitive when iterating over all
		               stored dep_strings
		"""

		def logmatch ( score=self.max_score ):
			"""Wrapper function that logs a successful match and
			returns its score.

			arguments:
			* score -- score of this match, defaults to self.max_score
			"""

			self.logger.debug ( "matches %s with score %i and priority %i." %
				( dep_env.dep_str, score, self.priority )
			)
			return score
		# --- end of logmatch (...) ---

		if lowercase:
			#lower_dep_str = dep_env.dep_str.lower()
			for alias in self.dep_alias:
				if alias.lower() == dep_env.dep_str_low:
					return logmatch ()
		elif dep_env.dep_str in self.dep_alias:
			return logmatch ()

		return 0
	# --- end of matches (...) ---

	def get_dep ( self ):
		"""Returns the textual portage package representation of this rule,
		which is None 'cause this is an ignored dependency.
		"""
		return None
	# --- end of get_dep (...) ---

	def export_rule ( self, resolving_to=None ):
		"""Returns this rule as a list of text lines that can be written into
		a file.
		An empty list will be returned if dep_alias has zero length.

		arguments:
		* resolving_to -- portage package that the exported rule should
		                  resolve to, defaults to self.resolving_package or
		                  an ignore keyword such as '!'.
		"""

		alias_count = len ( self.dep_alias )

		retlist = []

		if alias_count:
			if resolving_to is None:
				if hasattr ( self, 'resolving_package'):
					resolving_package = self.resolving_package
				else:
					resolving_package = '!'
			else:
				resolving_package = resolving_to

			# todo hardcoded here
			if alias_count > 1:

				retlist = [ resolving_package + ' {\n' ] + \
					[ "\t%s\n" % alias for alias in self.dep_alias ] + \
					[ '}\n' ]
			else:
				retlist = [
					"%s :: %s\n" % ( resolving_package, self.dep_alias [0] )
				]

		# -- if

		return retlist
	# --- end of export_rule (...) ---


class SimpleDependencyRule ( SimpleIgnoreDependencyRule ):

	def __init__ ( self, resolving_package, dep_str=None, priority=70 ):
		"""Initializes a SimpleDependencyRule. This is
		a SimpleIgnoreDependencyRule extended by a portage package string.

		arguments:
		* resolving package --
		* dep_str --
		* priority --
		"""
		super ( SimpleDependencyRule, self ) . __init__ (
			dep_str=dep_str, priority=priority
		)

		self.resolving_package = resolving_package

		self.logger = TMP_LOGGER.getChild ( resolving_package )

	# --- end of __init__ (...) ---

	def get_dep ( self ):
		"""Returns the textual portage package representation of this rule,
		e.g. 'dev-lang/R'.
		"""
		return self.resolving_package
	# --- end of get_dep (...) ---


class SimpleDependencyRulePool ( deprule.DependencyRulePool ):

	def __init__ ( self, name, priority=70, filepath=None ):
		"""Initializes a SimpleDependencyRulePool, which is a DependencyRulePool
		specialized in simple dependency rules;
		it offers loading rules from files.

		arguments:
		* name     -- string identifier for this pool
		* priority -- of this pool
		* filepath -- if set and not None: load a rule file directly
		"""
		super ( SimpleDependencyRulePool, self ) . __init__ ( name, priority )

		if not filepath is None:
			self.load_rule_file ( filepath )

	# --- end of __init__ (...) ---

	def add ( self, rule ):
		"""Adds a rule to this pool.
		Its class has to be SimpleIgnoreDependencyRule or derived from it.

		arguments:
		* rule --
		"""
		if isinstance ( rule, SimpleIgnoreDependencyRule ):
			self.rules.append ( rule )
		else:
			raise Exception ( "bad usage (simple dependency rule expected)." )

	# --- end of add (...) ---

	def load_rule_file ( self, filepath ):
		"""Loads a rule file and adds the read rules to this pool.

		arguments:
		* filepath -- file to read
		"""
		reader = SimpleDependencyRuleReader()

		new_rules = reader.read_file ( filepath )
		for rule in new_rules:
			self.add ( rule )

	# --- end of load_rule_file (...) ---

	def export_rules ( self, fh ):
		"""Exports all rules from this pool into the given file handle.

		arguments:
		* fh -- object that has a writelines ( list ) method

		raises: IOError (fh)
		"""
		for rule in self.rules:
			to_write = fh.export_rule()
			if isinstance ( to_write, str ):
				fh.write ( to_write )
			else:
				fh.writelines ( to_write )

	# --- end of export_rules (...) ---


class SimpleDependencyRuleReader ( object ):

	one_line_separator = re.compile ( '\s+::\s+' )
	multiline_start    = '{'
	multiline_stop     = '}'
	comment_chars      = list ( '#;' )
	# todo: const/config?
	package_ignore     = [ '!' ]


	def __init__ ( self ):
		""" A SimpleDependencyRuleReader reads such rules from a file."""
		pass
	# --- end of __init__  (...) ---

	def read_file ( self, filepath ):
		"""Reads a file that contains simple dependency rules
		(SimpleIgnoreDependencyRules/SimpleDependencyRules).

		arguments:
		* filepath -- file to read
		"""

		# line number is used for logging
		lineno = 0

		try:
			logging.debug ( "Reading simple dependency rule file %s." % filepath )
			fh = open ( filepath, 'r' )

			# the list of read rules
			rules = list ()

			# next rule is set when in a multi line rule (else None)
			next_rule = None

			for line in fh.readlines():
				lineno += 1
				line    = line.strip()

				if not line:
					# empty
					pass

				elif not next_rule is None:
					# in a multiline rule

					if line [0] == SimpleDependencyRuleReader.multiline_stop:
						# end of a multiline rule,
						#  add rule to rules and set next_rule to None
						rules.append ( next_rule )
						next_rule = None
					else:
						# new resolved str
						next_rule.add_resolved ( line )

				elif line [0] in SimpleDependencyRuleReader.comment_chars:
					# comment
					#  it is intented that multi line rules cannot contain comments
					pass

				elif line [-1] == SimpleDependencyRuleReader.multiline_start:
					# start of a multiline rule
					portpkg = line [:-1].rstrip()
					if portpkg in SimpleDependencyRuleReader.package_ignore:
						next_rule = SimpleIgnoreDependencyRule ( None, 60 )
					else:
						next_rule = SimpleDependencyRule ( portpkg, None, 70 )

				else:
					# single line rule?
					rule_str = \
						SimpleDependencyRuleReader.one_line_separator.split (line, 1)

					if len ( rule_str ) == 2:
						# is a single line rule

						if rule_str [0] in SimpleDependencyRuleReader.package_ignore:
							rules.append (
								SimpleIgnoreDependencyRule ( rule_str [1], 40 )
							)
						else:
							rules.append (
								SimpleDependencyRule ( rule_str [0], rule_str [1], 50 )
							)
					else:
						logging.error (
							"In %s, line %i : cannot use this line." %
								( filepath, lineno )
						)
				# ---

			if fh: fh.close ()

			logging.info (
				"%s: read %i dependency rules (in %i lines)" %
					( filepath, len ( rules ), lineno )
			)

			return rules

		except IOError as ioerr:
			if lineno:
				logging.error (
					"Failed to read file %s after %i lines." % ( filepath, lineno )
				)
			else:
				logging.error ( "Could not read file %s." % filepath )
			raise

		# --- end of read_file (...) ---