Exemplo n.º 1
0
    def make_BareConfig(self):
        a = BareConfig()

        # Test components of the BareConfig class:
        self.test_url = 'https://api.gentoo.org/overlays/repositories.xml'
        assertEqual(a['overlay'], self.test_url)
        self.test_keys =  ['bzr_addopts', 'bzr_command', 'bzr_postsync',
                      'bzr_syncopts', 'cache', 'config', 'configdir',
                      'custom_news_func', 'custom_news_pkg', 'cvs_addopts',
                      'cvs_command', 'cvs_postsync', 'cvs_syncopts',
                      'darcs_addopts', 'darcs_command', 'darcs_postsync',
                      'darcs_syncopts', 'g-common_command',
                      'g-common_generateopts', 'g-common_postsync',
                      'g-common_syncopts', 'git_addopts', 'git_command',
                      'git_email', 'git_postsync', 'git_syncopts', 'git_user',
                      'installed', 'local_list', 'make_conf',
                      'mercurial_addopts', 'mercurial_command',
                      'mercurial_postsync', 'mercurial_syncopts',
                      'news_reporter', 'nocheck', 'nocolor', 'output',
                      'overlay_defs', 'overlays', 'proxy', 'quiet',
                      'quietness', 'rsync_command', 'rsync_postsync',
                      'rsync_syncopts', 'stderr', 'stdin', 'stdout', 'storage',
                      'svn_addopts', 'svn_command', 'svn_postsync',
                      'svn_syncopts', 't/f_options', 'tar_command',
                      'tar_postsync', 'umask', 'verbose', 'width']
        assertEqual(sorted(a), self.test_keys)
        assertEqual(a.get_option('nocheck'), True)
Exemplo n.º 2
0
    def make_BareConfig(self):
        a = BareConfig()

        # Test components of the BareConfig class:
        self.test_url = 'https://api.gentoo.org/overlays/repositories.xml'
        assertEqual(a['overlay'], self.test_url)
        self.test_keys = [
            'bzr_addopts', 'bzr_command', 'bzr_postsync', 'bzr_syncopts',
            'cache', 'config', 'configdir', 'custom_news_func',
            'custom_news_pkg', 'cvs_addopts', 'cvs_command', 'cvs_postsync',
            'cvs_syncopts', 'darcs_addopts', 'darcs_command', 'darcs_postsync',
            'darcs_syncopts', 'g-common_command', 'g-common_generateopts',
            'g-common_postsync', 'g-common_syncopts', 'git_addopts',
            'git_command', 'git_email', 'git_postsync', 'git_syncopts',
            'git_user', 'installed', 'local_list', 'make_conf',
            'mercurial_addopts', 'mercurial_command', 'mercurial_postsync',
            'mercurial_syncopts', 'news_reporter', 'nocheck', 'nocolor',
            'output', 'overlay_defs', 'overlays', 'proxy', 'quiet',
            'quietness', 'rsync_command', 'rsync_postsync', 'rsync_syncopts',
            'stderr', 'stdin', 'stdout', 'storage', 'svn_addopts',
            'svn_command', 'svn_postsync', 'svn_syncopts', 't/f_options',
            'tar_command', 'tar_postsync', 'umask', 'verbose', 'width'
        ]
        assertEqual(sorted(a), self.test_keys)
        assertEqual(a.get_option('nocheck'), True)
Exemplo n.º 3
0
    def write_db(self):
        tmpdir = tempfile.mkdtemp(prefix='laymantmp_')
        test_xml = os.path.join(tmpdir, 'test.xml')
        test_json = os.path.join(tmpdir, 'test.json')
        config = BareConfig()

        a = DbBase(config, [HERE + '/testfiles/global-overlays.xml', ])
        b = DbBase({'output': Message(), 'db_type': 'xml'}, [test_xml,])

        b.overlays['wrobel-stable'] = a.overlays['wrobel-stable']
        b.write(test_xml)

        c = DbBase({'output': Message(), 'db_type': 'xml'}, [test_xml,])
        keys = sorted(c.overlays)
        self.assertEqual(keys, ['wrobel-stable'])

        config.set_option('db_type', 'json')
        a = DbBase(config, [HERE + '/testfiles/global-overlays.json', ])
        b = DbBase({'output': Message(), 'db_type': 'json'}, [test_json,])

        b.overlays['twitch153'] = a.overlays['twitch153']
        b.write(test_json)

        c = DbBase({'output': Message(), 'db_type': 'json'}, [test_json,])
        keys = sorted(c.overlays)
        self.assertEqual(keys, ['twitch153'])

        # Clean up:
        os.unlink(test_xml)
        os.unlink(test_json)
        shutil.rmtree(tmpdir)
Exemplo n.º 4
0
    def write_db(self):
        tmpdir = tempfile.mkdtemp(prefix='laymantmp_')
        test_xml = os.path.join(tmpdir, 'test.xml')
        test_json = os.path.join(tmpdir, 'test.json')
        config = BareConfig()

        a = DbBase(config, [
            HERE + '/testfiles/global-overlays.xml',
        ])
        b = DbBase({
            'output': Message(),
            'db_type': 'xml'
        }, [
            test_xml,
        ])

        b.overlays['wrobel-stable'] = a.overlays['wrobel-stable']
        b.write(test_xml)

        c = DbBase({
            'output': Message(),
            'db_type': 'xml'
        }, [
            test_xml,
        ])
        keys = sorted(c.overlays)
        self.assertEqual(keys, ['wrobel-stable'])

        config.set_option('db_type', 'json')
        a = DbBase(config, [
            HERE + '/testfiles/global-overlays.json',
        ])
        b = DbBase({
            'output': Message(),
            'db_type': 'json'
        }, [
            test_json,
        ])

        b.overlays['twitch153'] = a.overlays['twitch153']
        b.write(test_json)

        c = DbBase({
            'output': Message(),
            'db_type': 'json'
        }, [
            test_json,
        ])
        keys = sorted(c.overlays)
        self.assertEqual(keys, ['twitch153'])

        # Clean up:
        os.unlink(test_xml)
        os.unlink(test_json)
        shutil.rmtree(tmpdir)
Exemplo n.º 5
0
def init_layman(config=None):
    '''Returns the initialized ``LaymanAPI``.

    :param config: the layman's configuration to use (optional)
    '''
    if config is None: config = BareConfig(read_configfile=True, quietness=1)
    return LaymanAPI(config)
Exemplo n.º 6
0
    def __init__(self, config=None, report_errors=False, output=None):
        """
        @param configfile: optional config file to use instead of the default.
                                        can be a BareConfig or ArgsParser config class.
                                        default is BareConfig(output=output)
        @param report_errors: optional bool to silence some error reporting to stdout
                                                default is False
        @param output: optional Message class instance created with your settings.
                                    default is Message(module='layman') other params are defaults.
        """

        self.config = config if config is not None else BareConfig(
            output=output)

        self.output = self.config['output']

        self.report_errors = report_errors

        # add our error recording function to output
        self.output.error_callback = self._error

        # get installed and available dbs
        self._installed_db = None
        self._installed_ids = None
        self._available_db = None
        self._available_ids = None
        self._error_messages = []
        self.sync_results = []

        self.config.set_option(
            'mounts',
            Mounter(self._get_installed_db,
                    self.get_installed,
                    config=self.config))
Exemplo n.º 7
0
 def __init__(self,
              stdout=sys.stdout,
              stdin=sys.stdin,
              stderr=sys.stderr,
              config=None,
              read_configfile=True,
              quiet=False,
              quietness=4,
              verbose=False,
              nocolor=False,
              width=0,
              root=None):
     """Input parameters are optional to override the defaults.
     sets up our LaymanAPI with defaults or passed in values
     and returns an instance of it"""
     self.message = Message(out=stdout, err=stderr)
     self.config = BareConfig(output=self.message,
                              stdout=stdout,
                              stdin=stdin,
                              stderr=stderr,
                              config=config,
                              read_configfile=read_configfile,
                              quiet=quiet,
                              quietness=quietness,
                              verbose=verbose,
                              nocolor=nocolor,
                              width=width,
                              root=root)
     LaymanAPI.__init__(self,
                        self.config,
                        report_errors=True,
                        output=self.config['output'])
     return
Exemplo n.º 8
0
    def _get_layman_api(self):
        '''
        Initializes layman api.

        @rtype layman.api.LaymanAPI instance
        '''
        # Make it so that we aren't initializing the
        # LaymanAPI instance if it already exists and
        # if the current storage location hasn't been
        # changed for the new repository.
        self.storage = self.repo.location.replace(self.repo.name, '')

        if self._layman and self.storage in self.current_storage:
            return self._layman

        config = BareConfig()
        configdir = {'configdir': config.get_option('configdir')}

        self.message = Message(out=sys.stdout, err=sys.stderr)
        self.current_storage = self.storage
        options = {
            'config': config.get_option('config') % (configdir),
            'quiet': self.settings.get('PORTAGE_QUIET'),
            'quietness': config.get_option('quietness'),
            'overlay_defs': config.get_option('overlay_defs') % (configdir),
            'output': self.message,
            'nocolor': self.settings.get('NOCOLOR'),
            'root': self.settings.get('EROOT'),
            'storage': self.current_storage,
            'verbose': self.settings.get('PORTAGE_VERBOSE'),
            'width': self.settings.get('COLUMNWIDTH'),

        }
        self.config = OptionConfig(options=options, root=options['root'])

        # Reloads config to read custom overlay
        # xml files.
        reload_config(self.config)

        layman_api = LaymanAPI(self.config,
                               report_errors=True,
                               output=self.config['output']
                               )

        self._layman = layman_api

        return layman_api
Exemplo n.º 9
0
 def _overlays_bug(self, number):
     config = BareConfig()
     filename = os.path.join(HERE, 'testfiles', 'overlays_bug_%d.xml'\
                                                 % number)
     o = DbBase(config, [filename])
     for verbose in (True, False):
         for t in o.list(verbose=verbose):
             print(t[0].decode('utf-8'))
             print()
Exemplo n.º 10
0
def install_overlay(module, name, list_url=None):
    '''Installs the overlay repository. If not on the central overlays list,
    then :list_url of an alternative list must be provided. The list will be
    fetched and saved under ``%(overlay_defs)/%(name.xml)`` (location of the
    ``overlay_defs`` is read from the Layman's configuration).

    :param name: the overlay id
    :param list_url: the URL of the remote repositories list to look for the overlay
        definition (optional, default: None)

    :returns: True if the overlay was installed, or False if already exists
        (i.e. nothing has changed)
    :raises ModuleError
    '''
    # read Layman configuration
    layman_conf = BareConfig(read_configfile=True)
    layman = init_layman(layman_conf)

    if layman.is_installed(name):
        return False

    if module.check_mode:
        mymsg = 'Would add layman repo \'' + name + '\''
        module.exit_json(changed=True, msg=mymsg)

    if not layman.is_repo(name):
        if not list_url:
            raise ModuleError(
                "Overlay '%s' is not on the list of known "
                "overlays and URL of the remote list was not provided." % name)

        overlay_defs = layman_conf.get_option('overlay_defs')
        dest = path.join(overlay_defs, name + '.xml')

        download_url(module, list_url, dest)

        # reload config
        layman = init_layman()

    if not layman.add_repos(name):
        raise ModuleError(layman.get_errors())

    return True
Exemplo n.º 11
0
def install_overlay(module, name, list_url=None):
    '''Installs the overlay repository. If not on the central overlays list,
    then :list_url of an alternative list must be provided. The list will be
    fetched and saved under ``%(overlay_defs)/%(name.xml)`` (location of the
    ``overlay_defs`` is read from the Layman's configuration).

    :param name: the overlay id
    :param list_url: the URL of the remote repositories list to look for the overlay
        definition (optional, default: None)

    :returns: True if the overlay was installed, or False if already exists
        (i.e. nothing has changed)
    :raises ModuleError
    '''
    # read Layman configuration
    layman_conf = BareConfig(read_configfile=True)
    layman = init_layman(layman_conf)

    if layman.is_installed(name):
        return False    
    
    if module.check_mode:
        mymsg = 'Would add layman repo \'' + name + '\''
        module.exit_json(changed=True, msg=mymsg)

    if not layman.is_repo(name):
        if not list_url:
            raise ModuleError("Overlay '%s' is not on the list of known " \
                "overlays and URL of the remote list was not provided." % name)

        overlay_defs = layman_conf.get_option('overlay_defs')
        dest = path.join(overlay_defs, name + '.xml')

        download_url(module, list_url, dest)

        # reload config
        layman = init_layman()

    if not layman.add_repos(name):
        raise ModuleError(layman.get_errors())

    return True
Exemplo n.º 12
0
    def test(self):
        archives = []
        try:
            from layman.overlays.modules.tar.tar import TarOverlay
            archives.append('tar')
            from layman.overlays.modules.squashfs.squashfs import SquashfsOverlay
            archives.append('squashfs')
        except ImportError:
            pass

        for archive in archives:
            xml_text, repo_name, temp_archive_path = getattr(
                self, "_create_%(archive)s_overlay" % {'archive': archive})()

            (fd, temp_collection_path) = tempfile.mkstemp()
            with os.fdopen(fd, 'w') as f:
                f.write(xml_text)

            # Make playground directory
            temp_dir_path = tempfile.mkdtemp()

            # Make DB from it
            config = BareConfig()
            # Necessary for all mountable overlay types
            layman_inst = LaymanAPI(config=config)
            db = DbBase(config, [temp_collection_path])

            specific_overlay_path = os.path.join(temp_dir_path, repo_name)
            o = db.select(repo_name)

            # Actual testcase
            o.add(temp_dir_path)
            self.assertTrue(os.path.exists(specific_overlay_path))
            # (1/2) Sync with source available
            o.sync(temp_dir_path)
            self.assertTrue(os.path.exists(specific_overlay_path))
            os.unlink(temp_archive_path)
            try:
                # (2/2) Sync with source _not_ available
                o.sync(temp_dir_path)
            except:
                pass
            self.assertTrue(os.path.exists(specific_overlay_path))
            o.delete(temp_dir_path)
            self.assertFalse(os.path.exists(specific_overlay_path))

            # Cleanup
            os.unlink(temp_collection_path)
            os.rmdir(temp_dir_path)
Exemplo n.º 13
0
    def _run(self, number):
        #config = {'output': Message()}
        config = BareConfig()

        # Discuss renaming files to "branch-%d.xml"
        filename1 = os.path.join(HERE, 'testfiles', 'subpath-%d.xml' % number)

        # Read, write, re-read, compare
        os1 = DbBase(config, [filename1])
        filename2 = tempfile.mkstemp()[1]
        os1.write(filename2)
        os2 = DbBase(config, [filename2])
        os.unlink(filename2)
        self.assertTrue(os1 == os2)

        # Pass original overlays
        return os1
Exemplo n.º 14
0
    def _get_layman_api(self):
        '''
        Initializes layman api.

        @rtype layman.api.LaymanAPI instance
        '''
        # Make it so that we aren't initializing the
        # LaymanAPI instance if it already exists and
        # if the current storage location hasn't been
        # changed for the new repository.
        self.storage = self.repo.location.replace(self.repo.name, '')

        if self._layman and self.storage in self.current_storage:
            return self._layman

        config = BareConfig()
        configdir = {'configdir': config.get_option('configdir')}

        self.message = Message(out=sys.stdout, err=sys.stderr)
        self.current_storage = self.storage
        options = {
            'config': config.get_option('config') % (configdir),
            'quiet': self.settings.get('PORTAGE_QUIET'),
            'quietness': config.get_option('quietness'),
            'overlay_defs': config.get_option('overlay_defs') % (configdir),
            'output': self.message,
            'nocolor': self.settings.get('NOCOLOR'),
            'root': self.settings.get('EROOT'),
            'storage': self.current_storage,
            'verbose': self.settings.get('PORTAGE_VERBOSE'),
            'width': self.settings.get('COLUMNWIDTH'),
        }
        self.config = OptionConfig(options=options, root=options['root'])

        # Reloads config to read custom overlay
        # xml files.
        reload_config(self.config)

        layman_api = LaymanAPI(self.config,
                               report_errors=True,
                               output=self.config['output'])

        self._layman = layman_api

        return layman_api
Exemplo n.º 15
0
def create_overlay_package(config=None,
                           repo=None,
                           logger=None,
                           xterm_titles=None):
    '''
    Creates a layman overlay object
    from the given repos.conf repo info.

    @params config: layman.config class object
    @params repo: portage.repo class object
    @rtype tuple: overlay name and layman.overlay object or None
    '''
    if repo:
        overlay = {'sources': []}
        desc = 'Defined and created from info in %(repo)s config file...'\
                % ({'repo': repo.name})
        if not config:
            config = BareConfig()
        if not repo.branch:
            repo.branch = ''

        overlay['name'] = repo.name
        overlay['descriptions'] = [desc]
        overlay['owner_name'] = 'repos.conf'
        overlay['owner_email'] = '127.0.0.1'
        overlay['sources'].append(
            [repo.sync_uri, repo.layman_type, repo.branch])
        overlay['priority'] = repo.priority

        ovl = Overlay.Overlay(config=config, ovl_dict=overlay, ignore=1)
        return (repo.name, ovl)

    msg = '!!! laymansync sez... Error: repo not found.'
    if logger and xterm_titles:
        logger(xterm_titles, msg)
    writemsg_level(msg + '\n', level=logging.ERROR, noiselevel=-1)
    return None
Exemplo n.º 16
0
    def __init__(self, args=None, stdout=None, stdin=None, stderr=None,
                root=None
                ):
        '''
        Creates and describes all possible polymeraZe options and creates
        a Message object.

        >>> import os.path
        >>> here = os.path.dirname(os.path.realpath(__file__))
        >>> sys.argv.append('--config')
        >>> sys.argv.append(here + '/../etc/layman.cfg')
        >>> sys.argv.append('--overlay_defs')
        >>> sys.argv.append('')
        >>> a = ArgsParser()
        >>> a['overlays']
        '\\nhttp://www.gentoo.org/proj/en/overlays/repositories.xml'
        >>> sorted(a.keys())
        ['bzr_addopts', 'bzr_command', 'bzr_postsync', 'bzr_syncopts', 'cache', 'config', 'configdir', 'custom_news_pkg', 'cvs_addopts', 'cvs_command', 'cvs_postsync', 'cvs_syncopts', 'darcs_addopts', 'darcs_command', 'darcs_postsync', 'darcs_syncopts', 'g-common_command', 'g-common_generateopts', 'g-common_postsync', 'g-common_syncopts', 'git_addopts', 'git_command', 'git_email', 'git_postsync', 'git_syncopts', 'git_user', 'installed', 'local_list', 'make_conf', 'mercurial_addopts', 'mercurial_command', 'mercurial_postsync', 'mercurial_syncopts', 'news_reporter', 'nocheck', 'overlay_defs', 'overlays', 'proxy', 'quietness', 'rsync_command', 'rsync_postsync', 'rsync_syncopts', 'storage', 'svn_addopts', 'svn_command', 'svn_postsync', 'svn_syncopts', 't/f_options', 'tar_command', 'tar_postsync', 'umask', 'width']
                '''

        BareConfig.__init__(self, stdout=stdout, stderr=stderr,
                            stdin=stdin, root=root)
        if args == None:
            args = sys.argv

        # get a couple BareConfig items
        self.defaults = self.get_defaults()
        self.output = self.get_option('output')

        self.parser = OptionParser(
            usage   = _USAGE,
            version = VERSION)

        #-----------------------------------------------------------------
        # Main Options

        group = OptionGroup(self.parser,
                            '<Actions>')

        group.add_option('-a',
                         '--add',
                         action = 'append',
                         help = 'Add the given overlay from the cached remote li'
                         'st to your locally installed overlays.. Specify "ALL" '
                         'to add all overlays from the remote list.')

        group.add_option('-d',
                         '--delete',
                         action = 'append',
                         help = 'Remove the given overlay from your locally inst'
                         'alled overlays. Specify "ALL" to remove all overlays')

        group.add_option('-s',
                         '--sync',
                         action = 'append',
                         help = 'Update the specified overlay. Use "ALL" as para'
                         'meter to synchronize all overlays')

        group.add_option('-i',
                         '--info',
                         action = 'append',
                         help = 'Display information about the specified overlay'
                         '.')

        group.add_option('-S',
                         '--sync-all',
                         action = 'store_true',
                         help = 'Update all overlays.')

        group.add_option('-L',
                         '--list',
                         action = 'store_true',
                         help = 'List the contents of the remote list.')

        group.add_option('-l',
                         '--list-local',
                         action = 'store_true',
                         help = 'List the locally installed overlays.')

        group.add_option('-f',
                         '--fetch',
                         action = 'store_true',
                         help = 'Fetch a remote list of overlays. This option is'
                         ' deprecated. The fetch operation will be performed by '
                         'default when you run sync, sync-all, or list.')

        group.add_option('-n',
                         '--nofetch',
                         action = 'store_true',
                         help = 'Do not fetch a remote list of overlays.')

        group.add_option('-p',
                         '--priority',
                         action = 'store',
                         help = 'Use this with the --add switch to set the prior'
                         'ity of the added overlay. This will influence the sort'
                         'ing order of the overlays in the PORTDIR_OVERLAY varia'
                         'ble.')

        self.parser.add_option_group(group)

        #-----------------------------------------------------------------
        # Additional Options

        group = OptionGroup(self.parser,
                            '<Path options>')

        group.add_option('-c',
                         '--config',
                         action = 'store',
                         help = 'Path to the config file [default: ' \
                         + self.defaults['config'] + '].')

        group.add_option('-O',
                         '--overlay_defs',
                         action = 'store',
                         help = 'Path to aditional overlay.xml files [default: '\
                         + self.defaults['overlay_defs'] + '].')

        group.add_option('-o',
                         '--overlays',
                         action = 'append',
                         help = 'The list of overlays [default: ' \
                         + self.defaults['overlays'] + '].')

        self.parser.add_option_group(group)

        #-----------------------------------------------------------------
        # Output Options

        group = OptionGroup(self.parser,
                            '<Output options>')

        group.add_option('-v',
                         '--verbose',
                         action = 'store_true',
                         help = 'Increase the amount of output and describe the '
                         'overlays.')

        group.add_option('-q',
                         '--quiet',
                         action = 'store_true',
                         help = 'Yield no output. Please be careful with this op'
                         'tion: If the processes spawned by layman when adding o'
                         'r synchronizing overlays require any input layman will'
                         ' hang without telling you why. This might happen for e'
                         'xample if your overlay resides in subversion and the S'
                         'SL certificate of the server needs acceptance.')

        group.add_option('-N',
                         '--nocolor',
                         action = 'store_true',
                         help = 'Remove color codes from the layman output.')

        group.add_option('-Q',
                         '--quietness',
                         action = 'store',
                         type = 'int',
                         default = '4',
                         help = 'Set the level of output (0-4). Default: 4. Once'
                         ' you set this below 2 the same warning as given for --'
                         'quiet applies! ')

        group.add_option('-W',
                         '--width',
                         action = 'store',
                         type = 'int',
                         default = '0',
                         help = 'Sets the screen width. This setting is usually '
                         'not required as layman is capable of detecting the '
                         'available number of columns automatically.')

        group.add_option('-k',
                         '--nocheck',
                         action = 'store_true',
                         help = 'Do not check overlay definitions and do not i'
                         'ssue a warning if description or contact information'
                         ' are missing.')

        group.add_option('--debug-level',
                         action = 'store',
                         type = 'int',
                         help = 'A value between 0 and 10. 0 means no debugging '
                         'messages will be selected, 10 selects all debugging me'
                         'ssages. Default is "4".')


        self.parser.add_option_group(group)

        #-----------------------------------------------------------------
        # Debug Options

        #self.output.cli_opts(self.parser)

        # Parse the command line first since we need to get the config
        # file option.
        if len(args) == 1:
            self.output.notice('Usage:%s' % _USAGE)
            sys.exit(0)

        (self.options, remain_args) = self.parser.parse_args(args)
        # remain_args starts with something like "bin/layman" ...
        if len(remain_args) > 1:
            self.parser.error("ArgsParser(): Unhandled parameters: %s"
                % ', '.join(('"%s"' % e) for e in remain_args[1:]))

        # handle debugging
        #self.output.cli_handle(self.options)

        if (self.options.__dict__.has_key('debug_level') and
            self.options.__dict__['debug_level']):
            dbglvl = int(self.options.__dict__['debug_level'])
            if dbglvl < 0:
                dbglvl = 0
            if dbglvl > 10:
                dbglvl = 10
            self.output.set_debug_level(dbglvl)

        if self.options.__dict__['nocolor']:
            self.output.set_colorize(OFF)

        # Set only alternate config settings from the options
        if self.options.__dict__['config'] is not None:
            self.defaults['config'] = self.options.__dict__['config']
            self.output.debug('ARGSPARSER: Got config file at ' + \
                self.defaults['config'], 8)
        else: # fix the config path
            self.defaults['config'] = self.defaults['config'] \
                % {'configdir': self.defaults['configdir']}
        if self.options.__dict__['overlay_defs'] is not None:
            self.defaults['overlay_defs'] = self.options.__dict__['overlay_defs']
            self.output.debug('ARGSPARSER: Got overlay_defs location at ' + \
                self.defaults['overlay_defs'], 8)

        # Now parse the config file
        self.output.debug('ARGSPARSER: Reading config file at ' + \
            self.defaults['config'], 8)
        self.read_config(self.defaults)

        # handle quietness
        if self.options.__dict__['quiet']:
            self.set_option('quiet', True)
        elif self.options.__dict__['quietness']:
            self.set_option('quietness', self.options.__dict__['quietness'])
Exemplo n.º 17
0
    def __init__(self, args=None, stdout=None, stdin=None, stderr=None,
                root=None
                ):
        '''
        Creates and describes all possible polymeraZe options and creates
        a Message object.
        '''
        BareConfig.__init__(self, stdout=stdout, stderr=stderr,
                            stdin=stdin, root=root)

        # get a couple BareConfig items
        self.defaults = self.get_defaults()
        self.output = self.get_option('output')

        self.parser = ArgumentParser(
            usage   = _USAGE)

        self.parser.add_argument('-H',
                        '--setup-help',
                        action = 'store_true',
                        help = 'Print the NEW INSTALL help messages.')

        self.parser.add_argument('-V',
                          '--version',
                          action = 'version',
                          version = VERSION)

        #-----------------------------------------------------------------
        # Main Options

        actions = self.parser.add_argument_group('<Actions>')

        actions.add_argument('-a',
                             '--add',
                             nargs = '+',
                             help = 'Add the given overlay from the cached remote li'
                             'st to your locally installed overlays.. Specify "ALL" '
                             'to add all overlays from the remote list.')

        actions.add_argument('-d',
                             '--delete',
                             nargs = '+',
                             help = 'Remove the given overlay from your locally inst'
                             'alled overlays. Specify "ALL" to remove all overlays.')

        actions.add_argument('-D',
                             '--disable',
                             nargs = '+',
                             help = 'Disable the given overlay from portage. Specify'
                             ' "ALL" to disable all installed overlay.')

        actions.add_argument('-E',
                             '--enable',
                             nargs = '+',
                             help = 'Re-enable a previously disabled overlay. Specif'
                             'y "ALL" to enable all installed overlays.')

        actions.add_argument('-f',
                             '--fetch',
                             action = 'store_true',
                             help = 'Fetch a remote list of overlays. This option is'
                             ' deprecated. The fetch operation will be performed by '
                             'default when you run sync, sync-all, or list.')

        actions.add_argument('-i',
                             '--info',
                             nargs = '+',
                             help = 'Display information about the specified overlay'
                             '.')

        actions.add_argument('-L',
                             '--list',
                             action = 'store_true',
                             help = 'List the contents of the remote list.')

        actions.add_argument('-l',
                             '--list-local',
                             action = 'store_true',
                             help = 'List the locally installed overlays.')

        actions.add_argument('-n',
                             '--nofetch',
                             action = 'store_true',
                             help = 'Do not fetch a remote list of overlays.')

        actions.add_argument('-p',
                             '--priority',
                             action = 'store',
                             help = 'Use this with the --add switch to set the prior'
                             'ity of the added overlay. This will influence the sort'
                             'ing order of the overlays in the PORTDIR_OVERLAY varia'
                             'ble.')

        actions.add_argument('-r',
                             '--readd',
                             nargs = '+',
                             help = 'Remove and re-add the given overlay from the cached'
                             ' remote list to your locally installed overlays... Specify'
                             ' "ALL" to re-add all local overlays.')

        actions.add_argument('-s',
                             '--sync',
                             nargs = '+',
                             help = 'Update the specified overlay. Use "ALL" as para'
                            'meter to synchronize all overlays.')

        actions.add_argument('-S',
                             '--sync-all',
                             action = 'store_true',
                             help = 'Update all overlays.')

        #-----------------------------------------------------------------
        # Path Options

        path_opts = self.parser.add_argument_group('<Path options>')

        path_opts.add_argument('-c',
                               '--config',
                               action = 'store',
                               default = self.defaults['config'],
                               # Force interpolation (to prevent argparse tracebacks)
                               help = 'Path to the config file [default: '
                               '%s].' % (self.defaults['config'] %self.defaults))

        path_opts.add_argument('-C',
                               '--configdir',
                               action = 'store',
                               default = self.defaults['configdir'],
                               help = 'Directory path to user for all layman '
                               'configuration information [default:'\
                               + self.defaults['configdir'] + '].')

        path_opts.add_argument('-o',
                               '--overlays',
                               nargs = '+',
                               help = 'The list of overlays [default: ' \
                               + self.defaults['overlays'] + '].')

        path_opts.add_argument('-O',
                               '--overlay_defs',
                               action = 'store',
                               default = self.defaults['overlay_defs'],
                               # Force interpolation (to prevent argparse tracebacks)
                               help = 'Path to aditional overlay.xml files [default: '
                               '%s].' % (self.defaults['overlay_defs'] %self.defaults))

        path_opts.add_argument('-z',
                               '--storage',
                               action = 'store',
                               default = self.defaults['storage'],
                               help = 'Directory path to user for layman overlay inst'
                               'allation location [default: /var/lib/layman].')

        #-----------------------------------------------------------------
        # Output Options

        out_opts = self.parser.add_argument_group('<Output options>')

        out_opts.add_argument('--debug-level',
                              action = 'store',
                              type = int,
                              help = 'A value between 0 and 10. 0 means no debugging '
                              'messages will be selected, 10 selects all debugging me'
                              'ssages. Default is "4".')

        out_opts.add_argument('-k',
                              '--nocheck',
                              action = 'store_true',
                              help = 'Do not check overlay definitions and do not i'
                              'ssue a warning if description or contact information'
                              ' are missing.')

        out_opts.add_argument('-N',
                              '--nocolor',
                              action = 'store_true',
                              help = 'Remove color codes from the layman output.')

        out_opts.add_argument('-q',
                              '--quiet',
                              action = 'store_true',
                              help = 'Yield no output. Please be careful with this op'
                              'tion: If the processes spawned by layman when adding o'
                              'r synchronizing overlays require any input layman will'
                              ' hang without telling you why. This might happen for e'
                              'xample if your overlay resides in subversion and the S'
                              'SL certificate of the server needs acceptance.')

        out_opts.add_argument('-Q',
                              '--quietness',
                              action = 'store',
                              type = int,
                              default = 4,
                              help = 'Set the level of output (0-4). Default: 4. Once'
                              ' you set this below 2 the same warning as given for --'
                              'quiet applies!')

        out_opts.add_argument('-v',
                              '--verbose',
                              action = 'store_true',
                              help = 'Increase the amount of output and describe the '
                              'overlays.')

        out_opts.add_argument('-W',
                              '--width',
                              action = 'store',
                              type = int,
                              default = 0,
                              help = 'Sets the screen width. This setting is usually '
                              'not required as layman is capable of detecting the '
                              'available number of columns automatically.')

        #-----------------------------------------------------------------
        # Additional Options
        etc_opts = self.parser.add_argument_group('<Additional options>')

        etc_opts.add_argument('--protocol_filter',
                              nargs = '+',
                              help = 'Sets the protocol filter that determines '
                              'which protocols will be used when adding '
                              'overlays or updating their source URLs.')

        #-----------------------------------------------------------------
        # Debug Options

        #self.output.cli_opts(self.parser)

        # Parse the command line first since we need to get the config
        # file option.

        # If no flags are present print out usage
        if len(sys.argv) == 1:
            self.output.notice('usage:%s' % _USAGE)
            sys.exit(0)

        self.options = self.parser.parse_args()
        self.options = vars(self.options)
        # Applying interpolation of values
        for v in ['configdir', 'config']:
            self.options[v] = self.options[v] % self.options
            self.defaults[v] = self.options[v]

        if ('debug_level' in self.options and
            self.options['debug_level']):
            dbglvl = int(self.options['debug_level'])
            if dbglvl < 0:
                dbglvl = 0
            if dbglvl > 10:
                dbglvl = 10
            self.output.set_debug_level(dbglvl)

        if self.options['nocolor']:
            self.output.set_colorize(OFF)

        # Set only alternate config settings from the options
        if self.options['config'] is not None:
            self.defaults['config'] = self.options['config']
            self.output.debug('ARGSPARSER: Got config file at ' + \
                self.defaults['config'], 8)
        else: # fix the config path
            self.defaults['config'] = self.defaults['config'] \
                % {'configdir': self.defaults['configdir']}

        self._options['setup_help'] = self.options['setup_help']

        # Now parse the config file
        self.output.debug('ARGSPARSER: Reading config file at ' + \
            self.defaults['config'], 8)
        self.read_config(self.defaults)


        # Handle the overlay_defs option:
        if ('%(configdir)s' in self.options['overlay_defs']
            and self.config.has_option('MAIN', 'overlay_defs')):
            # If it hasn't been interpolated then it's not being set as a
            # command line argument. So we first try to set it to the config
            # value.
            self.options['overlay_defs'] = self.config.get('MAIN',
                                                           'overlay_defs')
        elif self.defaults['overlay_defs'] == self.options['overlay_defs']:
            # If it isn't a command line argument and no config option then
            # set it to the default.
            self.defaults['overlay_defs'] = self.defaults['overlay_defs'] % self.options
            self.options['overlay_defs'] = self.defaults['overlay_defs']

        # handle quietness
        if self.options['quiet']:
            self.set_option('quiet', True)
        elif self.options['quietness']:
            self.set_option('quietness', self.options['quietness'])
Exemplo n.º 18
0
    def __init__(self,
                 args=None,
                 stdout=None,
                 stdin=None,
                 stderr=None,
                 root=None):
        '''
        Creates and describes all possible polymeraZe options and creates
        a Message object.
        '''
        BareConfig.__init__(self,
                            stdout=stdout,
                            stderr=stderr,
                            stdin=stdin,
                            root=root)

        # get a couple BareConfig items
        self.defaults = self.get_defaults()
        self.output = self.get_option('output')

        self.parser = ArgumentParser(usage=_USAGE)

        self.parser.add_argument('-H',
                                 '--setup-help',
                                 action='store_true',
                                 help='Print the NEW INSTALL help messages.')

        self.parser.add_argument('-V',
                                 '--version',
                                 action='version',
                                 version=VERSION)

        #-----------------------------------------------------------------
        # Main Options

        actions = self.parser.add_argument_group('<Actions>')

        actions.add_argument(
            '-a',
            '--add',
            nargs='+',
            help='Add the given overlay from the cached remote li'
            'st to your locally installed overlays.. Specify "ALL" '
            'to add all overlays from the remote list.')

        actions.add_argument(
            '-d',
            '--delete',
            nargs='+',
            help='Remove the given overlay from your locally inst'
            'alled overlays. Specify "ALL" to remove all overlays.')

        actions.add_argument(
            '-D',
            '--disable',
            nargs='+',
            help='Disable the given overlay from portage. Specify'
            ' "ALL" to disable all installed overlay.')

        actions.add_argument(
            '-E',
            '--enable',
            nargs='+',
            help='Re-enable a previously disabled overlay. Specif'
            'y "ALL" to enable all installed overlays.')

        actions.add_argument(
            '-f',
            '--fetch',
            action='store_true',
            help='Fetch a remote list of overlays. This option is'
            ' deprecated. The fetch operation will be performed by '
            'default when you run sync, sync-all, or list.')

        actions.add_argument(
            '-i',
            '--info',
            nargs='+',
            help='Display information about the specified overlay'
            '.')

        actions.add_argument('-L',
                             '--list',
                             action='store_true',
                             help='List the contents of the remote list.')

        actions.add_argument('-l',
                             '--list-local',
                             action='store_true',
                             help='List the locally installed overlays.')

        actions.add_argument('-n',
                             '--nofetch',
                             action='store_true',
                             help='Do not fetch a remote list of overlays.')

        actions.add_argument(
            '-p',
            '--priority',
            action='store',
            help='Use this with the --add switch to set the prior'
            'ity of the added overlay. This will influence the sort'
            'ing order of the overlays in the PORTDIR_OVERLAY varia'
            'ble.')

        actions.add_argument(
            '-r',
            '--readd',
            nargs='+',
            help='Remove and re-add the given overlay from the cached'
            ' remote list to your locally installed overlays... Specify'
            ' "ALL" to re-add all local overlays.')

        actions.add_argument(
            '-s',
            '--sync',
            nargs='+',
            help='Update the specified overlay. Use "ALL" as para'
            'meter to synchronize all overlays.')

        actions.add_argument('-S',
                             '--sync-all',
                             action='store_true',
                             help='Update all overlays.')

        #-----------------------------------------------------------------
        # Path Options

        path_opts = self.parser.add_argument_group('<Path options>')

        path_opts.add_argument(
            '-c',
            '--config',
            action='store',
            default=self.defaults['config'],
            # Force interpolation (to prevent argparse tracebacks)
            help='Path to the config file [default: '
            '%s].' % (self.defaults['config'] % self.defaults))

        path_opts.add_argument('-C',
                               '--configdir',
                               action = 'store',
                               default = self.defaults['configdir'],
                               help = 'Directory path to user for all layman '
                               'configuration information [default:'\
                               + self.defaults['configdir'] + '].')

        path_opts.add_argument('-o',
                               '--overlays',
                               nargs = '+',
                               help = 'The list of overlays [default: ' \
                               + self.defaults['overlays'] + '].')

        path_opts.add_argument(
            '-O',
            '--overlay_defs',
            action='store',
            default=self.defaults['overlay_defs'],
            # Force interpolation (to prevent argparse tracebacks)
            help='Path to additional overlay.xml files [default: '
            '%s].' % (self.defaults['overlay_defs'] % self.defaults))

        path_opts.add_argument(
            '-z',
            '--storage',
            action='store',
            default=self.defaults['storage'],
            help='Directory path to user for layman overlay inst'
            'allation location [default: /var/lib/layman].')

        #-----------------------------------------------------------------
        # Output Options

        out_opts = self.parser.add_argument_group('<Output options>')

        out_opts.add_argument(
            '--debug-level',
            action='store',
            type=int,
            help='A value between 0 and 10. 0 means no debugging '
            'messages will be selected, 10 selects all debugging me'
            'ssages. Default is "4".')

        out_opts.add_argument(
            '-k',
            '--nocheck',
            action='store_true',
            help='Do not check overlay definitions and do not i'
            'ssue a warning if description or contact information'
            ' are missing.')

        out_opts.add_argument(
            '-N',
            '--nocolor',
            action='store_true',
            help='Remove color codes from the layman output.')

        out_opts.add_argument(
            '-q',
            '--quiet',
            action='store_true',
            help='Yield no output. Please be careful with this op'
            'tion: If the processes spawned by layman when adding o'
            'r synchronizing overlays require any input layman will'
            ' hang without telling you why. This might happen for e'
            'xample if your overlay resides in subversion and the S'
            'SL certificate of the server needs acceptance.')

        out_opts.add_argument(
            '-Q',
            '--quietness',
            action='store',
            type=int,
            default=4,
            help='Set the level of output (0-4). Default: 4. Once'
            ' you set this below 2 the same warning as given for --'
            'quiet applies!')

        out_opts.add_argument(
            '-v',
            '--verbose',
            action='store_true',
            help='Increase the amount of output and describe the '
            'overlays.')

        out_opts.add_argument(
            '-W',
            '--width',
            action='store',
            type=int,
            default=0,
            help='Sets the screen width. This setting is usually '
            'not required as layman is capable of detecting the '
            'available number of columns automatically.')

        #-----------------------------------------------------------------
        # Additional Options
        etc_opts = self.parser.add_argument_group('<Additional options>')

        etc_opts.add_argument('--protocol_filter',
                              nargs='+',
                              help='Sets the protocol filter that determines '
                              'which protocols will be used when adding '
                              'overlays or updating their source URLs.')

        #-----------------------------------------------------------------
        # Debug Options

        #self.output.cli_opts(self.parser)

        # Parse the command line first since we need to get the config
        # file option.

        # If no flags are present print out usage
        if len(sys.argv) == 1:
            self.output.notice('usage:%s' % _USAGE)
            sys.exit(0)

        self.options = self.parser.parse_args()
        self.options = vars(self.options)
        # Applying interpolation of values
        for v in ['configdir', 'config']:
            self.options[v] = self.options[v] % self.options
            self.defaults[v] = self.options[v]

        if ('debug_level' in self.options and self.options['debug_level']):
            dbglvl = int(self.options['debug_level'])
            if dbglvl < 0:
                dbglvl = 0
            if dbglvl > 10:
                dbglvl = 10
            self.output.set_debug_level(dbglvl)

        if self.options['nocolor']:
            self.output.set_colorize(OFF)

        # Set only alternate config settings from the options
        if self.options['config'] is not None:
            self.defaults['config'] = self.options['config']
            self.output.debug('ARGSPARSER: Got config file at ' + \
                self.defaults['config'], 8)
        else:  # fix the config path
            self.defaults['config'] = self.defaults['config'] \
                % {'configdir': self.defaults['configdir']}

        self._options['setup_help'] = self.options['setup_help']

        # Now parse the config file
        self.output.debug('ARGSPARSER: Reading config file at ' + \
            self.defaults['config'], 8)
        self.read_config(self.defaults)

        # Handle the overlay_defs option:
        if ('%(configdir)s' in self.options['overlay_defs']
                and self.config.has_option('MAIN', 'overlay_defs')):
            # If it hasn't been interpolated then it's not being set as a
            # command line argument. So we first try to set it to the config
            # value.
            self.options['overlay_defs'] = self.config.get(
                'MAIN', 'overlay_defs')
        elif self.defaults['overlay_defs'] == self.options['overlay_defs']:
            # If it isn't a command line argument and no config option then
            # set it to the default.
            self.defaults[
                'overlay_defs'] = self.defaults['overlay_defs'] % self.options
            self.options['overlay_defs'] = self.defaults['overlay_defs']

        # handle quietness
        if self.options['quiet']:
            self.set_option('quiet', True)
        elif self.options['quietness']:
            self.set_option('quietness', self.options['quietness'])