aboutsummaryrefslogtreecommitdiff
blob: fb68965428f22641e8a553142e7674efd36df87e (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
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
#!/usr/bin/python
#
# Copyright 2004, Karl Trygve Kalleberg <karltk@gentoo.org>
# Copyright 2004-2010 Gentoo Foundation
#
# Licensed under the GNU General Public License, v2
#
# $Header$

"""Provides an interface to package information stored by package managers.

The Package class is the heart of much of Gentoolkit. Given a CPV
(category/package-version) string, it can reveal the package's status in the
tree and VARDB (/var/db/), provide rich comparison and sorting, and expose
important parts of Portage's back-end.

Example usage:
	>>> portage = Package('sys-apps/portage-2.1.6.13')
	>>> portage.ebuild_path()
	'/usr/portage/sys-apps/portage/portage-2.1.6.13.ebuild'
	>>> portage.is_masked()
	False
	>>> portage.is_installed()
	True
"""

__all__ = (
	'Package',
	'PackageFormatter'
)

# =======
# Imports
# =======

import os

import portage
from portage import settings

import gentoolkit.pprinter as pp
from gentoolkit import errors
from gentoolkit.cpv import CPV
from gentoolkit.dbapi import PORTDB, VARDB
from gentoolkit.dependencies import Dependencies
from gentoolkit.metadata import MetaData

# =======
# Classes
# =======

class Package(CPV):
	"""Exposes the state of a given CPV."""

	def __init__(self, cpv):
		if isinstance(cpv, CPV):
			self.__dict__.update(cpv.__dict__)
		else:
			CPV.__init__(self, cpv)
		del cpv

		if not all(hasattr(self, x) for x in ('category', 'version')):
			# CPV allows some things that Package must not
			raise errors.GentoolkitInvalidPackage(self.cpv)

		# Set dynamically
		self._package_path = None
		self._dblink = None
		self._metadata = None
		self._deps = None
		self._portdir_path = None

	def __repr__(self):
		return "<%s %r>" % (self.__class__.__name__, self.cpv)

	def __hash__(self):
		return hash(self.cpv)

	def __contains__(self, key):
		return key in self.cpv

	def __str__(self):
		return self.cpv

	@property
	def metadata(self):
		"""Instantiate a L{gentoolkit.metadata.MetaData} object here."""

		if self._metadata is None:
			metadata_path = os.path.join(
				self.package_path(), 'metadata.xml'
			)
			self._metadata = MetaData(metadata_path)

		return self._metadata

	@property
	def dblink(self):
		"""Instantiate a L{portage.dbapi.vartree.dblink} object here."""

		if self._dblink is None:
			self._dblink = portage.dblink(
				self.category,
				"%s-%s" % (self.name, self.fullversion),
				settings["ROOT"],
				settings
			)

		return self._dblink

	@property
	def deps(self):
		"""Instantiate a L{gentoolkit.dependencies.Dependencies} object here."""

		if self._deps is None:
			self._deps = Dependencies(self.cpv)

		return self._deps

	def environment(self, envvars, prefer_vdb=True, fallback=True):
		"""Returns one or more of the predefined environment variables.

		Available envvars are:
		----------------------
			BINPKGMD5  COUNTER         FEATURES   LICENSE  SRC_URI
			CATEGORY   CXXFLAGS        HOMEPAGE   PDEPEND  USE
			CBUILD     DEFINED_PHASES  INHERITED  PF
			CFLAGS     DEPEND          IUSE       PROVIDE
			CHOST      DESCRIPTION     KEYWORDS   RDEPEND
			CONTENTS   EAPI            LDFLAGS    SLOT

		Example usage:
			>>> pkg = Package('sys-apps/portage-2.1.6.13')
			>>> pkg.environment('USE')
			'elibc_glibc kernel_linux userland_GNU x86'
			>>> pkg.environment(('USE', 'IUSE'))
			['elibc_glibc kernel_linux userland_GNU x86',
				'build doc epydoc selinux linguas_pl']

		@type envvars: str or array
		@param envvars: one or more of (DEPEND, SRC_URI, etc.)
		@type prefer_vdb: bool
		@keyword prefer_vdb: if True, look in the vardb before portdb, else
			reverse order. Specifically KEYWORDS will get more recent
			information by preferring portdb.
		@type fallback: bool
		@keyword fallback: query only the preferred db if False
		@rtype: str or list
		@return: str if envvars is str, list if envvars is array
		@raise KeyError: if key is not found in requested db(s)
		"""

		got_string = False
		if isinstance(envvars, basestring):
			got_string = True
			envvars = (envvars,)
		if prefer_vdb:
			try:
				result = VARDB.aux_get(self.cpv, envvars)
			except KeyError:
				try:
					if not fallback:
						raise KeyError
					result = PORTDB.aux_get(self.cpv, envvars)
				except KeyError:
					err = "aux_get returned unexpected results"
					raise errors.GentoolkitFatalError(err)
		else:
			try:
				result = PORTDB.aux_get(self.cpv, envvars)
			except KeyError:
				try:
					if not fallback:
						raise KeyError
					result = VARDB.aux_get(self.cpv, envvars)
				except KeyError:
					err = "aux_get returned unexpected results"
					raise errors.GentoolkitFatalError(err)

		if got_string:
			return result[0]
		return result

	def exists(self):
		"""Return True if package exists in the Portage tree, else False"""

		return bool(PORTDB.cpv_exists(self.cpv))

	@staticmethod
	def settings(key):
		"""Returns the value of the given key for this package (useful
		for package.* files."""

		if settings.locked:
			settings.unlock()
		try:
			result = settings[key]
		finally:
			settings.lock()
		return result

	def mask_status(self):
		"""Shortcut to L{portage.getmaskingstatus}.

		@rtype: None or list
		@return: a list containing none or some of:
			'profile'
			'package.mask'
			license(s)
			"kmask" keyword
			'missing keyword'
		"""

		if settings.locked:
			settings.unlock()
		try:
			result = portage.getmaskingstatus(self.cpv,
				settings=settings,
				portdb=PORTDB)
		except KeyError:
			# getmaskingstatus doesn't support packages without ebuilds in the
			# Portage tree.
			result = None

		return result

	def mask_reason(self):
		"""Shortcut to L{portage.getmaskingreason}.

		@rtype: None or tuple
		@return: empty tuple if pkg not masked OR
			('mask reason', 'mask location')
		"""

		try:
			result = portage.getmaskingreason(self.cpv,
				settings=settings,
				portdb=PORTDB,
				return_location=True)
			if result is None:
				result = tuple()
		except KeyError:
			# getmaskingstatus doesn't support packages without ebuilds in the
			# Portage tree.
			result = None

		return result

	def ebuild_path(self, in_vartree=False):
		"""Returns the complete path to the .ebuild file.

		Example usage:
			>>> pkg.ebuild_path()
			'/usr/portage/sys-apps/portage/portage-2.1.6.13.ebuild'
			>>> pkg.ebuild_path(in_vartree=True)
			'/var/db/pkg/sys-apps/portage-2.1.6.13/portage-2.1.6.13.ebuild'
		"""

		if in_vartree:
			return VARDB.findname(self.cpv)
		return PORTDB.findname(self.cpv)

	def package_path(self, in_vartree=False):
		"""Return the path to where the ebuilds and other files reside."""

		if in_vartree:
			return self.dblink.getpath()
		return os.sep.join(self.ebuild_path().split(os.sep)[:-1])

	def repo_name(self, fallback=True):
		"""Determine the repository name.

		@type fallback: bool
		@param fallback: if the repo_name file does not exist, return the
			repository name from the path
		@rtype: str
		@return: output of the repository metadata file, which stores the 
			repo_name variable, or try to get the name of the repo from
			the path.
		@raise GentoolkitFatalError: if fallback is False and repo_name is
			not specified by the repository.
		"""

		try:
			return self.environment('repository')
		except errors.GentoolkitFatalError:
			if fallback:
				return self.package_path().split(os.sep)[-3]
			raise

	def use(self):
		"""Returns the USE flags active at time of installation."""

		return self.dblink.getstring("USE")

	def parsed_contents(self):
		"""Returns the parsed CONTENTS file.

		@rtype: dict
		@return: {'/full/path/to/obj': ['type', 'timestamp', 'md5sum'], ...}
		"""

		return self.dblink.getcontents()

	def size(self):
		"""Estimates the installed size of the contents of this package.

		@rtype: tuple
		@return: (size, number of files in total, number of uncounted files)
		"""

		seen = set()
		content_stats = (os.lstat(x) for x in self.parsed_contents())
		# Remove hardlinks by checking for duplicate inodes. Bug #301026.
		unique_file_stats = (x for x in content_stats if x.st_ino not in seen
			and not seen.add(x.st_ino))
		size = n_uncounted = n_files = 0
		for st in unique_file_stats:
			try:
				size += st.st_size
				n_files += 1
			except OSError:
				n_uncounted += 1
		return (size, n_files, n_uncounted)

	def is_installed(self):
		"""Returns True if this package is installed (merged)"""

		return self.dblink.exists()

	def is_overlay(self):
		"""Returns True if the package is in an overlay."""

		ebuild, tree = PORTDB.findname2(self.cpv)
		if not ebuild:
			return None
		if self._portdir_path is None:
			self._portdir_path = os.path.realpath(settings["PORTDIR"])
		return (tree and tree != self._portdir_path)

	def is_masked(self):
		"""Returns true if this package is masked against installation.
		Note: We blindly assume that the package actually exists on disk
		somewhere."""

		unmasked = PORTDB.xmatch("match-visible", self.cpv)
		return self.cpv not in unmasked


class PackageFormatter(object):
	"""When applied to a L{gentoolkit.package.Package} object, determine the
	location (Portage Tree vs. overlay), install status and masked status. That
	information can then be easily formatted and displayed.

	Example usage:
		>>> from gentoolkit.helpers import find_packages
		>>> from gentoolkit.package import PackageFormatter
		>>> pkgs = [PackageFormatter(x) for x in find_packages('gcc')]
		>>> for pkg in pkgs:
		...     # Only print packages that are installed and from the Portage
		...     # tree
		...     if set('IP').issubset(pkg.location):
		...             print pkg
		...
		[IP-] [  ] sys-devel/gcc-4.3.2-r3 (4.3)

	@type pkg: L{gentoolkit.package.Package}
	@param pkg: package to format
	@type format: L{bool}
	@param format: Whether to format the package name or not.
		Essentially C{format} should be set to False when piping or when
		quiet output is desired. If C{do_format} is False, only the location
		attribute will be created to save time.
	"""

	def __init__(self, pkg, do_format=True):
		self.pkg = pkg
		self.do_format = do_format
		self.location = self.format_package_location() or ''

	def __repr__(self):
		return "<%s %s @%#8x>" % (self.__class__.__name__, self.pkg, id(self))

	def __str__(self):
		if self.do_format:
			maskmodes = ['  ', ' ~', ' -', 'M ', 'M~', 'M-', '??']
			maskmode = maskmodes[self.format_mask_status()[0]]
			return "[%(location)s] [%(mask)s] %(package)s:%(slot)s" % {
				'location': self.location,
				'mask': pp.keyword(
					maskmode,
					stable=not maskmode.strip(),
					hard_masked=set(('M', '?', '-')).intersection(maskmode)
				),
				'package': pp.cpv(str(self.pkg.cpv)),
				'slot': pp.slot(self.pkg.environment("SLOT"))
			}
		else:
			return str(self.pkg.cpv)

	def format_package_location(self):
		"""Get the install status (in /var/db/?) and origin (from and overlay
		and the Portage tree?).

		@rtype: str
		@return: one of:
			'I--' : Installed but ebuild doesn't exist on system anymore
			'-P-' : Not installed and from the Portage tree
			'--O' : Not installed and from an overlay
			'IP-' : Installed and from the Portage tree
			'I-O' : Installed and from an overlay
		"""

		result = ['-', '-', '-']

		if self.pkg.is_installed():
			result[0] = 'I'

		overlay = self.pkg.is_overlay()
		if overlay is None:
			pass
		elif overlay:
			result[2] = 'O'
		else:
			result[1] = 'P'

		return ''.join(result)

	def format_mask_status(self):
		"""Get the mask status of a given package.

		@rtype: tuple: (int, list)
		@return: int = an index for this list:
			["  ", " ~", " -", "M ", "M~", "M-", "??"]
			0 = not masked
			1 = keyword masked
			2 = arch masked
			3 = hard masked
			4 = hard and keyword masked,
			5 = hard and arch masked
			6 = ebuild doesn't exist on system anymore

			list = original output of portage.getmaskingstatus
		"""

		result = 0
		masking_status = self.pkg.mask_status()
		if masking_status is None:
			return (6, [])

		if ("~%s keyword" % self.pkg.settings("ARCH")) in masking_status:
			result += 1
		if "missing keyword" in masking_status:
			result += 2
		if set(('profile', 'package.mask')).intersection(masking_status):
			result += 3

		return (result, masking_status)


# vim: set ts=4 sw=4 tw=79: