예제 #1
0
def main(input_args):
    """Parse input and run the program"""

    short_opts = "h:fen"
    long_opts = ('help', 'full-regex', 'early-out', 'earlyout', 'name-only')

    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)

    if CONFIG['verbose']:
        pp.uprint(" * Searching for %s ... " %
                  (pp.regexpquery(",".join(queries))))

    printer_fn = BelongsPrinter(verbose=CONFIG['verbose'],
                                name_only=QUERY_OPTS['name_only'])

    find_owner = FileOwner(is_regex=QUERY_OPTS['full_regex'],
                           early_out=QUERY_OPTS['early_out'],
                           printer_fn=printer_fn)

    if not find_owner(queries):
        sys.exit(1)
예제 #2
0
파일: has.py 프로젝트: zmedico/gentoolkit
def display_pkg(query, env_var, pkg):
	"""Display information for a given package."""

	if CONFIG['verbose']:
		pkgstr = PackageFormatter(
			pkg,
			do_format=True,
			custom_format=QUERY_OPTS["package_format"]
		)
	else:
		pkgstr = PackageFormatter(
			pkg,
			do_format=False,
			custom_format=QUERY_OPTS["package_format"]
		)

	if (QUERY_OPTS["in_installed"] and
		not QUERY_OPTS["in_porttree"] and
		not QUERY_OPTS["in_overlay"]):
		if not 'I' in  pkgstr.location:
			return False
	if (QUERY_OPTS["in_porttree"] and
		not QUERY_OPTS["in_overlay"]):
		if not 'P' in  pkgstr.location:
			return False
	if (QUERY_OPTS["in_overlay"] and
		not QUERY_OPTS["in_porttree"]):
		if not 'O' in  pkgstr.location:
			return False
	pp.uprint(pkgstr)

	return True
예제 #3
0
파일: query.py 프로젝트: zmedico/gentoolkit
	def print_summary(self):
		"""Print a summary of the query."""

		if self.query_type == "set":
			cat_str = ""
			pkg_str = pp.emph(self.query)
		else:
			try:
				cat, pkg = self.category, self.name + self.fullversion
			except errors.GentoolkitInvalidCPV:
				cat = ''
				pkg = self.atom
			if cat and not self.is_regex:
				cat_str = "in %s " % pp.emph(cat.lstrip('><=~!'))
			else:
				cat_str = ""

			if self.is_regex:
				pkg_str = pp.emph(self.query)
			else:
				pkg_str = pp.emph(pkg)

		repo = ''
		if self.repo_filter is not None:
			repo = ' %s' % pp.section(self.repo_filter)

		pp.uprint(" * Searching%s for %s %s..." % (repo, pkg_str, cat_str))
예제 #4
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)
예제 #5
0
 def print_quiet(self, pkg, cfile):
     "Format for minimal output."
     if self.name_only:
         name = pkg.cp
     else:
         name = str(pkg.cpv)
     pp.uprint(name)
예제 #6
0
파일: size.py 프로젝트: mjsir911/gentoolkit
def display_size(match_set):
    """Display the total size of all accessible files owned by packages.

	@type match_set: list
	@param match_set: package cat/pkg-ver strings
	"""

    for pkg in match_set:
        size, files, uncounted = pkg.size()

        if CONFIG['verbose']:
            pp.uprint(" * %s" % pp.cpv(str(pkg.cpv)))
            print("Total files : %s".rjust(25) % pp.number(str(files)))

            if uncounted:
                print(("Inaccessible files : %s".rjust(25) %
                       pp.number(str(uncounted))))

            if QUERY_OPTS["size_in_bytes"]:
                size_str = pp.number(str(size))
            else:
                size_str = "%s %s" % format_bytes(size)

            print("Total size  : %s".rjust(25) % size_str)
        else:
            info = "%s: total(%d), inaccessible(%d), size(%s)"
            pp.uprint(info % (str(pkg.cpv), files, uncounted, size))
예제 #7
0
파일: scan.py 프로젝트: tomspur/euscan
def scan_upstream_urls(cpv, urls):
    versions = []

    for filename in urls:
        for url in urls[filename]:
            if not CONFIG['quiet']:
                pp.uprint()
            euscan.output.einfo("SRC_URI is '%s'" % url)

            if '://' not in url:
                euscan.output.einfo("Invalid url '%s'" % url)
                continue

            ''' Try normal scan '''
            if CONFIG["scan-dir"]:
                versions.extend(handlers.scan(cpv, url))

            if versions and CONFIG['oneshot']:
                break

            ''' Brute Force '''
            if CONFIG["brute-force"] > 0:
                versions.extend(handlers.brute_force(cpv, url))

            if versions and CONFIG['oneshot']:
                break

    cp, ver, rev = portage.pkgsplit(cpv)
    return filter_versions(cp, versions)
예제 #8
0
def print_file(path):
    """Display the contents of a file."""

    with open(_unicode_encode(path, encoding=_encodings['fs']),
              mode="rb") as open_file:
        lines = open_file.read()
        pp.uprint(lines.strip())
예제 #9
0
def display_useflags(query, pkg):
    """Display USE flag information for a given package."""

    try:
        useflags = [x.lstrip("+-") for x in pkg.environment("IUSE").split()]
    except errors.GentoolkitFatalError:
        # aux_get KeyError or other unexpected result
        return False

    if query not in useflags:
        return False

    if CONFIG['verbose']:
        pkgstr = PackageFormatter(pkg,
                                  do_format=True,
                                  custom_format=QUERY_OPTS["package_format"])
    else:
        pkgstr = PackageFormatter(pkg,
                                  do_format=False,
                                  custom_format=QUERY_OPTS["package_format"])

    if (QUERY_OPTS["in_installed"] and not QUERY_OPTS["in_porttree"]
            and not QUERY_OPTS["in_overlay"]):
        if not 'I' in pkgstr.location:
            return False
    if (QUERY_OPTS["in_porttree"] and not QUERY_OPTS["in_overlay"]):
        if not 'P' in pkgstr.location:
            return False
    if (QUERY_OPTS["in_overlay"] and not QUERY_OPTS["in_porttree"]):
        if not 'O' in pkgstr.location:
            return False
    pp.uprint(pkgstr)

    return True
예제 #10
0
def display_pkg(query, env_var, pkg):
    """Display information for a given package."""

    if CONFIG['verbose']:
        pkgstr = PackageFormatter(pkg,
                                  do_format=True,
                                  custom_format=QUERY_OPTS["package_format"])
    else:
        pkgstr = PackageFormatter(pkg,
                                  do_format=False,
                                  custom_format=QUERY_OPTS["package_format"])

    if (QUERY_OPTS["in_installed"] and not QUERY_OPTS["in_porttree"]
            and not QUERY_OPTS["in_overlay"]):
        if not 'I' in pkgstr.location:
            return False
    if (QUERY_OPTS["in_porttree"] and not QUERY_OPTS["in_overlay"]):
        if not 'P' in pkgstr.location:
            return False
    if (QUERY_OPTS["in_overlay"] and not QUERY_OPTS["in_porttree"]):
        if not 'O' in pkgstr.location:
            return False
    pp.uprint(pkgstr)

    return True
예제 #11
0
    def print_summary(self):
        """Print a summary of the query."""

        if self.query_type == "set":
            cat_str = ""
            pkg_str = pp.emph(self.query)
        else:
            try:
                cat, pkg = self.category, self.name + self.fullversion
            except errors.GentoolkitInvalidCPV:
                cat = ''
                pkg = self.atom
            if cat and not self.is_regex:
                cat_str = "in %s " % pp.emph(cat.lstrip('><=~!'))
            else:
                cat_str = ""

            if self.is_regex:
                pkg_str = pp.emph(self.query)
            else:
                pkg_str = pp.emph(pkg)

        repo = ''
        if self.repo_filter is not None:
            repo = ' %s' % pp.section(self.repo_filter)

        pp.uprint(" * Searching%s for %s %s..." % (repo, pkg_str, cat_str))
예제 #12
0
def checks_printer(cpv, data, verbose=True, only_failures=False):
    """Output formatted results of pkg file(s) checks"""
    seen = []

    n_passed, n_checked, errs = data
    n_failed = n_checked - n_passed
    if only_failures and not n_failed:
        return
    else:
        if verbose:
            if not cpv in seen:
                pp.uprint("* Checking %s ..." % (pp.emph(str(cpv))))
                seen.append(cpv)
        else:
            pp.uprint("%s:" % cpv, end=' ')

    if verbose:
        for err in errs:
            sys.stderr.write(pp.error(err))

    if verbose:
        n_passed = pp.number(str(n_passed))
        n_checked = pp.number(str(n_checked))
        info = "   %(n_passed)s out of %(n_checked)s files passed"
        print(info % locals())
        print()
    else:
        print("failed(%s)" % n_failed)
예제 #13
0
	def print_quiet(self, pkg, cfile):
		"Format for minimal output."
		if self.name_only:
			name = pkg.cp
		else:
			name = str(pkg.cpv)
		pp.uprint(name)
예제 #14
0
파일: size.py 프로젝트: zmedico/gentoolkit
def display_size(match_set):
	"""Display the total size of all accessible files owned by packages.

	@type match_set: list
	@param match_set: package cat/pkg-ver strings
	"""

	for pkg in match_set:
		size, files, uncounted = pkg.size()

		if CONFIG['verbose']:
			pp.uprint(" * %s" % pp.cpv(str(pkg.cpv)))
			print("Total files : %s".rjust(25) % pp.number(str(files)))

			if uncounted:
				print(("Inaccessible files : %s".rjust(25) %
					pp.number(str(uncounted))))

			if QUERY_OPTS["size_in_bytes"]:
				size_str = pp.number(str(size))
			else:
				size_str = "%s %s" % format_bytes(size)

			print("Total size  : %s".rjust(25) % size_str)
		else:
			info = "%s: total(%d), inaccessible(%d), size(%s)"
			pp.uprint(info % (str(pkg.cpv), files, uncounted, size))
예제 #15
0
def checks_printer(cpv, data, verbose=True, only_failures=False):
	"""Output formatted results of pkg file(s) checks"""
	seen = []

	n_passed, n_checked, errs = data
	n_failed = n_checked - n_passed
	if only_failures and not n_failed:
		return
	else:
		if verbose:
			if not cpv in seen:
				pp.uprint("* Checking %s ..." % (pp.emph(str(cpv))))
				seen.append(cpv)
		else:
			pp.uprint("%s:" % cpv, end=' ')

	if verbose:
		for err in errs:
			sys.stderr.write(pp.error(err))

	if verbose:
		n_passed = pp.number(str(n_passed))
		n_checked = pp.number(str(n_checked))
		info = "   %(n_passed)s out of %(n_checked)s files passed"
		print(info % locals())
	else:
		print("failed(%s)" % n_failed)
예제 #16
0
 def print_verbose(self, pkg, cfile):
     "Format for full output."
     file_str = pp.path(format_filetype(cfile, pkg.parsed_contents()[cfile]))
     if self.name_only:
         name = pkg.cp
     else:
         name = str(pkg.cpv)
     pp.uprint(pp.cpv(name), "(" + file_str + ")")
예제 #17
0
	def print_verbose(self, pkg, cfile):
		"Format for full output."
		file_str = pp.path(format_filetype(cfile, pkg.parsed_contents()[cfile]))
		if self.name_only:
			name = pkg.cp
		else:
			name = str(pkg.cpv)
		pp.uprint(pp.cpv(name), "(" + file_str + ")")
예제 #18
0
def depgraph_printer(depth,
                     pkg,
                     dep,
                     no_use=False,
                     no_atom=False,
                     no_indent=False,
                     initial_pkg=False,
                     no_mask=False):
    """Display L{gentoolkit.dependencies.Dependencies.graph_depends} results.

	@type depth: int
	@param depth: depth of indirection, used to calculate indent
	@type pkg: L{gentoolkit.package.Package}
	@param pkg: "best match" package matched by B{dep}
	@type dep: L{gentoolkit.atom.Atom}
	@param dep: dependency that matched B{pkg}
	@type no_use: bool
	@param no_use: don't output USE flags
	@type no_atom: bool
	@param no_atom: don't output dep atom
	@type no_indent: bool
	@param no_indent: don't output indent based on B{depth}
	@type initial_pkg: bool
	@param initial_pkg: somewhat of a hack used to print the root package of
		the graph with absolutely no indent
	"""
    indent = '' if no_indent or initial_pkg else ' ' + (' ' * depth)
    decorator = '[%3d] ' % depth if no_indent else '`-- '
    use = ''
    atom = ''
    mask = ''
    try:
        if not no_atom:
            if dep.operator == '=*':
                atom += ' (=%s*)' % dep.cpv
            else:
                atom += ' (%s%s)' % (dep.operator, dep.cpv)
        if not no_use and dep is not None and dep.use:
            use = ' [%s]' % ' '.join(
                pp.useflag(x, enabled=True) for x in dep.use.tokens)
    except AttributeError:
        # 'NoneType' object has no attribute 'atom'
        pass
    if pkg and not no_mask:
        mask = pkg.mask_status()
        if not mask:
            mask = [
                determine_keyword(portage.settings["ARCH"],
                                  portage.settings["ACCEPT_KEYWORDS"],
                                  pkg.environment('KEYWORDS'))
            ]
        mask = pp.masking(mask)
    try:
        pp.uprint(' '.join(
            (indent, decorator, pp.cpv(str(pkg.cpv)), atom, mask, use)))
    except AttributeError:
        # 'NoneType' object has no attribute 'cpv'
        pp.uprint(''.join((indent, decorator, "(no match for %r)" % dep.atom)))
예제 #19
0
def print_entries(entries):
	"""Print entries and strip trailing whitespace from the last entry."""

	len_entries = len(entries)
	for i, entry in enumerate(entries, start=1):
		if i < len_entries:
			pp.uprint(entry)
		else:
			pp.uprint(entry.strip())
예제 #20
0
def print_entries(entries):
    """Print entries and strip trailing whitespace from the last entry."""

    len_entries = len(entries)
    for i, entry in enumerate(entries, start=1):
        if i < len_entries:
            pp.uprint(entry)
        else:
            pp.uprint(entry.strip())
예제 #21
0
def main(input_args):
    """Parse input and run the program"""

    short_opts = "hiIpoF:"  # -i was option for default action
    # --installed is no longer needed, kept for compatibility (djanderson '09)
    long_opts = (
        "help",
        "installed",
        "exclude-installed",
        "portage-tree",
        "overlay-tree",
        "format=",
    )

    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)

    matches = Query("*").smart_find(**QUERY_OPTS)
    matches.sort()

    #
    # Output
    #

    first_run = True
    got_match = False
    for query in queries:
        if not first_run:
            print()

        if CONFIG["verbose"]:
            pp.uprint(" * Searching for USE flag %s ... " % pp.emph(query))

        for pkg in matches:
            if display_useflags(query, pkg):
                got_match = True

        first_run = False

    if not got_match:
        sys.exit(1)
예제 #22
0
def main(input_args):
	"""Parse input and run the program"""

	# -e, --exact-name is legacy option. djanderson '09
	short_opts = "hemstf:"
	long_opts = ('help', 'exact-name', 'md5sum', 'timestamp', 'type', 'tree',
		'filter=')

	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)

	# Turn off filtering for tree output
	if QUERY_OPTS["output_tree"]:
		QUERY_OPTS["type_filter"] = None

	#
	# Output files
	#

	first_run = True
	for query in queries:
		if not first_run:
			print()

		matches = Query(query).smart_find(**QUERY_OPTS)

		if not matches:
			sys.stderr.write(
				pp.error("No matching packages found for %s" % query)
			)

		matches.sort()

		for pkg in matches:
			if CONFIG['verbose']:
				pp.uprint(" * Contents of %s:" % pp.cpv(str(pkg.cpv)))

			contents = pkg.parsed_contents()
			display_files(filter_contents(contents))

		first_run = False
예제 #23
0
파일: files.py 프로젝트: pamxy/gentoolkit
def main(input_args):
    """Parse input and run the program"""

    # -e, --exact-name is legacy option. djanderson '09
    short_opts = "hemstf:"
    long_opts = ('help', 'exact-name', 'md5sum', 'timestamp', 'type', 'tree',
                 'filter=')

    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)

    # Turn off filtering for tree output
    if QUERY_OPTS["output_tree"]:
        QUERY_OPTS["type_filter"] = None

    #
    # Output files
    #

    first_run = True
    for query in queries:
        if not first_run:
            print()

        matches = Query(query).smart_find(**QUERY_OPTS)

        if not matches:
            sys.stderr.write(
                pp.error("No matching packages found for %s" % query))

        matches.sort()

        for pkg in matches:
            if CONFIG['verbose']:
                pp.uprint(" * Contents of %s:" % pp.cpv(str(pkg.cpv)))

            contents = pkg.parsed_contents()
            display_files(filter_contents(contents))

        first_run = False
예제 #24
0
파일: scan.py 프로젝트: mgorny/euscan
def scan_upstream_urls(cpv, urls, on_progress):
    versions = []

    maxval = len(urls) + 5
    curval = 1

    for filename in urls:
        curval += 1
        if on_progress:
            on_progress(maxval, curval)

        for url in urls[filename]:
            if not CONFIG['quiet'] and not CONFIG['format']:
                pp.uprint()
            output.einfo("SRC_URI is '%s'" % url)

            if '://' not in url:
                output.einfo("Invalid url '%s'" % url)
                continue

            # Try normal scan
            if CONFIG["scan-dir"]:
                try:
                    versions.extend(handlers.scan(cpv, url))
                except Exception as e:
                    output.ewarn("Handler failed: [%s] %s"
                            % (e.__class__.__name__, e.message))

            if versions and CONFIG['oneshot']:
                break

            # Brute Force
            if CONFIG["brute-force"] > 0:
                versions.extend(handlers.brute_force(cpv, url))

            if versions and CONFIG['oneshot']:
                break

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

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

    result = filter_versions(cp, versions)

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

    return result
예제 #25
0
def display_useflags(output):
    """Print USE flag descriptions and statuses.

	@type output: list
	@param output: [(inuse, inused, flag, desc, restrict), ...]
		inuse (int) = 0 or 1; if 1, flag is set in make.conf
		inused (int) = 0 or 1; if 1, package is installed with flag enabled
		flag (str) = the name of the USE flag
		desc (str) = the flag's description
		restrict (str) = corresponds to the text of restrict in metadata
	"""

    maxflag_len = len(max([t[2] for t in output], key=len))

    twrap = TextWrapper()
    twrap.width = CONFIG['termWidth']
    twrap.subsequent_indent = " " * (maxflag_len + 8)

    markers = ("-", "+")
    color = (partial(pp.useflag,
                     enabled=False), partial(pp.useflag, enabled=True))
    for in_makeconf, in_installed, flag, desc, restrict in output:
        if CONFIG['verbose']:
            flag_name = ""
            if in_makeconf != in_installed:
                flag_name += pp.emph(
                    " %s %s" % (markers[in_makeconf], markers[in_installed]))
            else:
                flag_name += (" %s %s" %
                              (markers[in_makeconf], markers[in_installed]))

            flag_name += " " + color[in_makeconf](flag.ljust(maxflag_len))
            flag_name += " : "

            # Strip initial whitespace at the start of the description
            # Bug 432530
            if desc:
                desc = desc.lstrip()

            # print description
            if restrict:
                restrict = "(%s %s)" % (pp.emph("Restricted to"),
                                        pp.cpv(restrict))
                twrap.initial_indent = flag_name
                pp.uprint(twrap.fill(restrict))
                if desc:
                    twrap.initial_indent = twrap.subsequent_indent
                    pp.uprint(twrap.fill(desc))
                else:
                    print(" : <unknown>")
            else:
                if desc:
                    twrap.initial_indent = flag_name
                    desc = twrap.fill(desc)
                    pp.uprint(desc)
                else:
                    twrap.initial_indent = flag_name
                    print(twrap.fill("<unknown>"))
        else:
            pp.uprint(markers[in_makeconf] + flag)
예제 #26
0
def depgraph_printer(depth, pkg, dep, no_use=False, no_atom=False, no_indent=False, initial_pkg=False, no_mask=False):
    """Display L{gentoolkit.dependencies.Dependencies.graph_depends} results.

	@type depth: int
	@param depth: depth of indirection, used to calculate indent
	@type pkg: L{gentoolkit.package.Package}
	@param pkg: "best match" package matched by B{dep}
	@type dep: L{gentoolkit.atom.Atom}
	@param dep: dependency that matched B{pkg}
	@type no_use: bool
	@param no_use: don't output USE flags
	@type no_atom: bool
	@param no_atom: don't output dep atom
	@type no_indent: bool
	@param no_indent: don't output indent based on B{depth}
	@type initial_pkg: bool
	@param initial_pkg: somewhat of a hack used to print the root package of
		the graph with absolutely no indent
	"""
    indent = "" if no_indent or initial_pkg else " " + (" " * depth)
    decorator = "[%3d] " % depth if no_indent else "`-- "
    use = ""
    atom = ""
    mask = ""
    try:
        if not no_atom:
            if dep.operator == "=*":
                atom += " (=%s*)" % dep.cpv
            else:
                atom += " (%s%s)" % (dep.operator, dep.cpv)
        if not no_use and dep is not None and dep.use:
            use = " [%s]" % " ".join(pp.useflag(x, enabled=True) for x in dep.use.tokens)
    except AttributeError:
        # 'NoneType' object has no attribute 'atom'
        pass
    if pkg and not no_mask:
        mask = pkg.mask_status()
        if not mask:
            mask = [
                determine_keyword(
                    portage.settings["ARCH"], portage.settings["ACCEPT_KEYWORDS"], pkg.environment("KEYWORDS")
                )
            ]
        mask = pp.masking(mask)
    try:
        pp.uprint(" ".join((indent, decorator, pp.cpv(str(pkg.cpv)), atom, mask, use)))
    except AttributeError:
        # 'NoneType' object has no attribute 'cpv'
        pp.uprint("".join((indent, decorator, "(no match for %r)" % dep.atom)))
예제 #27
0
def main(input_args):
	"""Parse input and run the program"""

	short_opts = "hiIpoF:" # -i was option for default action
	# --installed is no longer needed, kept for compatibility (djanderson '09)
	long_opts = ('help', 'installed', 'exclude-installed', 'portage-tree',
		'overlay-tree', 'format=')

	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)

	matches = Query("*").smart_find(**QUERY_OPTS)
	matches.sort()

	#
	# Output
	#

	first_run = True
	got_match = False
	for query in queries:
		if not first_run:
			print()

		if CONFIG['verbose']:
			pp.uprint(" * Searching for USE flag %s ... " % pp.emph(query))

		for pkg in matches:
			if display_useflags(query, pkg):
				got_match = True

		first_run = False

	if not got_match:
		sys.exit(1)
예제 #28
0
def display_useflags(query, pkg):
	"""Display USE flag information for a given package."""

	try:
		useflags = [x.lstrip("+-") for x in pkg.environment("IUSE").split()]
	except errors.GentoolkitFatalError:
		# aux_get KeyError or other unexpected result
		return False

	if query not in useflags:
		return False

	if CONFIG['verbose']:
		pkgstr = PackageFormatter(
			pkg,
			do_format=True,
			custom_format=QUERY_OPTS["package_format"]
		)
	else:
		pkgstr = PackageFormatter(
			pkg,
			do_format=False,
			custom_format=QUERY_OPTS["package_format"]
		)

	if (QUERY_OPTS["in_installed"] and
		not QUERY_OPTS["in_porttree"] and
		not QUERY_OPTS["in_overlay"]):
		if not 'I' in  pkgstr.location:
			return False
	if (QUERY_OPTS["in_porttree"] and
		not QUERY_OPTS["in_overlay"]):
		if not 'P' in  pkgstr.location:
			return False
	if (QUERY_OPTS["in_overlay"] and
		not QUERY_OPTS["in_porttree"]):
		if not 'O' in  pkgstr.location:
			return False
	pp.uprint(pkgstr)

	return True
예제 #29
0
def make_depgraph(pkg, printer_fn):
    """Create and display depgraph for each package."""

    print()
    if CONFIG['verbose']:
        pp.uprint(" * " + pp.subsection("dependency graph for ") +
                  pp.cpv(str(pkg.cpv)))
    else:
        pp.uprint("%s:" % pkg.cpv)

    # Print out the first package
    printer_fn(0, pkg, None, initial_pkg=True)

    deps = pkg.deps.graph_depends(
        max_depth=QUERY_OPTS['depth'],
        printer_fn=printer_fn,
        # Use this to set this pkg as the graph's root; better way?
        result=[(0, pkg)])

    if CONFIG['verbose']:
        pkgname = pp.cpv(str(pkg.cpv))
        n_packages = pp.number(str(len(deps)))
        max_seen = pp.number(str(max(x[0] for x in deps)))
        info = "[ %s stats: packages (%s), max depth (%s) ]"
        pp.uprint(info % (pkgname, n_packages, max_seen))
예제 #30
0
def make_depgraph(pkg, printer_fn):
    """Create and display depgraph for each package."""

    print()
    if CONFIG["verbose"]:
        pp.uprint(" * " + pp.subsection("dependency graph for ") + pp.cpv(str(pkg.cpv)))
    else:
        pp.uprint("%s:" % pkg.cpv)

        # Print out the first package
    printer_fn(0, pkg, None, initial_pkg=True)

    deps = pkg.deps.graph_depends(
        max_depth=QUERY_OPTS["depth"],
        printer_fn=printer_fn,
        # Use this to set this pkg as the graph's root; better way?
        result=[(0, pkg)],
    )

    if CONFIG["verbose"]:
        pkgname = pp.cpv(str(pkg.cpv))
        n_packages = pp.number(str(len(deps)))
        max_seen = pp.number(str(max(x[0] for x in deps)))
        info = "[ %s stats: packages (%s), max depth (%s) ]"
        pp.uprint(info % (pkgname, n_packages, max_seen))
예제 #31
0
def main(input_args):
	"""Parse input and run the program"""

	short_opts = "h:fen"
	long_opts = ('help', 'full-regex', 'early-out', 'earlyout',
		'name-only')

	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)

	if CONFIG['verbose']:
		pp.uprint(" * Searching for %s ... " % (
			pp.regexpquery(",".join(queries)))
		)

	printer_fn = BelongsPrinter(
		verbose=CONFIG['verbose'], name_only=QUERY_OPTS['name_only']
	)

	find_owner = FileOwner(
		is_regex=QUERY_OPTS['full_regex'],
		early_out=QUERY_OPTS['early_out'],
		printer_fn=printer_fn
	)

	if not find_owner(queries):
		sys.exit(1)
예제 #32
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)
예제 #33
0
def main(input_args):
    """Parse input and run the program"""

    short_opts = "hiIpoF:"  # -i was option for default action
    # --installed is no longer needed, kept for compatibility (djanderson '09)
    long_opts = ('help', 'installed', 'exclude-installed', 'portage-tree',
                 'overlay-tree', 'format=', 'package=')

    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)

    query_scope = QUERY_OPTS['package_filter'] or '*'
    matches = Query(query_scope).smart_find(**QUERY_OPTS)
    matches.sort()

    # split out the first query since it is suppose to be the env_var
    QUERY_OPTS['env_var'] = queries.pop(0)
    env_var = QUERY_OPTS['env_var']

    #
    # Output
    #

    if not queries:
        if not QUERY_OPTS['package_filter']:
            err = "Used ENV_VAR without match_expression or --package"
            raise errors.GentoolkitFatalError(err, is_serious=False)
        else:
            if len(matches) > 1:
                raise errors.AmbiguousPackageName(matches)
            for match in matches:
                env = QUERY_OPTS['env_var']
                print(match.environment(env))

    first_run = True
    got_match = False
    for query in queries:
        if not first_run:
            print()

        if CONFIG['verbose']:
            status = " * Searching for {0} {1} ... "
            pp.uprint(status.format(env_var, pp.emph(query)))

        for pkg in matches:
            if query_in_env(query, env_var, pkg):
                display_pkg(query, env_var, pkg)
                got_match = True
        first_run = False

    if not got_match:
        sys.exit(1)
예제 #34
0
def print_file(path):
	"""Display the contents of a file."""

	with open(path, "rb") as open_file:
		lines = open_file.read()
		pp.uprint(lines.strip())
예제 #35
0
파일: scan.py 프로젝트: mgorny/euscan
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
예제 #36
0
def print_sequence(seq):
    """Print every item of a sequence."""

    for item in seq:
        pp.uprint(item)
예제 #37
0
파일: scan.py 프로젝트: EvaSDK/euscan
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
예제 #38
0
    def print_verbose(indent, cpv, use_conditional, depatom):
        """Verbosely prints a set of dep strings."""

        sep = ' ? ' if (depatom and use_conditional) else ''
        pp.uprint(indent + pp.cpv(cpv),
                  "(" + use_conditional + sep + depatom + ")")
예제 #39
0
파일: meta.py 프로젝트: gronkern/gentoolkit
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'))
예제 #40
0
def print_sequence(seq):
	"""Print every item of a sequence."""

	for item in seq:
		pp.uprint(item)
예제 #41
0
파일: uses.py 프로젝트: zmedico/gentoolkit
def display_useflags(output):
	"""Print USE flag descriptions and statuses.

	@type output: list
	@param output: [(inuse, inused, flag, desc, restrict), ...]
		inuse (int) = 0 or 1; if 1, flag is set in make.conf
		inused (int) = 0 or 1; if 1, package is installed with flag enabled
		flag (str) = the name of the USE flag
		desc (str) = the flag's description
		restrict (str) = corresponds to the text of restrict in metadata
	"""

	maxflag_len = len(max([t[2] for t in output], key=len))

	twrap = TextWrapper()
	twrap.width = CONFIG['termWidth']
	twrap.subsequent_indent = " " * (maxflag_len + 8)

	markers = ("-", "+")
	color = (
		partial(pp.useflag, enabled=False), partial(pp.useflag, enabled=True)
	)
	for in_makeconf, in_installed, flag, desc, restrict in output:
		if CONFIG['verbose']:
			flag_name = ""
			if in_makeconf != in_installed:
				flag_name += pp.emph(" %s %s" %
					(markers[in_makeconf], markers[in_installed]))
			else:
				flag_name += (" %s %s" %
					(markers[in_makeconf], markers[in_installed]))

			flag_name += " " + color[in_makeconf](flag.ljust(maxflag_len))
			flag_name += " : "

			# Strip initial whitespace at the start of the description
			# Bug 432530
			if desc:
				desc = desc.lstrip()

			# print description
			if restrict:
				restrict = "(%s %s)" % (pp.emph("Restricted to"),
					pp.cpv(restrict))
				twrap.initial_indent = flag_name
				pp.uprint(twrap.fill(restrict))
				if desc:
					twrap.initial_indent = twrap.subsequent_indent
					pp.uprint(twrap.fill(desc))
				else:
					print(" : <unknown>")
			else:
				if desc:
					twrap.initial_indent = flag_name
					desc = twrap.fill(desc)
					pp.uprint(desc)
				else:
					twrap.initial_indent = flag_name
					print(twrap.fill("<unknown>"))
		else:
			pp.uprint(markers[in_makeconf] + flag)
예제 #42
0
def print_file(path):
	"""Display the contents of a file."""

	with open(path, "rb") as open_file:
		lines = open_file.read()
		pp.uprint(lines.strip())
예제 #43
0
	def print_quiet(indent, cpv, use_conditional, depatom):
		"""Quietly prints a subset set of dep strings."""

		pp.uprint(indent + cpv)
예제 #44
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
예제 #45
0
def main(input_args):
	"""Parse input and run the program"""

	short_opts = "hdbefiImopF:" # -i, -e were options for default actions

	# 04/09: djanderson
	# --all is no longer needed. Kept for compatibility.
	# --installed is no longer needed. Kept for compatibility.
	# --exact-name is no longer needed. Kept for compatibility.
	long_opts = ('help', 'all', 'installed', 'exclude-installed',
		'mask-reason', 'portage-tree', 'overlay-tree', 'format=', 'full-regex',
		'exact-name', 'duplicates', 'binpkgs-missing')

	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)

	# Only search installed packages when listing duplicate or missing binary packages
	if QUERY_OPTS["duplicates"] or QUERY_OPTS["binpkgs-missing"]:
		QUERY_OPTS["in_installed"] = True
		QUERY_OPTS["in_porttree"] = False
		QUERY_OPTS["in_overlay"] = False
		QUERY_OPTS["include_mask_reason"] = False

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

	first_run = True
	for query in (Query(x, QUERY_OPTS['is_regex']) for x in queries):
		if not first_run:
			print()

		# if we are in quiet mode, do not raise GentoolkitNoMatches exception
		# instead we raise GentoolkitNonZeroExit to exit with an exit value of 3
		try:
			matches = query.smart_find(**QUERY_OPTS)
		except errors.GentoolkitNoMatches:
			if CONFIG['verbose']:
				raise
			else:
				raise errors.GentoolkitNonZeroExit(3)

		# Find duplicate packages
		if QUERY_OPTS["duplicates"]:
			matches = get_duplicates(matches)

		# Find missing binary packages
		if QUERY_OPTS["binpkgs-missing"]:
			matches = get_binpkgs_missing(matches)

		matches.sort()

		#
		# Output
		#

		for pkg in matches:
			pkgstr = PackageFormatter(
				pkg,
				do_format=CONFIG['verbose'],
				custom_format=QUERY_OPTS["package_format"]
			)

			if (QUERY_OPTS["in_porttree"] and
				not QUERY_OPTS["in_overlay"]):
				if not 'P' in pkgstr.location:
					continue
			if (QUERY_OPTS["in_overlay"] and
				not QUERY_OPTS["in_porttree"]):
				if not 'O' in pkgstr.location:
					continue
			pp.uprint(pkgstr)

			if QUERY_OPTS["include_mask_reason"]:
				ms_int, ms_orig = pkgstr.format_mask_status()
				if ms_int < 3:
					# ms_int is a number representation of mask level.
					# Only 2 and above are "hard masked" and have reasons.
					continue
				mask_reason = pkg.mask_reason()
				if not mask_reason:
					# Package not on system or not masked
					continue
				elif not any(mask_reason):
					print(" * No mask reason given")
				else:
					status = ', '.join(ms_orig)
					explanation = mask_reason[0]
					mask_location = mask_reason[1]
					pp.uprint(" * Masked by %r" % status)
					pp.uprint(" * %s:" % mask_location)
					pp.uprint('\n'.join(
						[' * %s' % line.lstrip(' #')
							for line in explanation.splitlines()]
						))

		first_run = False
예제 #46
0
def main(input_args):
    """Parse input and run the program"""

    short_opts = "hdbefiImopF:"  # -i, -e were options for default actions

    # 04/09: djanderson
    # --all is no longer needed. Kept for compatibility.
    # --installed is no longer needed. Kept for compatibility.
    # --exact-name is no longer needed. Kept for compatibility.
    long_opts = ('help', 'all', 'installed', 'exclude-installed',
                 'mask-reason', 'portage-tree', 'overlay-tree', 'format=',
                 'full-regex', 'exact-name', 'duplicates', 'binpkgs-missing')

    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)

    # Only search installed packages when listing duplicate or missing binary packages
    if QUERY_OPTS["duplicates"] or QUERY_OPTS["binpkgs-missing"]:
        QUERY_OPTS["in_installed"] = True
        QUERY_OPTS["in_porttree"] = False
        QUERY_OPTS["in_overlay"] = False
        QUERY_OPTS["include_mask_reason"] = False

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

    first_run = True
    for query in (Query(x, QUERY_OPTS['is_regex']) for x in queries):
        if not first_run:
            print()

        # if we are in quiet mode, do not raise GentoolkitNoMatches exception
        # instead we raise GentoolkitNonZeroExit to exit with an exit value of 3
        try:
            matches = query.smart_find(**QUERY_OPTS)
        except errors.GentoolkitNoMatches:
            if CONFIG['verbose']:
                raise
            else:
                raise errors.GentoolkitNonZeroExit(3)

        # Find duplicate packages
        if QUERY_OPTS["duplicates"]:
            matches = get_duplicates(matches)

        # Find missing binary packages
        if QUERY_OPTS["binpkgs-missing"]:
            matches = get_binpkgs_missing(matches)

        matches.sort()

        #
        # Output
        #

        for pkg in matches:
            pkgstr = PackageFormatter(
                pkg,
                do_format=CONFIG['verbose'],
                custom_format=QUERY_OPTS["package_format"])

            if (QUERY_OPTS["in_porttree"] and not QUERY_OPTS["in_overlay"]):
                if not 'P' in pkgstr.location:
                    continue
            if (QUERY_OPTS["in_overlay"] and not QUERY_OPTS["in_porttree"]):
                if not 'O' in pkgstr.location:
                    continue
            pp.uprint(pkgstr)

            if QUERY_OPTS["include_mask_reason"]:
                ms_int, ms_orig = pkgstr.format_mask_status()
                if ms_int < 3:
                    # ms_int is a number representation of mask level.
                    # Only 2 and above are "hard masked" and have reasons.
                    continue
                mask_reason = pkg.mask_reason()
                if not mask_reason:
                    # Package not on system or not masked
                    continue
                elif not any(mask_reason):
                    print(" * No mask reason given")
                else:
                    status = ', '.join(ms_orig)
                    explanation = mask_reason[0]
                    mask_location = mask_reason[1]
                    pp.uprint(" * Masked by %r" % status)
                    pp.uprint(" * %s:" % mask_location)
                    pp.uprint('\n'.join([
                        ' * %s' % line.lstrip(' #')
                        for line in explanation.splitlines()
                    ]))

        first_run = False
예제 #47
0
파일: files.py 프로젝트: pamxy/gentoolkit
def display_files(contents):
    """Display the content of an installed package.

	@see: gentoolkit.package.Package.parsed_contents
	@type contents: dict
	@param contents: {'path': ['filetype', ...], ...}
	"""

    filenames = list(contents.keys())
    filenames.sort()
    last = []

    for name in filenames:
        if QUERY_OPTS["output_tree"]:
            dirdepth = name.count('/')
            indent = " "
            if dirdepth == 2:
                indent = "   "
            elif dirdepth > 2:
                indent = "   " * (dirdepth - 1)

            basename = name.rsplit("/", dirdepth - 1)
            if contents[name][0] == "dir":
                if len(last) == 0:
                    last = basename
                    pp.uprint(pp.path(indent + basename[0]))
                    continue
                for i, directory in enumerate(basename):
                    try:
                        if directory in last[i]:
                            continue
                    except IndexError:
                        pass
                    last = basename
                    if len(last) == 1:
                        pp.uprint(pp.path(indent + last[0]))
                        continue
                    pp.uprint(pp.path(indent + "> /" + last[-1]))
            elif contents[name][0] == "sym":
                pp.uprint(pp.path(indent + "+"), end=' ')
                pp.uprint(
                    pp.path_symlink(basename[-1] + " -> " + contents[name][2]))
            else:
                pp.uprint(pp.path(indent + "+ ") + basename[-1])
        else:
            pp.uprint(
                format_filetype(name,
                                contents[name],
                                show_type=QUERY_OPTS["show_type"],
                                show_md5=QUERY_OPTS["show_MD5"],
                                show_timestamp=QUERY_OPTS["show_timestamp"]))
예제 #48
0
파일: has.py 프로젝트: zmedico/gentoolkit
def main(input_args):
	"""Parse input and run the program"""

	short_opts = "hiIpoF:" # -i was option for default action
	# --installed is no longer needed, kept for compatibility (djanderson '09)
	long_opts = ('help', 'installed', 'exclude-installed', 'portage-tree',
		'overlay-tree', 'format=', 'package=')

	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)

	query_scope = QUERY_OPTS['package_filter'] or '*'
	matches = Query(query_scope).smart_find(**QUERY_OPTS)
	matches.sort()

	# split out the first query since it is suppose to be the env_var
	QUERY_OPTS['env_var'] = queries.pop(0)
	env_var = QUERY_OPTS['env_var']

	#
	# Output
	#

	if not queries:
		if not QUERY_OPTS['package_filter']:
			err = "Used ENV_VAR without match_expression or --package"
			raise errors.GentoolkitFatalError(err, is_serious=False)
		else:
			if len(matches) > 1:
				raise errors.AmbiguousPackageName(matches)
			for match in matches:
				env = QUERY_OPTS['env_var']
				print(match.environment(env))

	first_run = True
	got_match = False
	for query in queries:
		if not first_run:
			print()

		if CONFIG['verbose']:
			status = " * Searching for {0} {1} ... "
			pp.uprint(status.format(env_var, pp.emph(query)))

		for pkg in matches:
			if query_in_env(query, env_var, pkg):
				display_pkg(query, env_var, pkg)
				got_match = True
		first_run = False

	if not got_match:
		sys.exit(1)
예제 #49
0
    def print_quiet(indent, cpv, use_conditional, depatom):
        """Quietly prints a subset set of dep strings."""

        pp.uprint(indent + cpv)
예제 #50
0
def display_files(contents):
	"""Display the content of an installed package.

	@see: gentoolkit.package.Package.parsed_contents
	@type contents: dict
	@param contents: {'path': ['filetype', ...], ...}
	"""

	filenames = list(contents.keys())
	filenames.sort()
	last = []

	for name in filenames:
		if QUERY_OPTS["output_tree"]:
			dirdepth = name.count('/')
			indent = " "
			if dirdepth == 2:
				indent = "   "
			elif dirdepth > 2:
				indent = "   " * (dirdepth - 1)

			basename = name.rsplit("/", dirdepth - 1)
			if contents[name][0] == "dir":
				if len(last) == 0:
					last = basename
					pp.uprint(pp.path(indent + basename[0]))
					continue
				for i, directory in enumerate(basename):
					try:
						if directory in last[i]:
							continue
					except IndexError:
						pass
					last = basename
					if len(last) == 1:
						pp.uprint(pp.path(indent + last[0]))
						continue
					pp.uprint(pp.path(indent + "> /" + last[-1]))
			elif contents[name][0] == "sym":
				pp.uprint(pp.path(indent + "+"), end=' ')
				pp.uprint(pp.path_symlink(basename[-1] + " -> " +
					contents[name][2]))
			else:
				pp.uprint(pp.path(indent + "+ ") + basename[-1])
		else:
			pp.uprint(format_filetype(
				name,
				contents[name],
				show_type=QUERY_OPTS["show_type"],
				show_md5=QUERY_OPTS["show_MD5"],
				show_timestamp=QUERY_OPTS["show_timestamp"]
			))
예제 #51
0
파일: scan.py 프로젝트: tomspur/euscan
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)
예제 #52
0
	def print_verbose(indent, cpv, use_conditional, depatom):
		"""Verbosely prints a set of dep strings."""

		sep = ' ? ' if (depatom and use_conditional) else ''
		pp.uprint(indent + pp.cpv(cpv), "(" + use_conditional +
			sep + depatom + ")")
예제 #53
0
def main(input_args):
    """Parse input and run the program"""

    short_opts = "hlf"
    long_opts = ('help', 'full', 'from=', 'latest', 'limit=', 'to=')

    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)

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

        match = query.find_best()
        if match is None:
            continue

        got_match = True
        changelog_path = os.path.join(match.package_path(), 'ChangeLog')
        changelog = ChangeLog(changelog_path)

        #
        # Output
        #

        if (QUERY_OPTS['only_latest']
                or (changelog.entries and not changelog.indexed_entries)):
            pp.uprint(changelog.latest.strip())
        else:
            end = QUERY_OPTS['limit'] or len(changelog.indexed_entries)
            if QUERY_OPTS['to'] or QUERY_OPTS['from']:
                print_entries(
                    changelog.entries_matching_range(
                        from_ver=QUERY_OPTS['from'],
                        to_ver=QUERY_OPTS['to'])[:end])
            elif QUERY_OPTS['show_full_log']:
                print_entries(changelog.full[:end])
            else:
                # Raises GentoolkitInvalidAtom here if invalid
                if query.is_ranged():
                    atom = Atom(str(query))
                else:
                    atom = '=' + str(match.cpv)
                print_entries(changelog.entries_matching_atom(atom)[:end])

        first_run = False

    if not got_match:
        sys.exit(1)
예제 #54
0
def print_file(path):
	"""Display the contents of a file."""

	with open(_unicode_encode(path, encoding=_encodings['fs']), mode="rb") as open_file:
		lines = open_file.read()
		pp.uprint(lines.strip())
예제 #55
0
def main(input_args):
	"""Parse input and run the program"""

	short_opts = "hlf"
	long_opts = ('help', 'full', 'from=', 'latest', 'limit=', 'to=')

	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)

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

		match = query.find_best()
		if match is None:
			continue

		got_match = True
		changelog_path = os.path.join(match.package_path(), 'ChangeLog')
		changelog = ChangeLog(changelog_path)

		#
		# Output
		#

		if (QUERY_OPTS['only_latest'] or (
			changelog.entries and not changelog.indexed_entries
		)):
			pp.uprint(changelog.latest.strip())
		else:
			end = QUERY_OPTS['limit'] or len(changelog.indexed_entries)
			if QUERY_OPTS['to'] or QUERY_OPTS['from']:
				print_entries(
					changelog.entries_matching_range(
						from_ver=QUERY_OPTS['from'],
						to_ver=QUERY_OPTS['to']
					)[:end]
				)
			elif QUERY_OPTS['show_full_log']:
				print_entries(changelog.full[:end])
			else:
				# Raises GentoolkitInvalidAtom here if invalid
				if query.is_ranged():
					atom = Atom(str(query))
				else:
					atom = '=' + str(match.cpv)
				print_entries(changelog.entries_matching_atom(atom)[:end])

		first_run = False
	
	if not got_match:
		sys.exit(1)
예제 #56
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'))