Esempio n. 1
0
def parse_module_options(module_opts):
    """Parse module options and update QUERY_OPTS"""

    opts = (x[0] for x in module_opts)
    posargs = (x[1] for x in module_opts)
    for opt, posarg in zip(opts, posargs):
        if opt in ("-h", "--help"):
            print_help()
            sys.exit(0)
        elif opt in ("-I", "--exclude-installed"):
            QUERY_OPTS["in_installed"] = False
        elif opt in ("-p", "--portage-tree"):
            QUERY_OPTS["in_porttree"] = True
        elif opt in ("-o", "--overlay-tree"):
            QUERY_OPTS["in_overlay"] = True
        elif opt in ("-f", "--full-regex"):
            QUERY_OPTS["is_regex"] = True
        elif opt in ("-m", "--mask-reason"):
            QUERY_OPTS["include_mask_reason"] = True
        elif opt in ("-e", "--exact-name"):
            sys.stderr.write(pp.warn("-e, --exact-name is now default."))
            sys.stderr.write(
                pp.warn("Use globbing to simulate the old behavior."))
            print()
        elif opt in ("-d", "--duplicates"):
            QUERY_OPTS["duplicates"] = True
        elif opt in ("-b", "--binpkgs-missing"):
            QUERY_OPTS["binpkgs-missing"] = True
        elif opt in ("-F", "--format"):
            QUERY_OPTS["package_format"] = posarg
Esempio n. 2
0
def parse_module_options(module_opts):
    """Parse module options and update QUERY_OPTS"""

    opts = (x[0] for x in module_opts)
    posargs = (x[1] for x in module_opts)
    for opt, posarg in zip(opts, posargs):
        if opt in ('-h', '--help'):
            print_help()
            sys.exit(0)
        elif opt in ('-I', '--exclude-installed'):
            QUERY_OPTS['in_installed'] = False
        elif opt in ('-p', '--portage-tree'):
            QUERY_OPTS['in_porttree'] = True
        elif opt in ('-o', '--overlay-tree'):
            QUERY_OPTS['in_overlay'] = True
        elif opt in ('-f', '--full-regex'):
            QUERY_OPTS['is_regex'] = True
        elif opt in ('-m', '--mask-reason'):
            QUERY_OPTS['include_mask_reason'] = True
        elif opt in ('-e', '--exact-name'):
            sys.stderr.write(pp.warn("-e, --exact-name is now default."))
            sys.stderr.write(
                pp.warn("Use globbing to simulate the old behavior."))
            print()
        elif opt in ('-d', '--duplicates'):
            QUERY_OPTS['duplicates'] = True
        elif opt in ('-b', '--binpkgs-missing'):
            QUERY_OPTS['binpkgs-missing'] = True
        elif opt in ('-F', '--format'):
            QUERY_OPTS["package_format"] = posarg
Esempio n. 3
0
def parse_module_options(module_opts):
	"""Parse module options and update QUERY_OPTS"""

	opts = (x[0] for x in module_opts)
	posargs = (x[1] for x in module_opts)
	for opt, posarg in zip(opts, posargs):
		if opt in ('-h', '--help'):
			print_help()
			sys.exit(0)
		elif opt in ('-I', '--exclude-installed'):
			QUERY_OPTS['in_installed'] = False
		elif opt in ('-p', '--portage-tree'):
			QUERY_OPTS['in_porttree'] = True
		elif opt in ('-o', '--overlay-tree'):
			QUERY_OPTS['in_overlay'] = True
		elif opt in ('-f', '--full-regex'):
			QUERY_OPTS['is_regex'] = True
		elif opt in ('-m', '--mask-reason'):
			QUERY_OPTS['include_mask_reason'] = True
		elif opt in ('-e', '--exact-name'):
			sys.stderr.write(pp.warn("-e, --exact-name is now default."))
			sys.stderr.write(
				pp.warn("Use globbing to simulate the old behavior.")
			)
			print()
		elif opt in ('-d', '--duplicates'):
			QUERY_OPTS['duplicates'] = True
		elif opt in ('-b', '--binpkgs-missing'):
			QUERY_OPTS['binpkgs-missing'] = True
		elif opt in ('-F', '--format'):
			QUERY_OPTS["package_format"] = posarg
Esempio n. 4
0
def scan_upstream(query):
    matches = Query(query).find(
        include_masked=True,
        in_installed=False
    )

    if not matches:
        sys.stderr.write(pp.warn("No package matching '%s'" % pp.pkgquery(query)))
        return []

    matches = sorted(matches)
    pkg = matches.pop()

    while '9999' in pkg.version and len(matches):
        pkg = matches.pop()

    if not pkg:
        sys.stderr.write(pp.warn("Package '%s' only have a dev version (9999)"
                                 % pp.pkgquery(pkg.cp)))
        return []

    if pkg.cp in BLACKLIST_PACKAGES:
        sys.stderr.write(pp.warn("Package '%s' is blacklisted" % pp.pkgquery(pkg.cp)))
        return []

    if not CONFIG['quiet']:
        pp.uprint(" * %s [%s]" % (pp.cpv(pkg.cpv), pp.section(pkg.repo_name())))
        pp.uprint()

        ebuild_path = pkg.ebuild_path()
        if ebuild_path:
            pp.uprint('Ebuild: ' + pp.path(os.path.normpath(ebuild_path)))

        pp.uprint('Repository: ' + pkg.repo_name())
        pp.uprint('Homepage: ' + pkg.environment("HOMEPAGE"))
        pp.uprint('Description: ' + pkg.environment("DESCRIPTION"))

    cpv = pkg.cpv
    metadata = {
        "EAPI"    : port_settings["EAPI"],
        "SRC_URI" : pkg.environment("SRC_URI", False),
    }
    use = frozenset(port_settings["PORTAGE_USE"].split())
    try:
        alist = porttree._parse_uri_map(cpv, metadata, use=use)
        aalist = porttree._parse_uri_map(cpv, metadata)
    except Exception as e:
        sys.stderr.write(pp.warn("%s\n" % str(e)))
        sys.stderr.write(pp.warn("Invalid SRC_URI for '%s'" % pp.pkgquery(cpv)))
        return []

    if "mirror" in portage.settings.features:
        urls = aalist
    else:
        urls = alist

    return scan_upstream_urls(pkg.cpv, urls)
Esempio n. 5
0
def get_global_useflags():
    """Get global and expanded USE flag variables from
    PORTDIR/profiles/use.desc and PORTDIR/profiles/desc/*.desc respectively.

    @rtype: dict
    @return: {'flag_name': 'flag description', ...}
    """

    global_usedesc = {}
    # Get global USE flag descriptions
    try:
        path = os.path.join(settings["PORTDIR"], "profiles", "use.desc")
        with open(
                _unicode_encode(path, encoding=_encodings["fs"]),
                encoding=_encodings["content"],
        ) as open_file:
            for line in open_file:
                if line.startswith("#"):
                    continue
                # Ex. of fields: ['syslog', 'Enables support for syslog\n']
                fields = line.split(" - ", 1)
                if len(fields) == 2:
                    global_usedesc[fields[0]] = fields[1].rstrip()
    except IOError:
        sys.stderr.write(
            pp.warn("Could not load USE flag descriptions from %s" %
                    pp.path(path)))

    del path, open_file
    # Add USE_EXPANDED variables to usedesc hash -- Bug #238005
    for path in glob(
            os.path.join(settings["PORTDIR"], "profiles", "desc", "*.desc")):
        try:
            with open(
                    _unicode_encode(path, encoding=_encodings["fs"]),
                    encoding=_encodings["content"],
            ) as open_file:
                for line in open_file:
                    if line.startswith("#"):
                        continue
                    fields = [field.strip() for field in line.split(" - ", 1)]
                    if len(fields) == 2:
                        expanded_useflag = "%s_%s" % (
                            path.split("/")[-1][0:-5],
                            fields[0],
                        )
                        global_usedesc[expanded_useflag] = fields[1]
        except IOError:
            sys.stderr.write(
                pp.warn("Could not load USE flag descriptions from %s" % path))

    return global_usedesc
Esempio n. 6
0
def get_global_useflags():
	"""Get global and expanded USE flag variables from
	PORTDIR/profiles/use.desc and PORTDIR/profiles/desc/*.desc respectively.

	@rtype: dict
	@return: {'flag_name': 'flag description', ...}
	"""

	global_usedesc = {}
	# Get global USE flag descriptions
	try:
		path = os.path.join(settings["PORTDIR"], 'profiles', 'use.desc')
		with open(_unicode_encode(path, encoding=_encodings['fs']),
				encoding=_encodings['content']) as open_file:
			for line in open_file:
				if line.startswith('#'):
					continue
				# Ex. of fields: ['syslog', 'Enables support for syslog\n']
				fields = line.split(" - ", 1)
				if len(fields) == 2:
					global_usedesc[fields[0]] = fields[1].rstrip()
	except IOError:
		sys.stderr.write(
			pp.warn(
				"Could not load USE flag descriptions from %s" % pp.path(path)
			)
		)

	del path, open_file
	# Add USE_EXPANDED variables to usedesc hash -- Bug #238005
	for path in glob(os.path.join(settings["PORTDIR"],
		'profiles', 'desc', '*.desc')):
		try:
			with open(_unicode_encode(path, encoding=_encodings['fs']),
					encoding=_encodings['content']) as open_file:
				for line in open_file:
					if line.startswith('#'):
						continue
					fields = [field.strip() for field in line.split(" - ", 1)]
					if len(fields) == 2:
						expanded_useflag = "%s_%s" % \
							(path.split("/")[-1][0:-5], fields[0])
						global_usedesc[expanded_useflag] = fields[1]
		except IOError:
			sys.stderr.write(
				pp.warn("Could not load USE flag descriptions from %s" % path)
			)

	return global_usedesc
Esempio n. 7
0
def print_help(with_description=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()

	# Deprecation warning added by djanderson, 12/2008
	depwarning = (
		"Default action for this module has changed in Gentoolkit 0.3.",
		"Use globbing to simulate the old behavior (see man equery).",
		"Use '*' to check all installed packages.",
		"Use 'foo-bar/*' to filter by category."
	)
	for line in depwarning:
		sys.stderr.write(pp.warn(line))
	print()

	print(mod_usage(mod_name="check"))
	print()
	print(pp.command("options"))
	print(format_options((
		(" -h, --help", "display this help message"),
		(" -f, --full-regex", "query is a regular expression"),
		(" -o, --only-failures", "only display packages that do not pass"),
	)))
Esempio n. 8
0
def main(input_args):
	"""Parse input and run the program"""

	short_opts = "hai"
	long_opts = ('help', 'all', 'ignore-linguas')

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

	parse_module_options(module_opts)

	if not queries:
		print_help()
		sys.exit(2)

	#
	# Output
	#

	first_run = True
	legend_printed = False
	for query in (Query(x) for x in queries):
		if not first_run:
			print()

		if QUERY_OPTS["all_versions"]:
			matches = query.find(include_masked=True)
		else:
			matches = [query.find_best()]

		if not any(matches):
			raise errors.GentoolkitNoMatches(query)

		matches.sort()

		global_usedesc = get_global_useflags()
		for pkg in matches:

			output = get_output_descriptions(pkg, global_usedesc)
			if output:
				if CONFIG['verbose']:
					if not legend_printed:
						print_legend()
						legend_printed = True
					print((" * Found these USE flags for %s:" %
						pp.cpv(str(pkg.cpv))))
					print(pp.emph(" U I"))
				display_useflags(output)
			else:
				if CONFIG['verbose']:
					sys.stderr.write(
						pp.warn("No USE flags found for %s" % pp.cpv(pkg.cpv))
					)

		first_run = False
Esempio n. 9
0
def print_help(with_description=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()

    # Deprecation warning added by djanderson, 12/2008
    depwarning = (
        "Default action for this module has changed in Gentoolkit 0.3.",
        "Use globbing to simulate the old behavior (see man equery).",
        "Use '*' to check all installed packages.",
        "Use 'foo-bar/*' to filter by category.")
    for line in depwarning:
        sys.stderr.write(pp.warn(line))
    print()

    print(mod_usage(mod_name="check"))
    print()
    print(pp.command("options"))
    print(
        format_options((
            (" -h, --help", "display this help message"),
            (" -f, --full-regex", "query is a regular expression"),
            (" -o, --only-failures", "only display packages that do not pass"),
        )))
Esempio n. 10
0
def main(input_args):
	"""Parse input and run the program"""

	short_opts = "hai"
	long_opts = ('help', 'all', 'ignore-l10n')

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

	parse_module_options(module_opts)

	if not queries:
		print_help()
		sys.exit(2)

	#
	# Output
	#

	first_run = True
	legend_printed = False
	for query in (Query(x) for x in queries):
		if not first_run:
			print()

		if QUERY_OPTS["all_versions"]:
			matches = query.find(include_masked=True)
		else:
			matches = [query.find_best()]

		if not any(matches):
			raise errors.GentoolkitNoMatches(query)

		matches.sort()

		global_usedesc = get_global_useflags()
		for pkg in matches:

			output = get_output_descriptions(pkg, global_usedesc)
			if output:
				if CONFIG['verbose']:
					if not legend_printed:
						print_legend()
						legend_printed = True
					print((" * Found these USE flags for %s:" %
						pp.cpv(str(pkg.cpv))))
					print(pp.emph(" U I"))
				display_useflags(output)
			else:
				if CONFIG['verbose']:
					sys.stderr.write(
						pp.warn("No USE flags found for %s" % pp.cpv(pkg.cpv))
					)

		first_run = False
Esempio n. 11
0
def main(input_args):
    """Parse input and run the program"""

    short_opts = "hme"
    long_opts = ('help', 'include-masked', 'ebuild')

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

    parse_module_options(module_opts)

    if not queries:
        print_help()
        sys.exit(2)

    for query in (Query(x) for x in queries):
        matches = query.find(include_masked=QUERY_OPTS['include_masked'],
                             in_installed=False)
        if matches:
            pkg = sorted(matches).pop()
            ebuild_path = pkg.ebuild_path()
            if ebuild_path:
                pp.uprint(os.path.normpath(ebuild_path))
                if QUERY_OPTS['ebuild']:
                    print_ebuild(ebuild_path)
            else:
                sys.stderr.write(pp.warn("No ebuilds to satisfy %s" % pkg.cpv))
        else:
            raise errors.GentoolkitNoMatches(query)
Esempio n. 12
0
	def print_help(self, with_description=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()
			print(__doc__.strip())
			print()
		if self.warning:
			print()
			for line in self.warning:
				sys.stderr.write(pp.warn(line))
			print()
		print(mod_usage(mod_name=self.module_name, arg=self.arg_spec, optional=self.arg_option))
		print()
		print(pp.command("options"))
		print(format_options( self.formatted_options ))
		if self.formatted_args:
			print()
			print(pp.command(self.arg_spec))
			print(format_options(self.formatted_args))
		print()
Esempio n. 13
0
def re_find_package_name(package, regexps, uri):
    if not isinstance(regexps, (list, tuple)):
        regexps = ((regexps, 1),)

    match = None
    group = -1

    for regexp in regexps:
        if isinstance(regexp, (list, tuple)):
            regexp, group = regexp
        else:
            group = 1
        match = regexp.match(uri)
        if match:
            break

    if not match:
        sys.stderr.write(pp.warn("Can't find package name in '%s'" % uri))
        return None

    package_name = match.group(group)

    # Try to strip version, if present
    if "-%s" % package.version in package_name:
        package_name.replace("-%s" % package.version, "")
    cpv = "fake/" + package_name
    cpv = portage.pkgsplit(cpv)

    if cpv:
        package_name = cpv[0].replace("fake/", "", 1)
    return package_name
Esempio n. 14
0
def download_data(url, data=None):
    try:
        return urllib2.urlopen(url, data).read()
    except Exception as err:
        if _options.verbose:
            sys.stderr.write(pp.warn("Failed to get %s: " % url + str(err)))
        return False
Esempio n. 15
0
	def print_help(self, with_description=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()
			print(__doc__.strip())
			print()
		if self.warning:
			print()
			for line in self.warning:
				sys.stderr.write(pp.warn(line))
			print()
		print(mod_usage(mod_name=self.module_name, arg=self.arg_spec, optional=self.arg_option))
		print()
		print(pp.command("options"))
		print(format_options( self.formatted_options ))
		if self.formatted_args:
			print()
			print(pp.command(self.arg_spec))
			print(format_options(self.formatted_args))
		print()
Esempio n. 16
0
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 ('-b', '--bytes'):
            QUERY_OPTS["size_in_bytes"] = True
        elif opt in ('-e', '--exact-name'):
            sys.stderr.write(pp.warn("-e, --exact-name is now default."))
            warning = pp.warn("Use globbing to simulate the old behavior.")
            sys.stderr.write(warning)
            print()
        elif opt in ('-f', '--full-regex'):
            QUERY_OPTS['is_regex'] = True
Esempio n. 17
0
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 ('-b', '--bytes'):
			QUERY_OPTS["size_in_bytes"] = True
		elif opt in ('-e', '--exact-name'):
			sys.stderr.write(pp.warn("-e, --exact-name is now default."))
			warning = pp.warn("Use globbing to simulate the old behavior.")
			sys.stderr.write(warning)
			print()
		elif opt in ('-f', '--full-regex'):
			QUERY_OPTS['is_regex'] = True
Esempio n. 18
0
def main(input_args):
    """Parse input and run the program."""

    short_opts = "hdHklmrSuUx"
    long_opts = (
        "help",
        "description",
        "herd",
        "keywords",
        "license",
        "maintainer",
        "reverse",
        "stablereq",
        "useflags",
        "upstream",
        "xml",
    )

    try:
        module_opts, queries = gnu_getopt(input_args, short_opts, long_opts)
    except GetoptError as 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 (Query(x) for x in queries):
        best_match = query.find_best()
        matches = query.find(include_masked=True)
        if best_match is None or not matches:
            raise errors.GentoolkitNoMatches(query)

        if best_match.metadata is None:
            print(
                pp.warn("Package {0} is missing "
                        "metadata.xml".format(best_match.cpv)),
                file=sys.stderr,
            )
            continue

        if not first_run:
            print()

        matches.sort()
        matches.sort(reverse=any(name in ("-r", "--reverse")
                                 for name, opt in module_opts))
        call_format_functions(best_match, matches)

        first_run = False
Esempio n. 19
0
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 ('-e', '--early-out', '--earlyout'):
			if opt == '--earlyout':
				sys.stderr.write(pp.warn("Use of --earlyout is deprecated."))
				sys.stderr.write(pp.warn("Please use --early-out."))
				print()
			QUERY_OPTS['early_out'] = True
		elif opt in ('-f', '--full-regex'):
			QUERY_OPTS['full_regex'] = True
		elif opt in ('-n', '--name-only'):
			QUERY_OPTS['name_only'] = True
Esempio n. 20
0
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 ("-e", "--early-out", "--earlyout"):
            if opt == "--earlyout":
                sys.stderr.write(pp.warn("Use of --earlyout is deprecated."))
                sys.stderr.write(pp.warn("Please use --early-out."))
                print()
            QUERY_OPTS["early_out"] = True
        elif opt in ("-f", "--full-regex"):
            QUERY_OPTS["full_regex"] = True
        elif opt in ("-n", "--name-only"):
            QUERY_OPTS["name_only"] = True
Esempio n. 21
0
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 ('-e', '--early-out', '--earlyout'):
            if opt == '--earlyout':
                sys.stderr.write(pp.warn("Use of --earlyout is deprecated."))
                sys.stderr.write(pp.warn("Please use --early-out."))
                print()
            QUERY_OPTS['early_out'] = True
        elif opt in ('-f', '--full-regex'):
            QUERY_OPTS['full_regex'] = True
        elif opt in ('-n', '--name-only'):
            QUERY_OPTS['name_only'] = True
Esempio n. 22
0
def check_query(query, action):
    matches = Query(query).find(include_masked=True, in_installed=False)

    if not matches:
        sys.stderr.write(pp.warn("No package matching '%s'" % pp.pkgquery(query)))
        return

    matches = sorted(matches)

    for package in matches:
        action(package)
Esempio n. 23
0
def del_remote_id_tag(data, remote_type, remote_id):
    pattern = r"\s*?<remote-id\s+type=('|\")%s\1>%s</remote-id>\s*?"
    pattern = pattern % (remote_type, remote_id)

    m = re.search(pattern, data)

    if not m:
        sys.stderr.write(pp.warn("Can't find bad remote id tag '%s' '%s'" % (remote_type, remote_id)))
        return

    return data[: m.start()] + data[m.end() :]
Esempio n. 24
0
def upstream_remote_id(query):
    matches = Query(query).find(include_masked=True, in_installed=False)

    if not matches:
        sys.stderr.write(pp.warn("No package matching '%s'" % pp.pkgquery(query)))
        return

    matches = sorted(matches)
    matches.reverse()
    # Only latest version
    matches = matches[:1]
    for package in matches:
        upstream_remote_id_package(package)
Esempio n. 25
0
def php_package_name(package, uri):
    match = None
    for regexp in _php_package_name_re:
        match = regexp.search(uri)
        if match:
            break

    if not match:
        sys.stderr.write(pp.warn("Can't find package name in '%s'" % uri))
        return None, None

    channel = match.group(1)
    pkg = match.group(2)
    return pkg, channel
Esempio n. 26
0
def print_help(with_description=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()

    # Deprecation warning added by djanderson, 12/2008
    depwarning = (
        "Default action for this module has changed in Gentoolkit 0.3.",
        "Use globbing to simulate the old behavior (see man equery).",
        "Use '*' to check all installed packages.",
        "Use 'foo-bar/*' to filter by category.",
    )
    for line in depwarning:
        sys.stderr.write(pp.warn(line))
    print()

    print(mod_usage(mod_name="list"))
    print()
    print(pp.command("options"))
    print(
        format_options((
            (" -h, --help", "display this help message"),
            (" -d, --duplicates", "list only installed duplicate packages"),
            (
                " -b, --binpkgs-missing",
                "list only installed packages without a corresponding binary package",
            ),
            (" -f, --full-regex", "query is a regular expression"),
            (" -m, --mask-reason", "include reason for package mask"),
            (" -I, --exclude-installed",
             "exclude installed packages from output"),
            (" -o, --overlay-tree", "list packages in overlays"),
            (" -p, --portage-tree", "list packages in the main portage tree"),
            (" -F, --format=TMPL", "specify a custom output format"),
            ("              TMPL", "a format template using (see man page):"),
        )))
    print(" " * 24, ", ".join(pp.emph(x) for x in FORMAT_TMPL_VARS))
Esempio n. 27
0
def main(input_args):
	"""Parse input and run the program."""

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

	try:
		module_opts, queries = gnu_getopt(input_args, short_opts, long_opts)
	except GetoptError as 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 (Query(x) for x in queries):
		best_match = query.find_best()
		matches = query.find(include_masked=True)
		if best_match is None or not matches:
			raise errors.GentoolkitNoMatches(query)

		if best_match.metadata is None:
			print(pp.warn("Package {0} is missing "
				"metadata.xml".format(best_match.cpv)),
				file = sys.stderr)
			continue

		if not first_run:
			print()

		matches.sort()
		call_format_functions(best_match, matches)

		first_run = False
Esempio n. 28
0
def print_help(with_description=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()

	# Deprecation warning added by djanderson, 12/2008
	depwarning = (
		"Default action for this module has changed in Gentoolkit 0.3.",
		"Use globbing to simulate the old behavior (see man equery).",
		"Use '*' to check all installed packages.",
		"Use 'foo-bar/*' to filter by category."
	)
	for line in depwarning:
		sys.stderr.write(pp.warn(line))
	print()

	print(mod_usage(mod_name="list"))
	print()
	print(pp.command("options"))
	print(format_options((
		(" -h, --help", "display this help message"),
		(" -d, --duplicates", "list only installed duplicate packages"),
		(" -b, --binpkgs-missing", "list only installed packages without a corresponding binary package"),
		(" -f, --full-regex", "query is a regular expression"),
		(" -m, --mask-reason", "include reason for package mask"),
		(" -I, --exclude-installed",
			"exclude installed packages from output"),
		(" -o, --overlay-tree", "list packages in overlays"),
		(" -p, --portage-tree", "list packages in the main portage tree"),
		(" -F, --format=TMPL", "specify a custom output format"),
        ("              TMPL",
			"a format template using (see man page):")
	)))
	print(" " * 24, ', '.join(pp.emph(x) for x in FORMAT_TMPL_VARS))			
Esempio n. 29
0
def main(input_args):
	"""Parse input and run the program"""

	short_opts = "hme"
	long_opts = ('help', 'include-masked', 'ebuild')

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

	parse_module_options(module_opts)

	if not queries:
		print_help()
		sys.exit(2)

	for query in (Query(x) for x in queries):
		matches = query.find(
			include_masked=QUERY_OPTS['include_masked'],
			in_installed=False
		)
		if matches:
			pkg = sorted(matches).pop()
			ebuild_path = pkg.ebuild_path()
			if ebuild_path:
				pp.uprint(os.path.normpath(ebuild_path))
				if QUERY_OPTS['ebuild']:
					print_ebuild(ebuild_path)
			else:
				sys.stderr.write(
					pp.warn("No ebuilds to satisfy %s" % pkg.cpv)
				)
		else:
			raise errors.GentoolkitNoMatches(query)
Esempio n. 30
0
from portage.dep import Atom, use_reduce
from portage.dep._slot_operator import strip_slots

import gentoolkit.pprinter as pp
from gentoolkit.eclean.exclude import (exclDictMatchCP, exclDictExpand,
                                       exclDictExpandPkgname,
                                       exclMatchFilename)

# Misc. shortcuts to some portage stuff:
port_settings = portage.settings
pkgdir = port_settings["PKGDIR"]

err = sys.stderr
deprecated_message = """"Deprecation Warning: Installed package: %s
	Is no longer in the tree or an installed overlay"""
DEPRECATED = pp.warn(deprecated_message)

debug_modules = []


def dprint(module, message):
    if module in debug_modules:
        print(message)


def get_distdir():
    """Returns DISTDIR if sane, else barfs."""

    d = portage.settings["DISTDIR"]
    if not os.path.isdir(d):
        e = pp.error("%s does not appear to be a directory.\n" % d)
Esempio n. 31
0
def call_format_functions(best_match, matches):
    """Call information gathering functions and display the results."""

    if CONFIG['verbose']:
        repo = best_match.repo_name()
        pp.uprint(" * %s [%s]" % (pp.cpv(best_match.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 = best_match.metadata.herds(include_email=True)
        if any(not h[0] for h in herds):
            print(pp.warn("The packages metadata.xml has an empty <herd> tag"),
                  file=sys.stderr)
            herds = [x for x in herds if x[0]]
        herds = format_herds(herds)
        if QUERY_OPTS["herd"]:
            print_sequence(format_list(herds))
        else:
            for herd in herds:
                pp.uprint(format_line(herd, "Herd:        ", " " * 13))

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

    if QUERY_OPTS["upstream"] or not got_opts:
        upstream = format_upstream(best_match.metadata.upstream())
        homepage = format_homepage(best_match.environment("HOMEPAGE"))
        if QUERY_OPTS["upstream"]:
            upstream = format_list(upstream)
        else:
            upstream = format_list(upstream, "Upstream:    ", " " * 13)
        print_sequence(upstream)
        print_sequence(homepage)

    if not got_opts:
        pkg_loc = best_match.package_path()
        pp.uprint(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"]:
                pp.uprint(keywords_line)
            else:
                indent = " " * (16 + verstr_len)
                pp.uprint(format_line(keywords_line, "Keywords:    ", indent))

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

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

    if QUERY_OPTS["license"] or not got_opts:
        _license = best_match.environment(["LICENSE"])
        if QUERY_OPTS["license"]:
            _license = format_list(_license)
        else:
            _license = format_list(_license, "License:     ", " " * 13)
        print_sequence(_license)

    if QUERY_OPTS["stablereq"]:
        # Get {<Package 'dev-libs/glib-2.20.5'>: [u'ia64', u'm68k', ...], ...}
        stablereq_map = stablereq(matches)
        for match in matches:
            slot = match.environment('SLOT')
            verstr_len = len(match.fullversion) + len(slot)
            fmtd_ccs = ','.join(sorted(stablereq_map[match]))
            stablereq_line = format_stablereq_line(match, fmtd_ccs, slot)
            #print("STABLEREQ:", )
            pp.uprint(stablereq_line)

    if QUERY_OPTS["xml"]:
        print_file(os.path.join(best_match.package_path(), 'metadata.xml'))
Esempio n. 32
0
import portage

import gentoolkit
import gentoolkit.pprinter as pp
from gentoolkit.eclean.exclude import exclDictMatchCP, exclDictExpand, exclDictExpandPkgname, exclMatchFilename


# Misc. shortcuts to some portage stuff:
port_settings = portage.settings
pkgdir = port_settings["PKGDIR"]

err = sys.stderr
deprecated_message = """"Deprecation Warning: Installed package: %s
	Is no longer in the tree or an installed overlay"""
DEPRECATED = pp.warn(deprecated_message)

debug_modules = []


def dprint(module, message):
    if module in debug_modules:
        print(message)


def get_distdir():
    """Returns DISTDIR if sane, else barfs."""

    d = portage.settings["DISTDIR"]
    if not os.path.isdir(d):
        e = pp.error("%s does not appear to be a directory.\n" % d)
Esempio n. 33
0
def scan_upstream(query, on_progress=None):
    """
    Scans the upstream searching new versions for the given query
    """

    maxval = 3
    curval = 0

    matches = []

    if query.endswith(".ebuild"):
        cpv = package_from_ebuild(query)
        if cpv:
            reload_gentoolkit()
            matches = [Package(cpv)]
    else:
        matches = Query(query).find(
            include_masked=True,
            in_installed=False
        )

    if not matches:
        output.ewarn(
            pp.warn("No package matching '%s'" % pp.pkgquery(query))
        )
        return None

    matches = sorted(matches)
    pkg = matches.pop()

    while '9999' in pkg.version and len(matches):
        pkg = matches.pop()

    if not pkg:
        output.ewarn(
            pp.warn("Package '%s' only have a dev version (9999)"
                    % pp.pkgquery(pkg.cp))
        )
        return None

    # useful data only for formatted output
    start_time = datetime.now()
    output.metadata("datetime", start_time.isoformat(), show=False)
    output.metadata("cp", pkg.cp, show=False)
    output.metadata("cpv", pkg.cpv, show=False)

    curval += 1
    if on_progress:
        on_progress(maxval, curval)

    if pkg.cp in BLACKLIST_PACKAGES:
        output.ewarn(
            pp.warn("Package '%s' is blacklisted" % pp.pkgquery(pkg.cp))
        )
        return None

    if not CONFIG['quiet']:
        if not CONFIG['format']:
            pp.uprint(
                " * %s [%s]" % (pp.cpv(pkg.cpv), pp.section(pkg.repo_name()))
            )
            pp.uprint()
        else:
            output.metadata("overlay", pp.section(pkg.repo_name()))

        ebuild_path = pkg.ebuild_path()
        if ebuild_path:
            output.metadata(
                "ebuild", pp.path(os.path.normpath(ebuild_path))
            )

        output.metadata("repository", pkg.repo_name())
        output.metadata("homepage", pkg.environment("HOMEPAGE"))
        output.metadata("description", pkg.environment("DESCRIPTION"))

    cpv = pkg.cpv
    metadata = {
        "EAPI": portage.settings["EAPI"],
        "SRC_URI": pkg.environment("SRC_URI", False),
    }
    use = frozenset(portage.settings["PORTAGE_USE"].split())
    try:
        alist = porttree._parse_uri_map(cpv, metadata, use=use)
        aalist = porttree._parse_uri_map(cpv, metadata)
    except Exception as e:
        output.ewarn(pp.warn("%s\n" % str(e)))
        output.ewarn(
            pp.warn("Invalid SRC_URI for '%s'" % pp.pkgquery(cpv))
        )
        return None

    if "mirror" in portage.settings.features:
        urls = aalist
    else:
        urls = alist

    # output scan time for formatted output
    scan_time = (datetime.now() - start_time).total_seconds()
    output.metadata("scan_time", scan_time, show=False)

    curval += 1
    if on_progress:
        on_progress(maxval, curval)

    result = scan_upstream_urls(pkg.cpv, urls, on_progress)

    curval += 1
    if on_progress:
        on_progress(maxval, curval)

    return result
Esempio n. 34
0
def scan_upstream(query, on_progress=None):
    """
    Scans the upstream searching new versions for the given query
    """
    matches = []

    if query.endswith(".ebuild"):
        cpv = package_from_ebuild(query)
        reload_gentoolkit()
        if cpv:
            matches = [Package(cpv)]
    else:
        matches = Query(query).find(
            include_masked=True,
            in_installed=False,
        )

    if not matches:
        output.ewarn(pp.warn("No package matching '%s'" % pp.pkgquery(query)))
        return None

    matches = sorted(matches)
    pkg = matches.pop()

    while '9999' in pkg.version and len(matches):
        pkg = matches.pop()

    if not pkg:
        output.ewarn(
            pp.warn("Package '%s' only have a dev version (9999)" %
                    pp.pkgquery(pkg.cp)))
        return None

    # useful data only for formatted output
    start_time = datetime.now()
    output.metadata("datetime", start_time.isoformat(), show=False)
    output.metadata("cp", pkg.cp, show=False)
    output.metadata("cpv", pkg.cpv, show=False)

    if on_progress:
        on_progress(increment=10)

    if pkg.cp in BLACKLIST_PACKAGES:
        output.ewarn(
            pp.warn("Package '%s' is blacklisted" % pp.pkgquery(pkg.cp)))
        return None

    if not CONFIG['quiet']:
        if not CONFIG['format']:
            pp.uprint(" * %s [%s]" %
                      (pp.cpv(pkg.cpv), pp.section(pkg.repo_name())))
            pp.uprint()
        else:
            output.metadata("overlay", pp.section(pkg.repo_name()))

        ebuild_path = pkg.ebuild_path()
        if ebuild_path:
            output.metadata("ebuild", pp.path(os.path.normpath(ebuild_path)))

        uris, homepage, description = pkg.environment(
            ('SRC_URI', 'HOMEPAGE', 'DESCRIPTION'))

        output.metadata("repository", pkg.repo_name())
        output.metadata("homepage", homepage)
        output.metadata("description", description)
    else:
        uris = pkg.environment('SRC_URI')

    cpv = pkg.cpv

    uris = parse_src_uri(uris)
    uris_expanded = [
        from_mirror(uri) if 'mirror://' in uri else uri for uri in uris
    ]

    pkg._uris = uris
    pkg._uris_expanded = uris_expanded

    versions = handlers.scan(pkg, uris, on_progress)

    cp, ver, rev = portage.pkgsplit(pkg.cpv)

    result = filter_versions(cp, versions)

    if on_progress:
        on_progress(increment=10)

    # output scan time for formatted output
    scan_time = (datetime.now() - start_time).total_seconds()
    output.metadata("scan_time", scan_time, show=False)

    is_current_version_stable = is_version_stable(ver)
    if len(result) > 0:
        if not (CONFIG['format'] or CONFIG['quiet']):
            print("")
        for cp, url, version, handler, confidence in result:
            if CONFIG["ignore-pre-release"]:
                if not is_version_stable(version):
                    continue
            if CONFIG["ignore-pre-release-if-stable"]:
                if is_current_version_stable and \
                   not is_version_stable(version):
                    continue
            if CONFIG['progress']:
                print("", file=sys.stderr)
            output.result(cp, version, url, handler, confidence)

    return result
Esempio n. 35
0
def call_format_functions(best_match, matches):
	"""Call information gathering functions and display the results."""

	if CONFIG['verbose']:
		repo = best_match.repo_name()
		pp.uprint(" * %s [%s]" % (pp.cpv(best_match.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 = best_match.metadata.herds(include_email=True)
		if any(not h[0] for h in herds):
			print(pp.warn("The packages metadata.xml has an empty <herd> tag"),
				file = sys.stderr)
			herds = [x for x in herds if x[0]]
		herds = format_herds(herds)
		if QUERY_OPTS["herd"]:
			print_sequence(format_list(herds))
		else:
			for herd in herds:
				pp.uprint(format_line(herd, "Herd:        ", " " * 13))

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

	if QUERY_OPTS["upstream"] or not got_opts:
		upstream = format_upstream(best_match.metadata.upstream())
		homepage = format_homepage(best_match.environment("HOMEPAGE"))
		if QUERY_OPTS["upstream"]:
			upstream = format_list(upstream)
		else:
			upstream = format_list(upstream, "Upstream:    ", " " * 13)
		print_sequence(upstream)
		print_sequence(homepage)

	if not got_opts:
		pkg_loc = best_match.package_path()
		pp.uprint(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"]:
				pp.uprint(keywords_line)
			else:
				indent = " " * (16 + verstr_len)
				pp.uprint(format_line(keywords_line, "Keywords:    ", indent))

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

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

	if QUERY_OPTS["stablereq"]:
		# Get {<Package 'dev-libs/glib-2.20.5'>: [u'ia64', u'm68k', ...], ...}
		stablereq_map = stablereq(matches)
		for match in matches:
			slot = match.environment('SLOT')
			verstr_len = len(match.fullversion) + len(slot)
			fmtd_ccs = ','.join(sorted(stablereq_map[match]))
			stablereq_line = format_stablereq_line(
				match, fmtd_ccs, slot
			)
			#print("STABLEREQ:", )
			pp.uprint(stablereq_line)

	if QUERY_OPTS["xml"]:
		print_file(os.path.join(best_match.package_path(), 'metadata.xml'))
Esempio n. 36
0
def scan_upstream(query, on_progress=None):
    """
    Scans the upstream searching new versions for the given query
    """
    matches = []

    if query.endswith(".ebuild"):
        cpv = package_from_ebuild(query)
        reload_gentoolkit()
        if cpv:
            matches = [Package(cpv)]
    else:
        matches = Query(query).find(
            include_masked=True,
            in_installed=False,
        )

    if not matches:
        output.ewarn(
            pp.warn("No package matching '%s'" % pp.pkgquery(query))
        )
        return None

    matches = sorted(matches)
    pkg = matches.pop()

    while '9999' in pkg.version and len(matches):
        pkg = matches.pop()

    if not pkg:
        output.ewarn(
            pp.warn("Package '%s' only have a dev version (9999)"
                    % pp.pkgquery(pkg.cp))
        )
        return None

    # useful data only for formatted output
    start_time = datetime.now()
    output.metadata("datetime", start_time.isoformat(), show=False)
    output.metadata("cp", pkg.cp, show=False)
    output.metadata("cpv", pkg.cpv, show=False)

    if on_progress:
        on_progress(increment=10)

    if pkg.cp in BLACKLIST_PACKAGES:
        output.ewarn(
            pp.warn("Package '%s' is blacklisted" % pp.pkgquery(pkg.cp))
        )
        return None

    if not CONFIG['quiet']:
        if not CONFIG['format']:
            pp.uprint(
                " * %s [%s]" % (pp.cpv(pkg.cpv), pp.section(pkg.repo_name()))
            )
            pp.uprint()
        else:
            output.metadata("overlay", pp.section(pkg.repo_name()))

        ebuild_path = pkg.ebuild_path()
        if ebuild_path:
            output.metadata(
                "ebuild", pp.path(os.path.normpath(ebuild_path))
            )

        uris, homepage, description = pkg.environment(
            ('SRC_URI', 'HOMEPAGE', 'DESCRIPTION')
        )

        output.metadata("repository", pkg.repo_name())
        output.metadata("homepage", homepage)
        output.metadata("description", description)
    else:
        uris = pkg.environment('SRC_URI')

    cpv = pkg.cpv

    uris = parse_src_uri(uris)
    uris_expanded = [
        from_mirror(uri) if 'mirror://' in uri else uri for uri in uris
    ]

    pkg._uris = uris
    pkg._uris_expanded = uris_expanded

    versions = handlers.scan(pkg, uris, on_progress)

    cp, ver, rev = portage.pkgsplit(pkg.cpv)

    result = filter_versions(cp, versions)

    if on_progress:
        on_progress(increment=10)

    # output scan time for formatted output
    scan_time = (datetime.now() - start_time).total_seconds()
    output.metadata("scan_time", scan_time, show=False)

    is_current_version_stable = is_version_stable(ver)
    if len(result) > 0:
        if not (CONFIG['format'] or CONFIG['quiet']):
            print("")
        for cp, url, version, handler, confidence in result:
            if CONFIG["ignore-pre-release"]:
                if not is_version_stable(version):
                    continue
            if CONFIG["ignore-pre-release-if-stable"]:
                if is_current_version_stable and \
                   not is_version_stable(version):
                    continue
            if CONFIG['progress']:
                print("", file=sys.stderr)
            output.result(cp, version, url, handler, confidence)

    return result