Example #1
0
def parseopts(opts, config=None):

    if config is None:
        config = CONFIG

    # reset the default
    config['showtitles'] = "notitles" not in portage.features
    for a in opts[0]:
        arg = a[0]
        if arg in ("-h", "--help"):
            usage()
        elif arg in ("-w", "--webrsync"):
            config['syncprogram'] = SyncOpts["webrsync"]
        elif arg in ("-d", "--delta-webrsync"):
            config['syncprogram'] = SyncOpts["delta-webrsync"]
        elif arg in ("-m", "--metadata"):
            config['syncprogram'] = SyncOpts["metadata"]
        elif arg in ('-l', '--layman-sync'):
            config['layman-sync'] = True
        elif arg in ("-n", "--nocolor"):
            nocolor()
            config["nocolor"] = True
            config['showtitles'] = False
        elif arg in ("-q", "--quiet"):
            config['eupdatedb_extra_options'] = "-q"
            config['verbose'] = -1
        elif arg in ("-v", "--verbose"):
            config['verbose'] = 1
        elif arg in ("-s", "--nospinner"):
            config['eupdatedb_extra_options'] = "-q"
    return config
Example #2
0
def _repoman_init(argv):
    config_root = os.environ.get("PORTAGE_CONFIGROOT")
    repoman_settings = portage.config(config_root=config_root,
                                      local_config=False)
    repoman_settings.valid_versions = VALID_VERSIONS

    if repoman_settings.get("NOCOLOR", "").lower() in ("yes", "true") or \
     repoman_settings.get('TERM') == 'dumb' or \
     not sys.stdout.isatty():
        nocolor()

    options, arguments = parse_args(
        argv, repoman_settings.get("REPOMAN_DEFAULT_OPTS", ""))

    if options.version:
        print("Repoman", VERSION, "(portage-%s)" % portage.VERSION)
        return _repoman_main_vars(None, 0, None, None, None, None, None)

    logger = logging.getLogger()

    if options.verbosity > 0:
        logger.setLevel(LOGLEVEL - 10 * options.verbosity)
    else:
        logger.setLevel(LOGLEVEL)

    # Set this to False when an extraordinary issue (generally
    # something other than a QA issue) makes it impossible to
    # commit (like if Manifest generation fails).
    can_force = ExtendedFuture(True)
    repo_settings, vcs_settings, scanner, qadata = _create_scanner(
        options, can_force, config_root, repoman_settings)
    return _repoman_main_vars(can_force, None, options, qadata, repo_settings,
                              scanner, vcs_settings)
Example #3
0
def main(argv):
    if argv is None:
        argv = sys.argv[1:]

    # Extract the args ourselves.  This is to allow things like -hppa
    # without tripping over the -h/--help flags.  We can't use the
    # parse_known_args function either.
    # This sucks and really wish we didn't need to do this ...
    parse_args = []
    work_args = []
    while argv:
        arg = argv.pop(0)
        if arg.startswith('--'):
            if arg == '--':
                work_args += argv
                break
            else:
                parse_args.append(arg)
            # Handle flags that take arguments.
            if arg in ('--format', ):
                if argv:
                    parse_args.append(argv.pop(0))
        elif len(arg) == 2 and arg[0] == '-':
            parse_args.append(arg)
        else:
            work_args.append(arg)

    parser = get_parser()
    opts = parser.parse_args(parse_args)
    if not work_args:
        parser.error('need ebuilds to process')

    if opts.style == 'auto':
        if not portage_settings().get('NOCOLOR',
                                      'false').lower() in ('no', 'false'):
            nocolor()
            opts.style = 'short'
        else:
            opts.style = 'color-inline'

    arch_status = load_profile_data()
    try:
        work = args_to_work(work_args,
                            arch_status=arch_status,
                            quiet=opts.quiet)
    except ValueError as e:
        parser.error(e)

    for ebuild, ops in work:
        process_ebuild(ebuild,
                       ops,
                       arch_status=arch_status,
                       verbose=opts.verbose,
                       quiet=opts.quiet,
                       dry_run=opts.dry_run,
                       style=opts.style,
                       manifest=opts.manifest)

    return os.EX_OK
