Commits

Arnaud Grausem  committed b8d26f2

Exceptions

  • Participants
  • Parent commits ca20e58

Comments (0)

Files changed (6)

File src/adama/__init__.py

 import sys
 import os
 
-from .commandment import Commander, OrderError, QG
+from .commandment import Commander, QG
+from .exceptions import UnknownOrderError
 
 
-VERSION = ('0', '3', '1', 'beta')
+VERSION = ('0', '3', '2', 'beta')
 
 
 def get_version(command=''):
         order_name = argv[1] if not order_help else argv[2]
         try:
             order = commander[order_name]
-        except KeyError as e:
-            return commander(argv[1:])
+        except UnknownOrderError as e:
+            return e()
         else:
             if order_help:
                 return order.explanations()

File src/adama/commandment.py

 import sys
 
 from .utils import find_orders, AdamaOptionParser
-
-
-class OrderError(Exception):
-    """
-    """
-    pass
-
+from .exceptions import UnknownOrderError, OrderError
 
 
 class QG(object):
     def usage(self):
         """Usage of the command
         """
-        return 'Usage: %prog order [options] [args]'
+        return 'Usage: {0} order [options] [args]'.format(self.command)
 
     @property
     def decrypter(self):
         options, args = self.decrypt(sysargs)
         try:
             result = self.execute(*args, **options.__dict__)
-        except OrderError, e:
-            sys.stderr.write(str(e))
-            sys.exit(1)
-
+        except OrderError as e:
+            return e()
+        return result
 
 class Commander(QG):
     """Program class
         epilog = """
 Type '{0} help <order>' for help on a specific order.
 
-Available orders:
-{1}
+{1}{2}
 
 """
+        create_help = "\n\nType 'adama create_order [options] {0} <order_name>' to create one"\
+                .format(self.module)
+        # Formats the epilog
+        decrypter.epilog = epilog.format(
+            self.command, self.available_orders, create_help if not self.__orders else ''
+        )
+
+        return decrypter
+
+    def get_order(self, name):
+        """Gives an order by name
+        """
+        return self.orders[name]
+
+    @property
+    def available_orders(self):
+        """
+        """
+        available = "Available orders:\n{0}"
         if self.orders:
             # Returns the longest line length that will be printed on terminal
             max_ordername_len = max((len(name) for name in self.orders))
                 for name, order in self.orders.items())
         else:
             # Help output when no orders can be found under package
-            available_orders = """
-No orders available.
-Type 'adama create_order [options] {0} <order_name>' to create one"""\
-                .format(self.module)
-        # Formats the epilog
-        decrypter.epilog = epilog.format(self.command, available_orders)
+            available_orders = "No orders available."
+        return available.format(available_orders)
 
-        return decrypter
-
-    def get_order(self, name):
-        """Gives an order by name
-        """
-        return self.orders[name]
 
     def __getitem__(self, key):
-        return self.get_order(key)
+        try:
+            return self.get_order(key)
+        except KeyError:
+            raise UnknownOrderError('The order "{0}" doesn\'t exist'\
+                .format(key), self)
 
     def execute(self, args, options):
         """Bad use of command so we print usage
     """
 
     def __init__(self, module, command=''):
-        super(BaseOrder, self).__init__(module, command='')
+        super(BaseOrder, self).__init__(module, command=command)
         self.name = self.__class__.__module__.split('.')[-1] \
 
     def usage(self):
         """Usage of a command
         """
-        return '%prog {0.name} [options] {0.args}'.format(self)
+        return 'Usage: {0.command} {0.name} [options] {0.args}'.format(self)
 
     @property
     def decrypter(self):
         decrypter = super(BaseOrder, self).decrypter
         decrypter.epilog = self.examples
         return decrypter
+
+    def __str__(self):
+        return self.usage()

File src/adama/exceptions.py

+# -*- coding: utf-8 -*-
+
+"""Adama's exceptions declaration
+"""
+
+
+class AdamaError(Exception):
+    """Base exception for adama
+    """
+
+    def __init__(self, msg, number=1):
+        self.message = msg
+        self.number = number
+
+    def print_error(self):
+        """Prints error in shell"""
+        raise NotImplementedError
+
+    def __str__(self):
+        return self.message
+
+    def __call__(self):
+        print(self.print_error())
+        return self.number
+
+
+class UnknownOrderError(AdamaError):
+    """
+    """
+
+    def __init__(self, msg, commander):
+        super(UnknownOrderError, self).__init__(msg, 11)
+        self.commander = commander
+
+    def print_error(self):
+        return '{0!s}\n\n{0.commander.available_orders}\n'\
+            .format(self)
+
+    def __str__(self):
+        return self.message
+
+    def __repr__(self):
+        return '<UnknownOrderError: {0.commander.command}>'.format(self)
+
+
+class OrderError(AdamaError):
+    """
+    """
+
+    def __init__(self, msg, order):
+        super(OrderError, self).__init__(msg, 12)
+        self.order = order
+
+    def print_error(self):
+        return '{0!s}\n{0.order!s}\n'.format(self)
+
+    def __repr__(self):
+        return '<OrderError: {0.name}>'.format(self.order)

File src/adama/orders/create_order.py

 import os
 from optparse import make_option
 
-from ..commandment import BaseOrder, OrderError
+from ..commandment import BaseOrder
+from ..exceptions import OrderError
 from . import get_template, get_module, get_command, touch
 
 
 
     def execute(self, *args, **options):
         if len(args) != 2:
-            raise OrderError('The create_program has 2 required arguments', self.usage())
+            raise OrderError('The create_order order has two required arguments', self)
 
         # adds a path to pythonpath if options has been selected
         # and if it is not already there and returns a module

File src/adama/orders/create_program.py

 import os
 from optparse import make_option
 
-from ..commandment import BaseOrder, OrderError
+from ..commandment import BaseOrder
+from ..exceptions import OrderError
 from . import get_module, get_template, get_command
 
 class Order(BaseOrder):
 
     def execute(self, *args, **options):
         if len(args) != 1:
-            raise OrderError('The create_program has one required argument',
-                self.usage())
+            raise OrderError('The create_program order has one required argument',
+                self)
 
         module = get_module(args[0], options['pythonpath'])
 

File src/adama/templates/order.template

 
 from optparse import make_option
 
-from adama.commandment import BaseOrder, OrderError
+from adama.commandment import BaseOrder
+from adama.exceptions import OrderError
 
 
 class Order(BaseOrder):