# -*- coding: iso-8859-1 -*-

# ==============================================================================
# COPYRIGHT (C) 1991 - 2003  EDF R&D                  WWW.CODE-ASTER.ORG
# THIS PROGRAM IS FREE SOFTWARE; YOU CAN REDISTRIBUTE IT AND/OR MODIFY
# IT UNDER THE TERMS OF THE GNU GENERAL PUBLIC LICENSE AS PUBLISHED BY
# THE FREE SOFTWARE FOUNDATION; EITHER VERSION 2 OF THE LICENSE, OR
# (AT YOUR OPTION) ANY LATER VERSION.
#
# THIS PROGRAM IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT
# WITHOUT ANY WARRANTY; WITHOUT EVEN THE IMPLIED WARRANTY OF
# MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU
# GENERAL PUBLIC LICENSE FOR MORE DETAILS.
#
# YOU SHOULD HAVE RECEIVED A COPY OF THE GNU GENERAL PUBLIC LICENSE
# ALONG WITH THIS PROGRAM; IF NOT, WRITE TO EDF R&D CODE_ASTER,
#    1 AVENUE DU GENERAL DE GAULLE, 92141 CLAMART CEDEX, FRANCE.
# ==============================================================================

"""This class adds an action to the parser.
"""

__revision__ = "$Id: as_option.py 2566 2006-12-08 10:09:20Z courtois $"


from optparse import Option, OptionError, OptionValueError

class ASTER_OPTION(Option):
   """Add 'store_const_once' action, it works like 'store_const' except that
   a value can be stored only once, next occurences will raise an error.
   """
   ACTIONS = Option.ACTIONS + ("store_const_once",)
   STORE_ACTIONS = Option.STORE_ACTIONS + ("store_const_once",)
   TYPED_ACTIONS = Option.TYPED_ACTIONS + ("store_const_once",)

   def take_action (self, action, dest, opt, value, values, parser):
      """Uses 'store_const_once' or standard actions.
      """
      if action == "store_const_once":
         # ----- store_const_once
         if not hasattr(values, dest) or not getattr(values, dest):
            setattr(values, dest, getattr(self, 'const'))
         else:
            raise OptionValueError("%r is invalid because '%s' previously occurs" \
                  % (getattr(self, 'const'), dest))
      else:
         # ----- standard actions
         Option.take_action(self, action, dest, opt, value, values, parser)

   def _check_const (self):
      if self.action != "store_const" and self.action != "store_const_once" \
            and getattr(self, 'const') is not None:
         raise OptionError(
               "'const' must not be supplied for action %r" % self.action, self)

   # ----- because of changes to private method _check_conf
   CHECK_METHODS = [Option._check_action,
                    Option._check_type,
                    Option._check_choice,
                    Option._check_dest,
                    _check_const,
                    Option._check_nargs,
                    Option._check_callback]