Example #4
0
def main(argv, indirect=False):
    global ignore_slots, bold, order, topper

    #opts parsing
    opts = process_args(argv)
    ignore_slots = opts.ignore_slot
    use_overlays = opts.overlays
    # user can do both --arch=a,b,c or --arch a b c
    if len(opts.arch) > 1:
        opts.arch = ','.join(opts.arch)
    highlight_arch = ''.join(opts.arch).split(',')
    bold = opts.bold
    order = opts.align
    topper = opts.top_position
    prefix = opts.prefix
    color = opts.color
    package = opts.package

    # equery support
    if indirect and len(package) <= 0:
        msg_err = 'No packages specified'
        raise SystemExit(msg_err)

    # disable colors when redirected and they are not forced on
    if not color and not sys.stdout.isatty():
        # disable colors
        porto.nocolor()
    keywords = keywords_header(prefix, highlight_arch, order)
    if len(package) > 0:
        mysettings = portc(local_config=False)
        dbapi = portdbapi(mysettings=mysettings)
        if not use_overlays:
            dbapi.porttrees = [dbapi.porttree_root]
        for pkg in package:
            process_display(pkg, keywords, dbapi)
    else:
        currdir = os.getcwd()
        # check if there are actualy some ebuilds
        ebuilds = [
            '%s' % x for x in os.listdir(currdir)
            if fnmatch.fnmatch(x, '*.ebuild')
        ]
        if len(ebuilds) <= 0:
            msg_err = 'No ebuilds at "%s"' % currdir
            raise SystemExit(msg_err)
        package = '%s/%s' % (os.path.basename(
            os.path.abspath('../')), os.path.basename(currdir))
        ourtree = os.path.abspath('../../')
        overlays = '%s %s' % (ports['PORTDIR_OVERLAY'], ourtree)
        mysettings = portc(local_config=False,
                           env={'PORTDIR_OVERLAY': overlays})
        dbapi = portdbapi(mysettings=mysettings)
        # specify that we want just our nice tree we are in cwd
        dbapi.porttrees = [ourtree]
        process_display(package, keywords, dbapi)
    return 0
Example #5
0
def main(argv):
	if argv is None:
		argv = sys.argv[1:]

	# Extract the args ourselves.  This is to allow things like -hppa
	# without tripping over the -h/--help flags.  We can't use the
	# parse_known_args function either.
	# This sucks and really wish we didn't need to do this ...
	parse_args = []
	work_args = []
	while argv:
		arg = argv.pop(0)
		if arg.startswith('--'):
			if arg == '--':
				work_args += argv
				break
			else:
				parse_args.append(arg)
			# Handle flags that take arguments.
			if arg in ('--format',):
				if argv:
					parse_args.append(argv.pop(0))
		elif arg[0] == '-' and len(arg) == 2:
			parse_args.append(arg)
		else:
			work_args.append(arg)

	parser = get_parser()
	opts = parser.parse_args(parse_args)
	if opts.version:
		print('version: %s' % VERSION)
		return os.EX_OK
	if not work_args:
		parser.error('need arches/ebuilds to process')

	if opts.format == 'auto':
		if not portage.db['/']['vartree'].settings.get('NOCOLOR', 'false').lower() in ('no', 'false'):
			nocolor()
			opts.format = 'short'
		else:
			opts.format = 'color-inline'

	arch_status = load_profile_data()
	try:
		work = args_to_work(work_args, arch_status=arch_status, quiet=opts.quiet)
	except ValueError as e:
		parser.error(e)

	for ebuild, ops in work:
		process_ebuild(ebuild, ops, arch_status=arch_status,
		               verbose=opts.verbose, quiet=opts.quiet,
		               dry_run=opts.dry_run, format=opts.format)

	return os.EX_OK
Example #6
0
def main(argv, indirect = False):
	global ignore_slots, bold, order, topper

	#opts parsing
	opts = process_args(argv)
	ignore_slots = opts.ignore_slot
	use_overlays = opts.overlays
	# user can do both --arch=a,b,c or --arch a b c
	if len(opts.arch) > 1:
		opts.arch = ','.join(opts.arch)
	highlight_arch = ''.join(opts.arch).split(',')
	bold = opts.bold
	order = opts.align
	topper = opts.top_position
	prefix = opts.prefix
	color = opts.color
	package = opts.package

	# equery support
	if indirect and len(package) <= 0:
		msg_err = 'No packages specified'
		raise SystemExit(msg_err)

	# disable colors when redirected and they are not forced on
	if not color and not sys.stdout.isatty():
		# disable colors
		porto.nocolor()
	keywords = keywords_header(prefix, highlight_arch, order)
	if len(package) > 0:
		mysettings = portc(local_config=False)
		dbapi = portdbapi(mysettings=mysettings)
		if not use_overlays:
			dbapi.porttrees = [dbapi.porttree_root]
		for pkg in package:
			process_display(pkg, keywords, dbapi)
	else:
		currdir = os.getcwd()
		# check if there are actualy some ebuilds
		ebuilds = ['%s' % x for x in os.listdir(currdir)
			if fnmatch.fnmatch(x, '*.ebuild')]
		if len(ebuilds) <= 0:
			msg_err = 'No ebuilds at "%s"' % currdir
			raise SystemExit(msg_err)
		package= '%s/%s' % (os.path.basename(os.path.abspath('../')), os.path.basename(currdir))
		ourtree = os.path.abspath('../../')
		overlays = '%s %s' % (ports['PORTDIR_OVERLAY'], ourtree)
		mysettings = portc(local_config=False, env={'PORTDIR_OVERLAY': overlays})
		dbapi = portdbapi(mysettings=mysettings)
		# specify that we want just our nice tree we are in cwd
		dbapi.porttrees = [ourtree]
		process_display(package, keywords, dbapi)
	return 0
