def test_extend_comma_toggle_action(self): parser = argparse_helpers.mangle_parser(arghparse.ArgumentParser()) parser.add_argument('--testing', action='extend_comma_toggle') parser.add_argument('--testing-nargs', nargs='+', action='extend_comma_toggle') test_values = ( ('', ([], [])), (',', ([], [])), (',,', ([], [])), ('a', ([], ['a'])), ('a,-b,-c,d', (['b', 'c'], ['a', 'd'])), ) for raw_val, expected in test_values: namespace = parser.parse_args([ '--testing=' + raw_val, '--testing-nargs', raw_val, raw_val, ]) self.assertEqual(namespace.testing, expected) self.assertEqual(namespace.testing_nargs, (expected[0] * 2, expected[1] * 2)) # start with negated arg namespace = parser.parse_args(['--testing=-a']) self.assertEqual(namespace.testing, (['a'], []))
def test_debug(self): # debug passed parser = argparse_helpers.mangle_parser(arghparse.ArgumentParser(debug=True)) namespace = parser.parse_args(["--debug"]) assert parser.debug is False assert namespace.debug is True # debug not passed namespace = parser.parse_args([]) assert parser.debug is False assert namespace.debug is False # debug passed in sys.argv -- early debug attr on the parser instance is set with mock.patch('sys.argv', ['script', '--debug']): parser = argparse_helpers.mangle_parser(arghparse.ArgumentParser(debug=True)) assert parser.debug is True
def test_bool_type(self): parser = argparse_helpers.mangle_parser(arghparse.ArgumentParser()) parser.add_argument("--testing", action=arghparse.StoreBool, default=None) for raw_val in ("n", "no", "false"): for allowed in (raw_val.upper(), raw_val.lower()): namespace = parser.parse_args(['--testing=' + allowed]) self.assertEqual( namespace.testing, False, msg="for --testing=%s, got %r, expected False" % (allowed, namespace.testing)) for raw_val in ("y", "yes", "true"): for allowed in (raw_val.upper(), raw_val.lower()): namespace = parser.parse_args(['--testing=' + allowed]) self.assertEqual( namespace.testing, True, msg="for --testing=%s, got %r, expected False" % (allowed, namespace.testing)) try: parser.parse_args(["--testing=invalid"]) except argparse_helpers.Error: pass else: self.fail("no error message thrown for --testing=invalid")
def test_debug_disabled(self): parser = argparse_helpers.mangle_parser(arghparse.ArgumentParser(debug=False)) # ensure the option isn't there if disabled with pytest.raises(argparse_helpers.Error): namespace = parser.parse_args(["--debug"]) namespace = parser.parse_args([]) # parser attribute still exists assert parser.debug is False # but namespace attribute doesn't assert not hasattr(namespace, 'debug')
def test_verbosity_disabled(self): parser = argparse_helpers.mangle_parser( arghparse.ArgumentParser(quiet=False, verbose=False)) # ensure the options aren't there if disabled for args in ('-q', '--quiet', '-v', '--verbose'): with pytest.raises(argparse_helpers.Error): namespace = parser.parse_args([args]) namespace = parser.parse_args([]) # parser attribute still exists assert parser.verbosity == 0 # but namespace attribute doesn't assert not hasattr(namespace, 'verbosity')
def test_help(self, capsys): parser = argparse_helpers.mangle_parser(arghparse.ArgumentParser()) with mock.patch('subprocess.Popen') as popen: # --help long option tries man page first before falling back to help output with pytest.raises(argparse_helpers.Exit): namespace = parser.parse_args(['--help']) popen.assert_called_once() assert popen.call_args[0][0][0] == 'man' captured = capsys.readouterr() assert captured.out.strip().startswith('usage: ') popen.reset_mock() # -h short option just displays the regular help output with pytest.raises(argparse_helpers.Exit): namespace = parser.parse_args(['-h']) popen.assert_not_called() captured = capsys.readouterr() assert captured.out.strip().startswith('usage: ') popen.reset_mock()
def test_verbosity(self): values = ( ([], 0), (['-q'], -1), (['--quiet'], -1), (['-v'], 1), (['--verbose'], 1), (['-q', '-v'], 0), (['--quiet', '--verbose'], 0), (['-q', '-q'], -2), (['-v', '-v'], 2), ) for args, val in values: with mock.patch('sys.argv', ['script'] + args): parser = argparse_helpers.mangle_parser( arghparse.ArgumentParser(quiet=True, verbose=True)) namespace = parser.parse_args(args) assert parser.verbosity == val, '{} failed'.format(args) assert namespace.verbosity == val, '{} failed'.format(args)
def test_extend_comma_action(self): parser = argparse_helpers.mangle_parser(arghparse.ArgumentParser()) parser.add_argument('--testing', action='extend_comma') parser.add_argument('--testing-nargs', nargs='+', action='extend_comma') test_values = ( ('', []), (',', []), (',,', []), ('a', ['a']), ('a,b,-c', ['a', 'b', '-c']), ) for raw_val, expected in test_values: namespace = parser.parse_args([ '--testing=' + raw_val, '--testing-nargs', raw_val, raw_val, ]) self.assertEqual(namespace.testing, expected) self.assertEqual(namespace.testing_nargs, expected * 2)
version=False, domain=False, add_help=False), ) shared_options_domain = (commandline.ArgumentParser(config=False, color=False, debug=False, quiet=False, verbose=False, version=False, domain=True, add_help=False), ) pkgcore_opts = commandline.ArgumentParser(domain=False, script=(__file__, __name__)) argparser = arghparse.ArgumentParser(suppress=True, description=__doc__, parents=(pkgcore_opts, )) subparsers = argparser.add_subparsers( description="configuration related subcommands") classes = subparsers.add_parser( "classes", parents=shared_options, description="list all classes referenced by the config") @classes.bind_main_func def classes_main(options, out, err): """List all classes referenced by the config.""" configmanager = options.config sections = [] for name in configmanager.sections():
import os from pkgcore.operations import observer as observer_mod from pkgcore.restrictions import packages from pkgcore.util.parserestrict import parse_match from snakeoil.cli import arghparse from .argparsers import cwd_repo_argparser manifest = arghparse.ArgumentParser(prog='pkgdev manifest', description='update package manifests', parents=(cwd_repo_argparser, )) manifest.add_argument('target', nargs='*', help='packages to target', docs=""" Packages matching any of these restrictions will have their manifest entries updated. If no target is specified a path restriction is created based on the current working directory. In other words, if ``pkgdev manifest`` is run within an ebuild's directory, all the ebuilds within that directory will be manifested. """) manifest_opts = manifest.add_argument_group('manifest options') manifest_opts.add_argument('-d', '--distdir', type=arghparse.create_dir, help='target download directory', docs=""" Use a specified target directory for downloads instead of the configured DISTDIR. """)
def setup_method(self, method): self.parser = argparse_helpers.mangle_parser( arghparse.ArgumentParser())
"""Argparse argument type for bind mount variants.""" opts = {'recursive': recursive, 'readonly': readonly} return {s: opts} class mountpoints(argparse.Action): """Argparse action that adds specified mountpoint to be mounted.""" def __call__(self, parser, namespace, values, option_string=None): if not getattr(namespace, 'mountpoints', False): namespace.mountpoints = {} namespace.mountpoints.update(values) argparser = arghparse.ArgumentParser(color=False, debug=False, quiet=False, verbose=False, description=__doc__, script=(__file__, __name__)) argparser.add_argument('path', help='path to newroot') argparser.add_argument('command', nargs=argparse.REMAINDER, help='optional command to run', docs=""" Optional command to run. Similar to chroot(1), if unspecified this defaults to $SHELL from the host environment and if that's unset it executes /bin/sh. """) chroot_options = argparser.add_argument_group('chroot options') chroot_options.add_argument('--no-mounts',
'snakeoil:compatibility', 'snakeoil.fileutils:AtomicWriteFile', 'snakeoil.osutils:pjoin,listdir_dirs', 'snakeoil.sequences:iter_stable_unique', 'pkgcore.ebuild:processor,triggers', 'pkgcore.fs:contents,livefs', 'pkgcore.merge:triggers@merge_triggers', 'pkgcore.operations:observer', 'pkgcore.package:mutated', 'pkgcore.repository:multiplex', 'pkgcore.restrictions:packages', 'pkgcore.util.parserestrict:parse_match', ) argparser = arghparse.ArgumentParser( suppress=True, description=__doc__, parents=(commandline.ArgumentParser(domain=False), )) subparsers = argparser.add_subparsers(description="general system maintenance") shared_options = (commandline.ArgumentParser(config=False, color=False, debug=False, quiet=False, verbose=False, version=False, domain=False, add_help=False), ) shared_options_domain = (commandline.ArgumentParser(config=False, color=False, debug=False, quiet=False,
from itertools import groupby from operator import itemgetter from typing import List from pkgcore.ebuild.atom import MalformedAtom from pkgcore.ebuild.atom import atom as atom_cls from pkgcore.ebuild.profiles import ProfileNode from snakeoil.bash import iter_read_bash from snakeoil.cli import arghparse from snakeoil.osutils import pjoin from .. import git from .argparsers import cwd_repo_argparser, git_repo_argparser mask = arghparse.ArgumentParser(prog='pkgdev mask', description='mask packages', parents=(cwd_repo_argparser, git_repo_argparser)) mask.add_argument('targets', metavar='TARGET', nargs='*', help='package to mask', docs=""" Packages matching any of these restrictions will have a mask entry in profiles/package.mask added for them. If no target is specified a path restriction is created based on the current working directory. In other words, if ``pkgdev mask`` is run within an ebuild's directory, all the ebuilds within that directory will be masked. """) mask_opts = mask.add_argument_group('mask options') mask_opts.add_argument('-r', '--rites',
def bindmount(s, recursive=False, readonly=False): opts = {'recursive': recursive, 'readonly': readonly} return {s: opts} class mountpoints(argparse.Action): def __call__(self, parser, namespace, values, option_string=None): if not getattr(namespace, 'mountpoints', False): namespace.mountpoints = {} namespace.mountpoints.update(values) argparser = arghparse.ArgumentParser(color=False, debug=False, quiet=False, verbose=False, description=__doc__) argparser.add_argument('path', help='path to newroot') argparser.add_argument('command', nargs=argparse.REMAINDER, help='optional command to run', docs=""" Optional command to run. Similar to chroot(1), if unspecified this defaults to $SHELL from the host environment and if that's unset it executes /bin/sh. """) argparser.add_argument('--no-mounts', action='store_true', help='disable the default bind mounts',
"""display package keywords""" import os from functools import partial from pkgcore.ebuild import restricts from pkgcore.util import commandline from pkgcore.util import packages as pkgutils from snakeoil.cli import arghparse from snakeoil.strings import pluralism from .._vendor.tabulate import tabulate, tabulate_formats showkw = arghparse.ArgumentParser( prog='pkgdev showkw', description='show package keywords') showkw.add_argument( 'targets', metavar='target', nargs='*', action=commandline.StoreTarget, help='extended atom matching of packages') output_opts = showkw.add_argument_group('output options') output_opts.add_argument( '-f', '--format', default='showkw', metavar='FORMAT', choices=tabulate_formats, help='keywords table format', docs=f""" Output table using specified tabular format (defaults to compressed, custom format). Available formats: {', '.join(tabulate_formats)}
def test_debug_disabled(self): # ensure the option isn't there if disabled. parser = argparse_helpers.mangle_parser( arghparse.ArgumentParser(debug=False)) namespace = parser.parse_args([]) assert not hasattr(namespace, 'debug')
# Copyright: 2011 Brian Harring <*****@*****.**> # Copyright: 2006 Marien Zwart <*****@*****.**> # License: BSD/GPL2 """filter a bash environment dump""" import argparse import sys from pkgcore.ebuild import filter_env from pkgcore.log import logger from snakeoil.cli import arghparse argparser = arghparse.ArgumentParser(verbose=False, color=False, description=__doc__) def stdin_default(namespace, attr): if sys.stdin.isatty(): raise ValueError("Refusing to read from stdin since it's a TTY") setattr(namespace, attr, sys.stdin) argparser.add_argument( '-i', '--input', action='store', type=argparse.FileType(), default=arghparse.DelayedValue(stdin_default, 0), help='Filename to read the env from (uses stdin if omitted).')
def _parser(self, **kwargs): return arghparse.ArgumentParser(**kwargs)