aboutsummaryrefslogtreecommitdiff
blob: 19c23a6c63532e4ab3aa8f87d3a831c775bf87a2 (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
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
# Copyright 2009-2010 Gentoo Foundation
#
# Licensed under the GNU General Public License, v2 or higher
#
# $Header: $

"""Display metadata about a given package"""

# Move to Imports section after Python-2.6 is stable
from __future__ import with_statement

__docformat__ = 'epytext'

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

import os
import re
import sys
from getopt import gnu_getopt, GetoptError

import gentoolkit.pprinter as pp
from gentoolkit import errors
from gentoolkit.equery import format_options, mod_usage, CONFIG
from gentoolkit.helpers import find_packages, print_sequence, print_file
from gentoolkit.textwrap_ import TextWrapper

# =======
# Globals
# =======

# E1101: Module 'portage.output' has no $color member
# portage.output creates color functions dynamically
# pylint: disable-msg=E1101

QUERY_OPTS = {
	'current': False,
	'description': False,
	'herd': False,
	'keywords': False,
	'maintainer': False,
	'useflags': False,
	'upstream': False,
	'xml': False
}

# =========
# Functions
# =========

def print_help(with_description=True, with_usage=True):
	"""Print description, usage and a detailed help message.

	@type with_description: bool
	@param with_description: if true, print module's __doc__ string
	"""

	if with_description:
		print __doc__.strip()
		print
	if with_usage:
		print mod_usage(mod_name="meta")
		print
	print pp.command("options")
	print format_options((
		(" -h, --help", "display this help message"),
		(" -d, --description", "show an extended package description"),
		(" -H, --herd", "show the herd(s) for the package"),
		(" -k, --keywords", "show keywords for all matching package versions"),
		(" -m, --maintainer", "show the maintainer(s) for the package"),
		(" -u, --useflags", "show per-package USE flag descriptions"),
		(" -U, --upstream", "show package's upstream information"),
		(" -x, --xml", "show the plain metadata.xml file")
	))


def filter_keywords(matches):
	"""Filters non-unique keywords per slot.

	Does not filter arch mask keywords (-). Besides simple non-unique keywords,
	also remove unstable keywords (~) if a higher version in the same slot is
	stable. This view makes version bumps easier for package maintainers.

	@type matches: array
	@param matches: set of L{gentoolkit.package.Package} instances whose
		'key' are all the same.
	@rtype: dict
	@return: a dict with L{gentoolkit.package.Package} instance keys and
		'array of keywords not found in a higher version of pkg within the
		same slot' values.
	"""
	def del_archmask(keywords):
		"""Don't add arch_masked to filter set."""
		return [x for x in keywords if not x.startswith('-')]

	def add_unstable(keywords):
		"""Add unstable keyword for all stable keywords to filter set."""
		result = list(keywords)
		result.extend(
			['~%s' % x for x in keywords if not x.startswith(('-', '~'))]
		)
		return result

	result = {}
	slot_map = {}
	# Start from the newest
	rev_matches = reversed(matches)
	for pkg in rev_matches:
		keywords_str, slot = pkg.environment(('KEYWORDS', 'SLOT'),
			prefer_vdb=False)
		keywords = keywords_str.split()
		result[pkg] = [x for x in keywords if x not in slot_map.get(slot, [])]
		try:
			slot_map[slot].update(del_archmask(add_unstable(keywords)))
		except KeyError:
			slot_map[slot] = set(del_archmask(add_unstable(keywords)))

	return result


def format_herds(herds):
	"""Format herd information for display."""

	result = []
	for herd in herds:
		herdstr = ''
		email = "(%s)" % herd[1] if herd[1] else ''
		herdstr = herd[0]
		if CONFIG['verbose']:
			herdstr += " %s" % (email,)
		result.append(herdstr)

	return result


def format_maintainers(maints):
	"""Format maintainer information for display."""

	result = []
	for maint in maints:
		maintstr = ''
		maintstr = maint.email
		if CONFIG['verbose']:
			maintstr += " (%s)" % (maint.name,) if maint.name else ''
			maintstr += " - %s" % (maint.restrict,) if maint.restrict else ''
			maintstr += "\n%s" % (
				(maint.description,) if maint.description else ''
			)
		result.append(maintstr)

	return result


def format_upstream(upstream):
	"""Format upstream information for display."""

	def _format_upstream_docs(docs):
		result = []
		for doc in docs:
			doc_location = doc[0]
			doc_lang = doc[1]
			docstr = doc_location
			if doc_lang is not None:
				docstr += " (%s)" % (doc_lang,)
			result.append(docstr)
		return result

	def _format_upstream_ids(ids):
		result = []
		for id_ in ids:
			site = id_[0]
			proj_id = id_[1]
			idstr = "%s ID: %s" % (site, proj_id)
			result.append(idstr)
		return result

	result = []
	for up in upstream:
		upmaints = format_maintainers(up.maintainers)
		for upmaint in upmaints:
			result.append(format_line(upmaint, "Maintainer:  ", " " * 13))

		for upchange in up.changelogs:
			result.append(format_line(upchange, "ChangeLog:   ", " " * 13))

		updocs = _format_upstream_docs(up.docs)
		for updoc in updocs:
			result.append(format_line(updoc, "Docs:       ", " " * 13))

		for upbug in up.bugtrackers:
			result.append(format_line(upbug, "Bugs-to:     ", " " * 13))

		upids = _format_upstream_ids(up.remoteids)
		for upid in upids:
			result.append(format_line(upid, "Remote-ID:   ", " " * 13))

	return result


def format_useflags(useflags):
	"""Format USE flag information for display."""

	result = []
	for flag in useflags:
		result.append(pp.useflag(flag.name))
		result.append(flag.description)
		result.append("")

	return result


def format_keywords(keywords):
	"""Sort and colorize keywords for display."""

	result = []

	for kw in sorted(keywords):
		if kw.startswith('-'):
			# arch masked
			kw = pp.keyword(kw, stable=False, hard_masked=True)
		elif kw.startswith('~'):
			# keyword masked
			kw = pp.keyword(kw, stable=False, hard_masked=False)
		else:
			# stable
			kw = pp.keyword(kw, stable=True, hard_masked=False)
		result.append(kw)

	return ' '.join(result)


def format_keywords_line(pkg, fmtd_keywords, slot, verstr_len):
	"""Format the entire keywords line for display."""

	ver = pkg.fullversion
	result = "%s:%s: %s" % (ver, pp.slot(slot), fmtd_keywords)
	if CONFIG['verbose'] and fmtd_keywords:
		result = format_line(fmtd_keywords, "%s:%s: " % (ver, pp.slot(slot)),
			" " * (verstr_len + 2))

	return result


# R0912: *Too many branches (%s/%s)*
# pylint: disable-msg=R0912
def call_format_functions(matches):
	"""Call information gathering functions and display the results."""

	# Choose a good package to reference metadata from
	ref_pkg = get_reference_pkg(matches)

	if CONFIG['verbose']:
		repo = ref_pkg.repo_name()
		print " * %s [%s]" % (pp.cpv(ref_pkg.cp), pp.section(repo))

	got_opts = False
	if any(QUERY_OPTS.values()):
		# Specific information requested, less formatting
		got_opts = True

	if QUERY_OPTS["herd"] or not got_opts:
		herds = format_herds(ref_pkg.metadata.herds(include_email=True))
		if QUERY_OPTS["herd"]:
			print_sequence(format_list(herds))
		else:
			for herd in herds:
				print format_line(herd, "Herd:        ", " " * 13)

	if QUERY_OPTS["maintainer"] or not got_opts:
		maints = format_maintainers(ref_pkg.metadata.maintainers())
		if QUERY_OPTS["maintainer"]:
			print_sequence(format_list(maints))
		else:
			if not maints:
				print format_line([], "Maintainer:  ", " " * 13)
			else:
				for maint in maints:
					print format_line(maint, "Maintainer:  ", " " * 13)

	if QUERY_OPTS["upstream"] or not got_opts:
		upstream = format_upstream(ref_pkg.metadata.upstream())
		if QUERY_OPTS["upstream"]:
			upstream = format_list(upstream)
		else:
			upstream = format_list(upstream, "Upstream:    ", " " * 13)
		print_sequence(upstream)

	if not got_opts:
		pkg_loc = ref_pkg.package_path()
		print format_line(pkg_loc, "Location:    ", " " * 13)

	if QUERY_OPTS["keywords"] or not got_opts:
		# Get {<Package 'dev-libs/glib-2.20.5'>: [u'ia64', u'm68k', ...], ...}
		keyword_map = filter_keywords(matches)

		for match in matches:
			slot = match.environment('SLOT')
			verstr_len = len(match.fullversion) + len(slot)
			fmtd_keywords = format_keywords(keyword_map[match])
			keywords_line = format_keywords_line(
				match, fmtd_keywords, slot, verstr_len
			)
			if QUERY_OPTS["keywords"]:
				print keywords_line
			else:
				indent = " " * (16 + verstr_len)
				print format_line(keywords_line, "Keywords:    ", indent)

	if QUERY_OPTS["description"]:
		desc = ref_pkg.metadata.descriptions()
		print_sequence(format_list(desc))

	if QUERY_OPTS["useflags"]:
		useflags = format_useflags(ref_pkg.metadata.use())
		print_sequence(format_list(useflags))

	if QUERY_OPTS["xml"]:
		print_file(os.path.join(ref_pkg.package_path(), 'metadata.xml'))


def format_line(line, first="", subsequent="", force_quiet=False):
	"""Wrap a string at word boundaries and optionally indent the first line
	and/or subsequent lines with custom strings.

	Preserve newlines if the longest line is not longer than
	CONFIG['termWidth']. To force the preservation of newlines and indents,
	split the string into a list and feed it to format_line via format_list.

	@see: format_list()
	@type line: string
	@param line: text to format
	@type first: string
	@param first: text to prepend to the first line
	@type subsequent: string
	@param subsequent: text to prepend to subsequent lines
	@type force_quiet: boolean
	@rtype: string
	@return: A wrapped line
	"""

	if line:
		line = line.expandtabs().strip("\n").splitlines()
	else:
		if force_quiet:
			return
		else:
			return first + "None specified"

	if len(first) > len(subsequent):
		wider_indent = first
	else:
		wider_indent = subsequent

	widest_line_len = len(max(line, key=len)) + len(wider_indent)

	if widest_line_len > CONFIG['termWidth']:
		twrap = TextWrapper(width=CONFIG['termWidth'], expand_tabs=False,
			initial_indent=first, subsequent_indent=subsequent)
		line = " ".join(line)
		line = re.sub("\s+", " ", line)
		line = line.lstrip()
		result = twrap.fill(line)
	else:
		# line will fit inside CONFIG['termWidth'], so preserve whitespace and
		# newlines
		line[0] = first + line[0]          # Avoid two newlines if len == 1

		if len(line) > 1:
			line[0] = line[0] + "\n"
			for i in range(1, (len(line[1:-1]) + 1)):
				line[i] = subsequent + line[i] + "\n"
			line[-1] = subsequent + line[-1]  # Avoid two newlines on last line

		if line[-1].isspace():
			del line[-1]                # Avoid trailing blank lines

		result = "".join(line)

	return result.encode("utf-8")


def format_list(lst, first="", subsequent="", force_quiet=False):
	"""Feed elements of a list to format_line().

	@see: format_line()
	@type lst: list
	@param lst: list to format
	@type first: string
	@param first: text to prepend to the first line
	@type subsequent: string
	@param subsequent: text to prepend to subsequent lines
	@rtype: list
	@return: list with element text wrapped at CONFIG['termWidth']
	"""

	result = []
	if lst:
		# Format the first line
		line = format_line(lst[0], first, subsequent, force_quiet)
		result.append(line)
		# Format subsequent lines
		for elem in lst[1:]:
			if elem:
				result.append(format_line(elem, subsequent, subsequent,
					force_quiet))
			else:
				# We don't want to send a blank line to format_line()
				result.append("")
	else:
		if CONFIG['verbose']:
			if force_quiet:
				result = None
			else:
				# Send empty list, we'll get back first + `None specified'
				result.append(format_line(lst, first, subsequent))

	return result


def get_reference_pkg(matches):
	"""Find a package in the Portage tree to reference."""

	pkg = None
	rev_matches = list(reversed(matches))
	while rev_matches:
		pkg = rev_matches.pop()
		if not pkg.is_overlay():
			break

	return pkg


def parse_module_options(module_opts):
	"""Parse module options and update QUERY_OPTS"""

	opts = (x[0] for x in module_opts)
	for opt in opts:
		if opt in ('-h', '--help'):
			print_help()
			sys.exit(0)
		elif opt in ('-d', '--description'):
			QUERY_OPTS["description"] = True
		elif opt in ('-H', '--herd'):
			QUERY_OPTS["herd"] = True
		elif opt in ('-m', '--maintainer'):
			QUERY_OPTS["maintainer"] = True
		elif opt in ('-k', '--keywords'):
			QUERY_OPTS["keywords"] = True
		elif opt in ('-u', '--useflags'):
			QUERY_OPTS["useflags"] = True
		elif opt in ('-U', '--upstream'):
			QUERY_OPTS["upstream"] = True
		elif opt in ('-x', '--xml'):
			QUERY_OPTS["xml"] = True


def main(input_args):
	"""Parse input and run the program."""

	short_opts = "hdHkmuUx"
	long_opts = ('help', 'description', 'herd', 'keywords', 'maintainer',
		'useflags', 'upstream', 'xml')

	try:
		module_opts, queries = gnu_getopt(input_args, short_opts, long_opts)
	except GetoptError, err:
		sys.stderr.write(pp.error("Module %s" % err))
		print
		print_help(with_description=False)
		sys.exit(2)

	parse_module_options(module_opts)

	# Find queries' Portage directory and throw error if invalid
	if not queries:
		print_help()
		sys.exit(2)

	first_run = True
	for query in queries:
		matches = find_packages(query, include_masked=True)
		if not matches:
			raise errors.GentoolkitNoMatches(query)

		if not first_run:
			print

		matches.sort()
		call_format_functions(matches)

		first_run = False

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