Example #7
0
def parseopts(opts, config=None):

    if config is None:
        config = CONFIG

    if len(opts[1]) == 0:
        usage()

    for a in opts[0]:
        arg = a[0]
        if arg in ("-h", "--help"):
            usage()
        if arg in ("-S", "--searchdesc"):
            config['searchdesc'] = True
        elif arg in ("-F", "--fullname"):
            config['fullname'] = True
        elif arg in ("-I", "--instonly"):
            config['instonly'] = True
        elif arg in ("-N", "--notinst"):
            config['notinst'] = True
        elif arg in ("-c", "--compact"):
            config['outputm'] = COMPACT
        elif arg in ("-v", "--verbose"):
            config['outputm'] = VERBOSE
        elif arg in ("-e", "--ebuild"):
            config['portdir'] = settings["PORTDIR"]
            config['overlay'] = settings["PORTDIR_OVERLAY"]
            config['outputm'] = EBUILDS
        elif arg in ("-x", "--exclude"):
            config['exclude'].append(a[1])
        elif arg in ("-o", "--own"):
            config['outputm'] = OWN
            config['outputf'] = a[1]
        elif arg in ("-d", "--directory"):
            config['esearchdbdir'] = a[1]
            if not exists(config['esearchdbdir']):
                error("directory '" + darkgreen(config['esearchdbdir']) +
                      "' does not exist.",
                      stderr=config['stderr'])
        elif arg in ("-n", "--nocolor"):
            nocolor()
    if config['fullname'] and config['searchdesc']:
        error("Please use either " + darkgreen("--fullname") + " or " +
              darkgreen("--searchdesc"),
              stderr=config['stderr'])
    return config
Example #8
0
def parseopts(opts, config=None):

    if config is None:
        config = CONFIG

    if len(opts[1]) == 0:
        usage()

    for a in opts[0]:
        arg = a[0]
        if arg in ("-h", "--help"):
            usage()
        if arg in ("-S", "--searchdesc"):
            config['searchdesc'] = True
        elif arg in ("-F", "--fullname"):
            config['fullname'] = True
        elif arg in ("-I", "--instonly"):
            config['instonly'] = True
        elif arg in ("-N", "--notinst"):
            config['notinst'] = True
        elif arg in ("-c", "--compact"):
            config['outputm'] = COMPACT
        elif arg in ("-v", "--verbose"):
            config['outputm'] = VERBOSE
        elif arg in ("-e", "--ebuild"):
            config['portdir'] = settings["PORTDIR"]
            config['overlay'] = settings["PORTDIR_OVERLAY"]
            config['outputm'] = EBUILDS
        elif arg in ("-x", "--exclude"):
            config['exclude'].append(a[1])
        elif arg in ("-o", "--own"):
            config['outputm'] = OWN
            config['outputf'] = a[1]
        elif arg in ("-d", "--directory"):
            config['esearchdbdir'] = a[1]
            if not exists(config['esearchdbdir']):
                error("directory '" + darkgreen(config['esearchdbdir']) +
                    "' does not exist.", stderr=config['stderr'])
        elif arg in ("-n", "--nocolor"):
            nocolor()
    if config['fullname'] and config['searchdesc']:
        error("Please use either " + darkgreen("--fullname") +
            " or " + darkgreen("--searchdesc"), stderr=config['stderr'])
    return config
Example #9
0
def parseopts(opts, config=None):
    if config is None:
        config = CONFIG
    config['verbose'] = 0
    for a in opts[0]:
        arg = a[0]
        if arg in ("-h", "--help"):
            usage()
        elif arg in ("-v", "--verbose"):
            config['verbose'] = 1
        elif arg in ("-q", "--quiet"):
            config['verbose'] = -1
        elif arg in ("-d", "--directory"):
            config['esearchdbdir'] = a[1]
            if not exists(config['esearchdbdir']):
                error("directory '" + darkgreen(config['esearchdbdir']) +
                    "'", "does not exist.", stderr=config['stderr'])
        elif arg in ("-n", "--nocolor"):
            nocolor()
    return config
Example #10
0
def parseopts(opts, config=None):
    if config is None:
        config = CONFIG
    config['verbose'] = 0
    for a in opts[0]:
        arg = a[0]
        if arg in ("-h", "--help"):
            usage()
        elif arg in ("-v", "--verbose"):
            config['verbose'] = 1
        elif arg in ("-q", "--quiet"):
            config['verbose'] = -1
        elif arg in ("-d", "--directory"):
            config['esearchdbdir'] = a[1]
            if not exists(config['esearchdbdir']):
                error("directory '" + darkgreen(config['esearchdbdir']) + "'",
                      "does not exist.",
                      stderr=config['stderr'])
        elif arg in ("-n", "--nocolor"):
            nocolor()
    return config
Example #11
0
def main(settings=None, logger=None):
	"""Main program operation method....

	@param settings: dict.  defaults to settings.DEFAULTS
	@param logger: python logging module defaults to init_logger(settings)
	@return boolean  success/failure
	"""

	if settings is None:
		print("NO Input settings, using defaults...")
		settings = DEFAULTS.copy()

	if logger is None:
		logger = init_logger(settings)

	_libs_to_check = settings['library']

	if not settings['stdout'].isatty() or settings['nocolor']:
		nocolor()

	#TODO: Development warning
	logger.warn(blue(' * ') +
		yellow('This is a development version, '
			'so it may not work correctly'))
	logger.warn(blue(' * ') +
		yellow('The original revdep-rebuild script is '
			'installed as revdep-rebuild.sh'))

	if os.getuid() != 0 and not settings['PRETEND']:
		logger.warn(blue(' * ') +
			yellow('You are not root, adding --pretend to portage options'))
		settings['PRETEND'] = True

	if settings['library']:
		logger.warn(green(' * ') +
			"Looking for libraries: %s" % (bold(', '.join(settings['library']))))

	if settings['USE_TMP_FILES'] \
			and check_temp_files(settings['DEFAULT_TMP_DIR'], logger=logger):
		libraries, la_libraries, libraries_links, binaries = read_cache(
			settings['DEFAULT_TMP_DIR'])
		assigned = analyse(
			settings=settings,
			logger=logger,
			libraries=libraries,
			la_libraries=la_libraries,
			libraries_links=libraries_links,
			binaries=binaries,
			_libs_to_check=_libs_to_check)
	else:
		assigned = analyse(settings, logger, _libs_to_check=_libs_to_check)

	if not assigned:
		logger.warn('\n' + bold('Your system is consistent'))
		# return the correct exit code
		return 0

	has_masked = False
	tmp = []
	for ebuild in assigned:
		if get_masking_status(ebuild):
			has_masked = True
			logger.warn('!!! ' + red('All ebuilds that could satisfy: ') +
				green(ebuild) + red(' have been masked'))
		else:
			tmp.append(ebuild)
	assigned = tmp

	if has_masked:
		logger.info(red(' * ') +
			'Unmask all ebuild(s) listed above and call revdep-rebuild '
			'again or manually emerge given packages.')

	success = rebuild(logger, assigned, settings)
	logger.debug("rebuild return code = %i" %success)
	return success
Example #12
0
def repoman_main(argv):
    config_root = os.environ.get("PORTAGE_CONFIGROOT")
    repoman_settings = portage.config(config_root=config_root,
                                      local_config=False)
    repoman_settings.valid_versions = VALID_VERSIONS

    if repoman_settings.get("NOCOLOR", "").lower() in ("yes", "true") or \
     repoman_settings.get('TERM') == 'dumb' or \
     not sys.stdout.isatty():
        nocolor()

    options, arguments = parse_args(
        sys.argv, repoman_settings.get("REPOMAN_DEFAULT_OPTS", ""))

    if options.version:
        print("Repoman", VERSION, "(portage-%s)" % portage.VERSION)
        sys.exit(0)

    logger = logging.getLogger()

    if options.verbosity > 0:
        logger.setLevel(LOGLEVEL - 10 * options.verbosity)
    else:
        logger.setLevel(LOGLEVEL)

    # Set this to False when an extraordinary issue (generally
    # something other than a QA issue) makes it impossible to
    # commit (like if Manifest generation fails).
    can_force = ExtendedFuture(True)

    portdir, portdir_overlay, mydir = utilities.FindPortdir(repoman_settings)
    if portdir is None:
        sys.exit(1)

    myreporoot = os.path.basename(portdir_overlay)
    myreporoot += mydir[len(portdir_overlay):]

    # avoid a circular parameter repo_settings
    vcs_settings = VCSSettings(options, repoman_settings)
    qadata = QAData()

    logging.debug("repoman_main: RepoSettings init")
    repo_settings = RepoSettings(config_root, portdir, portdir_overlay,
                                 repoman_settings, vcs_settings, options,
                                 qadata)
    repoman_settings = repo_settings.repoman_settings
    repoman_settings.valid_versions = VALID_VERSIONS

    # Now set repo_settings
    vcs_settings.repo_settings = repo_settings
    # set QATracker qacats, qawarnings
    vcs_settings.qatracker.qacats = repo_settings.qadata.qacats
    vcs_settings.qatracker.qawarnings = repo_settings.qadata.qawarnings
    logging.debug("repoman_main: vcs_settings done")
    logging.debug("repoman_main: qadata: %s", repo_settings.qadata)

    if 'digest' in repoman_settings.features and options.digest != 'n':
        options.digest = 'y'

    logging.debug("vcs: %s" % (vcs_settings.vcs, ))
    logging.debug("repo config: %s" % (repo_settings.repo_config, ))
    logging.debug("options: %s" % (options, ))

    # It's confusing if these warnings are displayed without the user
    # being told which profile they come from, so disable them.
    env = os.environ.copy()
    env['FEATURES'] = env.get('FEATURES', '') + ' -unknown-features-warn'

    # Perform the main checks
    scanner = Scanner(repo_settings, myreporoot, config_root, options,
                      vcs_settings, mydir, env)
    scanner.scan_pkgs(can_force)

    if options.if_modified == "y" and len(scanner.effective_scanlist) < 1:
        logging.warning(
            "--if-modified is enabled, but no modified packages were found!")

    result = {
        # fail will be true if we have failed in at least one non-warning category
        'fail': 0,
        # warn will be true if we tripped any warnings
        'warn': 0,
        # full will be true if we should print a "repoman full" informational message
        'full': options.mode != 'full',
    }

    for x in qadata.qacats:
        if x not in vcs_settings.qatracker.fails:
            continue
        result['warn'] = 1
        if x not in qadata.qawarnings:
            result['fail'] = 1

    if result['fail'] or \
     (result['warn'] and not (options.quiet or options.mode == "scan")):
        result['full'] = 0

    commitmessage = None
    if options.commitmsg:
        commitmessage = options.commitmsg
    elif options.commitmsgfile:
        # we don't need the actual text of the commit message here
        # the filename will do for the next code block
        commitmessage = options.commitmsgfile

    # Save QA output so that it can be conveniently displayed
    # in $EDITOR while the user creates a commit message.
    # Otherwise, the user would not be able to see this output
    # once the editor has taken over the screen.
    qa_output = io.StringIO()
    style_file = ConsoleStyleFile(sys.stdout)
    if options.mode == 'commit' and \
     (not commitmessage or not commitmessage.strip()):
        style_file.write_listener = qa_output
    console_writer = StyleWriter(file=style_file, maxcol=9999)
    console_writer.style_listener = style_file.new_styles

    f = formatter.AbstractFormatter(console_writer)

    format_outputs = {
        'column': format_qa_output_column,
        'default': format_qa_output
    }

    format_output = format_outputs.get(options.output_style,
                                       format_outputs['default'])
    format_output(f, vcs_settings.qatracker.fails, result['full'],
                  result['fail'], options, qadata.qawarnings)

    style_file.flush()
    del console_writer, f, style_file

    # early out for manifest generation
    if options.mode == "manifest":
        return 1 if result['fail'] else 0

    qa_output = qa_output.getvalue()
    qa_output = qa_output.splitlines(True)

    # output the results
    actions = Actions(repo_settings, options, scanner, vcs_settings)
    if actions.inform(can_force.get(), result):
        # perform any other actions
        actions.perform(qa_output)

    sys.exit(0)
