コード例 #1
0
ファイル: cli.py プロジェクト: nuno-silva/gentoolkit
def main():
    """Parse command line and execute all actions."""
    # set default options
    options = {}
    options['nocolor'] = (port_settings.get("NOCOLOR") in ('yes', 'true')
                          or not sys.stdout.isatty())
    if options['nocolor']:
        pp.output.nocolor()
    # parse command line options and actions
    try:
        action = parseArgs(options)
    # filter exception to know what message to display
    except ParseArgsException as e:
        if e.value == 'help':
            printUsage(help='all')
            sys.exit(0)
        elif e.value[:5] == 'help-':
            printUsage(help=e.value[5:])
            sys.exit(0)
        elif e.value == 'version':
            printVersion()
            sys.exit(0)
        else:
            printUsage(e.value)
            sys.exit(2)
    output = OutputControl(options)
    options['verbose-output'] = lambda x: None
    if not options['quiet']:
        if options['verbose']:
            options['verbose-output'] = output.einfo
    # parse the exclusion file
    if not 'exclude-file' in options:
        # set it to the default exclude file if it exists
        exclude_file = "%s/etc/%s/%s.exclude" % (EPREFIX, __productname__,
                                                 action)
        if os.path.isfile(exclude_file):
            options['exclude-file'] = exclude_file
    if 'exclude-file' in options:
        try:
            exclude = parseExcludeFile(options['exclude-file'],
                                       options['verbose-output'])
        except ParseExcludeFileException as e:
            print(pp.error(str(e)), file=sys.stderr)
            print(pp.error("Invalid exclusion file: %s" %
                           options['exclude-file']),
                  file=sys.stderr)
            print(pp.error("See format of this file in `man %s`" %
                           __productname__),
                  file=sys.stderr)
            sys.exit(1)
    else:
        exclude = {}
    # security check for non-pretend mode
    if not options['pretend'] and portage.secpass == 0:
        print(pp.error("Permission denied: you must be root or belong to " +
                       "the portage group."),
              file=sys.stderr)
        sys.exit(1)
    # execute action
    doAction(action, options, exclude=exclude, output=output)
コード例 #2
0
ファイル: cli.py プロジェクト: zmedico/gentoolkit
def main():
	"""Parse command line and execute all actions."""
	# set default options
	options = {}
	options['nocolor'] = (port_settings.get("NOCOLOR") in ('yes','true')
		or not sys.stdout.isatty())
	if options['nocolor']:
		pp.output.nocolor()
	# parse command line options and actions
	try:
		action = parseArgs(options)
	# filter exception to know what message to display
	except ParseArgsException as e:
		if e.value == 'help':
			printUsage(help='all')
			sys.exit(0)
		elif e.value[:5] == 'help-':
			printUsage(help=e.value[5:])
			sys.exit(0)
		elif e.value == 'version':
			printVersion()
			sys.exit(0)
		else:
			printUsage(e.value)
			sys.exit(2)
	output = OutputControl(options)
	options['verbose-output'] = lambda x: None
	if not options['quiet']:
		if options['verbose']:
			options['verbose-output'] = output.einfo
	# parse the exclusion file
	if not 'exclude-file' in options:
		# set it to the default exclude file if it exists
		exclude_file = "%s/etc/%s/%s.exclude" % (EPREFIX,__productname__ , action)
		if os.path.isfile(exclude_file):
			options['exclude-file'] = exclude_file
	if 'exclude-file' in options:
		try:
			exclude = parseExcludeFile(options['exclude-file'],
					options['verbose-output'])
		except ParseExcludeFileException as e:
			print( pp.error(str(e)), file=sys.stderr)
			print( pp.error(
				"Invalid exclusion file: %s" % options['exclude-file']), file=sys.stderr)
			print( pp.error(
				"See format of this file in `man %s`" % __productname__), file=sys.stderr)
			sys.exit(1)
	else:
			exclude = {}
	# security check for non-pretend mode
	if not options['pretend'] and portage.secpass == 0:
		print( pp.error(
			"Permission denied: you must be root or belong to " +
			"the portage group."), file=sys.stderr)
		sys.exit(1)
	# execute action
	doAction(action, options, exclude=exclude,
		output=output)
コード例 #3
0
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)
        e += pp.error("Please set DISTDIR to a sane value.\n")
        e += pp.error("(Check your /etc/make.conf and environment).")
        print(e, file=sys.stderr)
        exit(1)
    return d
コード例 #4
0
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)
        e += pp.error("Please set DISTDIR to a sane value.\n")
        e += pp.error("(Check your make.conf file and environment).")
        print(e, file=sys.stderr)
        exit(1)
    return d
コード例 #5
0
def make_dir(path):
    """create the directory at path

	@param path: full pathname to create
	capable of multiple intermediate directory creations.
	Will Error and exit if the target dir already exits"""
    try:
        os.makedirs(path, dir_mode)
    except EnvironmentError as er:
        print(pp.error("Error creating path:%s" % path), file=sys.stderr)
        print(pp.error("Error: %s" % str(er), file=sys.stderr))
        sys.exit(1)
コード例 #6
0
def make_dir(path):
	"""create the directory at path

	@param path: full pathname to create
	capable of multiple intermediate directory creations.
	Will Error and exit if the target dir already exits"""
	try:
		os.makedirs(path, dir_mode)
	except EnvironmentError as er:
		print( pp.error("Error creating path:%s" %path), file=sys.stderr)
		print( pp.error("Error: %s" %str(er), file=sys.stderr))
		sys.exit(1)
コード例 #7
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
コード例 #8
0
ファイル: __init__.py プロジェクト: zmedico/gentoolkit
def main(argv):
	"""Parse input and run the program."""

	short_opts = "hqCNV"
	long_opts = (
		'help', 'quiet', 'nocolor', 'no-color', 'no-pipe', 'version', 'debug'
	)

	initialize_configuration()

	try:
		global_opts, args = getopt(argv[1:], short_opts, long_opts)
	except GetoptError as err:
		sys.stderr.write(pp.error("Global %s" % err))
		print_help(with_description=False)
		sys.exit(2)

	# Parse global options
	need_help = parse_global_options(global_opts, args)

	# verbose is shorthand for the very common 'not quiet or piping'
	if CONFIG['quiet'] or CONFIG['piping']:
		CONFIG['verbose'] = False
	else:
		CONFIG['verbose'] = True

	try:
		module_name, module_args = split_arguments(args)
	except IndexError:
		print_help()
		sys.exit(2)

	if need_help:
		module_args.append('--help')

	try:
		expanded_module_name = expand_module_name(module_name)
	except KeyError:
		sys.stderr.write(pp.error("Unknown module '%s'" % module_name))
		print_help(with_description=False)
		sys.exit(2)

	try:
		loaded_module = __import__(
			expanded_module_name, globals(), locals(), [], 1
		)
		loaded_module.main(module_args)
	except portage.exception.AmbiguousPackageName as err:
		raise errors.GentoolkitAmbiguousPackage(err.args[0])
	except IOError as err:
		if err.errno != errno.EPIPE:
			raise
コード例 #9
0
def main(argv):
    """Parse input and run the program."""

    short_opts = "hqCNV"
    long_opts = (
        'help', 'quiet', 'nocolor', 'no-color', 'no-pipe', 'version', 'debug'
    )

    initialize_configuration()

    try:
        global_opts, args = getopt(argv[1:], short_opts, long_opts)
    except GetoptError as err:
        sys.stderr.write(pp.error("Global %s" % err))
        print_help(with_description=False)
        sys.exit(2)

    # Parse global options
    need_help = parse_global_options(global_opts, args)

    # verbose is shorthand for the very common 'not quiet or piping'
    if CONFIG['quiet'] or CONFIG['piping']:
        CONFIG['verbose'] = False
    else:
        CONFIG['verbose'] = True

    try:
        module_name, module_args = split_arguments(args)
    except IndexError:
        print_help()
        sys.exit(2)

    if need_help:
        module_args.append('--help')

    try:
        expanded_module_name = expand_module_name(module_name)
    except KeyError:
        sys.stderr.write(pp.error("Unknown module '%s'" % module_name))
        print_help(with_description=False)
        sys.exit(2)

    try:
        loaded_module = __import__(
            expanded_module_name, globals(), locals(), [], 1
        )
        loaded_module.main(module_args)
    except portage.exception.AmbiguousPackageName as err:
        raise errors.GentoolkitAmbiguousPackage(err.args[0])
    except IOError as err:
        if err.errno != errno.EPIPE:
            raise
コード例 #10
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
コード例 #11
0
def main():
    """Parse input and run the program."""

    short_opts = "hqCNV"
    long_opts = ("help", "quiet", "nocolor", "no-color", "no-pipe", "version",
                 "debug")

    initialize_configuration()

    try:
        global_opts, args = getopt(sys.argv[1:], short_opts, long_opts)
    except GetoptError as err:
        sys.stderr.write(" \n")
        sys.stderr.write(pp.error("Global %s\n" % err))
        print_help(MODULE_INFO, FORMATTED_OPTIONS, with_description=False)
        sys.exit(2)

    # Parse global options
    need_help = parse_global_options(global_opts, args, MODULE_INFO,
                                     FORMATTED_OPTIONS)

    if gen.CONFIG["quiet"]:
        gen.CONFIG["verbose"] = False

    try:
        module_name, module_args = split_arguments(args)
    except IndexError:
        print_help(MODULE_INFO, FORMATTED_OPTIONS)
        sys.exit(2)

    if need_help:
        module_args.append("--help")

    try:
        expanded_module_name = expand_module_name(module_name)
    except KeyError:
        sys.stderr.write(pp.error("Unknown module '%s'" % module_name))
        print_help(MODULE_INFO, FORMATTED_OPTIONS, with_description=False)
        sys.exit(2)

    try:
        loaded_module = __import__(expanded_module_name, globals(), locals(),
                                   [], 1)
        loaded_module.main(module_args)
    except portage.exception.AmbiguousPackageName as err:
        raise errors.GentoolkitAmbiguousPackage(err.args[0])
    except IOError as err:
        if err.errno != errno.EPIPE:
            raise
コード例 #12
0
ファイル: pkgindex.py プロジェクト: zmedico/gentoolkit
	def _get_emaint_binhost(self):
		"""Obtain a reference to the binhost module class

		@sets: self.binhost to BinhostHandler class
		@rtype: boolean
		"""
		try:
			self.emaint_control = Modules()
			self.binhost = self.emaint_control._get_class('binhost')
		except InvalidModuleName as er:
			print( pp.error("Error importing emaint binhost module"), file=sys.stderr)
			print( pp.error("Original error: " + er), file=sys.stderr)
		except:
			return False
		return True
コード例 #13
0
ファイル: files.py プロジェクト: pamxy/gentoolkit
def parse_module_options(module_opts):
    """Parse module options and update QUERY_OPTS"""

    content_filter = []
    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 ('-m', '--md5sum'):
            QUERY_OPTS["show_MD5"] = True
        elif opt in ('-s', '--timestamp'):
            QUERY_OPTS["show_timestamp"] = True
        elif opt in ('-t', '--type'):
            QUERY_OPTS["show_type"] = True
        elif opt in ('--tree'):
            QUERY_OPTS["output_tree"] = True
        elif opt in ('-f', '--filter'):
            f_split = posarg.split(',')
            content_filter.extend(x.lstrip('=') for x in f_split)
            for rule in content_filter:
                if not rule in FILTER_RULES:
                    sys.stderr.write(
                        pp.error("Invalid filter rule '%s'" % rule))
                    print()
                    print_help(with_description=False)
                    sys.exit(2)
            QUERY_OPTS["type_filter"] = content_filter
コード例 #14
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)
コード例 #15
0
 def optionSwitch(option, opts, action=None):
     """local function for interpreting command line options
     and setting options accordingly"""
     return_code = True
     do_help = False
     for o, a in opts:
         if o in ("-h", "--help"):
             do_help = True
         elif o in ("-V", "--version"):
             raise ParseArgsException("version")
         elif o in ("-C", "--nocolor"):
             options["nocolor"] = True
             pp.output.nocolor()
         elif o in ("-d", "--deep", "--destructive"):
             options["destructive"] = True
         elif o in ("-D", "--deprecated"):
             options["deprecated"] = True
         elif o in ("-i", "--interactive") and not options["pretend"]:
             options["interactive"] = True
         elif o in ("-p", "--pretend"):
             options["pretend"] = True
             options["interactive"] = False
         elif o in ("-q", "--quiet"):
             options["quiet"] = True
             options["verbose"] = False
         elif o in ("-t", "--time-limit"):
             options["time-limit"] = parseTime(a)
         elif o in ("-e", "--exclude-file"):
             print("cli --exclude option")
             options["exclude-file"] = a
         elif o in ("-n", "--package-names"):
             options["package-names"] = True
         elif o in ("-f", "--fetch-restricted"):
             options["fetch-restricted"] = True
         elif o in ("-s", "--size-limit"):
             options["size-limit"] = parseSize(a)
         elif o in ("-v", "--verbose") and not options["quiet"]:
             options["verbose"] = True
         elif o in ("--changed-deps"):
             options["changed-deps"] = True
         elif o in ("-i", "--ignore-failure"):
             options["ignore-failure"] = True
         else:
             return_code = False
     # sanity check of --deep only options:
     for opt in ("fetch-restricted", "package-names"):
         if (not options["destructive"]) and options[opt]:
             if not options["quiet"]:
                 print(
                     pp.error("--%s only makes sense in --deep mode." %
                              opt),
                     file=sys.stderr,
                 )
             options[opt] = False
     if do_help:
         if action:
             raise ParseArgsException("help-" + action)
         else:
             raise ParseArgsException("help")
     return return_code
コード例 #16
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)
        if opt in ("-A", "--no-atom"):
            QUERY_OPTS["no_atom"] = True
        if opt in ("-U", "--no-useflags"):
            QUERY_OPTS["no_useflags"] = True
        if opt in ("-M", "--no-mask"):
            QUERY_OPTS["no_mask"] = True
        if opt in ("-l", "--linear"):
            QUERY_OPTS["no_indent"] = True
        if opt in ("--depth"):
            if posarg.isdigit():
                depth = int(posarg)
            else:
                err = "Module option --depth requires integer (got '%s')"
                sys.stderr.write(pp.error(err % posarg))
                print()
                print_help(with_description=False)
                sys.exit(2)
            QUERY_OPTS["depth"] = depth
コード例 #17
0
    def _get_emaint_binhost(self):
        """Obtain a reference to the binhost module class

		@sets: self.binhost to BinhostHandler class
		@rtype: boolean
		"""
        try:
            self.emaint_control = Modules()
            self.binhost = self.emaint_control._get_class('binhost')
        except InvalidModuleName as er:
            print(pp.error("Error importing emaint binhost module"),
                  file=sys.stderr)
            print(pp.error("Original error: " + er), file=sys.stderr)
        except:
            return False
        return True
コード例 #18
0
 def _get_size(self, key):
     """Determine the total size for an entry (may be several files)."""
     key_size = 0
     for file_ in key:
         # print file_
         # get total size for an entry (may be several files, and
         # links don't count
         # ...get its statinfo
         try:
             statinfo = os.stat(file_)
             if statinfo.st_nlink == 1:
                 key_size += statinfo.st_size
         except EnvironmentError as er:
             print(pp.error("Could not get stat info for:" + file_), file=sys.stderr)
             print(pp.error("Error: %s" % str(er)), file=sys.stderr)
     return key_size
コード例 #19
0
ファイル: uses.py プロジェクト: zmedico/gentoolkit
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
コード例 #20
0
ファイル: depgraph.py プロジェクト: pamxy/gentoolkit
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)
        if opt in ('-A', '--no-atom'):
            QUERY_OPTS["no_atom"] = True
        if opt in ('-U', '--no-useflags'):
            QUERY_OPTS["no_useflags"] = True
        if opt in ('-M', '--no-mask'):
            QUERY_OPTS["no_mask"] = True
        if opt in ('-l', '--linear'):
            QUERY_OPTS["no_indent"] = True
        if opt in ('--depth'):
            if posarg.isdigit():
                depth = int(posarg)
            else:
                err = "Module option --depth requires integer (got '%s')"
                sys.stderr.write(pp.error(err % posarg))
                print()
                print_help(with_description=False)
                sys.exit(2)
            QUERY_OPTS["depth"] = depth
コード例 #21
0
ファイル: __init__.py プロジェクト: zmedico/gentoolkit
def format_filetype(path, fdesc, show_type=False, show_md5=False,
		show_timestamp=False):
	"""Format a path for printing.

	@type path: str
	@param path: the path
	@type fdesc: list
	@param fdesc: [file_type, timestamp, MD5 sum/symlink target]
		file_type is one of dev, dir, obj, sym, fif.
		If file_type is dir, there is no timestamp or MD5 sum.
		If file_type is sym, fdesc[2] is the target of the symlink.
	@type show_type: bool
	@param show_type: if True, prepend the file's type to the formatted string
	@type show_md5: bool
	@param show_md5: if True, append MD5 sum to the formatted string
	@type show_timestamp: bool
	@param show_timestamp: if True, append time-of-creation after pathname
	@rtype: str
	@return: formatted pathname with optional added information
	"""

	ftype = fpath = stamp = md5sum = ""

	if fdesc[0] == "obj":
		ftype = "file"
		fpath = path
		stamp = format_timestamp(fdesc[1])
		md5sum = fdesc[2]
	elif fdesc[0] == "dir":
		ftype = "dir"
		fpath = pp.path(path)
	elif fdesc[0] == "sym":
		ftype = "sym"
		stamp = format_timestamp(fdesc[1])
		tgt = fdesc[2].split()[0]
		if CONFIG["piping"]:
			fpath = path
		else:
			fpath = pp.path_symlink(path + " -> " + tgt)
	elif fdesc[0] == "dev":
		ftype = "dev"
		fpath = path
	elif fdesc[0] == "fif":
		ftype = "fifo"
		fpath = path
	else:
		sys.stderr.write(
			pp.error("%s has unknown type: %s" % (path, fdesc[0]))
		)

	result = ""
	if show_type:
		result += "%4s " % ftype
	result += fpath
	if show_timestamp:
		result += "  " + stamp
	if show_md5:
		result += "  " + md5sum

	return result
コード例 #22
0
ファイル: uses.py プロジェクト: pamxy/gentoolkit
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
コード例 #23
0
def format_filetype(path, fdesc, show_type=False, show_md5=False,
        show_timestamp=False):
    """Format a path for printing.

    @type path: str
    @param path: the path
    @type fdesc: list
    @param fdesc: [file_type, timestamp, MD5 sum/symlink target]
        file_type is one of dev, dir, obj, sym, fif.
        If file_type is dir, there is no timestamp or MD5 sum.
        If file_type is sym, fdesc[2] is the target of the symlink.
    @type show_type: bool
    @param show_type: if True, prepend the file's type to the formatted string
    @type show_md5: bool
    @param show_md5: if True, append MD5 sum to the formatted string
    @type show_timestamp: bool
    @param show_timestamp: if True, append time-of-creation after pathname
    @rtype: str
    @return: formatted pathname with optional added information
    """

    ftype = fpath = stamp = md5sum = ""

    if fdesc[0] == "obj":
        ftype = "file"
        fpath = path
        stamp = format_timestamp(fdesc[1])
        md5sum = fdesc[2]
    elif fdesc[0] == "dir":
        ftype = "dir"
        fpath = pp.path(path)
    elif fdesc[0] == "sym":
        ftype = "sym"
        stamp = format_timestamp(fdesc[1])
        tgt = fdesc[2].split()[0]
        if CONFIG["piping"]:
            fpath = path
        else:
            fpath = pp.path_symlink(path + " -> " + tgt)
    elif fdesc[0] == "dev":
        ftype = "dev"
        fpath = path
    elif fdesc[0] == "fif":
        ftype = "fifo"
        fpath = path
    else:
        sys.stderr.write(
            pp.error("%s has unknown type: %s" % (path, fdesc[0]))
        )

    result = ""
    if show_type:
        result += "%4s " % ftype
    result += fpath
    if show_timestamp:
        result += "  " + stamp
    if show_md5:
        result += "  " + md5sum

    return result
コード例 #24
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)
コード例 #25
0
def parse_module_options(module_opts):
	"""Parse module options and update QUERY_OPTS"""

	content_filter = []
	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 ('-m', '--md5sum'):
			QUERY_OPTS["show_MD5"] = True
		elif opt in ('-s', '--timestamp'):
			QUERY_OPTS["show_timestamp"] = True
		elif opt in ('-t', '--type'):
			QUERY_OPTS["show_type"] = True
		elif opt in ('--tree'):
			QUERY_OPTS["output_tree"] = True
		elif opt in ('-f', '--filter'):
			f_split = posarg.split(',')
			content_filter.extend(x.lstrip('=') for x in f_split)
			for rule in content_filter:
				if not rule in FILTER_RULES:
					sys.stderr.write(
						pp.error("Invalid filter rule '%s'" % rule)
					)
					print()
					print_help(with_description=False)
					sys.exit(2)
			QUERY_OPTS["type_filter"] = content_filter
