public inbox for gentoo-commits@lists.gentoo.org
 help / color / mirror / Atom feed
* [gentoo-commits] proj/portage:master commit in: bin/, pym/portage/util/
@ 2012-05-01  2:31 Zac Medico
  0 siblings, 0 replies; 5+ messages in thread
From: Zac Medico @ 2012-05-01  2:31 UTC (permalink / raw
  To: gentoo-commits

commit:     aa63202838c5346692b49ae26fff16b6977fb56c
Author:     Zac Medico <zmedico <AT> gentoo <DOT> org>
AuthorDate: Tue May  1 02:26:52 2012 +0000
Commit:     Zac Medico <zmedico <AT> gentoo <DOT> org>
CommitDate: Tue May  1 02:30:10 2012 +0000
URL:        http://git.overlays.gentoo.org/gitweb/?p=proj/portage.git;a=commit;h=aa632028

repoman: ignore false Service desktop entry error

This will fix bug #414125.

---
 bin/repoman                        |    8 ++--
 pym/portage/util/_desktop_entry.py |   70 ++++++++++++++++++++++++++++++++++++
 2 files changed, 74 insertions(+), 4 deletions(-)

diff --git a/bin/repoman b/bin/repoman
index 0163f8d..1cdfcf6 100755
--- a/bin/repoman
+++ b/bin/repoman
@@ -76,6 +76,7 @@ from portage.output import bold, create_color_func, \
 	green, nocolor, red
 from portage.output import ConsoleStyleFile, StyleWriter
 from portage.util import cmp_sort_key, writemsg_level
+from portage.util._desktop_entry import validate_desktop_entry
 from portage.package.ebuild.digestgen import digestgen
 from portage.eapi import eapi_has_iuse_defaults, eapi_has_required_use
 
@@ -1565,15 +1566,14 @@ for x in effective_scanlist:
 					(checkdir, y, m.group(0)))
 
 			if desktop_file_validate and desktop_pattern.match(y):
-				status, cmd_output = subprocess_getstatusoutput(
-					"'%s' '%s'" % (desktop_file_validate, full_path))
-				if os.WIFEXITED(status) and os.WEXITSTATUS(status) != os.EX_OK:
+				cmd_output = validate_desktop_entry(full_path)
+				if cmd_output:
 					# Note: in the future we may want to grab the
 					# warnings in addition to the errors. We're
 					# just doing errors now since we don't want
 					# to generate too much noise at first.
 					error_re = re.compile(r'.*\s*error:\s*(.*)')
-					for line in cmd_output.splitlines():
+					for line in cmd_output:
 						error_match = error_re.match(line)
 						if error_match is None:
 							continue