Example #13
0
def main(settings=None, logger=None):
	"""Main program operation method....

	@param settings: dict.  defaults to settings.DEFAULTS
	@param logger: python logging module defaults to init_logger(settings)
	@return boolean  success/failure
	"""
	if settings is None:
		print("NO Input settings, using defaults...")
		settings = DEFAULTS.copy()

	if logger is None:
		logger = init_logger(settings)

	_libs_to_check = settings['library']

	if not settings['stdout'].isatty() or settings['nocolor']:
		nocolor()

	logger.warning(blue(' * ') +
		yellow('This is the new python coded version'))
	logger.warning(blue(' * ') +
		yellow('Please report any bugs found using it.'))
	logger.warning(blue(' * ') +
		yellow('The original revdep-rebuild script is '
			'installed as revdep-rebuild.sh'))
	logger.warning(blue(' * ') +
		yellow('Please file bugs at: '
			'https://bugs.gentoo.org/'))

	if os.getuid() != 0 and not settings['PRETEND']:
		logger.warning(blue(' * ') +
			yellow('You are not root, adding --pretend to portage options'))
		settings['PRETEND'] = True

	logger.debug("\tmain(), _libs_to_check = %s" % str(_libs_to_check))

	if settings['USE_TMP_FILES'] \
			and check_temp_files(settings['DEFAULT_TMP_DIR'], logger=logger):
		libraries, la_libraries, libraries_links, binaries = read_cache(
			settings['DEFAULT_TMP_DIR'])
		assigned, orphaned = analyse(
			settings=settings,
			logger=logger,
			libraries=libraries,
			la_libraries=la_libraries,
			libraries_links=libraries_links,
			binaries=binaries,
			_libs_to_check=_libs_to_check)
	else:
		assigned, orphaned = analyse(settings, logger, _libs_to_check=_libs_to_check)

	if not assigned and not orphaned:
		logger.warning('\n' + bold('Your system is consistent'))
		# return the correct exit code
		return 0
	elif orphaned:
		# blank line for beter visibility of the following lines
		logger.warning('')
		if settings['library']:
			logger.warning(red(' !!! Dependant orphaned files: ') +
				bold('No installed package was found for the following:'))
		else:
			logger.warning(red(' !!! Broken orphaned files: ') +
				bold('No installed package was found for the following:'))
		for filename in orphaned:
			logger.warning(red('\t* ') + filename)

	success = rebuild(logger, assigned, settings)
	logger.debug("rebuild return code = %i" %success)
	return success
Example #14
0
def main(argv, indirect = False):
	global ignore_slots, bold, order, topper

	#opts parsing
	opts = process_args(argv)
	ignore_slots = opts.ignore_slot
	use_overlays = opts.overlays
	highlight_arch = ''.join(opts.arch).split(',')
	bold = opts.bold
	order = opts.align
	topper = opts.top_position
	prefix = opts.prefix
	color = opts.color
	package = opts.package

	# equery support
	if indirect and len(package) <= 0:
		msg_err = 'No packages specified'
		raise SystemExit(msg_err)

	# disable colors when redirected and they are not forced on
	if not color and not sys.stdout.isatty():
		# disable colors
		porto.nocolor()

	# Imply prefix if user specified any architectures (Bug 578496)
	if len(opts.arch) > 0:
		prefix = True

	keywords = keywords_header(prefix, highlight_arch, order)
	if len(package) > 0:
		mysettings = portc(local_config=False)
		dbapi = portdbapi(mysettings=mysettings)
		if not use_overlays:
			dbapi.porttrees = [dbapi.porttree_root]
		for pkg in package:
			process_display(pkg, keywords, dbapi)
	else:
		currdir = os.getcwd()
		# check if there are actualy some ebuilds
		ebuilds = ['%s' % x for x in os.listdir(currdir)
			if fnmatch.fnmatch(x, '*.ebuild')]
		if len(ebuilds) <= 0:
			msg_err = 'No ebuilds at "%s"' % currdir
			raise SystemExit(msg_err)
		package= '%s/%s' % (os.path.basename(os.path.abspath('../')), os.path.basename(currdir))
		ourtree = os.path.realpath('../..')
		ourstat = os.stat(ourtree)
		ourstat = (ourstat.st_ino, ourstat.st_dev)
		for repo in ports.repositories:
			try:
				repostat = os.stat(repo.location)
			except OSError:
				continue
			if ourstat == (repostat.st_ino, repostat.st_dev):
				dbapi = portdbapi(mysettings=portc(local_config=False))
				break
		else:
			repos = {}
			for repo in ports.repositories:
				repos[repo.name] = repo.location

			with open(os.path.join(ourtree, 'profiles', 'repo_name'),
				'rt') as f:
				repo_name = f.readline().strip()

			repos[repo_name] = ourtree
			repos = ''.join('[{}]\nlocation={}\n'.format(k, v)
				for k, v in repos.items())
			mysettings = portc(local_config=False,
				env={'PORTAGE_REPOSITORIES': repos})
			dbapi = portdbapi(mysettings=mysettings)
		# specify that we want just our nice tree we are in cwd
		dbapi.porttrees = [ourtree]
		process_display(package, keywords, dbapi)
	return 0
Example #15
0
def main(argv, indirect=False):
    global ignore_slots, bold, order, topper

    #opts parsing
    opts = process_args(argv)
    ignore_slots = opts.ignore_slot
    use_overlays = opts.overlays
    highlight_arch = ''.join(opts.arch).split(',')
    bold = opts.bold
    order = opts.align
    topper = opts.top_position
    prefix = opts.prefix
    color = opts.color
    package = opts.package

    # equery support
    if indirect and len(package) <= 0:
        msg_err = 'No packages specified'
        raise SystemExit(msg_err)

    # disable colors when redirected and they are not forced on
    if not color and not sys.stdout.isatty():
        # disable colors
        porto.nocolor()

    # Imply prefix if user specified any architectures (Bug 578496)
    if len(opts.arch) > 0:
        prefix = True

    keywords = keywords_header(prefix, highlight_arch, order)
    if len(package) > 0:
        mysettings = portc(local_config=False)
        dbapi = portdbapi(mysettings=mysettings)
        if not use_overlays:
            dbapi.porttrees = [dbapi.porttree_root]
        for pkg in package:
            process_display(pkg, keywords, dbapi)
    else:
        currdir = os.getcwd()
        # check if there are actualy some ebuilds
        ebuilds = [
            '%s' % x for x in os.listdir(currdir)
            if fnmatch.fnmatch(x, '*.ebuild')
        ]
        if len(ebuilds) <= 0:
            msg_err = 'No ebuilds at "%s"' % currdir
            raise SystemExit(msg_err)
        package = '%s/%s' % (os.path.basename(
            os.path.abspath('../')), os.path.basename(currdir))
        ourtree = os.path.realpath('../..')
        ourstat = os.stat(ourtree)
        ourstat = (ourstat.st_ino, ourstat.st_dev)
        for repo in ports.repositories:
            try:
                repostat = os.stat(repo.location)
            except OSError:
                continue
            if ourstat == (repostat.st_ino, repostat.st_dev):
                dbapi = portdbapi(mysettings=portc(local_config=False))
                break
        else:
            repos = {}
            for repo in ports.repositories:
                repos[repo.name] = repo.location

            with open(os.path.join(ourtree, 'profiles', 'repo_name'),
                      'rt') as f:
                repo_name = f.readline().strip()

            repos[repo_name] = ourtree
            repos = ''.join('[{}]\nlocation={}\n'.format(k, v)
                            for k, v in repos.items())
            mysettings = portc(local_config=False,
                               env={'PORTAGE_REPOSITORIES': repos})
            dbapi = portdbapi(mysettings=mysettings)
        # specify that we want just our nice tree we are in cwd
        dbapi.porttrees = [ourtree]
        process_display(package, keywords, dbapi)
    return 0
Example #16
0
def repoman_main(argv):
	config_root = os.environ.get("PORTAGE_CONFIGROOT")
	repoman_settings = portage.config(config_root=config_root, local_config=False)
	repoman_settings.valid_versions = VALID_VERSIONS

	if repoman_settings.get("NOCOLOR", "").lower() in ("yes", "true") or \
		repoman_settings.get('TERM') == 'dumb' or \
		not sys.stdout.isatty():
		nocolor()

	options, arguments = parse_args(
		sys.argv, repoman_settings.get("REPOMAN_DEFAULT_OPTS", ""))

	if options.version:
		print("Repoman", VERSION, "(portage-%s)" % portage.VERSION)
		sys.exit(0)

	logger = logging.getLogger()

	if options.verbosity > 0:
		logger.setLevel(LOGLEVEL - 10 * options.verbosity)
	else:
		logger.setLevel(LOGLEVEL)

	# Set this to False when an extraordinary issue (generally
	# something other than a QA issue) makes it impossible to
	# commit (like if Manifest generation fails).
	can_force = ExtendedFuture(True)

	portdir, portdir_overlay, mydir = utilities.FindPortdir(repoman_settings)
	if portdir is None:
		sys.exit(1)

	myreporoot = os.path.basename(portdir_overlay)
	myreporoot += mydir[len(portdir_overlay):]

	# avoid a circular parameter repo_settings
	vcs_settings = VCSSettings(options, repoman_settings)
	qadata = QAData()

	logging.debug("repoman_main: RepoSettings init")
	repo_settings = RepoSettings(
		config_root, portdir, portdir_overlay,
		repoman_settings, vcs_settings, options, qadata)
	repoman_settings = repo_settings.repoman_settings
	repoman_settings.valid_versions = VALID_VERSIONS

	# Now set repo_settings
	vcs_settings.repo_settings = repo_settings
	# set QATracker qacats, qawarnings
	vcs_settings.qatracker.qacats = repo_settings.qadata.qacats
	vcs_settings.qatracker.qawarnings = repo_settings.qadata.qawarnings
	logging.debug("repoman_main: vcs_settings done")
	logging.debug("repoman_main: qadata: %s", repo_settings.qadata)

	if 'digest' in repoman_settings.features and options.digest != 'n':
		options.digest = 'y'

	logging.debug("vcs: %s" % (vcs_settings.vcs,))
	logging.debug("repo config: %s" % (repo_settings.repo_config,))
	logging.debug("options: %s" % (options,))

	# It's confusing if these warnings are displayed without the user
	# being told which profile they come from, so disable them.
	env = os.environ.copy()
	env['FEATURES'] = env.get('FEATURES', '') + ' -unknown-features-warn'

	# Perform the main checks
	scanner = Scanner(repo_settings, myreporoot, config_root, options,
					vcs_settings, mydir, env)
	scanner.scan_pkgs(can_force)

	if options.if_modified == "y" and len(scanner.effective_scanlist) < 1:
		logging.warning("--if-modified is enabled, but no modified packages were found!")

	result = {
		# fail will be true if we have failed in at least one non-warning category
		'fail': 0,
		# warn will be true if we tripped any warnings
		'warn': 0,
		# full will be true if we should print a "repoman full" informational message
		'full': options.mode != 'full',
	}

	# early out for manifest generation
	if options.mode == "manifest":
		sys.exit(result['fail'])

	for x in qadata.qacats:
		if x not in vcs_settings.qatracker.fails:
			continue
		result['warn'] = 1
		if x not in qadata.qawarnings:
			result['fail'] = 1

	if result['fail'] or \
		(result['warn'] and not (options.quiet or options.mode == "scan")):
		result['full'] = 0

	commitmessage = None
	if options.commitmsg:
		commitmessage = options.commitmsg
	elif options.commitmsgfile:
		# we don't need the actual text of the commit message here
		# the filename will do for the next code block
		commitmessage = options.commitmsgfile

	# Save QA output so that it can be conveniently displayed
	# in $EDITOR while the user creates a commit message.
	# Otherwise, the user would not be able to see this output
	# once the editor has taken over the screen.
	qa_output = io.StringIO()
	style_file = ConsoleStyleFile(sys.stdout)
	if options.mode == 'commit' and \
		(not commitmessage or not commitmessage.strip()):
		style_file.write_listener = qa_output
	console_writer = StyleWriter(file=style_file, maxcol=9999)
	console_writer.style_listener = style_file.new_styles

	f = formatter.AbstractFormatter(console_writer)

	format_outputs = {
		'column': format_qa_output_column,
		'default': format_qa_output
	}

	format_output = format_outputs.get(
		options.output_style, format_outputs['default'])
	format_output(f, vcs_settings.qatracker.fails, result['full'],
		result['fail'], options, qadata.qawarnings)

	style_file.flush()
	del console_writer, f, style_file
	qa_output = qa_output.getvalue()
	qa_output = qa_output.splitlines(True)

	# output the results
	actions = Actions(repo_settings, options, scanner, vcs_settings)
	if actions.inform(can_force.get(), result):
		# perform any other actions
		actions.perform(qa_output)

	sys.exit(0)
Example #17
0
def main(settings=None, logger=None):
    """Main program operation method....

	@param settings: dict.  defaults to settings.DEFAULTS
	@param logger: python logging module defaults to init_logger(settings)
	@return boolean  success/failure
	"""
    if settings is None:
        print("NO Input settings, using defaults...")
        settings = DEFAULTS.copy()

    if logger is None:
        logger = init_logger(settings)

    _libs_to_check = settings['library']

    if not settings['stdout'].isatty() or settings['nocolor']:
        nocolor()

    logger.warning(
        blue(' * ') + yellow('This is the new python coded version'))
    logger.warning(
        blue(' * ') + yellow('Please report any bugs found using it.'))
    logger.warning(
        blue(' * ') + yellow('The original revdep-rebuild script is '
                             'installed as revdep-rebuild.sh'))
    logger.warning(
        blue(' * ') + yellow('Please file bugs at: '
                             'https://bugs.gentoo.org/'))

    if os.getuid() != 0 and not settings['PRETEND']:
        logger.warning(
            blue(' * ') +
            yellow('You are not root, adding --pretend to portage options'))
        settings['PRETEND'] = True

    logger.debug("\tmain(), _libs_to_check = %s" % str(_libs_to_check))

    if settings['USE_TMP_FILES'] \
      and check_temp_files(settings['DEFAULT_TMP_DIR'], logger=logger):
        libraries, la_libraries, libraries_links, binaries = read_cache(
            settings['DEFAULT_TMP_DIR'])
        assigned, orphaned = analyse(settings=settings,
                                     logger=logger,
                                     libraries=libraries,
                                     la_libraries=la_libraries,
                                     libraries_links=libraries_links,
                                     binaries=binaries,
                                     _libs_to_check=_libs_to_check)
    else:
        assigned, orphaned = analyse(settings,
                                     logger,
                                     _libs_to_check=_libs_to_check)

    if not assigned and not orphaned:
        logger.warning('\n' + bold('Your system is consistent'))
        # return the correct exit code
        return 0
    elif orphaned:
        # blank line for beter visibility of the following lines
        logger.warning('')
        if settings['library']:
            logger.warning(
                red(' !!! Dependant orphaned files: ') +
                bold('No installed package was found for the following:'))
        else:
            logger.warning(
                red(' !!! Broken orphaned files: ') +
                bold('No installed package was found for the following:'))
        for filename in orphaned:
            logger.warning(red('\t* ') + filename)

    success = rebuild(logger, assigned, settings)
    logger.debug("rebuild return code = %i" % success)
    return success
Example #18
0
def main(settings=None, logger=None):
	"""Main program operation method....
	
	@param settings: dict.  defaults to settings.DEFAULTS
	@param logger: python logging module defaults to init_logger(settings)
	@return boolean  success/failure
	"""

	if settings is None:
		print("NO Input settings, using defaults...")
		settings = DEFAULTS.copy()

	if logger is None:
		logger = init_logger(settings)

	_libs_to_check = settings['library']

	if not settings['stdout'].isatty() or settings['nocolor']:
		nocolor()

	#TODO: Development warning
	logger.warn(blue(' * ') + 
		yellow('This is a development version, '
			'so it may not work correctly'))
	logger.warn(blue(' * ') + 
		yellow('The original revdep-rebuild script is '
			'installed as revdep-rebuild.sh'))

	if os.getuid() != 0 and not settings['PRETEND']:
		logger.warn(blue(' * ') + 
			yellow('You are not root, adding --pretend to portage options'))
		settings['PRETEND'] = True

	if settings['library']:
		logger.warn(green(' * ') + 
			"Looking for libraries: %s" % (bold(', '.join(settings['library']))))

	if settings['USE_TMP_FILES'] \
			and check_temp_files(settings['DEFAULT_TMP_DIR'], logger=logger):
		libraries, la_libraries, libraries_links, binaries = read_cache(
			settings['DEFAULT_TMP_DIR'])
		assigned = analyse(
			settings=settings,
			logger=logger,
			libraries=libraries,
			la_libraries=la_libraries, 
			libraries_links=libraries_links,
			binaries=binaries,
			_libs_to_check=_libs_to_check)
	else:
		assigned = analyse(settings, logger, _libs_to_check=_libs_to_check)

	if not assigned:
		logger.warn('\n' + bold('Your system is consistent'))
		# return the correct exit code
		return 0

	has_masked = False
	tmp = []
	for ebuild in assigned:
		if get_masking_status(ebuild):
			has_masked = True
			logger.warn('!!! ' + red('All ebuilds that could satisfy: ') + 
				green(ebuild) + red(' have been masked'))
		else:
			tmp.append(ebuild)
	assigned = tmp

	if has_masked:
		logger.info(red(' * ') + 
			'Unmask all ebuild(s) listed above and call revdep-rebuild '
			'again or manually emerge given packages.')

	success = rebuild(logger, assigned, settings)
	logger.debug("rebuild return code = %i" %success)
	return success