コード例 #26
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)
コード例 #27
0
ファイル: depends.py プロジェクト: gronkern/gentoolkit
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 ('-a', '--all-packages'):
            QUERY_OPTS['include_masked'] = True
        elif opt in ('-D', '--indirect'):
            QUERY_OPTS['only_direct'] = False
        elif opt in ('-F', '--format'):
            QUERY_OPTS["package_format"] = posarg
        elif opt in ('--depth'):
            if posarg.isdigit():
                depth = int(posarg)
            else:
                err = "Module option --depth requires integer (got '%s')"
                sys.stdout.write(pp.error(err % posarg))
                print()
                print_help(with_description=False)
                sys.exit(2)
            QUERY_OPTS["max_depth"] = depth
コード例 #28
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)
コード例 #29
0
	def not_implemented(self, target):
		"""Prints a standard module not implemented message"""
		print()
		print(pp.error(
			"Sorry %s module and/or target is not implenented yet."
			% pp.emph(self.command_name)))
		print("module: %s, target: %s" %(pp.emph(self.module_name), pp.emph(target)))
		print()
コード例 #30
0
 def _get_size(self, key):
     """Determine the total size for an entry (may be several files)."""
     key_size = 0
     for file_ in key:
         #print file_
         # get total size for an entry (may be several files, and
         # links don't count
         # ...get its statinfo
         try:
             statinfo = os.stat(file_)
             if statinfo.st_nlink == 1:
                 key_size += statinfo.st_size
         except EnvironmentError as er:
             print(pp.error("Could not get stat info for:" + file_),
                   file=sys.stderr)
             print(pp.error("Error: %s" % str(er)), file=sys.stderr)
     return key_size
コード例 #31
0
	def not_implemented(self, target):
		"""Prints a standard module not implemented message"""
		print()
		print(pp.error(
			"Sorry %s module and/or target is not implenented yet."
			% pp.emph(self.command_name)))
		print("module: %s, target: %s" %(pp.emph(self.module_name), pp.emph(target)))
		print()
コード例 #32
0
 def _clean_files(self, files, key, file_type):
     """File removal function."""
     clean_size = 0
     for file_ in files:
         # print file_, type(file_)
         # ...get its statinfo
         try:
             statinfo = os.stat(file_)
         except EnvironmentError as er:
             if not os.path.exists(os.readlink(file_)):
                 try:
                     os.remove(file_)
                     print(pp.error("Removed broken symbolic link " + file_), file=sys.stderr)
                     break
                 except EnvironmentError as er:
                     print(pp.error("Error deleting broken symbolic link " + file_), file=sys.stderr)
                     print(pp.error("Error: %s" % str(er)), file=sys.stderr)
                     break
             else:
                 print(pp.error("Could not get stat info for:" + file_), file=sys.stderr)
                 print(pp.error("Error: %s" % str(er)), file=sys.stderr)
         if self.controller(statinfo.st_size, key, file_, file_type):
             # ... try to delete it.
             try:
                 os.unlink(file_)
                 # only count size if successfully deleted and not a link
                 if statinfo.st_nlink == 1:
                     clean_size += statinfo.st_size
             except EnvironmentError as er:
                 print(pp.error("Could not delete " + file_), file=sys.stderr)
                 print(pp.error("Error: %s" % str(er)), file=sys.stderr)
     return clean_size
コード例 #33
0
def main(input_args):
    """Parse input and run the program"""

    short_opts = "hAMUl"
    long_opts = ("help", "no-atom", "no-useflags", "no-mask", "depth=")

    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
    for query in (Query(x) for x in queries):
        if not first_run:
            print()

        matches = query.smart_find(**QUERY_OPTS)

        if not matches:
            raise errors.GentoolkitNoMatches(query)

        matches.sort()

        if CONFIG["verbose"]:
            printer = partial(
                depgraph_printer,
                no_atom=QUERY_OPTS["no_atom"],
                no_indent=QUERY_OPTS["no_indent"],
                no_use=QUERY_OPTS["no_useflags"],
                no_mask=QUERY_OPTS["no_mask"],
            )
        else:
            printer = partial(
                depgraph_printer,
                no_atom=True,
                no_indent=True,
                no_use=True,
                no_mask=True,
            )

        for pkg in matches:
            make_depgraph(pkg, printer)

        first_run = False
コード例 #34
0
    def _get_emaint_binhost(self):
        """Obtain a reference to the binhost module class

		@sets: self.binhost to BinhostHandler class
		@rtype: boolean
		"""
        # About noqa below: I don't understand how this code can run at all.
        # TODO: verify soundness
        try:
            self.emaint_control = Modules()  # noqa
            self.binhost = self.emaint_control._get_class('binhost')
        except InvalidModuleName as er:  # noqa
            print(pp.error("Error importing emaint binhost module"),
                  file=sys.stderr)
            print(pp.error("Original error: " + er), file=sys.stderr)
        except:
            return False
        return True
コード例 #35
0
ファイル: meta.py プロジェクト: clayne/gentoolkit
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
コード例 #36
0
ファイル: cli.py プロジェクト: zmedico/gentoolkit
	def optionSwitch(option,opts,action=None):
		"""local function for interpreting command line options
		and setting options accordingly"""
		return_code = True
		do_help = False
		for o, a in opts:
			if o in ("-h", "--help"):
				do_help = True
			elif o in ("-V", "--version"):
				raise ParseArgsException('version')
			elif o in ("-C", "--nocolor"):
				options['nocolor'] = True
				pp.output.nocolor()
			elif o in ("-d", "--deep", "--destructive"):
				options['destructive'] = True
			elif o in ("-D", "--deprecated"):
				options['deprecated'] = True
			elif o in ("-i", "--interactive") and not options['pretend']:
				options['interactive'] = True
			elif o in ("-p", "--pretend"):
				options['pretend'] = True
				options['interactive'] = False
			elif o in ("-q", "--quiet"):
				options['quiet'] = True
				options['verbose'] = False
			elif o in ("-t", "--time-limit"):
				options['time-limit'] = parseTime(a)
			elif o in ("-e", "--exclude-file"):
				print("cli --exclude option")
				options['exclude-file'] = a
			elif o in ("-n", "--package-names"):
				options['package-names'] = True
			elif o in ("-f", "--fetch-restricted"):
				options['fetch-restricted'] = True
			elif o in ("-s", "--size-limit"):
				options['size-limit'] = parseSize(a)
			elif o in ("-v", "--verbose") and not options['quiet']:
					options['verbose'] = True
			elif o in ("-i", "--ignore-failure"):
				options['ignore-failure'] = True
			else:
				return_code = False
		# sanity check of --deep only options:
		for opt in ('fetch-restricted', 'package-names'):
			if (not options['destructive']) and options[opt]:
				if not options['quiet']:
					print( pp.error(
						"--%s only makes sense in --deep mode." % opt), file=sys.stderr)
				options[opt] = False
		if do_help:
			if action:
				raise ParseArgsException('help-'+action)
			else:
				raise ParseArgsException('help')
		return return_code
コード例 #37
0
ファイル: cli.py プロジェクト: pamxy/gentoolkit
    def optionSwitch(option, opts, action=None):
        """local function for interpreting command line options
		and setting options accordingly"""
        return_code = True
        do_help = False
        for o, a in opts:
            if o in ("-h", "--help"):
                do_help = True
            elif o in ("-V", "--version"):
                raise ParseArgsException('version')
            elif o in ("-C", "--nocolor"):
                options['nocolor'] = True
                pp.output.nocolor()
            elif o in ("-d", "--deep", "--destructive"):
                options['destructive'] = True
            elif o in ("-D", "--deprecated"):
                options['deprecated'] = True
            elif o in ("-i", "--interactive") and not options['pretend']:
                options['interactive'] = True
            elif o in ("-p", "--pretend"):
                options['pretend'] = True
                options['interactive'] = False
            elif o in ("-q", "--quiet"):
                options['quiet'] = True
                options['verbose'] = False
            elif o in ("-t", "--time-limit"):
                options['time-limit'] = parseTime(a)
            elif o in ("-e", "--exclude-file"):
                print("cli --exclude option")
                options['exclude-file'] = a
            elif o in ("-n", "--package-names"):
                options['package-names'] = True
            elif o in ("-f", "--fetch-restricted"):
                options['fetch-restricted'] = True
            elif o in ("-s", "--size-limit"):
                options['size-limit'] = parseSize(a)
            elif o in ("-v", "--verbose") and not options['quiet']:
                options['verbose'] = True
            else:
                return_code = False
        # sanity check of --deep only options:
        for opt in ('fetch-restricted', 'package-names'):
            if (not options['destructive']) and options[opt]:
                if not options['quiet']:
                    print(pp.error("--%s only makes sense in --deep mode." %
                                   opt),
                          file=sys.stderr)
                options[opt] = False
        if do_help:
            if action:
                raise ParseArgsException('help-' + action)
            else:
                raise ParseArgsException('help')
        return return_code
コード例 #38
0
def main(input_args):
    """Parse input and run the program"""

    short_opts = "h"
    long_opts = ('help')

    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 or len(queries) > 1:
        print_help()
        sys.exit(2)

    #
    # Output
    #
    query = Query(queries[0])
    matches = query.find(include_masked=True, in_installed=False)

    if not matches:
        raise errors.GentoolkitNoMatches(query)

    matches.sort()
    matches.reverse()

    if CONFIG['verbose']:
        print(matches[0].ebuild_path())
        print()

    pkgdeps = matches[0].deps
    deps = pkgdeps.get_all_depends(raw=True)
    deps = paren_reduce(deps)

    if CONFIG['verbose']:
        print(deps)
        print()

    kwdict = parse_list(deps)

    if CONFIG['verbose']:
        print()

    if not kwdict == None:
        print(' '.join(kwdict.values()))
    else:
        print()
コード例 #39
0
ファイル: pkgindex.py プロジェクト: zmedico/gentoolkit
	def call_emaint(self):
		"""Run the stand alone emaint script from
		a subprocess call.

		@rtype: integer
		@return: the difference in file size
		"""
		file_ = os.path.join(portage.settings['PKGDIR'], 'Packages')
		statinfo = os.stat(file_)
		size1 = statinfo.st_size
		try:
			retcode = subprocess.call(self.emaint_cmd, shell=True)
			if retcode < 0:
				print( pp.error("Child was terminated by signal" + str(-retcode)), file=sys.stderr)
		except OSError as e:
			print( pp.error("Execution failed:" + e), file=sys.stderr)
		print()
		statinfo = os.stat(file_)
		clean_size = size1 - statinfo.st_size
		self.controller(clean_size, "Packages Index", file_, "Index")
		return clean_size
コード例 #40
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)
コード例 #41
0
def main(input_args):
	"""Parse input and run the program"""
	short_opts = "hadD" # -d, --direct was old option for default action
	long_opts = ('help', 'all-packages', 'direct', 'indirect', 'depth=')

	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
	#

	dep_print = DependPrinter(verbose=CONFIG['verbose'])

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

		pkg = Dependencies(query)
		if QUERY_OPTS['include_masked']:
			pkggetter = get_cpvs
		else:
			pkggetter = get_installed_cpvs

		if CONFIG['verbose']:
			print(" * These packages depend on %s:" % pp.emph(pkg.cpv))
		if pkg.graph_reverse_depends(
			pkgset=sorted(pkggetter(), key=CPV),
			max_depth=QUERY_OPTS["max_depth"],
			only_direct=QUERY_OPTS["only_direct"],
			printer_fn=dep_print
		):
			got_match = True

		first_run = False

	if not got_match:
		sys.exit(1)
コード例 #42
0
def main(input_args):
    """Parse input and run the program"""

    short_opts = "hAMUl"
    long_opts = ("help", "no-atom", "no-useflags", "no-mask", "depth=")

    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
    for query in (Query(x) for x in queries):
        if not first_run:
            print()

        matches = query.smart_find(**QUERY_OPTS)

        if not matches:
            raise errors.GentoolkitNoMatches(query)

        matches.sort()

        if CONFIG["verbose"]:
            printer = partial(
                depgraph_printer,
                no_atom=QUERY_OPTS["no_atom"],
                no_indent=QUERY_OPTS["no_indent"],
                no_use=QUERY_OPTS["no_useflags"],
                no_mask=QUERY_OPTS["no_mask"],
            )
        else:
            printer = partial(depgraph_printer, no_atom=True, no_indent=True, no_use=True, no_mask=True)

        for pkg in matches:
            make_depgraph(pkg, printer)

        first_run = False
コード例 #43
0
def set_limit(posarg):
    """Set a limit in QUERY_OPTS on how many ChangeLog entries to display.

	Die if posarg is not an integer.
	"""

    if posarg.isdigit():
        QUERY_OPTS['limit'] = int(posarg)
    else:
        err = "Module option --limit requires integer (got '%s')"
        sys.stderr.write(pp.error(err % posarg))
        print()
        print_help(with_description=False)
        sys.exit(2)
コード例 #44
0
def set_limit(posarg):
	"""Set a limit in QUERY_OPTS on how many ChangeLog entries to display.

	Die if posarg is not an integer.
	"""

	if posarg.isdigit():
		QUERY_OPTS['limit'] = int(posarg)
	else:
		err = "Module option --limit requires integer (got '%s')"
		sys.stderr.write(pp.error(err % posarg))
		print()
		print_help(with_description=False)
		sys.exit(2)
コード例 #45
0
    def call_emaint(self):
        """Run the stand alone emaint script from
		a subprocess call.

		@rtype: integer
		@return: the difference in file size
		"""
        file_ = os.path.join(portage.settings['PKGDIR'], 'Packages')
        statinfo = os.stat(file_)
        size1 = statinfo.st_size
        try:
            retcode = subprocess.call(self.emaint_cmd, shell=True)
            if retcode < 0:
                print(pp.error("Child was terminated by signal" +
                               str(-retcode)),
                      file=sys.stderr)
        except OSError as e:
            print(pp.error("Execution failed:" + e), file=sys.stderr)
        print()
        statinfo = os.stat(file_)
        clean_size = size1 - statinfo.st_size
        self.controller(clean_size, "Packages Index", file_, "Index")
        return clean_size
コード例 #46
0
ファイル: size.py プロジェクト: mjsir911/gentoolkit
def main(input_args):
    """Parse input and run the program"""

    # -e, --exact-name is no longer needed. Kept for compatibility.
    # 04/09 djanderson
    short_opts = "hbfe"
    long_opts = ('help', 'bytes', 'full-regex', 'exact-name')

    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
    for query in (Query(x, QUERY_OPTS['is_regex']) for x in queries):
        if not first_run:
            print()

        matches = query.smart_find(**QUERY_OPTS)

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

        matches.sort()

        display_size(matches)

        first_run = False
コード例 #47
0
ファイル: size.py プロジェクト: zmedico/gentoolkit
def main(input_args):
	"""Parse input and run the program"""

	# -e, --exact-name is no longer needed. Kept for compatibility.
	# 04/09 djanderson
	short_opts = "hbfe"
	long_opts = ('help', 'bytes', 'full-regex', 'exact-name')

	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
	for query in (Query(x, QUERY_OPTS['is_regex']) for x in queries):
		if not first_run:
			print()

		matches = query.smart_find(**QUERY_OPTS)

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

		matches.sort()

		display_size(matches)

		first_run = False
コード例 #48
0
	def main_setup(self, input_args):
		"""Parse input and prepares the program"""

		try:
			module_opts, queries = gnu_getopt(input_args, self.short_opts, self.long_opts)
		except GetoptError as err:
			sys.stderr.write(pp.error("Module %s" % err))
			print()
			self.print_help(with_description=False)
			sys.exit(2)
		self.parse_module_options(module_opts)
		if self.need_queries and not queries:
			self.print_help()
			sys.exit(2)
		return queries
コード例 #49
0
	def main_setup(self, input_args):
		"""Parse input and prepares the program"""

		try:
			module_opts, queries = gnu_getopt(input_args, self.short_opts, self.long_opts)
		except GetoptError as err:
			sys.stderr.write(pp.error("Module %s" % err))
			print()
			self.print_help(with_description=False)
			sys.exit(2)
		self.parse_module_options(module_opts)
		if self.need_queries and not queries:
			self.print_help()
			sys.exit(2)
		return queries
コード例 #50
0
def main(input_args):
    """Parse input and run the program"""

    short_opts = "h"
    long_opts = ('help')

    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 or len(queries) > 1:
        print_help()
        sys.exit(2)

    #
    # Output
    #

    query = Query(queries[0])

    matches = query.find(include_masked=True, in_installed=False)

    if not matches:
        raise errors.GentoolkitNoMatches(query)

    matches.sort()
    matches.reverse()

    if CONFIG['verbose']:
        print(matches[0].ebuild_path())
        print()

    ebkw = matches[0].environment('KEYWORDS')
    uskw = []

    for kw in ebkw.split():
        if kw[0] != '-' and kw[0] != '~':
            uskw.append('~' + kw)
        else:
            uskw.append(kw)

    print(' '.join(uskw))
コード例 #51
0
ファイル: hasuse.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=')

	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)
コード例 #52
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
コード例 #53
0
def main(input_args):
	"""Parse input and run the program"""

	short_opts = "hof"
	long_opts = ('help', 'only-failures', 'full-regex')

	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
	for query in (Query(x, QUERY_OPTS['is_regex']) for x in queries):
		if not first_run:
			print()

		matches = query.smart_find(**QUERY_OPTS)

		if not matches:
			raise errors.GentoolkitNoMatches(query, in_installed=True)

		matches.sort()

		printer = partial(
			checks_printer,
			verbose=CONFIG['verbose'],
			only_failures=QUERY_OPTS['only_failures']
		)
		check = VerifyContents(printer_fn=printer)
		check(matches)

		first_run = False
コード例 #54
0
	def validate_query(self, query, depth=0):
		"""check that the query meets the modules TargetSpec
		If not it attempts to reduce it to a valid TargetSpec
		or prints the help message and exits
		"""
		if depth > 1:
			return []
		if len(query) > 1:
			query = list(set(self.arg_options).intersection(query))
			#print "reduced query =", query
			query = self.validate_query(query, depth+1)
		if isinstance(query, list):
			query = query[0]
		if query not in self.arg_options:
			print()
			print(pp.error(
				"Error starting module. Incorrect or No TargetSpec specified!"
				))
			print("query = ", query)
			self.print_help()
			sys.exit(2)
		return query
コード例 #55
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)
コード例 #56
0
ファイル: belongs.py プロジェクト: zmedico/gentoolkit
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)
コード例 #57
0
ファイル: depends.py プロジェクト: zmedico/gentoolkit
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 ('-a', '--all-packages'):
			QUERY_OPTS['include_masked'] = True
		elif opt in ('-D', '--indirect'):
			QUERY_OPTS['only_direct'] = False
		elif opt in ('--depth'):
			if posarg.isdigit():
				depth = int(posarg)
			else:
				err = "Module option --depth requires integer (got '%s')"
				sys.stdout.write(pp.error(err % posarg))
				print()
				print_help(with_description=False)
				sys.exit(2)
			QUERY_OPTS["max_depth"] = depth
コード例 #58
0
	def parse_module_options(self, module_opts):
		"""Parse module options and update self.options"""

		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'):
					self.print_help()
					sys.exit(0)
			opt_name, opt_type, opt_setting = self.module_opts[opt]
			if opt_type == 'boolean':
				self.options[opt_name] = opt_setting
			elif opt_type == 'int':
				if posarg.isdigit():
					val = int(posarg)
				else:
					print()
					err = "Module option %s requires integer (got '%s')"
					sys.stdout.write(pp.error(err % (opt,posarg)))
					print()
					self.print_help(with_description=False)
					sys.exit(2)
				self.options[opt_name] = val
コード例 #59
0
ファイル: remoteids.py プロジェクト: iksaif/portage-janitor
def upstream_remote_id_package(package):
    if not package.ebuild_path():
        return

    package._remoteids = set()
    package._remoteids_found = set()
    package._remoteids_new = set()
    package._remoteids_bad = set()

    for upstream in package.metadata.upstream():
        for remote_id, remote_type in upstream.upstream_remoteids():
            package._remoteids.add((remote_type, remote_id))

    for filename, uris in helpers.get_package_uris(package).iteritems():
        for uri in uris:
            uri_rules(package, uri)

    for homepage in package.environment("HOMEPAGE").split():
        uri_rules(package, homepage)

    to_check = set()
    if _options.check:
        to_check = to_check.union(package._remoteids.difference(package._remoteids_found))
    if _options.check_all:
        to_check = to_check.union(package._remoteids)
        to_check = to_check.union(package._remoteids_found)

    for remote_type, remote_id in to_check:
        if remote_type in CHECK_REMOTE_ID:
            if not CHECK_REMOTE_ID[remote_type](package, remote_id):
                bad_remote_id(package, remote_id, remote_type)
                if (remote_type, remote_id) in package._remoteids_found:
                    sys.stderr.write(pp.error("Generated bad tag for %s: %s %s" % (package, remote_type, remote_id)))

    if _options.diff:
        output_diff(package)