def parse_args(args): description = "emirrordist - a fetch tool for mirroring " \ "of package distfiles" usage = "emirrordist [options] <action>" parser = ArgumentParser(description=description, usage=usage) actions = parser.add_argument_group('Actions') actions.add_argument("--version", action="store_true", help="display portage version and exit") actions.add_argument("--mirror", action="store_true", help="mirror distfiles for the selected repository") common = parser.add_argument_group('Common options') for opt_info in common_options: opt_pargs = [opt_info["longopt"]] if opt_info.get("shortopt"): opt_pargs.append(opt_info["shortopt"]) opt_kwargs = {"help": opt_info["help"]} for k in ("action", "choices", "default", "metavar", "type"): if k in opt_info: opt_kwargs[k] = opt_info[k] common.add_argument(*opt_pargs, **opt_kwargs) options, args = parser.parse_known_args(args) return (parser, options, args)
def main(): suite = unittest.TestSuite() basedir = os.path.dirname(os.path.realpath(__file__)) usage = "usage: %s [options] [tests to run]" % os.path.basename(sys.argv[0]) parser = ArgumentParser(usage=usage) parser.add_argument("-l", "--list", help="list all tests", action="store_true", dest="list_tests") options, args = parser.parse_known_args(args=sys.argv) if os.environ.get("NOCOLOR") in ("yes", "true") or os.environ.get("TERM") == "dumb" or not sys.stdout.isatty(): portage.output.nocolor() if options.list_tests: testdir = os.path.dirname(sys.argv[0]) for mydir in getTestDirs(basedir): testsubdir = os.path.basename(mydir) for name in getTestNames(mydir): print("%s/%s/%s.py" % (testdir, testsubdir, name)) return os.EX_OK if len(args) > 1: suite.addTests(getTestFromCommandLine(args[1:], basedir)) else: for mydir in getTestDirs(basedir): suite.addTests(getTests(os.path.join(basedir, mydir), basedir)) result = TextTestRunner(verbosity=2).run(suite) if not result.wasSuccessful(): return 1 return os.EX_OK
def parse_args(args): description = "emirrordist - a fetch tool for mirroring " \ "of package distfiles" usage = "emirrordist [options] <action>" parser = ArgumentParser(description=description, usage=usage) actions = parser.add_argument_group('Actions') actions.add_argument("--version", action="store_true", help="display portage version and exit") actions.add_argument("--mirror", action="store_true", help="mirror distfiles for the selected repository") common = parser.add_argument_group('Common options') for opt_info in common_options: opt_pargs = [opt_info["longopt"]] if opt_info.get("shortopt"): opt_pargs.append(opt_info["shortopt"]) opt_kwargs = {"help" : opt_info["help"]} for k in ("action", "choices", "default", "metavar", "type"): if k in opt_info: opt_kwargs[k] = opt_info[k] common.add_argument(*opt_pargs, **opt_kwargs) options, args = parser.parse_known_args(args) return (parser, options, args)
def main(): suite = unittest.TestSuite() basedir = os.path.dirname(os.path.realpath(__file__)) usage = "usage: %s [options] [tests to run]" % os.path.basename(sys.argv[0]) parser = ArgumentParser(usage=usage) parser.add_argument("-l", "--list", help="list all tests", action="store_true", dest="list_tests") options, args = parser.parse_known_args(args=sys.argv) if (os.environ.get('NOCOLOR') in ('yes', 'true') or os.environ.get('TERM') == 'dumb' or not sys.stdout.isatty()): portage.output.nocolor() if options.list_tests: testdir = os.path.dirname(sys.argv[0]) for mydir in getTestDirs(basedir): testsubdir = os.path.basename(mydir) for name in getTestNames(mydir): print("%s/%s/%s.py" % (testdir, testsubdir, name)) return os.EX_OK if len(args) > 1: suite.addTests(getTestFromCommandLine(args[1:], basedir)) else: for mydir in getTestDirs(basedir): suite.addTests(getTests(os.path.join(basedir, mydir), basedir)) result = TextTestRunner(verbosity=2).run(suite) if not result.wasSuccessful(): return 1 return os.EX_OK
def main(argv): if argv and isinstance(argv[0], bytes): for i, x in enumerate(argv): argv[i] = portage._unicode_decode(x, errors='strict') valid_commands = ('recompose',) description = "Perform metadata operations on a binary package." usage = "usage: %s COMMAND [args]" % \ os.path.basename(argv[0]) parser = ArgumentParser(description=description, usage=usage) options, args = parser.parse_known_args(argv[1:]) if not args: parser.error("missing command argument") command = args[0] if command not in valid_commands: parser.error("invalid command: '%s'" % command) if command == 'recompose': rval = command_recompose(args[1:]) else: raise AssertionError("invalid command: '%s'" % command) return rval
def main(argv): parser = ArgumentParser(description=__doc__) parser.add_argument('location', default=None, help='root directory (e.g. $D)') parser.add_argument('old', default=None, help='original build prefix (e.g. /)') parser.add_argument('new', default=None, help='new install prefix (e.g. $EPREFIX)') opts = parser.parse_args(argv) location, old, new = opts.location, opts.old, opts.new is_text_file = IsTextFile() if not isinstance(location, bytes): location = location.encode(FS_ENCODING) if not isinstance(old, bytes): old = old.encode(FS_ENCODING) if not isinstance(new, bytes): new = new.encode(FS_ENCODING) st = os.lstat(location) if stat.S_ISDIR(st.st_mode): for parent, dirs, files in os.walk(location): for filename in files: filename = os.path.join(parent, filename) try: st = os.lstat(filename) except OSError: pass else: if stat.S_ISREG(st.st_mode): chpath_inplace(filename, is_text_file(filename), old, new) elif stat.S_ISLNK(st.st_mode): chpath_inplace_symlink(filename, st, old, new) elif stat.S_ISREG(st.st_mode): chpath_inplace(location, is_text_file(location), old, new) elif stat.S_ISLNK(st.st_mode): chpath_inplace_symlink(location, st, old, new) return os.EX_OK
def main(argv): parser = ArgumentParser(description=doc) parser.add_argument('paths', nargs='*', default=[]) actions = parser.add_argument_group('Actions') actions.add_argument('--dump', action='store_true', help='Dump the values of all extended ' 'attributes associated with null-separated' ' paths read from stdin.') actions.add_argument('--restore', action='store_true', help='Restore extended attributes using' ' a dump read from stdin.') options = parser.parse_args(argv) if sys.hexversion >= 0x3000000: file_in = sys.stdin.buffer.raw else: file_in = sys.stdin if not options.paths: options.paths += [x for x in file_in.read().split(b'\0') if x] if options.dump: if sys.hexversion >= 0x3000000: file_out = sys.stdout.buffer else: file_out = sys.stdout dump_xattrs(options.paths, file_out) elif options.restore: restore_xattrs(file_in) else: parser.error('missing action!') return os.EX_OK
def main(argv): parser = ArgumentParser(description=__doc__) parser.add_argument('paths', nargs='*', default=[]) actions = parser.add_argument_group('Actions') actions.add_argument('--dump', action='store_true', help='Dump the values of all extended ' 'attributes associated with null-separated' ' paths read from stdin.') actions.add_argument('--restore', action='store_true', help='Restore extended attributes using' ' a dump read from stdin.') options = parser.parse_args(argv) if sys.hexversion >= 0x3000000: file_in = sys.stdin.buffer.raw else: file_in = sys.stdin if not options.paths: options.paths += [x for x in file_in.read().split(b'\0') if x] if options.dump: if sys.hexversion >= 0x3000000: file_out = sys.stdout.buffer else: file_out = sys.stdout dump_xattrs(options.paths, file_out) elif options.restore: restore_xattrs(file_in) else: parser.error('missing action!') return os.EX_OK
def main(argv): parser = ArgumentParser(description=__doc__) try: parser.add_argument('location', default=None, help='root directory (e.g. $D)') parser.add_argument('old', default=None, help='original build prefix (e.g. /)') parser.add_argument('new', default=None, help='new install prefix (e.g. $EPREFIX)') opts = parser.parse_args(argv) location, old, new = opts.location, opts.old, opts.new except OptionError: # Argument parsing compatibility for Python 2.6 using optparse. if sys.hexversion < 0x2070000: parser = OptionParser(description=__doc__, usage="usage: %prog [-h] location old new\n\n" + \ " location: root directory (e.g. $D)\n" + \ " old: original build prefix (e.g. /)\n" + \ " new: new install prefix (e.g. $EPREFIX)") (opts, args) = parser.parse_args() if len(args) != 3: parser.print_usage() print("%s: error: expected 3 arguments, got %i" % (__file__, len(args))) return location, old, new = args[0:3] else: raise is_text_file = IsTextFile() if not isinstance(location, bytes): location = location.encode(FS_ENCODING) if not isinstance(old, bytes): old = old.encode(FS_ENCODING) if not isinstance(new, bytes): new = new.encode(FS_ENCODING) st = os.lstat(location) if stat.S_ISDIR(st.st_mode): for parent, dirs, files in os.walk(location): for filename in files: filename = os.path.join(parent, filename) try: st = os.lstat(filename) except OSError: pass else: if stat.S_ISREG(st.st_mode): chpath_inplace(filename, is_text_file(filename), old, new) elif stat.S_ISLNK(st.st_mode): chpath_inplace_symlink(filename, st, old, new) elif stat.S_ISREG(st.st_mode): chpath_inplace(location, is_text_file(location), old, new) elif stat.S_ISLNK(st.st_mode): chpath_inplace_symlink(location, st, old, new) return os.EX_OK
def parse_args(args): """ Parse the command line arguments using optparse for python 2.6 compatibility Args: args: a list of the white space delimited command line Returns: tuple of the Namespace of parsed options, and a list of order parameters """ parser = ArgumentParser(add_help=False) parser.add_argument( "-b", action="store_true", dest="shortopt_b" ) parser.add_argument( "--backup", action="store", dest="backup" ) parser.add_argument( "-c", action="store_true", dest="shortopt_c" ) parser.add_argument( "--compare", "-C", action="store_true", dest="compare" ) parser.add_argument( "--directory", "-d", action="store_true", dest="directory" ) parser.add_argument( "-D", action="store_true", dest="shortopt_D" ) parser.add_argument( "--owner", "-o", action="store", dest="owner" ) parser.add_argument( "--group", "-g", action="store", dest="group" ) parser.add_argument( "--mode", "-m", action="store", dest="mode" ) parser.add_argument( "--preserve-timestamps", "-p", action="store_true", dest="preserve_timestamps" ) parser.add_argument( "--strip", "-s", action="store_true", dest="strip" ) parser.add_argument( "--strip-program", action="store", dest="strip_program" ) parser.add_argument( "--suffix", "-S", action="store", dest="suffix" ) parser.add_argument( "--target-directory", "-t", action="store", dest="target_directory" ) parser.add_argument( "--no-target-directory", "-T", action="store_true", dest="no_target_directory" ) parser.add_argument( "--context", "-Z", action="store", dest="context" ) parser.add_argument( "--verbose", "-v", action="store_true", dest="verbose" ) parser.add_argument( "--help", action="store_true", dest="help" ) parser.add_argument( "--version", action="store_true", dest="version" ) # Use parse_known_args for maximum compatibility with # getopt handling of non-option file arguments. Note # that parser.add_argument("files", nargs='+') would # be subtly incompatible because it requires that all # of the file arguments be grouped sequentially. Also # note that we have to explicitly call add_argument # for known options in order for argparse to correctly # separate option arguments from file arguments in all # cases (it also allows for optparse compatibility). parsed_args = parser.parse_known_args() opts = parsed_args[0] files = parsed_args[1] files = [f for f in files if f != "--"] # filter out "--" return (opts, files)
def parse_opts(tmpcmdline, silent=False): myaction=None myopts = {} myfiles=[] actions = frozenset([ "clean", "check-news", "config", "depclean", "help", "info", "list-sets", "metadata", "moo", "prune", "regen", "search", "sync", "unmerge", "version", ]) longopt_aliases = {"--cols":"--columns", "--skip-first":"--skipfirst"} y_or_n = ("y", "n") true_y_or_n = ("True", "y", "n") true_y = ("True", "y") argument_options = { "--ask": { "shortopt" : "-a", "help" : "prompt before performing any actions", "choices" : true_y_or_n }, "--autounmask": { "help" : "automatically unmask packages", "choices" : true_y_or_n }, "--autounmask-unrestricted-atoms": { "help" : "write autounmask changes with >= atoms if possible", "choices" : true_y_or_n }, "--autounmask-keep-masks": { "help" : "don't add package.unmask entries", "choices" : true_y_or_n }, "--autounmask-write": { "help" : "write changes made by --autounmask to disk", "choices" : true_y_or_n }, "--accept-properties": { "help":"temporarily override ACCEPT_PROPERTIES", "action":"store" }, "--accept-restrict": { "help":"temporarily override ACCEPT_RESTRICT", "action":"store" }, "--backtrack": { "help" : "Specifies how many times to backtrack if dependency " + \ "calculation fails ", "action" : "store" }, "--buildpkg": { "shortopt" : "-b", "help" : "build binary packages", "choices" : true_y_or_n }, "--buildpkg-exclude": { "help" :"A space separated list of package atoms for which " + \ "no binary packages should be built. This option overrides all " + \ "possible ways to enable building of binary packages.", "action" : "append" }, "--config-root": { "help":"specify the location for portage configuration files", "action":"store" }, "--color": { "help":"enable or disable color output", "choices":("y", "n") }, "--complete-graph": { "help" : "completely account for all known dependencies", "choices" : true_y_or_n }, "--complete-graph-if-new-use": { "help" : "trigger --complete-graph behavior if USE or IUSE will change for an installed package", "choices" : y_or_n }, "--complete-graph-if-new-ver": { "help" : "trigger --complete-graph behavior if an installed package version will change (upgrade or downgrade)", "choices" : y_or_n }, "--deep": { "shortopt" : "-D", "help" : "Specifies how deep to recurse into dependencies " + \ "of packages given as arguments. If no argument is given, " + \ "depth is unlimited. Default behavior is to skip " + \ "dependencies of installed packages.", "action" : "store" }, "--depclean-lib-check": { "help" : "check for consumers of libraries before removing them", "choices" : true_y_or_n }, "--deselect": { "help" : "remove atoms/sets from the world file", "choices" : true_y_or_n }, "--dynamic-deps": { "help": "substitute the dependencies of installed packages with the dependencies of unbuilt ebuilds", "choices": y_or_n }, "--exclude": { "help" :"A space separated list of package names or slot atoms. " + \ "Emerge won't install any ebuild or binary package that " + \ "matches any of the given package atoms.", "action" : "append" }, "--fail-clean": { "help" : "clean temp files after build failure", "choices" : true_y_or_n }, "--ignore-built-slot-operator-deps": { "help": "Ignore the slot/sub-slot := operator parts of dependencies that have " "been recorded when packages where built. This option is intended " "only for debugging purposes, and it only affects built packages " "that specify slot/sub-slot := operator dependencies using the " "experimental \"4-slot-abi\" EAPI.", "choices": y_or_n }, "--jobs": { "shortopt" : "-j", "help" : "Specifies the number of packages to build " + \ "simultaneously.", "action" : "store" }, "--keep-going": { "help" : "continue as much as possible after an error", "choices" : true_y_or_n }, "--load-average": { "help" :"Specifies that no new builds should be started " + \ "if there are other builds running and the load average " + \ "is at least LOAD (a floating-point number).", "action" : "store" }, "--misspell-suggestions": { "help" : "enable package name misspell suggestions", "choices" : ("y", "n") }, "--with-bdeps": { "help":"include unnecessary build time dependencies", "choices":("y", "n") }, "--reinstall": { "help":"specify conditions to trigger package reinstallation", "choices":["changed-use"] }, "--reinstall-atoms": { "help" :"A space separated list of package names or slot atoms. " + \ "Emerge will treat matching packages as if they are not " + \ "installed, and reinstall them if necessary. Implies --deep.", "action" : "append", }, "--binpkg-respect-use": { "help" : "discard binary packages if their use flags \ don't match the current configuration", "choices" : true_y_or_n }, "--getbinpkg": { "shortopt" : "-g", "help" : "fetch binary packages", "choices" : true_y_or_n }, "--getbinpkgonly": { "shortopt" : "-G", "help" : "fetch binary packages only", "choices" : true_y_or_n }, "--usepkg-exclude": { "help" :"A space separated list of package names or slot atoms. " + \ "Emerge will ignore matching binary packages. ", "action" : "append", }, "--rebuild-exclude": { "help" :"A space separated list of package names or slot atoms. " + \ "Emerge will not rebuild these packages due to the " + \ "--rebuild flag. ", "action" : "append", }, "--rebuild-ignore": { "help" :"A space separated list of package names or slot atoms. " + \ "Emerge will not rebuild packages that depend on matching " + \ "packages due to the --rebuild flag. ", "action" : "append", }, "--package-moves": { "help" : "perform package moves when necessary", "choices" : true_y_or_n }, "--prefix": { "help" : "specify the installation prefix", "action" : "store" }, "--pkg-format": { "help" : "format of result binary package", "action" : "store", }, "--quiet": { "shortopt" : "-q", "help" : "reduced or condensed output", "choices" : true_y_or_n }, "--quiet-build": { "help" : "redirect build output to logs", "choices" : true_y_or_n, }, "--quiet-fail": { "help" : "suppresses display of the build log on stdout", "choices" : true_y_or_n, }, "--rebuild-if-new-slot": { "help" : ("Automatically rebuild or reinstall packages when slot/sub-slot := " "operator dependencies can be satisfied by a newer slot, so that " "older packages slots will become eligible for removal by the " "--depclean action as soon as possible."), "choices" : true_y_or_n }, "--rebuild-if-new-rev": { "help" : "Rebuild packages when dependencies that are " + \ "used at both build-time and run-time are built, " + \ "if the dependency is not already installed with the " + \ "same version and revision.", "choices" : true_y_or_n }, "--rebuild-if-new-ver": { "help" : "Rebuild packages when dependencies that are " + \ "used at both build-time and run-time are built, " + \ "if the dependency is not already installed with the " + \ "same version. Revision numbers are ignored.", "choices" : true_y_or_n }, "--rebuild-if-unbuilt": { "help" : "Rebuild packages when dependencies that are " + \ "used at both build-time and run-time are built.", "choices" : true_y_or_n }, "--rebuilt-binaries": { "help" : "replace installed packages with binary " + \ "packages that have been rebuilt", "choices" : true_y_or_n }, "--rebuilt-binaries-timestamp": { "help" : "use only binaries that are newer than this " + \ "timestamp for --rebuilt-binaries", "action" : "store" }, "--root": { "help" : "specify the target root filesystem for merging packages", "action" : "store" }, "--root-deps": { "help" : "modify interpretation of depedencies", "choices" :("True", "rdeps") }, "--select": { "shortopt" : "-w", "help" : "add specified packages to the world set " + \ "(inverse of --oneshot)", "choices" : true_y_or_n }, "--selective": { "help" : "identical to --noreplace", "choices" : true_y_or_n }, "--use-ebuild-visibility": { "help" : "use unbuilt ebuild metadata for visibility checks on built packages", "choices" : true_y_or_n }, "--useoldpkg-atoms": { "help" :"A space separated list of package names or slot atoms. " + \ "Emerge will prefer matching binary packages over newer unbuilt packages. ", "action" : "append", }, "--usepkg": { "shortopt" : "-k", "help" : "use binary packages", "choices" : true_y_or_n }, "--usepkgonly": { "shortopt" : "-K", "help" : "use only binary packages", "choices" : true_y_or_n }, "--verbose": { "shortopt" : "-v", "help" : "verbose output", "choices" : true_y_or_n }, "--verbose-slot-rebuilds": { "help" : "verbose slot rebuild output", "choices" : true_y_or_n }, } parser = ArgumentParser(add_help=False) for action_opt in actions: parser.add_argument("--" + action_opt, action="store_true", dest=action_opt.replace("-", "_"), default=False) for myopt in options: parser.add_argument(myopt, action="store_true", dest=myopt.lstrip("--").replace("-", "_"), default=False) for shortopt, longopt in shortmapping.items(): parser.add_argument("-" + shortopt, action="store_true", dest=longopt.lstrip("--").replace("-", "_"), default=False) for myalias, myopt in longopt_aliases.items(): parser.add_argument(myalias, action="store_true", dest=myopt.lstrip("--").replace("-", "_"), default=False) for myopt, kwargs in argument_options.items(): shortopt = kwargs.pop("shortopt", None) args = [myopt] if shortopt is not None: args.append(shortopt) parser.add_argument(dest=myopt.lstrip("--").replace("-", "_"), *args, **kwargs) tmpcmdline = insert_optional_args(tmpcmdline) myoptions, myargs = parser.parse_known_args(args=tmpcmdline) if myoptions.ask in true_y: myoptions.ask = True else: myoptions.ask = None if myoptions.autounmask in true_y: myoptions.autounmask = True if myoptions.autounmask_unrestricted_atoms in true_y: myoptions.autounmask_unrestricted_atoms = True if myoptions.autounmask_keep_masks in true_y: myoptions.autounmask_keep_masks = True if myoptions.autounmask_write in true_y: myoptions.autounmask_write = True if myoptions.buildpkg in true_y: myoptions.buildpkg = True if myoptions.buildpkg_exclude: bad_atoms = _find_bad_atoms(myoptions.buildpkg_exclude, less_strict=True) if bad_atoms and not silent: parser.error("Invalid Atom(s) in --buildpkg-exclude parameter: '%s'\n" % \ (",".join(bad_atoms),)) if myoptions.changed_use is not False: myoptions.reinstall = "changed-use" myoptions.changed_use = False if myoptions.deselect in true_y: myoptions.deselect = True if myoptions.binpkg_respect_use is not None: if myoptions.binpkg_respect_use in true_y: myoptions.binpkg_respect_use = 'y' else: myoptions.binpkg_respect_use = 'n' if myoptions.complete_graph in true_y: myoptions.complete_graph = True else: myoptions.complete_graph = None if myoptions.depclean_lib_check in true_y: myoptions.depclean_lib_check = True if myoptions.exclude: bad_atoms = _find_bad_atoms(myoptions.exclude) if bad_atoms and not silent: parser.error("Invalid Atom(s) in --exclude parameter: '%s' (only package names and slot atoms (with wildcards) allowed)\n" % \ (",".join(bad_atoms),)) if myoptions.reinstall_atoms: bad_atoms = _find_bad_atoms(myoptions.reinstall_atoms) if bad_atoms and not silent: parser.error("Invalid Atom(s) in --reinstall-atoms parameter: '%s' (only package names and slot atoms (with wildcards) allowed)\n" % \ (",".join(bad_atoms),)) if myoptions.rebuild_exclude: bad_atoms = _find_bad_atoms(myoptions.rebuild_exclude) if bad_atoms and not silent: parser.error("Invalid Atom(s) in --rebuild-exclude parameter: '%s' (only package names and slot atoms (with wildcards) allowed)\n" % \ (",".join(bad_atoms),)) if myoptions.rebuild_ignore: bad_atoms = _find_bad_atoms(myoptions.rebuild_ignore) if bad_atoms and not silent: parser.error("Invalid Atom(s) in --rebuild-ignore parameter: '%s' (only package names and slot atoms (with wildcards) allowed)\n" % \ (",".join(bad_atoms),)) if myoptions.usepkg_exclude: bad_atoms = _find_bad_atoms(myoptions.usepkg_exclude) if bad_atoms and not silent: parser.error("Invalid Atom(s) in --usepkg-exclude parameter: '%s' (only package names and slot atoms (with wildcards) allowed)\n" % \ (",".join(bad_atoms),)) if myoptions.useoldpkg_atoms: bad_atoms = _find_bad_atoms(myoptions.useoldpkg_atoms) if bad_atoms and not silent: parser.error("Invalid Atom(s) in --useoldpkg-atoms parameter: '%s' (only package names and slot atoms (with wildcards) allowed)\n" % \ (",".join(bad_atoms),)) if myoptions.fail_clean in true_y: myoptions.fail_clean = True if myoptions.getbinpkg in true_y: myoptions.getbinpkg = True else: myoptions.getbinpkg = None if myoptions.getbinpkgonly in true_y: myoptions.getbinpkgonly = True else: myoptions.getbinpkgonly = None if myoptions.keep_going in true_y: myoptions.keep_going = True else: myoptions.keep_going = None if myoptions.package_moves in true_y: myoptions.package_moves = True if myoptions.quiet in true_y: myoptions.quiet = True else: myoptions.quiet = None if myoptions.quiet_build in true_y: myoptions.quiet_build = 'y' if myoptions.quiet_fail in true_y: myoptions.quiet_fail = 'y' if myoptions.rebuild_if_new_slot in true_y: myoptions.rebuild_if_new_slot = 'y' if myoptions.rebuild_if_new_ver in true_y: myoptions.rebuild_if_new_ver = True else: myoptions.rebuild_if_new_ver = None if myoptions.rebuild_if_new_rev in true_y: myoptions.rebuild_if_new_rev = True myoptions.rebuild_if_new_ver = None else: myoptions.rebuild_if_new_rev = None if myoptions.rebuild_if_unbuilt in true_y: myoptions.rebuild_if_unbuilt = True myoptions.rebuild_if_new_rev = None myoptions.rebuild_if_new_ver = None else: myoptions.rebuild_if_unbuilt = None if myoptions.rebuilt_binaries in true_y: myoptions.rebuilt_binaries = True if myoptions.root_deps in true_y: myoptions.root_deps = True if myoptions.select in true_y: myoptions.select = True myoptions.oneshot = False elif myoptions.select == "n": myoptions.oneshot = True if myoptions.selective in true_y: myoptions.selective = True if myoptions.backtrack is not None: try: backtrack = int(myoptions.backtrack) except (OverflowError, ValueError): backtrack = -1 if backtrack < 0: backtrack = None if not silent: parser.error("Invalid --backtrack parameter: '%s'\n" % \ (myoptions.backtrack,)) myoptions.backtrack = backtrack if myoptions.deep is not None: deep = None if myoptions.deep == "True": deep = True else: try: deep = int(myoptions.deep) except (OverflowError, ValueError): deep = -1 if deep is not True and deep < 0: deep = None if not silent: parser.error("Invalid --deep parameter: '%s'\n" % \ (myoptions.deep,)) myoptions.deep = deep if myoptions.jobs: jobs = None if myoptions.jobs == "True": jobs = True else: try: jobs = int(myoptions.jobs) except ValueError: jobs = -1 if jobs is not True and \ jobs < 1: jobs = None if not silent: parser.error("Invalid --jobs parameter: '%s'\n" % \ (myoptions.jobs,)) myoptions.jobs = jobs if myoptions.load_average == "True": myoptions.load_average = None if myoptions.load_average: try: load_average = float(myoptions.load_average) except ValueError: load_average = 0.0 if load_average <= 0.0: load_average = None if not silent: parser.error("Invalid --load-average parameter: '%s'\n" % \ (myoptions.load_average,)) myoptions.load_average = load_average if myoptions.rebuilt_binaries_timestamp: try: rebuilt_binaries_timestamp = int(myoptions.rebuilt_binaries_timestamp) except ValueError: rebuilt_binaries_timestamp = -1 if rebuilt_binaries_timestamp < 0: rebuilt_binaries_timestamp = 0 if not silent: parser.error("Invalid --rebuilt-binaries-timestamp parameter: '%s'\n" % \ (myoptions.rebuilt_binaries_timestamp,)) myoptions.rebuilt_binaries_timestamp = rebuilt_binaries_timestamp if myoptions.use_ebuild_visibility in true_y: myoptions.use_ebuild_visibility = True else: # None or "n" pass if myoptions.usepkg in true_y: myoptions.usepkg = True else: myoptions.usepkg = None if myoptions.usepkgonly in true_y: myoptions.usepkgonly = True else: myoptions.usepkgonly = None if myoptions.verbose in true_y: myoptions.verbose = True else: myoptions.verbose = None for myopt in options: v = getattr(myoptions, myopt.lstrip("--").replace("-", "_")) if v: myopts[myopt] = True for myopt in argument_options: v = getattr(myoptions, myopt.lstrip("--").replace("-", "_"), None) if v is not None: myopts[myopt] = v if myoptions.searchdesc: myoptions.search = True for action_opt in actions: v = getattr(myoptions, action_opt.replace("-", "_")) if v: if myaction: multiple_actions(myaction, action_opt) sys.exit(1) myaction = action_opt if myaction is None and myoptions.deselect is True: myaction = 'deselect' myfiles += myargs return myaction, myopts, myfiles
def emaint_main(myargv): # Similar to emerge, emaint needs a default umask so that created # files (such as the world file) have sane permissions. os.umask(0o22) module_path = os.path.join( (os.path.dirname( os.path.realpath(__file__))), "modules" ) module_controller = Modules( path=module_path, namepath="portage.emaint.modules") module_names = module_controller.module_names[:] module_names.insert(0, "all") parser = ArgumentParser(usage=usage(module_controller)) # add default options parser_options = [] for opt in DEFAULT_OPTIONS: parser_options.append(OptionItem(DEFAULT_OPTIONS[opt])) for mod in module_names[1:]: desc = module_controller.get_func_descriptions(mod) if desc: for opt in desc: parser_options.append(OptionItem(desc[opt])) desc = module_controller.get_opt_descriptions(mod) if desc: for opt in desc: parser_options.append(OptionItem(desc[opt])) for opt in parser_options: parser.add_argument(*opt.pargs, **opt.kwargs) options, args = parser.parse_known_args(args=myargv) if options.version: print(portage.VERSION) return os.EX_OK if len(args) != 1: parser.error("Incorrect number of arguments") if args[0] not in module_names: parser.error("%s target is not a known target" % args[0]) check_opt = None func = status = long_action = None for opt in parser_options: if opt.long == '--check': # Default action check_opt = opt if opt.status and getattr(options, opt.target, False): if long_action is not None: parser.error("--%s and %s are exclusive options" % (long_action, opt.long)) status = opt.status func = opt.func long_action = opt.long.lstrip('-') if long_action is None: #print("DEBUG: long_action is None: setting to 'check'") long_action = 'check' func = check_opt.func status = check_opt.status if args[0] == "all": tasks = [] for m in module_names[1:]: #print("DEBUG: module: %s, functions: " % (m, str(module_controller.get_functions(m)))) if long_action in module_controller.get_functions(m): tasks.append(module_controller.get_class(m)) elif long_action in module_controller.get_functions(args[0]): tasks = [module_controller.get_class(args[0] )] else: portage.util.writemsg( "\nERROR: module '%s' does not have option '--%s'\n\n" % (args[0], long_action), noiselevel=-1) portage.util.writemsg(module_opts(module_controller, args[0]), noiselevel=-1) sys.exit(1) # need to pass the parser options dict to the modules # so they are available if needed. task_opts = options.__dict__ task_opts['return-messages'] = True taskmaster = TaskHandler(callback=print_results, module_output=sys.stdout) taskmaster.run_tasks(tasks, func, status, options=task_opts)
def parse_opts(tmpcmdline, silent=False): myaction = None myopts = {} myfiles = [] actions = frozenset([ "clean", "check-news", "config", "depclean", "help", "info", "list-sets", "metadata", "moo", "prune", "rage-clean", "regen", "search", "sync", "unmerge", "version", ]) longopt_aliases = {"--cols": "--columns", "--skip-first": "--skipfirst"} y_or_n = ("y", "n") true_y_or_n = ("True", "y", "n") true_y = ("True", "y") argument_options = { "--alert": { "shortopt" : "-A", "help" : "alert (terminal bell) on prompts", "choices" : true_y_or_n }, "--ask": { "shortopt" : "-a", "help" : "prompt before performing any actions", "choices" : true_y_or_n }, "--autounmask": { "help" : "automatically unmask packages", "choices" : true_y_or_n }, "--autounmask-unrestricted-atoms": { "help" : "write autounmask changes with >= atoms if possible", "choices" : true_y_or_n }, "--autounmask-keep-masks": { "help" : "don't add package.unmask entries", "choices" : true_y_or_n }, "--autounmask-write": { "help" : "write changes made by --autounmask to disk", "choices" : true_y_or_n }, "--accept-properties": { "help":"temporarily override ACCEPT_PROPERTIES", "action":"store" }, "--accept-restrict": { "help":"temporarily override ACCEPT_RESTRICT", "action":"store" }, "--backtrack": { "help" : "Specifies how many times to backtrack if dependency " + \ "calculation fails ", "action" : "store" }, "--binpkg-changed-deps": { "help" : ("reject binary packages with outdated " "dependencies"), "choices" : true_y_or_n }, "--buildpkg": { "shortopt" : "-b", "help" : "build binary packages", "choices" : true_y_or_n }, "--buildpkg-exclude": { "help" :"A space separated list of package atoms for which " + \ "no binary packages should be built. This option overrides all " + \ "possible ways to enable building of binary packages.", "action" : "append" }, "--changed-deps": { "help" : ("replace installed packages with " "outdated dependencies"), "choices" : true_y_or_n }, "--config-root": { "help":"specify the location for portage configuration files", "action":"store" }, "--color": { "help":"enable or disable color output", "choices":("y", "n") }, "--complete-graph": { "help" : "completely account for all known dependencies", "choices" : true_y_or_n }, "--complete-graph-if-new-use": { "help" : "trigger --complete-graph behavior if USE or IUSE will change for an installed package", "choices" : y_or_n }, "--complete-graph-if-new-ver": { "help" : "trigger --complete-graph behavior if an installed package version will change (upgrade or downgrade)", "choices" : y_or_n }, "--deep": { "shortopt" : "-D", "help" : "Specifies how deep to recurse into dependencies " + \ "of packages given as arguments. If no argument is given, " + \ "depth is unlimited. Default behavior is to skip " + \ "dependencies of installed packages.", "action" : "store" }, "--depclean-lib-check": { "help" : "check for consumers of libraries before removing them", "choices" : true_y_or_n }, "--deselect": { "help" : "remove atoms/sets from the world file", "choices" : true_y_or_n }, "--dynamic-deps": { "help": "substitute the dependencies of installed packages with the dependencies of unbuilt ebuilds", "choices": y_or_n }, "--exclude": { "help" :"A space separated list of package names or slot atoms. " + \ "Emerge won't install any ebuild or binary package that " + \ "matches any of the given package atoms.", "action" : "append" }, "--fail-clean": { "help" : "clean temp files after build failure", "choices" : true_y_or_n }, "--ignore-built-slot-operator-deps": { "help": "Ignore the slot/sub-slot := operator parts of dependencies that have " "been recorded when packages where built. This option is intended " "only for debugging purposes, and it only affects built packages " "that specify slot/sub-slot := operator dependencies using the " "experimental \"4-slot-abi\" EAPI.", "choices": y_or_n }, "--ignore-soname-deps": { "help": "Ignore the soname dependencies of binary and " "installed packages. This option is enabled by " "default, since soname dependencies are relatively " "new, and the required metadata is not guaranteed to " "exist for binary and installed packages built with " "older versions of portage.", "choices": y_or_n }, "--jobs": { "shortopt" : "-j", "help" : "Specifies the number of packages to build " + \ "simultaneously.", "action" : "store" }, "--keep-going": { "help" : "continue as much as possible after an error", "choices" : true_y_or_n }, "--load-average": { "help" :"Specifies that no new builds should be started " + \ "if there are other builds running and the load average " + \ "is at least LOAD (a floating-point number).", "action" : "store" }, "--misspell-suggestions": { "help" : "enable package name misspell suggestions", "choices" : ("y", "n") }, "--with-bdeps": { "help":"include unnecessary build time dependencies", "choices":("y", "n") }, "--reinstall": { "help":"specify conditions to trigger package reinstallation", "choices":["changed-use"] }, "--reinstall-atoms": { "help" :"A space separated list of package names or slot atoms. " + \ "Emerge will treat matching packages as if they are not " + \ "installed, and reinstall them if necessary. Implies --deep.", "action" : "append", }, "--binpkg-respect-use": { "help" : "discard binary packages if their use flags \ don't match the current configuration" , "choices" : true_y_or_n }, "--getbinpkg": { "shortopt" : "-g", "help" : "fetch binary packages", "choices" : true_y_or_n }, "--getbinpkgonly": { "shortopt" : "-G", "help" : "fetch binary packages only", "choices" : true_y_or_n }, "--usepkg-exclude": { "help" :"A space separated list of package names or slot atoms. " + \ "Emerge will ignore matching binary packages. ", "action" : "append", }, "--rebuild-exclude": { "help" :"A space separated list of package names or slot atoms. " + \ "Emerge will not rebuild these packages due to the " + \ "--rebuild flag. ", "action" : "append", }, "--rebuild-ignore": { "help" :"A space separated list of package names or slot atoms. " + \ "Emerge will not rebuild packages that depend on matching " + \ "packages due to the --rebuild flag. ", "action" : "append", }, "--package-moves": { "help" : "perform package moves when necessary", "choices" : true_y_or_n }, "--prefix": { "help" : "specify the installation prefix", "action" : "store" }, "--pkg-format": { "help" : "format of result binary package", "action" : "store", }, "--quiet": { "shortopt" : "-q", "help" : "reduced or condensed output", "choices" : true_y_or_n }, "--quiet-build": { "help" : "redirect build output to logs", "choices" : true_y_or_n, }, "--quiet-fail": { "help" : "suppresses display of the build log on stdout", "choices" : true_y_or_n, }, "--read-news": { "help" : "offer to read unread news via eselect", "choices" : true_y_or_n }, "--rebuild-if-new-slot": { "help" : ("Automatically rebuild or reinstall packages when slot/sub-slot := " "operator dependencies can be satisfied by a newer slot, so that " "older packages slots will become eligible for removal by the " "--depclean action as soon as possible."), "choices" : true_y_or_n }, "--rebuild-if-new-rev": { "help" : "Rebuild packages when dependencies that are " + \ "used at both build-time and run-time are built, " + \ "if the dependency is not already installed with the " + \ "same version and revision.", "choices" : true_y_or_n }, "--rebuild-if-new-ver": { "help" : "Rebuild packages when dependencies that are " + \ "used at both build-time and run-time are built, " + \ "if the dependency is not already installed with the " + \ "same version. Revision numbers are ignored.", "choices" : true_y_or_n }, "--rebuild-if-unbuilt": { "help" : "Rebuild packages when dependencies that are " + \ "used at both build-time and run-time are built.", "choices" : true_y_or_n }, "--rebuilt-binaries": { "help" : "replace installed packages with binary " + \ "packages that have been rebuilt", "choices" : true_y_or_n }, "--rebuilt-binaries-timestamp": { "help" : "use only binaries that are newer than this " + \ "timestamp for --rebuilt-binaries", "action" : "store" }, "--root": { "help" : "specify the target root filesystem for merging packages", "action" : "store" }, "--root-deps": { "help" : "modify interpretation of depedencies", "choices" :("True", "rdeps") }, "--search-index": { "help": "Enable or disable indexed search (enabled by default)", "choices": y_or_n }, "--select": { "shortopt" : "-w", "help" : "add specified packages to the world set " + \ "(inverse of --oneshot)", "choices" : true_y_or_n }, "--selective": { "help" : "identical to --noreplace", "choices" : true_y_or_n }, "--sync-submodule": { "help" : ("Restrict sync to the specified submodule(s)." " (--sync action only)"), "choices" : tuple(_SUBMODULE_PATH_MAP), "action" : "append", }, "--use-ebuild-visibility": { "help" : "use unbuilt ebuild metadata for visibility checks on built packages", "choices" : true_y_or_n }, "--useoldpkg-atoms": { "help" :"A space separated list of package names or slot atoms. " + \ "Emerge will prefer matching binary packages over newer unbuilt packages. ", "action" : "append", }, "--usepkg": { "shortopt" : "-k", "help" : "use binary packages", "choices" : true_y_or_n }, "--usepkgonly": { "shortopt" : "-K", "help" : "use only binary packages", "choices" : true_y_or_n }, "--verbose": { "shortopt" : "-v", "help" : "verbose output", "choices" : true_y_or_n }, "--verbose-slot-rebuilds": { "help" : "verbose slot rebuild output", "choices" : true_y_or_n }, "--with-test-deps": { "help" : "pull in test deps for packages " + \ "matched by arguments", "choices" : true_y_or_n }, } parser = ArgumentParser(add_help=False) for action_opt in actions: parser.add_argument("--" + action_opt, action="store_true", dest=action_opt.replace("-", "_"), default=False) for myopt in options: parser.add_argument(myopt, action="store_true", dest=myopt.lstrip("--").replace("-", "_"), default=False) for shortopt, longopt in shortmapping.items(): parser.add_argument("-" + shortopt, action="store_true", dest=longopt.lstrip("--").replace("-", "_"), default=False) for myalias, myopt in longopt_aliases.items(): parser.add_argument(myalias, action="store_true", dest=myopt.lstrip("--").replace("-", "_"), default=False) for myopt, kwargs in argument_options.items(): shortopt = kwargs.pop("shortopt", None) args = [myopt] if shortopt is not None: args.append(shortopt) parser.add_argument(dest=myopt.lstrip("--").replace("-", "_"), *args, **kwargs) tmpcmdline = insert_optional_args(tmpcmdline) myoptions, myargs = parser.parse_known_args(args=tmpcmdline) if myoptions.alert in true_y: myoptions.alert = True else: myoptions.alert = None if myoptions.ask in true_y: myoptions.ask = True else: myoptions.ask = None if myoptions.autounmask in true_y: myoptions.autounmask = True if myoptions.autounmask_unrestricted_atoms in true_y: myoptions.autounmask_unrestricted_atoms = True if myoptions.autounmask_keep_masks in true_y: myoptions.autounmask_keep_masks = True if myoptions.autounmask_write in true_y: myoptions.autounmask_write = True if myoptions.binpkg_changed_deps is not None: if myoptions.binpkg_changed_deps in true_y: myoptions.binpkg_changed_deps = 'y' else: myoptions.binpkg_changed_deps = 'n' if myoptions.buildpkg in true_y: myoptions.buildpkg = True if myoptions.buildpkg_exclude: bad_atoms = _find_bad_atoms(myoptions.buildpkg_exclude, less_strict=True) if bad_atoms and not silent: parser.error("Invalid Atom(s) in --buildpkg-exclude parameter: '%s'\n" % \ (",".join(bad_atoms),)) if myoptions.changed_deps is not None: if myoptions.changed_deps in true_y: myoptions.changed_deps = 'y' else: myoptions.changed_deps = 'n' if myoptions.changed_use is not False: myoptions.reinstall = "changed-use" myoptions.changed_use = False if myoptions.deselect in true_y: myoptions.deselect = True if myoptions.binpkg_respect_use is not None: if myoptions.binpkg_respect_use in true_y: myoptions.binpkg_respect_use = 'y' else: myoptions.binpkg_respect_use = 'n' if myoptions.complete_graph in true_y: myoptions.complete_graph = True else: myoptions.complete_graph = None if myoptions.depclean_lib_check in true_y: myoptions.depclean_lib_check = True if myoptions.exclude: bad_atoms = _find_bad_atoms(myoptions.exclude) if bad_atoms and not silent: parser.error("Invalid Atom(s) in --exclude parameter: '%s' (only package names and slot atoms (with wildcards) allowed)\n" % \ (",".join(bad_atoms),)) if myoptions.reinstall_atoms: bad_atoms = _find_bad_atoms(myoptions.reinstall_atoms) if bad_atoms and not silent: parser.error("Invalid Atom(s) in --reinstall-atoms parameter: '%s' (only package names and slot atoms (with wildcards) allowed)\n" % \ (",".join(bad_atoms),)) if myoptions.rebuild_exclude: bad_atoms = _find_bad_atoms(myoptions.rebuild_exclude) if bad_atoms and not silent: parser.error("Invalid Atom(s) in --rebuild-exclude parameter: '%s' (only package names and slot atoms (with wildcards) allowed)\n" % \ (",".join(bad_atoms),)) if myoptions.rebuild_ignore: bad_atoms = _find_bad_atoms(myoptions.rebuild_ignore) if bad_atoms and not silent: parser.error("Invalid Atom(s) in --rebuild-ignore parameter: '%s' (only package names and slot atoms (with wildcards) allowed)\n" % \ (",".join(bad_atoms),)) if myoptions.usepkg_exclude: bad_atoms = _find_bad_atoms(myoptions.usepkg_exclude) if bad_atoms and not silent: parser.error("Invalid Atom(s) in --usepkg-exclude parameter: '%s' (only package names and slot atoms (with wildcards) allowed)\n" % \ (",".join(bad_atoms),)) if myoptions.useoldpkg_atoms: bad_atoms = _find_bad_atoms(myoptions.useoldpkg_atoms) if bad_atoms and not silent: parser.error("Invalid Atom(s) in --useoldpkg-atoms parameter: '%s' (only package names and slot atoms (with wildcards) allowed)\n" % \ (",".join(bad_atoms),)) if myoptions.fail_clean in true_y: myoptions.fail_clean = True if myoptions.getbinpkg in true_y: myoptions.getbinpkg = True else: myoptions.getbinpkg = None if myoptions.getbinpkgonly in true_y: myoptions.getbinpkgonly = True else: myoptions.getbinpkgonly = None if myoptions.keep_going in true_y: myoptions.keep_going = True else: myoptions.keep_going = None if myoptions.package_moves in true_y: myoptions.package_moves = True if myoptions.quiet in true_y: myoptions.quiet = True else: myoptions.quiet = None if myoptions.quiet_build in true_y: myoptions.quiet_build = 'y' if myoptions.quiet_fail in true_y: myoptions.quiet_fail = 'y' if myoptions.read_news in true_y: myoptions.read_news = True else: myoptions.read_news = None if myoptions.rebuild_if_new_slot in true_y: myoptions.rebuild_if_new_slot = 'y' if myoptions.rebuild_if_new_ver in true_y: myoptions.rebuild_if_new_ver = True else: myoptions.rebuild_if_new_ver = None if myoptions.rebuild_if_new_rev in true_y: myoptions.rebuild_if_new_rev = True myoptions.rebuild_if_new_ver = None else: myoptions.rebuild_if_new_rev = None if myoptions.rebuild_if_unbuilt in true_y: myoptions.rebuild_if_unbuilt = True myoptions.rebuild_if_new_rev = None myoptions.rebuild_if_new_ver = None else: myoptions.rebuild_if_unbuilt = None if myoptions.rebuilt_binaries in true_y: myoptions.rebuilt_binaries = True if myoptions.root_deps in true_y: myoptions.root_deps = True if myoptions.select in true_y: myoptions.select = True myoptions.oneshot = False elif myoptions.select == "n": myoptions.oneshot = True if myoptions.selective in true_y: myoptions.selective = True if myoptions.backtrack is not None: try: backtrack = int(myoptions.backtrack) except (OverflowError, ValueError): backtrack = -1 if backtrack < 0: backtrack = None if not silent: parser.error("Invalid --backtrack parameter: '%s'\n" % \ (myoptions.backtrack,)) myoptions.backtrack = backtrack if myoptions.deep is not None: deep = None if myoptions.deep == "True": deep = True else: try: deep = int(myoptions.deep) except (OverflowError, ValueError): deep = -1 if deep is not True and deep < 0: deep = None if not silent: parser.error("Invalid --deep parameter: '%s'\n" % \ (myoptions.deep,)) myoptions.deep = deep if myoptions.jobs: jobs = None if myoptions.jobs == "True": jobs = True else: try: jobs = int(myoptions.jobs) except ValueError: jobs = -1 if jobs is not True and \ jobs < 1: jobs = None if not silent: parser.error("Invalid --jobs parameter: '%s'\n" % \ (myoptions.jobs,)) myoptions.jobs = jobs if myoptions.load_average == "True": myoptions.load_average = None if myoptions.load_average: try: load_average = float(myoptions.load_average) except ValueError: load_average = 0.0 if load_average <= 0.0: load_average = None if not silent: parser.error("Invalid --load-average parameter: '%s'\n" % \ (myoptions.load_average,)) myoptions.load_average = load_average if myoptions.rebuilt_binaries_timestamp: try: rebuilt_binaries_timestamp = int( myoptions.rebuilt_binaries_timestamp) except ValueError: rebuilt_binaries_timestamp = -1 if rebuilt_binaries_timestamp < 0: rebuilt_binaries_timestamp = 0 if not silent: parser.error("Invalid --rebuilt-binaries-timestamp parameter: '%s'\n" % \ (myoptions.rebuilt_binaries_timestamp,)) myoptions.rebuilt_binaries_timestamp = rebuilt_binaries_timestamp if myoptions.use_ebuild_visibility in true_y: myoptions.use_ebuild_visibility = True else: # None or "n" pass if myoptions.usepkg in true_y: myoptions.usepkg = True else: myoptions.usepkg = None if myoptions.usepkgonly in true_y: myoptions.usepkgonly = True else: myoptions.usepkgonly = None if myoptions.verbose in true_y: myoptions.verbose = True else: myoptions.verbose = None if myoptions.with_test_deps in true_y: myoptions.with_test_deps = True else: myoptions.with_test_deps = None for myopt in options: v = getattr(myoptions, myopt.lstrip("--").replace("-", "_")) if v: myopts[myopt] = True for myopt in argument_options: v = getattr(myoptions, myopt.lstrip("--").replace("-", "_"), None) if v is not None: myopts[myopt] = v if myoptions.searchdesc: myoptions.search = True for action_opt in actions: v = getattr(myoptions, action_opt.replace("-", "_")) if v: if myaction: multiple_actions(myaction, action_opt) sys.exit(1) myaction = action_opt if myaction is None and myoptions.deselect is True: myaction = 'deselect' myfiles += myargs return myaction, myopts, myfiles
def parse_args(argv, qahelp, repoman_default_opts): """Use a customized optionParser to parse command line arguments for repoman Args: argv - a sequence of command line arguments qahelp - a dict of qa warning to help message Returns: (opts, args), just like a call to parser.parse_args() """ argv = portage._decode_argv(argv) modes = { 'commit': 'Run a scan then commit changes', 'ci': 'Run a scan then commit changes', 'fix': 'Fix simple QA issues (stray digests, missing digests)', 'full': 'Scan directory tree and print all issues (not a summary)', 'help': 'Show this screen', 'manifest': 'Generate a Manifest (fetches files if necessary)', 'manifest-check': 'Check Manifests for missing or incorrect digests', 'scan': 'Scan directory tree for QA issues' } output_choices = { 'default': 'The normal output format', 'column': 'Columnar output suitable for use with grep' } mode_keys = list(modes) mode_keys.sort() output_keys = sorted(output_choices) parser = ArgumentParser( usage="repoman [options] [mode]", description="Modes: %s" % " | ".join(mode_keys), epilog="For more help consult the man page.") parser.add_argument( '-a', '--ask', dest='ask', action='store_true', default=False, help='Request a confirmation before commiting') parser.add_argument( '-m', '--commitmsg', dest='commitmsg', help='specify a commit message on the command line') parser.add_argument( '-M', '--commitmsgfile', dest='commitmsgfile', help='specify a path to a file that contains a commit message') parser.add_argument( '--digest', choices=('y', 'n'), metavar='<y|n>', help='Automatically update Manifest digests for modified files') parser.add_argument( '-p', '--pretend', dest='pretend', default=False, action='store_true', help='don\'t commit or fix anything; just show what would be done') parser.add_argument( '-q', '--quiet', dest="quiet", action="count", default=0, help='do not print unnecessary messages') parser.add_argument( '--echangelog', choices=('y', 'n', 'force'), metavar="<y|n|force>", help=( 'for commit mode, call echangelog if ChangeLog is unmodified (or ' 'regardless of modification if \'force\' is specified)')) parser.add_argument( '--experimental-inherit', choices=('y', 'n'), metavar="<y|n>", default='n', help=( 'Enable experimental inherit.missing checks which may misbehave' ' when the internal eclass database becomes outdated')) parser.add_argument( '-f', '--force', dest='force', action='store_true', default=False, help='Commit with QA violations') parser.add_argument( '--vcs', dest='vcs', help='Force using specific VCS instead of autodetection') parser.add_argument( '-v', '--verbose', dest="verbosity", action='count', help='be very verbose in output', default=0) parser.add_argument( '-V', '--version', dest='version', action='store_true', help='show version info') parser.add_argument( '-x', '--xmlparse', dest='xml_parse', action='store_true', default=False, help='forces the metadata.xml parse check to be carried out') parser.add_argument( '--if-modified', choices=('y', 'n'), default='n', metavar="<y|n>", help='only check packages that have uncommitted modifications') parser.add_argument( '-i', '--ignore-arches', dest='ignore_arches', action='store_true', default=False, help='ignore arch-specific failures (where arch != host)') parser.add_argument( "--ignore-default-opts", action="store_true", help="do not use the REPOMAN_DEFAULT_OPTS environment variable") parser.add_argument( '-I', '--ignore-masked', dest='ignore_masked', action='store_true', default=False, help='ignore masked packages (not allowed with commit mode)') parser.add_argument( '--include-arches', dest='include_arches', metavar='ARCHES', action='append', help=( 'A space separated list of arches used to ' 'filter the selection of profiles for dependency checks')) parser.add_argument( '-d', '--include-dev', dest='include_dev', action='store_true', default=False, help='include dev profiles in dependency checks') parser.add_argument( '-e', '--include-exp-profiles', choices=('y', 'n'), metavar='<y|n>', default=False, help='include exp profiles in dependency checks') parser.add_argument( '--unmatched-removal', dest='unmatched_removal', action='store_true', default=False, help=( 'enable strict checking of package.mask and package.unmask files' ' for unmatched removal atoms')) parser.add_argument( '--without-mask', dest='without_mask', action='store_true', default=False, help=( 'behave as if no package.mask entries exist' ' (not allowed with commit mode)')) parser.add_argument( '--output-style', dest='output_style', choices=output_keys, help='select output type', default='default') parser.add_argument( '--mode', dest='mode', choices=mode_keys, help='specify which mode repoman will run in (default=full)') opts, args = parser.parse_known_args(argv[1:]) if not opts.ignore_default_opts: default_opts = util.shlex_split(repoman_default_opts) if default_opts: opts, args = parser.parse_known_args(default_opts + sys.argv[1:]) if opts.mode == 'help': parser.print_help(short=False) for arg in args: if arg in modes: if not opts.mode: opts.mode = arg break else: parser.error("invalid mode: %s" % arg) if not opts.mode: opts.mode = 'full' if opts.mode == 'ci': opts.mode = 'commit' # backwards compat shortcut # Use verbosity and quiet options to appropriately fiddle with the loglevel for val in range(opts.verbosity): logger = logging.getLogger() logger.setLevel(logger.getEffectiveLevel() - 10) for val in range(opts.quiet): logger = logging.getLogger() logger.setLevel(logger.getEffectiveLevel() + 10) if opts.mode == 'commit' and not (opts.force or opts.pretend): if opts.ignore_masked: opts.ignore_masked = False logging.warn('Commit mode automatically disables --ignore-masked') if opts.without_mask: opts.without_mask = False logging.warn('Commit mode automatically disables --without-mask') return (opts, args)
def emaint_main(myargv): # Similar to emerge, emaint needs a default umask so that created # files (such as the world file) have sane permissions. os.umask(0o22) module_path = os.path.join((os.path.dirname(os.path.realpath(__file__))), "modules") module_controller = Modules(path=module_path, namepath="portage.emaint.modules") module_names = module_controller.module_names[:] module_names.insert(0, "all") parser = ArgumentParser(usage=usage(module_controller)) # add default options parser_options = [] for opt in DEFAULT_OPTIONS: parser_options.append(OptionItem(DEFAULT_OPTIONS[opt])) for mod in module_names[1:]: desc = module_controller.get_func_descriptions(mod) if desc: for opt in desc: parser_options.append(OptionItem(desc[opt])) desc = module_controller.get_opt_descriptions(mod) if desc: for opt in desc: parser_options.append(OptionItem(desc[opt])) for opt in parser_options: parser.add_argument(*opt.pargs, **opt.kwargs) options, args = parser.parse_known_args(args=myargv) if options.version: print(portage.VERSION) return os.EX_OK if len(args) != 1: parser.error("Incorrect number of arguments") if args[0] not in module_names: parser.error("%s target is not a known target" % args[0]) check_opt = None func = status = long_action = None for opt in parser_options: if opt.long == '--check': # Default action check_opt = opt if opt.status and getattr(options, opt.target, False): if long_action is not None: parser.error("--%s and %s are exclusive options" % (long_action, opt.long)) status = opt.status func = opt.func long_action = opt.long.lstrip('-') if long_action is None: #print("DEBUG: long_action is None: setting to 'check'") long_action = 'check' func = check_opt.func status = check_opt.status if args[0] == "all": tasks = [] for m in module_names[1:]: #print("DEBUG: module: %s, functions: " % (m, str(module_controller.get_functions(m)))) if long_action in module_controller.get_functions(m): tasks.append(module_controller.get_class(m)) elif long_action in module_controller.get_functions(args[0]): tasks = [module_controller.get_class(args[0])] else: portage.util.writemsg( "\nERROR: module '%s' does not have option '--%s'\n\n" % (args[0], long_action), noiselevel=-1) portage.util.writemsg(module_opts(module_controller, args[0]), noiselevel=-1) sys.exit(1) # need to pass the parser options dict to the modules # so they are available if needed. task_opts = options.__dict__ task_opts['return-messages'] = True taskmaster = TaskHandler(callback=print_results, module_output=sys.stdout) taskmaster.run_tasks(tasks, func, status, options=task_opts)
def parse_args(argv, qahelp, repoman_default_opts): """Use a customized optionParser to parse command line arguments for repoman Args: argv - a sequence of command line arguments qahelp - a dict of qa warning to help message Returns: (opts, args), just like a call to parser.parse_args() """ argv = portage._decode_argv(argv) modes = { "commit": "Run a scan then commit changes", "ci": "Run a scan then commit changes", "fix": "Fix simple QA issues (stray digests, missing digests)", "full": "Scan directory tree and print all issues (not a summary)", "help": "Show this screen", "manifest": "Generate a Manifest (fetches files if necessary)", "manifest-check": "Check Manifests for missing or incorrect digests", "scan": "Scan directory tree for QA issues", } output_choices = {"default": "The normal output format", "column": "Columnar output suitable for use with grep"} mode_keys = list(modes) mode_keys.sort() output_keys = sorted(output_choices) parser = ArgumentParser( usage="repoman [options] [mode]", description="Modes: %s" % " | ".join(mode_keys), epilog="For more help consult the man page.", ) parser.add_argument( "-a", "--ask", dest="ask", action="store_true", default=False, help="Request a confirmation before commiting" ) parser.add_argument("-m", "--commitmsg", dest="commitmsg", help="specify a commit message on the command line") parser.add_argument( "-M", "--commitmsgfile", dest="commitmsgfile", help="specify a path to a file that contains a commit message" ) parser.add_argument( "--digest", choices=("y", "n"), metavar="<y|n>", help="Automatically update Manifest digests for modified files" ) parser.add_argument( "-p", "--pretend", dest="pretend", default=False, action="store_true", help="don't commit or fix anything; just show what would be done", ) parser.add_argument( "-q", "--quiet", dest="quiet", action="count", default=0, help="do not print unnecessary messages" ) parser.add_argument( "--echangelog", choices=("y", "n", "force"), metavar="<y|n|force>", help=( "for commit mode, call echangelog if ChangeLog is unmodified (or " "regardless of modification if 'force' is specified)" ), ) parser.add_argument( "--experimental-inherit", choices=("y", "n"), metavar="<y|n>", default="n", help=( "Enable experimental inherit.missing checks which may misbehave" " when the internal eclass database becomes outdated" ), ) parser.add_argument( "-f", "--force", dest="force", action="store_true", default=False, help="Commit with QA violations" ) parser.add_argument( "-S", "--straight-to-stable", dest="straight_to_stable", default=False, action="store_true", help="Allow committing straight to stable", ) parser.add_argument("--vcs", dest="vcs", help="Force using specific VCS instead of autodetection") parser.add_argument( "-v", "--verbose", dest="verbosity", action="count", help="be very verbose in output", default=0 ) parser.add_argument("-V", "--version", dest="version", action="store_true", help="show version info") parser.add_argument( "-x", "--xmlparse", dest="xml_parse", action="store_true", default=False, help="forces the metadata.xml parse check to be carried out", ) parser.add_argument( "--if-modified", choices=("y", "n"), default="n", metavar="<y|n>", help="only check packages that have uncommitted modifications", ) parser.add_argument( "-i", "--ignore-arches", dest="ignore_arches", action="store_true", default=False, help="ignore arch-specific failures (where arch != host)", ) parser.add_argument( "--ignore-default-opts", action="store_true", help="do not use the REPOMAN_DEFAULT_OPTS environment variable" ) parser.add_argument( "-I", "--ignore-masked", dest="ignore_masked", action="store_true", default=False, help="ignore masked packages (not allowed with commit mode)", ) parser.add_argument( "--include-arches", dest="include_arches", metavar="ARCHES", action="append", help=("A space separated list of arches used to " "filter the selection of profiles for dependency checks"), ) parser.add_argument( "-d", "--include-dev", dest="include_dev", action="store_true", default=False, help="include dev profiles in dependency checks", ) parser.add_argument( "-e", "--include-exp-profiles", choices=("y", "n"), metavar="<y|n>", default=False, help="include exp profiles in dependency checks", ) parser.add_argument( "--unmatched-removal", dest="unmatched_removal", action="store_true", default=False, help=("enable strict checking of package.mask and package.unmask files" " for unmatched removal atoms"), ) parser.add_argument( "--without-mask", dest="without_mask", action="store_true", default=False, help=("behave as if no package.mask entries exist" " (not allowed with commit mode)"), ) parser.add_argument( "--output-style", dest="output_style", choices=output_keys, help="select output type", default="default" ) parser.add_argument( "--mode", dest="mode", choices=mode_keys, help="specify which mode repoman will run in (default=full)" ) opts, args = parser.parse_known_args(argv[1:]) if not opts.ignore_default_opts: default_opts = util.shlex_split(repoman_default_opts) if default_opts: opts, args = parser.parse_known_args(default_opts + sys.argv[1:]) if opts.mode == "help": parser.print_help(short=False) for arg in args: if arg in modes: if not opts.mode: opts.mode = arg break else: parser.error("invalid mode: %s" % arg) if not opts.mode: opts.mode = "full" if opts.mode == "ci": opts.mode = "commit" # backwards compat shortcut # Use verbosity and quiet options to appropriately fiddle with the loglevel for val in range(opts.verbosity): logger = logging.getLogger() logger.setLevel(logger.getEffectiveLevel() - 10) for val in range(opts.quiet): logger = logging.getLogger() logger.setLevel(logger.getEffectiveLevel() + 10) if opts.mode == "commit" and opts.commitmsg: opts.commitmsg = _unicode_decode(opts.commitmsg) if opts.mode == "commit" and not (opts.force or opts.pretend): if opts.ignore_masked: opts.ignore_masked = False logging.warn("Commit mode automatically disables --ignore-masked") if opts.without_mask: opts.without_mask = False logging.warn("Commit mode automatically disables --without-mask") return (opts, args)
def parse_args(args): """ Parse the command line arguments using optparse for python 2.6 compatibility Args: args: a list of the white space delimited command line Returns: tuple of the Namespace of parsed options, and a list of order parameters """ parser = ArgumentParser(add_help=False) parser.add_argument("-b", action="store_true", dest="shortopt_b") parser.add_argument("--backup", action="store", dest="backup") parser.add_argument("-c", action="store_true", dest="shortopt_c") parser.add_argument("--compare", "-C", action="store_true", dest="compare") parser.add_argument("--directory", "-d", action="store_true", dest="directory") parser.add_argument("-D", action="store_true", dest="shortopt_D") parser.add_argument("--owner", "-o", action="store", dest="owner") parser.add_argument("--group", "-g", action="store", dest="group") parser.add_argument("--mode", "-m", action="store", dest="mode") parser.add_argument("--preserve-timestamps", "-p", action="store_true", dest="preserve_timestamps") parser.add_argument("--strip", "-s", action="store_true", dest="strip") parser.add_argument("--strip-program", action="store", dest="strip_program") parser.add_argument("--suffix", "-S", action="store", dest="suffix") parser.add_argument("--target-directory", "-t", action="store", dest="target_directory") parser.add_argument("--no-target-directory", "-T", action="store_true", dest="no_target_directory") parser.add_argument("--context", "-Z", action="store", dest="context") parser.add_argument("--verbose", "-v", action="store_true", dest="verbose") parser.add_argument("--help", action="store_true", dest="help") parser.add_argument("--version", action="store_true", dest="version") # Use parse_known_args for maximum compatibility with # getopt handling of non-option file arguments. Note # that parser.add_argument("files", nargs='+') would # be subtly incompatible because it requires that all # of the file arguments be grouped sequentially. Also # note that we have to explicitly call add_argument # for known options in order for argparse to correctly # separate option arguments from file arguments in all # cases (it also allows for optparse compatibility). parsed_args = parser.parse_known_args() opts = parsed_args[0] files = parsed_args[1] files = [f for f in files if f != "--"] # filter out "--" return (opts, files)