diff --git a/pym/portage/util/_desktop_entry.py b/pym/portage/util/_desktop_entry.py
new file mode 100644
index 0000000..101965f
--- /dev/null
+++ b/pym/portage/util/_desktop_entry.py
@@ -0,0 +1,70 @@
+# Copyright 2012 Gentoo Foundation
+# Distributed under the terms of the GNU General Public License v2
+
+import io
+import subprocess
+
+try:
+	from configparser import Error as ConfigParserError, RawConfigParser
+except ImportError:
+	from ConfigParser import Error as ConfigParserError, RawConfigParser
+
+from portage import _encodings, _unicode_encode, _unicode_decode
+
+def parse_desktop_entry(path):
+	"""
+	Parse the given file with RawConfigParser and return the
+	result. This may raise an IOError from io.open(), or a
+	ParsingError from RawConfigParser.
+	"""
+	parser = RawConfigParser()
+
+	# use read_file/readfp in order to control decoding of unicode
+	try:
+		# Python >=3.2
+		read_file = parser.read_file
+	except AttributeError:
+		read_file = parser.readfp
+
+	with io.open(_unicode_encode(path,
+		encoding=_encodings['fs'], errors='strict'),
+		mode='r', encoding=_encodings['repo.content'],
+		errors='replace') as f:
+		read_file(f)
+
+	return parser
+
+_ignored_service_errors = (
+	'error: required key "Name" in group "Desktop Entry" is not present',
+	'error: key "Actions" is present in group "Desktop Entry", but the type is "Service" while this key is only valid for type "Application"',
+	'error: key "MimeType" is present in group "Desktop Entry", but the type is "Service" while this key is only valid for type "Application"',
+)
+
+def validate_desktop_entry(path):
+	proc = subprocess.Popen([b"desktop-file-validate", _unicode_encode(path)],
+		stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
+	output_lines = _unicode_decode(proc.communicate()[0]).splitlines()
+	proc.wait()
+
+	if output_lines:
+		try:
+			desktop_entry = parse_desktop_entry(path)
+		except ConfigParserError:
+			pass
+		else:
+			if desktop_entry.has_section("Desktop Entry"):
+				try:
+					entry_type = desktop_entry.get("Desktop Entry", "Type")
+				except ConfigParserError:
+					pass
+				else:
+					if entry_type == "Service":
+						# Filter false errors for Type=Service (bug #414125).
+						filtered_output = []
+						for line in output_lines:
+							if line[len(path)+2:] in _ignored_service_errors:
+								continue
+							filtered_output.append(line)
+						output_lines = filtered_output
+
+	return output_lines



^ permalink raw reply related	[flat|nested] 5+ messages in thread

* [gentoo-commits] proj/portage:master commit in: bin/, pym/portage/util/
@ 2013-07-30 22:23 Zac Medico
  0 siblings, 0 replies; 5+ messages in thread
From: Zac Medico @ 2013-07-30 22:23 UTC (permalink / raw
  To: gentoo-commits

commit:     2cebb23f1497a1c50967e7772d4e36e7dc89b70e
Author:     Zac Medico <zmedico <AT> gentoo <DOT> org>
AuthorDate: Tue Jul 30 22:21:48 2013 +0000
Commit:     Zac Medico <zmedico <AT> gentoo <DOT> org>
CommitDate: Tue Jul 30 22:21:48 2013 +0000
URL:        http://git.overlays.gentoo.org/gitweb/?p=proj/portage.git;a=commit;h=2cebb23f

install.py: split out optparse compat code

---
 bin/install.py                | 16 +---------------
 pym/portage/util/_argparse.py | 19 +++++++++++++++++++
 2 files changed, 20 insertions(+), 15 deletions(-)

diff --git a/bin/install.py b/bin/install.py
index 0bf7a1f..b194941 100755
--- a/bin/install.py
+++ b/bin/install.py
@@ -8,24 +8,10 @@ import sys
 import subprocess
 import traceback
 
+from portage.util._argparse import ArgumentParser
 from portage.util.movefile import _copyxattr
 from portage.exception import OperationNotSupported
 
-try:
-	from argparse import ArgumentParser
-except ImportError:
-	# Compatibility with Python 2.6 and 3.1
-	from optparse import OptionParser
-
-	class ArgumentParser(object):
-		def __init__(self, **kwargs):
-			add_help = kwargs.pop("add_help", None)
-			if add_help is not None:
-				kwargs["add_help_option"] = add_help
-			parser = OptionParser(**kwargs)
-			self.add_argument = parser.add_option
-			self.parse_known_args = parser.parse_args
-
 # Change back to original cwd _after_ all imports (bug #469338).
 os.chdir(os.environ["__PORTAGE_HELPER_CWD"])
 

diff --git a/pym/portage/util/_argparse.py b/pym/portage/util/_argparse.py
new file mode 100644
index 0000000..5e6a9ba
--- /dev/null
+++ b/pym/portage/util/_argparse.py
@@ -0,0 +1,19 @@
+# Copyright 2013 Gentoo Foundation
+# Distributed under the terms of the GNU General Public License v2
+
+__all__ = ['ArgumentParser']
+
+try:
+	from argparse import ArgumentParser
+except ImportError:
+	# Compatibility with Python 2.6 and 3.1
+	from optparse import OptionParser
+
+	class ArgumentParser(object):
+		def __init__(self, **kwargs):
+			add_help = kwargs.pop("add_help", None)
+			if add_help is not None:
+				kwargs["add_help_option"] = add_help
+			parser = OptionParser(**kwargs)
+			self.add_argument = parser.add_option
+			self.parse_known_args = parser.parse_args


^ permalink raw reply related	[flat|nested] 5+ messages in thread

* [gentoo-commits] proj/portage:master commit in: bin/, pym/portage/util/
@ 2013-07-30 22:37 Zac Medico
  0 siblings, 0 replies; 5+ messages in thread
From: Zac Medico @ 2013-07-30 22:37 UTC (permalink / raw
  To: gentoo-commits

commit:     2b4abfec2576c6f50d23dd331827c17aace315b3
Author:     Alexander Berntsen <alexander <AT> plaimi <DOT> net>
AuthorDate: Tue Jul 30 20:15:34 2013 +0000
Commit:     Zac Medico <zmedico <AT> gentoo <DOT> org>
CommitDate: Tue Jul 30 22:36:42 2013 +0000
URL:        http://git.overlays.gentoo.org/gitweb/?p=proj/portage.git;a=commit;h=2b4abfec

bin/fixpackages: Add -h, fixes bug #394773

---
 bin/fixpackages               | 8 ++++++++
 pym/portage/util/_argparse.py | 1 +
 2 files changed, 9 insertions(+)

diff --git a/bin/fixpackages b/bin/fixpackages
index e224b62..e29d6ee 100755
--- a/bin/fixpackages
+++ b/bin/fixpackages
@@ -14,12 +14,20 @@ import portage
 portage._internal_caller = True
 from portage import os
 from portage.output import EOutput
+from portage.util._argparse import ArgumentParser
 from textwrap import wrap
 from portage._global_updates import _global_updates
 mysettings = portage.settings
 mytrees = portage.db
 mtimedb = portage.mtimedb
 
+description = """The fixpackages program performs package move updates on
+	configuration files, installed packages, and binary packages."""
+description = " ".join(description.split())
+
+parser = ArgumentParser(description=description)
+parser.parse_args()
+
 if mysettings['ROOT'] != "/":
 	out = EOutput()
 	msg = "The fixpackages program is not intended for use with " + \

diff --git a/pym/portage/util/_argparse.py b/pym/portage/util/_argparse.py
index 5e6a9ba..4227f4c 100644
--- a/pym/portage/util/_argparse.py
+++ b/pym/portage/util/_argparse.py
@@ -17,3 +17,4 @@ except ImportError:
 			parser = OptionParser(**kwargs)
 			self.add_argument = parser.add_option
 			self.parse_known_args = parser.parse_args
+			self.parse_args = parser.parse_args


^ permalink raw reply related	[flat|nested] 5+ messages in thread

* [gentoo-commits] proj/portage:master commit in: bin/, pym/portage/util/
@ 2013-08-03  0:11 Zac Medico
  0 siblings, 0 replies; 5+ messages in thread
From: Zac Medico @ 2013-08-03  0:11 UTC (permalink / raw
  To: gentoo-commits

commit:     4df4c27f33ad3a258eb667c502e7b57f2f9b486e
Author:     Zac Medico <zmedico <AT> gentoo <DOT> org>
AuthorDate: Sat Aug  3 00:10:34 2013 +0000
Commit:     Zac Medico <zmedico <AT> gentoo <DOT> org>
CommitDate: Sat Aug  3 00:10:34 2013 +0000
URL:        http://git.overlays.gentoo.org/gitweb/?p=proj/portage.git;a=commit;h=4df4c27f

portageq: portage.util._argparse

---
 bin/portageq                  | 146 +++++++++++++++++++++++++++---------------
 pym/portage/util/_argparse.py |   1 +
 2 files changed, 97 insertions(+), 50 deletions(-)

diff --git a/bin/portageq b/bin/portageq
index d31ae34..0756cdb 100755
--- a/bin/portageq
+++ b/bin/portageq
@@ -20,7 +20,6 @@ try:
 except KeyboardInterrupt:
 	sys.exit(128 + signal.SIGINT)
 
-import optparse
 import os
 import types
 
@@ -41,6 +40,7 @@ portage._internal_caller = True
 from portage import os
 from portage.eapi import eapi_has_repo_deps
 from portage.util import writemsg, writemsg_stdout
+from portage.util._argparse import ArgumentParser
 portage.proxy.lazyimport.lazyimport(globals(),
 	're',
 	'subprocess',
@@ -929,7 +929,7 @@ class HerdMatcher(object):
 		return any(x in herds for x in metadata_xml.herds())
 
 
-def pquery(parser, pquery_option_groups, opts, args):
+def pquery(parser, opts, args):
 	"""[options] [atom]+
 	Emulates a subset of Pkgcore's pquery tool.
 	"""
@@ -1122,7 +1122,81 @@ non_commands = frozenset(['elog', 'eval_atom_use', 'exithandler', 'main', 'usage
 commands = sorted(k for k, v in globals().items() \
 	if k not in non_commands and isinstance(v, types.FunctionType) and v.__module__ == "__main__")
 
-def usage(argv, parser=None, pquery_option_groups=None):
+
+def add_pquery_arguments(parser):
+	pquery_option_groups = (
+		(
+			'Repository matching options',
+			(
+				{
+					"longopt": "--no-filters",
+					"action": "store_true",
+					"help": "no visibility filters (ACCEPT_KEYWORDS, package masking, etc)"
+				},
+				{
+					"longopt": "--repo",
+					"help": "repo to use (default is PORTDIR if omitted)"
+				},
+				{
+					"longopt": "--all-repos",
+					"help": "search all repos"
+				}
+			)
+		),
+		(
+			'Package matching options',
+			(
+				{
+					"longopt": "--herd",
+					"action": "append",
+					"help": "exact match on a herd"
+				},
+				{
+					"longopt": "--maintainer-email",
+					"action": "append",
+					"help": "comma-separated list of maintainer email regexes to search for"
+				}
+			)
+		),
+		(
+			'Output formatting',
+			(
+				{
+					"shortopt": "-n",
+					"longopt": "--no-version",
+					"action": "store_true",
+					"help": "collapse multiple matching versions together"
+				},
+			)
+		),
+	)
+
+	for group_title, opt_data in pquery_option_groups:
+		arg_group = parser.add_argument_group(group_title)
+		for opt_info in opt_data:
+			pargs = []
+			try:
+				pargs.append(opt_info["shortopt"])
+			except KeyError:
+				pass
+			try:
+				pargs.append(opt_info["longopt"])
+			except KeyError:
+				pass
+
+			kwargs = {}
+			try:
+				kwargs["action"] = opt_info["action"]
+			except KeyError:
+				pass
+			try:
+				kwargs["help"] = opt_info["help"]
+			except KeyError:
+				pass
+			arg_group.add_argument(*pargs, **kwargs)
+
+
+def usage(argv):
 	print(">>> Portage information query tool")
 	print(">>> %s" % portage.VERSION)
 	print(">>> Usage: portageq <command> [<option> ...]")
@@ -1153,13 +1227,13 @@ def usage(argv, parser=None, pquery_option_groups=None):
 			for line in lines[1:]:
 				print("      " + line.strip())
 
-	if pquery_option_groups is not None:
-		parser.formatter.store_option_strings(parser)
-		print()
-		print('Pkgcore pquery compatible options:')
-		print()
-		for optgroup in pquery_option_groups:
-			print(optgroup.format_help(parser.formatter))
+	print()
+	print('Pkgcore pquery compatible options:')
+	print()
+	parser = ArgumentParser(add_help=False,
+		usage='portageq pquery [options] [atom ...]')
+	add_pquery_arguments(parser)
+	parser.print_help()
 
 	if len(argv) == 1:
 		print("\nRun portageq with --help for info")
@@ -1188,49 +1262,21 @@ def main(argv):
 	if nocolor in ('yes', 'true'):
 		portage.output.nocolor()
 
-	parser = optparse.OptionParser(add_help_option=False)
+	parser = ArgumentParser(add_help=False)
 
 	# used by envvar
-	parser.add_option("-v", dest="verbose", action="store_true")
-
-	actions = optparse.OptionGroup(parser, 'Actions')
-	actions.add_option("-h", "--help", action="store_true")
-	actions.add_option("--version", action="store_true")
-	parser.add_option_group(actions)
-
-	pquery_option_groups = []
-
-	repo_optgroup = optparse.OptionGroup(parser,
-		'Repository matching options')
-	repo_optgroup.add_option("--no-filters", action="store_true",
-		help="no visibility filters (ACCEPT_KEYWORDS, package masking, etc)")
-	repo_optgroup.add_option("--repo", action="store",
-		help="repo to use (default is PORTDIR if omitted)")
-	repo_optgroup.add_option("--all-repos", action="store_true",
-		help="search all repos")
-	parser.add_option_group(repo_optgroup)
-	pquery_option_groups.append(repo_optgroup)
-
-	matching_optgroup = optparse.OptionGroup(parser,
-		'Package matching options')
-	matching_optgroup.add_option("--herd", action="append",
-		help="exact match on a herd")
-	matching_optgroup.add_option("--maintainer-email", action="append",
-		help="comma-separated list of maintainer email regexes to search for")
-	parser.add_option_group(matching_optgroup)
-	pquery_option_groups.append(matching_optgroup)
-
-	formatting_optgroup = optparse.OptionGroup(parser,
-		'Output formatting')
-	formatting_optgroup.add_option("-n", "--no-version", action="store_true",
-		help="collapse multiple matching versions together")
-	parser.add_option_group(formatting_optgroup)
-	pquery_option_groups.append(formatting_optgroup)
-
-	opts, args = parser.parse_args(argv[1:])
+	parser.add_argument("-v", dest="verbose", action="store_true")
+
+	actions = parser.add_argument_group('Actions')
+	actions.add_argument("-h", "--help", action="store_true")
+	actions.add_argument("--version", action="store_true")
+
+	add_pquery_arguments(parser)
+
+	opts, args = parser.parse_known_args(argv[1:])
 
 	if opts.help:
-		usage(argv, parser=parser, pquery_option_groups=pquery_option_groups)
+		usage(argv)
 		return os.EX_OK
 	elif opts.version:
 		print("Portage", portage.VERSION)
@@ -1245,7 +1291,7 @@ def main(argv):
 		args = args[1:]
 
 	if cmd is None:
-		return pquery(parser, pquery_option_groups, opts, args)
+		return pquery(parser, opts, args)
 
 	if opts.verbose:
 		# used by envvar

diff --git a/pym/portage/util/_argparse.py b/pym/portage/util/_argparse.py
index 2f915dc..a9cdc9e 100644
--- a/pym/portage/util/_argparse.py
+++ b/pym/portage/util/_argparse.py
@@ -19,6 +19,7 @@ except ImportError:
 			self.add_argument = parser.add_option
 			self.parse_known_args = parser.parse_args
 			self.parse_args = parser.parse_args
+			self.print_help = parser.print_help
 			self.error = parser.error
 
 		def add_argument_group(self, title=None, **kwargs):


^ permalink raw reply related	[flat|nested] 5+ messages in thread

* [gentoo-commits] proj/portage:master commit in: bin/, pym/portage/util/
@ 2016-12-05  5:14 Brian Dolbec
  0 siblings, 0 replies; 5+ messages in thread
From: Brian Dolbec @ 2016-12-05  5:14 UTC (permalink / raw
  To: gentoo-commits

commit:     c2078c8e836282f20eebf4d756eb8e2859b9afc7
Author:     Brian Dolbec <dolsen <AT> gentoo <DOT> org>
AuthorDate: Wed Nov 30 02:25:36 2016 +0000
Commit:     Brian Dolbec <dolsen <AT> gentoo <DOT> org>
CommitDate: Mon Dec  5 05:13:15 2016 +0000
URL:        https://gitweb.gentoo.org/proj/portage.git/commit/?id=c2078c8e

egencache: Migrate _special_filename class to portage.utils.changelog for api use

Requested move by Robin <robbat2 <AT> gentoo.org> for the new split changelog repo scripts.
Rename the class more appropriately.
Make the file_type_lt() private.

 bin/egencache                 | 76 +++----------------------------------------
 pym/portage/util/changelog.py | 69 +++++++++++++++++++++++++++++++++++++++
 2 files changed, 74 insertions(+), 71 deletions(-)

diff --git a/bin/egencache b/bin/egencache
index 80738cf..e994b4a 100755
--- a/bin/egencache
+++ b/bin/egencache
@@ -52,16 +52,16 @@ from _emerge.MetadataRegen import MetadataRegen
 from portage.cache.cache_errors import CacheError, StatCollision
 from portage.cache.index.pkg_desc_index import pkg_desc_index_line_format
 from portage.const import TIMESTAMP_FORMAT
-from portage.manifest import guessManifestFileType
 from portage.package.ebuild._parallel_manifest.ManifestScheduler import ManifestScheduler
 from portage.util import cmp_sort_key, writemsg_level
 from portage.util._async.AsyncFunction import AsyncFunction
 from portage.util._async.run_main_scheduler import run_main_scheduler
 from portage.util._async.TaskScheduler import TaskScheduler
 from portage.util._eventloop.global_event_loop import global_event_loop
+from portage.util.changelog import ChangeLogTypeSort
 from portage import cpv_getkey
 from portage.dep import Atom, isjustname
-from portage.versions import pkgsplit, vercmp, _pkg_str
+from portage.versions import vercmp
 
 try:
 	from xml.etree import ElementTree
@@ -668,72 +668,6 @@ class GenUseLocalDesc(object):
 		os.utime(desc_path, (mtime, mtime))
 
 
-if sys.hexversion < 0x3000000:
-	_filename_base = unicode
-else:
-	_filename_base = str
-
-class _special_filename(_filename_base):
-	"""
-	Helps to sort file names by file type and other criteria.
-	"""
-	def __new__(cls, status_change, file_name):
-		return _filename_base.__new__(cls, status_change + file_name)
-
-	def __init__(self, status_change, file_name):
-		_filename_base.__init__(status_change + file_name)
-		self.status_change = status_change
-		self.file_name = file_name
-		self.file_type = guessManifestFileType(file_name)
-
-	@staticmethod
-	def file_type_lt(a, b):
-		"""
-		Defines an ordering between file types.
-		"""
-		first = a.file_type
-		second = b.file_type
-		if first == second:
-			return False
-
-		if first == "EBUILD":
-			return True
-		elif first == "MISC":
-			return second in ("EBUILD",)
-		elif first == "AUX":
-			return second in ("EBUILD", "MISC")
-		elif first == "DIST":
-			return second in ("EBUILD", "MISC", "AUX")
-		elif first is None:
-			return False
-		else:
-			raise ValueError("Unknown file type '%s'" % first)
-
-	def __lt__(self, other):
-		"""
-		Compare different file names, first by file type and then
-		for ebuilds by version and lexicographically for others.
-		EBUILD < MISC < AUX < DIST < None
-		"""
-		if self.__class__ != other.__class__:
-			raise NotImplementedError
-
-		# Sort by file type as defined by file_type_lt().
-		if self.file_type_lt(self, other):
-			return True
-		elif self.file_type_lt(other, self):
-			return False
-
-		# Files have the same type.
-		if self.file_type == "EBUILD":
-			# Sort by version. Lowest first.
-			ver = "-".join(pkgsplit(self.file_name[:-7])[1:3])
-			other_ver = "-".join(pkgsplit(other.file_name[:-7])[1:3])
-			return vercmp(ver, other_ver) < 0
-		else:
-			# Sort lexicographically.
-			return self.file_name < other.file_name
-
 class GenChangeLogs(object):
 	def __init__(self, portdb, changelog_output, changelog_reversed,
 		max_jobs=None, max_load=None):
@@ -853,11 +787,11 @@ class GenChangeLogs(object):
 					elif f[1].startswith('ChangeLog'):
 						pass
 					elif f[0].startswith('A'):
-						changed.append(_special_filename("+", f[1]))
+						changed.append(ChangeLogTypeSort("+", f[1]))
 					elif f[0].startswith('D'):
-						changed.append(_special_filename("-", f[1]))
+						changed.append(ChangeLogTypeSort("-", f[1]))
 					elif f[0].startswith('M'):
-						changed.append(_special_filename("", f[1]))
+						changed.append(ChangeLogTypeSort("", f[1]))
 					else:
 						writemsg_level(
 							"ERROR: unexpected git file status for %s: %s\n" % (cp,f,),

diff --git a/pym/portage/util/changelog.py b/pym/portage/util/changelog.py
new file mode 100644
index 0000000..9fc5ab6
--- /dev/null
+++ b/pym/portage/util/changelog.py
@@ -0,0 +1,69 @@
+#!/usr/bin/python -b
+# Copyright 2009-2015 Gentoo Foundation
+# Distributed under the terms of the GNU General Public License v2
+
+
+from portage.manifest import guessManifestFileType
+from portage.versions import _unicode, pkgsplit, vercmp
+
+
+class ChangeLogTypeSort(_unicode):
+	"""
+	Helps to sort file names by file type and other criteria.
+	"""
+	def __new__(cls, status_change, file_name):
+		return _unicode.__new__(cls, status_change + file_name)
+
+	def __init__(self, status_change, file_name):
+		_unicode.__init__(status_change + file_name)
+		self.status_change = status_change
+		self.file_name = file_name
+		self.file_type = guessManifestFileType(file_name)
+
+	@staticmethod
+	def _file_type_lt(a, b):
+		"""
+		Defines an ordering between file types.
+		"""
+		first = a.file_type
+		second = b.file_type
+		if first == second:
+			return False
+
+		if first == "EBUILD":
+			return True
+		elif first == "MISC":
+			return second in ("EBUILD",)
+		elif first == "AUX":
+			return second in ("EBUILD", "MISC")
+		elif first == "DIST":
+			return second in ("EBUILD", "MISC", "AUX")
+		elif first is None:
+			return False
+		else:
+			raise ValueError("Unknown file type '%s'" % first)
+
+	def __lt__(self, other):
+		"""
+		Compare different file names, first by file type and then
+		for ebuilds by version and lexicographically for others.
+		EBUILD < MISC < AUX < DIST < None
+		"""
+		if self.__class__ != other.__class__:
+			raise NotImplementedError
+
+		# Sort by file type as defined by _file_type_lt().
+		if self._file_type_lt(self, other):
+			return True
+		elif self._file_type_lt(other, self):
+			return False
+
+		# Files have the same type.
+		if self.file_type == "EBUILD":
+			# Sort by version. Lowest first.
+			ver = "-".join(pkgsplit(self.file_name[:-7])[1:3])
+			other_ver = "-".join(pkgsplit(other.file_name[:-7])[1:3])
+			return vercmp(ver, other_ver) < 0
+		else:
+			# Sort lexicographically.
+			return self.file_name < other.file_name


^ permalink raw reply related	[flat|nested] 5+ messages in thread

end of thread, other threads:[~2016-12-05  5:14 UTC | newest]

Thread overview: 5+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2013-08-03  0:11 [gentoo-commits] proj/portage:master commit in: bin/, pym/portage/util/ Zac Medico
  -- strict thread matches above, loose matches on Subject: below --
2016-12-05  5:14 Brian Dolbec
2013-07-30 22:37 Zac Medico
2013-07-30 22:23 Zac Medico
2012-05-01  2:31 Zac Medico

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox