public inbox for gentoo-commits@lists.gentoo.org
 help / color / mirror / Atom feed
* [gentoo-commits] proj/layman:master commit in: layman/, bin/
@ 2011-02-14  6:00 Brian Dolbec
  0 siblings, 0 replies; 4+ messages in thread
From: Brian Dolbec @ 2011-02-14  6:00 UTC (permalink / raw
  To: gentoo-commits

commit:     7aa228d25d1fb1f1343f9cddb187a84bc1cd5a50
Author:     Brian Dolbec <brian.dolbec <AT> gmail <DOT> com>
AuthorDate: Mon Jan 17 06:57:58 2011 +0000
Commit:     Brian Dolbec <brian.dolbec <AT> gmail <DOT> com>
CommitDate: Sun Feb 13 03:48:26 2011 +0000
URL:        http://git.overlays.gentoo.org/gitweb/?p=proj/layman.git;a=commit;h=7aa228d2

create a new cli interface to use the new api

---
 bin/layman    |    7 +-
 layman/cli.py |  286 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 291 insertions(+), 2 deletions(-)

diff --git a/bin/layman b/bin/layman
index fa1a3ab..965d89b 100755
--- a/bin/layman
+++ b/bin/layman
@@ -7,11 +7,13 @@
 # Copyright:
 #             (c) 2005 Gunnar Wrobel
 #             (c) 2009 Sebastian Pipping
+#             (c) 2011 Brian Dolbec
 #             Distributed under the terms of the GNU General Public License v2
 #
 # Author(s):
 #             Gunnar Wrobel <wrobel@gentoo.org>
 #             Sebastian Pipping <sebastian@pipping.org>
+#             Brian Dolbec <brian.dolbec@gmail.com>
 #
 
 __version__ = "$Id$"
@@ -23,7 +25,7 @@ __version__ = "$Id$"
 #-------------------------------------------------------------------------------
 
 from   layman.config            import ArgsParser
-from   layman.action            import main
+from   layman.cli            import Main
 
 #===============================================================================
 #
@@ -31,4 +33,5 @@ from   layman.action            import main
 #
 #-------------------------------------------------------------------------------
 
-main(ArgsParser())
+main = Main(ArgsParser())
+main()

diff --git a/layman/cli.py b/layman/cli.py
new file mode 100644
index 0000000..b273c89
--- /dev/null
+++ b/layman/cli.py
@@ -0,0 +1,286 @@
+#!/usr/bin/python
+# -*- coding: utf-8 -*-
+#################################################################################
+# LAYMAN ACTIONS
+#################################################################################
+# File:       cli.py
+#
+#             Handles layman actions via the command line interface.
+#
+# Copyright:
+#             (c) 2010 - 2011
+#                   Gunnar Wrobel
+#                   Brian Dolbec
+#             Distributed under the terms of the GNU General Public License v2
+#
+# Author(s):
+#             Gunnar Wrobel <wrobel@gentoo.org>
+#             Brian Dolbec <brian.dolbec@gmail.com
+#
+''' Provides the command line actions that can be performed by layman.'''
+
+__version__ = "$Id: cli.py 2011-01-15 23:52 PST Brian Dolbec$"
+
+
+import os, sys
+
+from layman.api import LaymanAPI
+from layman.utils import (decode_selection, encoder, get_encoding,
+    pad, terminal_width)
+from layman.constants import NOT_OFFICIAL_MSG, NOT_SUPPORTED_MSG
+
+
+
+class ListPrinter(object):
+    def __init__(self, config):
+        self.config = config
+        self.output = self.config['output']
+        if not self.config['width']:
+            self.width = terminal_width()
+        else:
+            self.width = self.config['width']
+        self.srclen = self.width - 43
+        self._encoding_ = get_encoding(self.output)
+        if config['verbose']:
+            self.my_lister = self.short_list # self.long_list
+        else:
+            self.my_lister = self.short_list
+
+    def print_shortdict(self, info, complain):
+        #print "ListPrinter.print_tuple()",info
+        ids = sorted(info)
+        #print "ids =======>", ids, "\n"
+        for _id in ids:
+            overlay = info[_id]
+            #print "overlay =", overlay
+            summary, supported, official = overlay
+            self.print_overlay(summary, supported, official, complain)
+
+    def print_shortlist(self, info, complain):
+        #print "ListPrinter.print_shortlist()",info
+        for summary, supported, official in info:
+            self.print_overlay(summary, supported, official, complain)
+
+
+    def print_fulldict(self, info, complain):
+        ids = sorted(info)
+        #print "ids =======>", ids, "\n"
+        for ovl in ids:
+            overlay = info[ovl]
+            #print overlay
+            self.print_overlay(self.my_lister(overlay),
+                               overlay['supported'],
+                               overlay['official'],
+                               complain)
+
+
+    def print_overlay(self, summary, supported, official, complain):
+        # Is the overlay supported?
+        if supported:
+            # Is this an official overlay?
+            if official:
+                 self.output.info(summary, 1)
+            # Unofficial overlays will only be listed if we are not
+            # checking or listing verbose
+            elif complain:
+                # Give a reason why this is marked yellow if it is a verbose
+                # listing
+                if self.config['verbose']:
+                    self.output.warn(NOT_OFFICIAL_MSG, 1)
+                self.output.warn(summary, 1)
+        # Unsupported overlays will only be listed if we are not checking
+        # or listing verbose
+        elif complain:
+            # Give a reason why this is marked red if it is a verbose
+            # listing
+            if self.config['verbose']:
+                self.output.error(NOT_SUPPORTED_MSG)
+            self.output.error(summary)
+
+
+    def short_list(self, overlay):
+        '''
+        >>> print short_list(overlay)
+        wrobel                    [Subversion] (https://o.g.o/svn/dev/wrobel         )
+        '''
+        name   = pad(overlay['name'], 25)
+
+        if len(set(e for e in overlay['src_types'])) == 1:
+            _type = overlay['src_types'][0]
+        else:
+            _type = '%s/..' % overlay['src_type'][0]
+        mtype  = ' [' + pad(_type, 10) + ']'
+
+        source = ', '.join(overlay['src_uris'])
+
+        if len(source) > self.srclen:
+            source = source.replace("overlays.gentoo.org", "o.g.o")
+        source = ' (' + pad(source, self.srclen) + ')'
+
+        return encoder(name + mtype + source, self._encoding_)
+
+
+class Main(object):
+    '''Performs the actions the user selected.
+    '''
+
+    def __init__(self, config):
+        self.config = config
+        #print "config.keys()", config.keys()
+        self.output = config['output']
+        self.api = LaymanAPI(config,
+                             report_errors=True,
+                             output=config.output)
+        # Given in order of precedence
+        self.actions = [('fetch',      'Fetch'),
+                        ('add',        'Add'),
+                        ('sync',       'Sync'),
+                        ('info',       'Info'),
+                        ('sync_all',   'Sync'),
+                        ('delete',     'Delete'),
+                        ('list',       'ListRemote'),
+                        ('list_local', 'ListLocal'),]
+
+    def __call__(self):
+        # Make fetching the overlay list a default action
+        if not 'nofetch' in self.config.keys():
+            # Actions that implicitely call the fetch operation before
+            fetch_actions = ['sync', 'sync_all', 'list']
+            for i in fetch_actions:
+                if i in self.config.keys():
+                    # Implicitely call fetch, break loop
+                    self.Fetch()
+                    break
+
+        result = 0
+
+        # Set the umask
+        umask = self.config['umask']
+        try:
+            new_umask = int(umask, 8)
+            old_umask = os.umask(new_umask)
+        except Exception, error:
+            self.output.die('Failed setting to umask "' + umask +
+                '"!\nError was: ' + str(error))
+
+        for action in self.actions:
+
+            self.output.debug('Checking for action', 7)
+
+            if action[0] in self.config.keys():
+                try:
+                    result += getattr(self, action[1])()
+                except Exception, error:
+                    self.output.error(self.api.get_errors())
+                    result = -1  # So it cannot remain 0, i.e. success
+                    break
+
+        # Reset umask
+        os.umask(old_umask)
+
+        if not result:
+            sys.exit(0)
+        else:
+            sys.exit(1)
+
+
+    def Fetch(self):
+        ''' Fetches the overlay listing.
+        '''
+        return self.api.fetch_remote_list()
+
+
+    def Add(self):
+        ''' Adds the selected overlays.
+        '''
+        selection = decode_selection(self.config['add'])
+        if 'ALL' in selection:
+            selection = self.api.get_available()
+        self.output.debug('Adding selected overlays', 6)
+        return self.api.add_repos(selection)
+
+
+    def Sync(self):
+        ''' Syncs the selected overlays.
+        '''
+        selection = decode_selection(self.config['sync'])
+        if self.config['sync_all'] or 'ALL' in selection:
+            selection = self.api.get_installed()
+        self.output.debug('Updating selected overlays', 6)
+        return self.api.sync(selection)
+
+
+    def Delete(self):
+        ''' Deletes the selected overlays.
+        '''
+        selection = decode_selection(self.config['delete'])
+        if 'ALL' in selection:
+            selection = self.api.get_installed()
+        self.output.debug('Deleting selected overlays', 6)
+        return self.api.delete_repos(selection)
+
+
+    def Info(self):
+        ''' Print information about the specified overlays.
+        '''
+        selection = decode_selection(self.config['info'])
+        if 'ALL' in selection:
+            selection = self.api.get_available()
+        info = self.api.get_info_str(selection)
+
+        for overlay in info:
+            # Is the overlay supported?
+            self.output.info(overlay[0], 1)
+            if not overlay[1]:
+                self.output.warn(NOT_OFFICIAL_MSG, 1)
+            if not overlay[2]:
+                self.output.error(NOT_SUPPORTED_MSG)
+        return info != {}
+
+
+    def ListRemote(self):
+        ''' Lists the available overlays.
+        '''
+
+        self.output.debug('Printing remote overlays.', 6)
+        list_printer = ListPrinter(self.config)
+        width = list_printer.width
+
+        _complain = self.config['nocheck'] or self.config['verbose']
+        info = self.api.get_info_list(local=False, verbose=self.config['verbose'], width=width)
+        list_printer.print_shortlist(info, complain=_complain)
+
+        return info != {}
+
+
+    def ListLocal(self):
+        ''' Lists the local overlays.
+        '''
+        #print "ListLocal()"
+        self.output.debug('Printing installed overlays.', 6)
+        list_printer = ListPrinter(self.config)
+
+        _complain = self.config['nocheck'] or self.config['verbose']
+        #
+        # fast way
+        info = self.api.get_info_list(verbose=self.config['verbose'],
+                                      width=list_printer.width)
+        list_printer.print_shortlist(info, complain=_complain)
+        #
+        # slow way
+        #info = self.api.get_all_info(self.api.get_installed(), local=True)
+        #list_printer.print_fulldict(info, complain=_complain)
+
+        return info != {}
+
+
+if __name__ == '__main__':
+    import doctest
+
+    # Ignore warnings here. We are just testing
+    from warnings     import filterwarnings, resetwarnings
+    filterwarnings('ignore')
+
+    doctest.testmod(sys.modules[__name__])
+
+    resetwarnings()



^ permalink raw reply related	[flat|nested] 4+ messages in thread

* [gentoo-commits] proj/layman:master commit in: layman/, bin/
@ 2011-04-27 10:58 Brian Dolbec
  0 siblings, 0 replies; 4+ messages in thread
From: Brian Dolbec @ 2011-04-27 10:58 UTC (permalink / raw
  To: gentoo-commits

commit:     a79acc064e4bf9ba97e33b6fd66329f2fee9014d
Author:     Brian Dolbec <brian.dolbec <AT> gmail <DOT> com>
AuthorDate: Sat Feb 19 18:08:14 2011 +0000
Commit:     Brian Dolbec <brian.dolbec <AT> gmail <DOT> com>
CommitDate: Thu Feb 24 06:49:46 2011 +0000
URL:        http://git.overlays.gentoo.org/gitweb/?p=proj/layman.git;a=commit;h=a79acc06

separate out ArgsParser to it's own file and subclass BareConfig

---
 bin/layman           |    2 +-
 layman/argsparser.py |  333 +++++++++++++++++++++++++++++++++++++++++
 layman/config.py     |  404 ++++++--------------------------------------------
 3 files changed, 383 insertions(+), 356 deletions(-)

diff --git a/bin/layman b/bin/layman
index 965d89b..5723a58 100755
--- a/bin/layman
+++ b/bin/layman
@@ -24,7 +24,7 @@ __version__ = "$Id$"
 #
 #-------------------------------------------------------------------------------
 
-from   layman.config            import ArgsParser
+from   layman.argsparser            import ArgsParser
 from   layman.cli            import Main
 
 #===============================================================================

diff --git a/layman/argsparser.py b/layman/argsparser.py
new file mode 100644
index 0000000..ff7f8f7
--- /dev/null
+++ b/layman/argsparser.py
@@ -0,0 +1,333 @@
+#!/usr/bin/python
+# -*- coding: utf-8 -*-
+#################################################################################
+# LAYMAN CONFIGURATION
+#################################################################################
+# File:       argsparser.py
+#
+#             Handles layman command line interface configuration
+#
+# Copyright:
+#             (c) 2005 - 2009 Gunnar Wrobel
+#             (c) 2009        Sebastian Pipping
+#             (c) 2010 - 2011 Brian Dolbec
+#             Distributed under the terms of the GNU General Public License v2
+#
+# Author(s):
+#             Gunnar Wrobel <wrobel@gentoo.org>
+#             Sebastian Pipping <sebastian@pipping.org>
+#             Brian Dolbec <brian.dolbec@gmail.com>
+#
+'''Defines the configuration options and provides parsing functionality.'''
+
+__version__ = "$Id: config.py 286 2007-01-09 17:48:23Z wrobel $"
+
+#===============================================================================
+#
+# Dependencies
+#
+#-------------------------------------------------------------------------------
+
+import sys
+
+from optparse import OptionParser, OptionGroup
+
+from layman.config import BareConfig
+from layman.constants import OFF
+from layman.version import VERSION
+
+
+_USAGE = """
+  layman (-a|-d|-s|-i) (OVERLAY|ALL)
+  layman -f [-o URL]
+  layman (-l|-L|-S)"""
+
+
+class ArgsParser(BareConfig):
+    '''Handles the configuration and option parser.'''
+
+    def __init__(self, args=None, stdout=None, stdin=None, stderr=None):
+        '''
+        Creates and describes all possible polymeraZe options and creates
+        a debugging object.
+
+        >>> import os.path
+        >>> here = os.path.dirname(os.path.realpath(__file__))
+        >>> sys.argv.append('--config')
+        >>> sys.argv.append(here + '/../etc/layman.cfg')
+        >>> a = ArgsParser()
+        >>> a['overlays']
+        '\\nhttp://www.gentoo.org/proj/en/overlays/repositories.xml'
+        >>> sorted(a.keys())
+        ['bzr_command', 'cache', 'config', 'cvs_command', 'darcs_command',
+        'git_command', 'local_list', 'make_conf', 'mercurial_command',
+        'nocheck', 'overlays', 'proxy', 'quietness', 'rsync_command', 'storage',
+        'svn_command', 'tar_command', 'umask', 'width']
+        '''
+
+        BareConfig.__init__(self, stdout=stdout, stderr=stderr, stdin=stdin)
+        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',
+                         '--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.')
+
+        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:
+            print '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("Unhandled parameters: %s"
+                % ', '.join(('"%s"' % e) for e in remain_args[1:]))
+
+        # handle debugging
+        #self.output.cli_handle(self.options)
+
+        if self.options.__dict__['nocolor']:
+            self.output.set_colorize(OFF)
+
+        # Fetch only an alternate config setting from the options
+        #if not self.options.__dict__['config'] is None:
+        #    self._defaults['config'] = self.options.__dict__['config']
+
+            #self.output.debug('Got config file at ' + self.defaults['config'], 8)
+
+        # Now parse the config file
+        self.read_config(self._defaults)
+
+        # handle quietness
+        if self['quiet']:
+            self.set_option('quiet', True)
+        elif self.options.__dict__['quietness']:
+            self.set_option('quietness', self.options.__dict__['quietness'])
+
+        #self.output.debug('Reading config file at ' + self.defaults['config'], 8)
+
+        self.read_config(self.defaults)
+
+    def __getitem__(self, key):
+
+        if key == 'overlays':
+            overlays = ''
+            if (key in self.options.__dict__.keys()
+                and not self.options.__dict__[key] is None):
+                overlays = '\n'.join(self.options.__dict__[key])
+            if self.config.has_option('MAIN', 'overlays'):
+                overlays += '\n' + self.config.get('MAIN', 'overlays')
+            if overlays:
+                return  overlays
+
+        self.output.debug('Retrieving option', 8)
+
+        if (key in self.options.__dict__.keys()
+            and not self.options.__dict__[key] is None):
+            return self.options.__dict__[key]
+
+        self.output.debug('Retrieving option', 8)
+
+        if self.config.has_option('MAIN', key):
+            if key in self._defaults['T/F_options']:
+                return self.t_f_check(self.config.get('MAIN', key))
+            return self.config.get('MAIN', key)
+
+        self.output.debug('Retrieving option', 8)
+
+        if key in self._options.keys():
+            return self._options[key]
+
+        if key in self.defaults.keys():
+            return self.defaults[key]
+
+        self.output.debug('Retrieving option', 8)
+
+        return None
+
+
+    def keys(self):
+        '''Special handler for the configuration keys.'''
+
+        self.output.debug('Retrieving keys', 8)
+
+        keys = [i for i in self.options.__dict__.keys()
+                if not self.options.__dict__[i] is None]
+
+        self.output.debug('Retrieving keys', 8)
+
+        keys += [name for name, _ in self.config.items('MAIN')
+                 if not name in keys]
+
+        self.output.debug('Retrieving keys', 8)
+
+        keys += [i for i in self.defaults.keys()
+                 if not i in keys]
+
+        self.output.debug('Retrieving keys', 8)
+
+        return keys
+
+
+#===============================================================================
+#
+# Testing
+#
+#-------------------------------------------------------------------------------
+
+if __name__ == '__main__':
+    import doctest
+    doctest.testmod(sys.modules[__name__])

diff --git a/layman/config.py b/layman/config.py
index e8736ed..58e222a 100644
--- a/layman/config.py
+++ b/layman/config.py
@@ -1,52 +1,38 @@
 #!/usr/bin/python
 # -*- coding: utf-8 -*-
-#################################################################################
-# LAYMAN CONFIGURATION
-#################################################################################
-# File:       config.py
-#
-#             Handles layman configuration
-#
-# Copyright:
-#             (c) 2005 - 2009 Gunnar Wrobel
-#             (c) 2009        Sebastian Pipping
-#             (c) 2010 - 2011 Brian Dolbec
-#             Distributed under the terms of the GNU General Public License v2
-#
-# Author(s):
-#             Gunnar Wrobel <wrobel@gentoo.org>
-#             Sebastian Pipping <sebastian@pipping.org>
-#             Brian Dolbec <brian.dolbec@gmail.com>
-#
-'''Defines the configuration options and provides parsing functionality.'''
-
-__version__ = "$Id: config.py 286 2007-01-09 17:48:23Z wrobel $"
-
-#===============================================================================
-#
-# Dependencies
-#
-#-------------------------------------------------------------------------------
-
-import sys, ConfigParser
-import os
 
-from optparse import OptionParser, OptionGroup
+"""
+ LAYMAN CONFIGURATION
 
-#from layman.debug import OUT
-from layman.output import Message
+ File:       config.py
+
+             Handles Basic layman configuration
+
+ Copyright:
+             (c) 2005 - 2009 Gunnar Wrobel
+             (c) 2009        Sebastian Pipping
+             (c) 2010 - 2011 Brian Dolbec
+             Distributed under the terms of the GNU General Public License v2
 
-from layman.constants import OFF
-from layman.version import VERSION
+ Author(s):
+             Gunnar Wrobel <wrobel@gentoo.org>
+             Sebastian Pipping <sebastian@pipping.org>
+             Brian Dolbec <brian.dolbec@gmail.com>
+"""
 
+'''Defines the configuration options.'''
+
+__version__ = "0.2"
+
+
+import sys
+import os
+import ConfigParser
 
-_USAGE = """
-  layman (-a|-d|-s|-i) (OVERLAY|ALL)
-  layman -f [-o URL]
-  layman (-l|-L|-S)"""
+from layman.output import Message
 
 
-def read_config(config=None, defaults=None):
+def read_layman_config(config=None, defaults=None):
     """reads the config file defined in defaults['config']
     and updates the config
 
@@ -68,11 +54,6 @@ def read_config(config=None, defaults=None):
                 overlays.update(["file://" + path])
         config.set('MAIN', 'overlays', '\n'.join(overlays))
 
-def t_f_check(option):
-    """evaluates the option and returns
-    True or False
-    """
-    return option.lower() in ['yes', 'true', 'y', 't']
 
 
 class BareConfig(object):
@@ -130,9 +111,13 @@ class BareConfig(object):
                     }
         self.config = None
         if read_configfile:
-            self.config = ConfigParser.ConfigParser(self._defaults)
+            self.read_config(self.get_defaults())
+
+
+    def read_config(self, defaults):
+            self.config = ConfigParser.ConfigParser(defaults)
             self.config.add_section('MAIN')
-            read_config(self.config, self._defaults)
+            read_layman_config(self.config, defaults)
 
 
     def keys(self):
@@ -149,12 +134,14 @@ class BareConfig(object):
 
     def get_defaults(self):
         """returns our defaults dictionary"""
-        return self._defaults
+        _defaults = self._defaults.copy()
+        _defaults['config'] = self._options['config']
+        return _defaults
 
 
     def get_option(self, key):
         """returns the current option's value"""
-        return self.__getitem__(key)
+        return self._get_(key)
 
 
     def set_option(self, option, value):
@@ -164,18 +151,22 @@ class BareConfig(object):
         if option == 'quiet':
             if self._options['quiet']:
                 self._set_quietness(1)
+                self._options['quietness'] = 0
             else:
                 self._set_quietness(4)
         if option == 'quietness':
-            self._set_quietness()
+            self._set_quietness(value)
 
     def _set_quietness(self, value):
             self._options['output'].set_info_level(int(self['quietness']))
             self._options['output'].set_warn_level(int(self['quietness']))
 
-
     def __getitem__(self, key):
-        self._options['output'].debug('Retrieving BareConfig option', 8)
+        return self._get_(key)
+
+    def _get_(self, key):
+        self._options['output'].debug(
+            'Retrieving BareConfig option: %s' % key, 8)
         if key == 'overlays':
             overlays = ''
             if (key in self._options
@@ -199,307 +190,10 @@ class BareConfig(object):
             return self._defaults[key]
         return None
 
+    @staticmethod
+    def t_f_check(option):
+        """evaluates the option and returns
+        True or False
+        """
+        return option.lower() in ['yes', 'true', 'y', 't']
 
-class ArgsParser(object):
-    '''Handles the configuration and option parser.'''
-
-    def __init__(self, args=None, output=None,
-        stdout=None, stdin=None, stderr=None):
-        '''
-        Creates and describes all possible polymeraZe options and creates
-        a debugging object.
-
-        >>> import os.path
-        >>> here = os.path.dirname(os.path.realpath(__file__))
-        >>> sys.argv.append('--config')
-        >>> sys.argv.append(here + '/../etc/layman.cfg')
-        >>> a = ArgsParser()
-        >>> a['overlays']
-        '\\nhttp://www.gentoo.org/proj/en/overlays/repositories.xml'
-        >>> sorted(a.keys())
-        ['bzr_command', 'cache', 'config', 'cvs_command', 'darcs_command',
-        'git_command', 'local_list', 'make_conf', 'mercurial_command',
-        'nocheck', 'overlays', 'proxy', 'quietness', 'rsync_command', 'storage',
-        'svn_command', 'tar_command', 'umask', 'width']
-        '''
-        if args == None:
-            args = sys.argv
-
-        self.stdout = stdout if stdout else sys.stdout
-        self.stderr = stderr if stderr else sys.stderr
-        self.stdin = stdin if stdin else sys.stdin
-        self.output = output if output else Message()
-
-        bare_config = BareConfig(self.output, self.stdout,
-            self.stdin, self.stderr)
-        self.defaults = bare_config.get_defaults()
-        #print self.defaults
-
-        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',
-                         '--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.')
-
-        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:
-            print '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("Unhandled parameters: %s"
-                % ', '.join(('"%s"' % e) for e in remain_args[1:]))
-
-        # handle debugging
-        #self.output.cli_handle(self.options)
-
-        # add output to the options
-        self.options.__dict__['output'] = self.output
-
-        # add the std in/out/err to the options
-        self.options.__dict__['stdout'] = self.stdout
-        self.options.__dict__['stdin'] = self.stdin
-        self.options.__dict__['stderr'] = self.stderr
-
-
-        if self.options.__dict__['nocolor']:
-            self.output.set_colorize(OFF)
-
-        # Fetch only an alternate config setting from the options
-        if not self.options.__dict__['config'] is None:
-            self.defaults['config'] = self.options.__dict__['config']
-
-            #self.output.debug('Got config file at ' + self.defaults['config'], 8)
-
-        # Now parse the config file
-        self.config = ConfigParser.ConfigParser(self.defaults)
-        self.config.add_section('MAIN')
-
-        # handle quietness
-        if self['quiet']:
-            self.output.set_info_level(1)
-            self.output.set_warn_level(1)
-            self.defaults['quietness'] = 0
-        elif 'quietness' in self.keys():
-            self.output.set_info_level(int(self['quietness']))
-            self.output.set_warn_level(int(self['quietness']))
-
-        #self.output.debug('Reading config file at ' + self.defaults['config'], 8)
-
-        read_config(self.config, self.defaults)
-
-    def __getitem__(self, key):
-
-        if key == 'overlays':
-            overlays = ''
-            if (key in self.options.__dict__.keys()
-                and not self.options.__dict__[key] is None):
-                overlays = '\n'.join(self.options.__dict__[key])
-            if self.config.has_option('MAIN', 'overlays'):
-                overlays += '\n' + self.config.get('MAIN', 'overlays')
-            if overlays:
-                return  overlays
-
-        self.output.debug('Retrieving option', 8)
-
-        if (key in self.options.__dict__.keys()
-            and not self.options.__dict__[key] is None):
-            return self.options.__dict__[key]
-
-        self.output.debug('Retrieving option', 8)
-
-        if self.config.has_option('MAIN', key):
-            if key in self.defaults['T/F_options']:
-                return t_f_check(self.config.get('MAIN', key))
-            return self.config.get('MAIN', key)
-
-        self.output.debug('Retrieving option', 8)
-
-        if key in self.defaults.keys():
-            return self.defaults[key]
-
-        self.output.debug('Retrieving option', 8)
-
-        return None
-
-
-    def keys(self):
-        '''Special handler for the configuration keys.'''
-
-        self.output.debug('Retrieving keys', 8)
-
-        keys = [i for i in self.options.__dict__.keys()
-                if not self.options.__dict__[i] is None]
-
-        self.output.debug('Retrieving keys', 8)
-
-        keys += [name for name, _ in self.config.items('MAIN')
-                 if not name in keys]
-
-        self.output.debug('Retrieving keys', 8)
-
-        keys += [i for i in self.defaults.keys()
-                 if not i in keys]
-
-        self.output.debug('Retrieving keys', 8)
-
-        return keys
-
-
-#===============================================================================
-#
-# Testing
-#
-#-------------------------------------------------------------------------------
-
-if __name__ == '__main__':
-    import doctest
-    doctest.testmod(sys.modules[__name__])



^ permalink raw reply related	[flat|nested] 4+ messages in thread

* [gentoo-commits] proj/layman:master commit in: layman/, bin/
@ 2012-10-08 22:38 Brian Dolbec
  0 siblings, 0 replies; 4+ messages in thread
From: Brian Dolbec @ 2012-10-08 22:38 UTC (permalink / raw
  To: gentoo-commits

commit:     b2f4591004a0f16a4c348123e999b0912745833e
Author:     Brian Dolbec <dolsen <AT> gentoo <DOT> org>
AuthorDate: Mon Oct  8 22:37:58 2012 +0000
Commit:     Brian Dolbec <brian.dolbec <AT> gmail <DOT> com>
CommitDate: Mon Oct  8 22:37:58 2012 +0000
URL:        http://git.overlays.gentoo.org/gitweb/?p=proj/layman.git;a=commit;h=b2f45910

move the rename_db code to a standalone updater utility.

---
 bin/layman-updater |   24 +++++++++++++
 layman/db.py       |   30 +++--------------
 layman/updater.py  |   92 ++++++++++++++++++++++++++++++++++++++++++++++++++++
 3 files changed, 121 insertions(+), 25 deletions(-)

diff --git a/bin/layman-updater b/bin/layman-updater
new file mode 100755
index 0000000..ac9e841
--- /dev/null
+++ b/bin/layman-updater
@@ -0,0 +1,24 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+################################################################################
+# LAYMAN - A UTILITY TO UPDATE LAYMAN DB's
+################################################################################
+# Distributed under the terms of the GNU General Public License v2
+#
+# Copyright:
+#             (c) 2011 Brian Dolbec
+#             Distributed under the terms of the GNU General Public License v2
+#
+# Author(s):
+#             Brian Dolbec <brian.dolbec@gmail.com>
+#
+
+__version__ = "0.1"
+
+
+from layman.updater import Main
+
+
+main = Main()
+main()

diff --git a/layman/db.py b/layman/db.py
index 354481c..e2d740c 100644
--- a/layman/db.py
+++ b/layman/db.py
@@ -61,9 +61,6 @@ class DB(DbBase):
         else:
             ignore = 1
 
-        # check and handle the name change
-        #if not os.access(self.path, os.F_OK):
-        #    self.rename_db()
 
         DbBase.__init__(self,
                           config,
@@ -73,28 +70,11 @@ class DB(DbBase):
 
         self.output.debug('DB handler initiated', 6)
 
-
-    def rename_db(self):
-        """small upgrade function to handle the name change
-        for the installed xml file"""
-        if os.access(self.config['local_list'], os.F_OK):
-            self.output.info("Automatic db rename, old name was: %s"
-                % self.config['local_list'],2)
-            try:
-                os.rename(self.config['local_list'], self.path)
-                self.output.info("Automatic db rename, new installed db "
-                    "name is: %s" %self.path, 2)
-                self.output.notice('')
-                return
-            except OSError, err:
-                self.output.error("Automatic db rename failed:\n%s" %str(err))
-        else:
-            self.output.info("Automatic db rename, failed access to: %s"
-                % self.config['local_list'],2)
-        self.output.die("Please check that /etc/layman.cfg is up"
-                " to date\nThen try running layman again.\n"
-                "You may need to rename the old 'local_list' config setting"
-                " to\nthe new 'installed' config setting's filename.\n")
+        # check and handle the name change
+        if not os.access(self.config['installed'], os.F_OK) and \
+            os.access(self.config['local_list'], os.F_OK):
+                self.output.die("Please run layman-updater, "
+                    "then run layman again")
 
 
     # overrider

diff --git a/layman/updater.py b/layman/updater.py
new file mode 100644
index 0000000..48fad10
--- /dev/null
+++ b/layman/updater.py
@@ -0,0 +1,92 @@
+#!/usr/bin/python
+# -*- coding: utf-8 -*-
+
+from sys import stderr
+import os
+import argparse
+
+from layman.config import OptionConfig
+from layman.api import LaymanAPI
+from layman.version import VERSION
+
+
+def rename_db(config, newname, output):
+    """small upgrade function to handle the name change
+    for the installed xml file"""
+    if os.access(config['local_list'], os.F_OK):
+        output.info("Automatic db rename, old name was..: %s"
+            % config['local_list'],2)
+        try:
+            os.rename(config['local_list'], newname)
+            output.info("Automatic db rename, new "
+                "name is...: %s" %newname, 2)
+            output.notice('')
+            return
+        except OSError, err:
+            output.error("Automatic db rename failed:\n%s" %str(err))
+    else:
+        output.info("Automatic db rename, failed access to: %s"
+            % config['local_list'],2)
+    output.die("Please check that /etc/layman.cfg is up"
+            " to date\nThen try running layman again.\n"
+            "You may need to rename the old 'local_list' config setting"
+            " to\nthe new 'installed' config setting's filename.\n")
+
+
+class Main(object):
+
+    def __init__(self):
+        self.parser = None
+        self.output = None
+        self.config = None
+        self.args = None
+
+    def args_parser(self):
+        self.parser = argparse.ArgumentParser(prog='layman-updater',
+            description="Layman's DB update script")
+        self.parser.add_argument("-c", "--config",
+            help='the path to config file')
+        self.parser.add_argument('--version', action='version',
+            version='%(prog)s ' + VERSION)
+        self.args = self.parser.parse_args()
+
+    def __call__(self):
+        self.args_parser()
+        options = None
+        if self.args.config:
+            options = {
+                'config': self.args.config,
+            }
+
+        self.config = OptionConfig(options=options)
+        self.config.read_config(self.config.get_defaults())
+
+        layman_inst = LaymanAPI(config=self.config)
+
+        self.output = layman_inst.output
+
+        self.rename_check()
+
+
+    def rename_check(self):
+        '''Checks for and renames the installed db if needed
+        '''
+        newname = self.config['installed']
+
+        # check and handle the name change
+        if not os.access(newname, os.F_OK):
+            if os.access(self.config['local_list'], os.F_OK):
+                self.output.info("Layman automatic db rename utility, "
+                    "performing update", 2)
+                rename_db(self.config, newname, self.output)
+        elif os.access(newname, os.F_OK) and \
+            os.access(self.config['local_list'], os.F_OK):
+            self.output.error("Automatic db rename failed: "
+                "Both old and new files exist")
+            self.output.error("Old file: %s still exists"
+                % self.config['local_list'])
+            self.output.error("New file: %s already exists" % newname)
+        else:
+            self.output.info("Automatic db rename "
+                "already updated: %s" % newname)
+        return


^ permalink raw reply related	[flat|nested] 4+ messages in thread

* [gentoo-commits] proj/layman:master commit in: layman/, bin/
@ 2012-10-15  2:30 Brian Dolbec
  0 siblings, 0 replies; 4+ messages in thread
From: Brian Dolbec @ 2012-10-15  2:30 UTC (permalink / raw
  To: gentoo-commits

commit:     92a545dc6b64bbebfa9bc4c3788f1ae3db058788
Author:     Brian Dolbec <dolsen <AT> gentoo <DOT> org>
AuthorDate: Mon Oct 15 01:03:27 2012 +0000
Commit:     Brian Dolbec <brian.dolbec <AT> gmail <DOT> com>
CommitDate: Mon Oct 15 02:21:23 2012 +0000
URL:        http://git.overlays.gentoo.org/gitweb/?p=proj/layman.git;a=commit;h=92a545dc

Add checking for ROOT in the environment on statup, and setting it in the appropriate paths.
Add warnings for not finding the config file and installed db. Fix updaters config file path

---
 bin/layman           |   10 +++++++++-
 bin/layman-updater   |    8 +++++++-
 layman/__init__.py   |    5 +++--
 layman/argsparser.py |    7 +++++--
 layman/config.py     |   46 +++++++++++++++++++++++++++-------------------
 layman/dbbase.py     |    6 ++++++
 layman/updater.py    |   13 ++++++++++---
 7 files changed, 67 insertions(+), 28 deletions(-)

diff --git a/bin/layman b/bin/layman
index 6299d34..ba91c20 100755
--- a/bin/layman
+++ b/bin/layman
@@ -18,6 +18,8 @@
 
 __version__ = "0.2"
 
+import os
+
 #===============================================================================
 #
 # Dependencies
@@ -33,5 +35,11 @@ from   layman.cli            import Main
 #
 #-------------------------------------------------------------------------------
 
-main = Main(ArgsParser())
+root = None
+try:
+    root = os.environ['ROOT']
+except KeyError:
+    pass
+
+main = Main(ArgsParser(root=root))
 main()

diff --git a/bin/layman-updater b/bin/layman-updater
index ac9e841..51cf825 100755
--- a/bin/layman-updater
+++ b/bin/layman-updater
@@ -16,9 +16,15 @@
 
 __version__ = "0.1"
 
+import os
 
 from layman.updater import Main
 
+root = None
+try:
+    root = os.environ['ROOT']
+except KeyError:
+    pass
 
-main = Main()
+main = Main(root=root)
 main()

diff --git a/layman/__init__.py b/layman/__init__.py
index aa4a159..ce51804 100644
--- a/layman/__init__.py
+++ b/layman/__init__.py
@@ -22,7 +22,7 @@ class Layman(LaymanAPI):
 
     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
+        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
@@ -39,7 +39,8 @@ class Layman(LaymanAPI):
                 quietness=quietness,
                 verbose=verbose,
                 nocolor=nocolor,
-                width=width
+                width=width,
+                root=root
             )
         LaymanAPI.__init__(self, self.config,
                              report_errors=True,

diff --git a/layman/argsparser.py b/layman/argsparser.py
index 12898b8..3afc3ea 100644
--- a/layman/argsparser.py
+++ b/layman/argsparser.py
@@ -49,7 +49,9 @@ _USAGE = """
 class ArgsParser(BareConfig):
     '''Handles the configuration and option parser.'''
 
-    def __init__(self, args=None, stdout=None, stdin=None, stderr=None):
+    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.
@@ -67,7 +69,8 @@ class ArgsParser(BareConfig):
         ['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)
+        BareConfig.__init__(self, stdout=stdout, stderr=stderr,
+                            stdin=stdin, root=root)
         if args == None:
             args = sys.argv
 

diff --git a/layman/config.py b/layman/config.py
index 56cb6f3..3c57497 100644
--- a/layman/config.py
+++ b/layman/config.py
@@ -31,9 +31,9 @@ import os
 import ConfigParser
 
 from layman.output import Message
+from layman.utils import path
 
-
-def read_layman_config(config=None, defaults=None):
+def read_layman_config(config=None, defaults=None, output=None):
     """reads the config file defined in defaults['config']
     and updates the config
 
@@ -41,7 +41,10 @@ def read_layman_config(config=None, defaults=None):
     @param defaults: dict
     @modifies config['MAIN']['overlays']
     """
-    config.read(defaults['config'])
+    read_files = config.read(defaults['config'])
+    if read_files == [] and output is not None:
+        output.warn("Warning: not able to parse config file: %s"
+            % defaults['config'])
     if config.get('MAIN', 'overlay_defs'):
         try:
             filelist = os.listdir(config.get('MAIN', 'overlay_defs'))
@@ -70,7 +73,7 @@ class BareConfig(object):
 
     def __init__(self, output=None, stdout=None, stdin=None, stderr=None,
         config=None, read_configfile=False, quiet=False, quietness=4,
-        verbose=False, nocolor=False, width=0
+        verbose=False, nocolor=False, width=0, root=None
         ):
         '''
         Creates a bare config with defaults and a few output options.
@@ -84,10 +87,15 @@ class BareConfig(object):
         True
         '''
 
+        if root is None:
+            self.root = ''
+        else:
+            self.root = root
+
         self._defaults = {
-                    'configdir': EPREFIX + '/etc/layman',
+                    'configdir': path([self.root, EPREFIX,'/etc/layman']),
                     'config'    : '%(configdir)s/layman.cfg',
-                    'storage'   : EPREFIX + '/var/lib/layman',
+                    'storage'   : path([self.root, EPREFIX,'/var/lib/layman']),
                     'cache'     : '%(storage)s/cache',
                     'local_list': '%(storage)s/overlays.xml',
                     'installed': '%(storage)s/installed.xml',
@@ -100,15 +108,15 @@ class BareConfig(object):
                     'overlays'  :
                     'http://www.gentoo.org/proj/en/overlays/repositories.xml',
                     'overlay_defs': '%(configdir)s/overlays',
-                    'bzr_command': EPREFIX +'/usr/bin/bzr',
-                    'cvs_command': EPREFIX +'/usr/bin/cvs',
-                    'darcs_command': EPREFIX +'/usr/bin/darcs',
-                    'git_command': EPREFIX +'/usr/bin/git',
-                    'g-common_command': EPREFIX +'/usr/bin/g-common',
-                    'mercurial_command': EPREFIX +'/usr/bin/hg',
-                    'rsync_command': EPREFIX +'/usr/bin/rsync',
-                    'svn_command': EPREFIX +'/usr/bin/svn',
-                    'tar_command': EPREFIX +'/bin/tar',
+                    'bzr_command': path([self.root, EPREFIX,'/usr/bin/bzr']),
+                    'cvs_command': path([self.root, EPREFIX,'/usr/bin/cvs']),
+                    'darcs_command': path([self.root, EPREFIX,'/usr/bin/darcs']),
+                    'git_command': path([self.root, EPREFIX,'/usr/bin/git']),
+                    'g-common_command': path([self.root, EPREFIX,'/usr/bin/g-common']),
+                    'mercurial_command': path([self.root, EPREFIX,'/usr/bin/hg']),
+                    'rsync_command': path([self.root, EPREFIX,'/usr/bin/rsync']),
+                    'svn_command': path([self.root, EPREFIX,'/usr/bin/svn']),
+                    'tar_command': path([self.root, EPREFIX,'/bin/tar']),
                     't/f_options': ['nocheck'],
                     'bzr_addopts' : '',
                     'bzr_syncopts' : '',
@@ -158,13 +166,13 @@ class BareConfig(object):
                 # fix the config path
                 defaults['config'] = defaults['config'] \
                     % {'configdir': defaults['configdir']}
-            self.read_config(defaults)
+            self.read_config(self.config, defaults, output=self.output)
 
 
     def read_config(self, defaults):
         self.config = ConfigParser.ConfigParser(defaults)
         self.config.add_section('MAIN')
-        read_layman_config(self.config, defaults)
+        read_layman_config(self.config, defaults, self._options['output'])
 
 
     def keys(self):
@@ -256,7 +264,7 @@ class OptionConfig(BareConfig):
     by using dictionaries.
     """
 
-    def __init__(self, options=None, defaults=None):
+    def __init__(self, options=None, defaults=None, root=None):
         """
         @param options: dictionary of {'option': value, ...}
         @rtype OptionConfig class instance.
@@ -271,7 +279,7 @@ class OptionConfig(BareConfig):
         >>> sorted(a.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']
         """
-        BareConfig.__init__(self)
+        BareConfig.__init__(self, root=root)
 
         self.update_defaults(defaults)
 

diff --git a/layman/dbbase.py b/layman/dbbase.py
index 461038b..e5c0fd9 100644
--- a/layman/dbbase.py
+++ b/layman/dbbase.py
@@ -93,11 +93,17 @@ class DbBase(object):
 
         self.output.debug('Initializing overlay list handler', 8)
 
+        path_found = False
         for path in self.paths:
             if not os.path.exists(path):
                 continue
 
             self.read_file(path)
+            path_found = True
+
+        if not path_found:
+            self.output.warn("Warning: an installed db file was not found at: %s"
+                % str(self.paths))
 
 
     def __eq__(self, other):

diff --git a/layman/updater.py b/layman/updater.py
index 1ee7345..746a061 100644
--- a/layman/updater.py
+++ b/layman/updater.py
@@ -36,11 +36,12 @@ def rename_db(config, newname, output):
 
 class Main(object):
 
-    def __init__(self):
+    def __init__(self, root=None):
         self.parser = None
         self.output = None
         self.config = None
         self.args = None
+        self.root = root
 
     def args_parser(self):
         self.parser = argparse.ArgumentParser(prog='layman-updater',
@@ -59,8 +60,14 @@ class Main(object):
                 'config': self.args.config,
             }
 
-        self.config = OptionConfig(options=options)
-        self.config.read_config(self.config.get_defaults())
+        self.config = OptionConfig(options=options, root=self.root)
+        # fix the config path
+        defaults = self.config.get_defaults()
+        defaults['config'] = defaults['config'] \
+                % {'configdir': defaults['configdir']}
+        self.config.update_defaults({'config': defaults['config']})
+
+        self.config.read_config(defaults)
 
         layman_inst = LaymanAPI(config=self.config)
 


^ permalink raw reply related	[flat|nested] 4+ messages in thread

end of thread, other threads:[~2012-10-15  2:30 UTC | newest]

Thread overview: 4+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2012-10-15  2:30 [gentoo-commits] proj/layman:master commit in: layman/, bin/ Brian Dolbec
  -- strict thread matches above, loose matches on Subject: below --
2012-10-08 22:38 Brian Dolbec
2011-04-27 10:58 Brian Dolbec
2011-02-14  6:00 Brian Dolbec

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox