]> Frank Brehm's Git Trees - pixelpark/admin-tools.git/commitdiff
Command line processing in format-du.py and pp_lib/format_du.py
authorFrank Brehm <frank.brehm@pixelpark.com>
Wed, 15 Mar 2017 11:03:13 +0000 (12:03 +0100)
committerFrank Brehm <frank.brehm@pixelpark.com>
Wed, 15 Mar 2017 11:03:13 +0000 (12:03 +0100)
format-du.py
pp_lib/format_du.py

index 3292d5b1eea2dbce9d6d21d10f7986a5ba5646b5..e57de8b973be39a607eb19d10effaca8c0d3f847 100755 (executable)
@@ -23,8 +23,10 @@ log = logging.getLogger(__name__)
 __author__ = 'Frank Brehm <frank.brehm@pixelpark.com>'
 __copyright__ = '(C) 2017 by Frank Brehm, Pixelpark GmbH, Berlin'
 
+appname = os.path.basename(sys.argv[0])
 
-app = FormatDuApp()
+
+app = FormatDuApp(appname=appname)
 #app.initialized = True
 
 if app.verbose > 2:
index d2a2a7c19f56d01c9f9de0677d0ae6c0b8da57a0..804310e4afe625e6ab8366df737d3fd686b93725 100644 (file)
@@ -11,6 +11,7 @@ from __future__ import absolute_import
 # Standard modules
 import logging
 import textwrap
+import sys
 
 import six
 
@@ -34,14 +35,22 @@ class FormatDuApp(PpApplication):
     Application class for the format-du command
     """
 
+    units = ['K', 'k', 'M', 'm', 'G', 'g', 'H', 'h']
+
+    unit_exp = {
+        'K': 0,
+        'M': 1,
+        'G': 2,
+    }
+
     # -------------------------------------------------------------------------
     def __init__(
-            self, verbose=0, version=my_version, *arg, **kwargs):
+            self, appname=None, verbose=0, version=my_version, *arg, **kwargs):
 
         indent = ' ' * self.usage_term_len
 
         usage = textwrap.dedent("""\
-        %(prog)s [General options] [Format options] [FILE]
+        %(prog)s [--color [{{yes,no,auto}}]] [-v] [Format options] [FILE]
 
         {i}%(prog)s --usage
         {i}%(prog)s -h|--help
@@ -50,9 +59,15 @@ class FormatDuApp(PpApplication):
 
         desc = """Formats the output of 'du -k' for various modifiers."""
 
+        self.precision = 0
+        self.unit = 'K'
+        self.factor = 1
+        self.total = False
+
         super(FormatDuApp, self).__init__(
             usage=usage,
             description=desc,
+            appname=appname,
             verbose=verbose,
             version=version,
             *arg, **kwargs
@@ -61,6 +76,75 @@ class FormatDuApp(PpApplication):
         self.post_init()
         self.initialized = True
 
+    # -------------------------------------------------------------------------
+    def init_arg_parser(self):
+        """
+        Method to initiate the argument parser.
+        """
+
+        super(FormatDuApp, self).init_arg_parser()
+
+        format_options = self.arg_parser.add_argument_group('Format options')
+
+        format_options.add_argument(
+            '-c', '--total',
+            action='store_true', dest='total',
+            help="Produces a grand total",
+        )
+
+        format_options.add_argument(
+            '-u', '--unit',
+            dest='unit', metavar='UNIT',
+            choices=self.units,
+            help=(
+                "Unit for displaying the results. Valid units are: 'K' (KiBytes, the default), "
+                "'M' (MiBytes), 'G' (GiBytes) and 'H' (human readable, the most appropriate unit "
+                "will be used. In case of 'K', no unit will be displayed.")
+        )
+
+        format_options.add_argument(
+            '-p', '--precision',
+            type=int, default=0, metavar='DIGITS',
+            help="Number of digits for displaying the result (default: %(default)r).",
+        )
+
+        self.arg_parser.add_argument(
+            'file',
+            metavar='FILE', type=str, nargs='?',
+            help=(
+                'A file with the output of "du -k". If not given or "-", then '
+                'the standard input will be read.'),
+        )
+
+
+    # -------------------------------------------------------------------------
+    def perform_arg_parser(self):
+        """
+        Public available method to execute some actions after parsing
+        the command line parameters.
+
+        Descendant classes may override this method.
+        """
+
+        if self.args.total:
+            self.total = True
+
+        if self.args.unit:
+            self.unit = self.args.unit.upper()
+            if self.unit in self.unit_exp:
+                exp = self.unit_exp[self.unit]
+                self.factor = 1024 ** exp
+
+        if self.args.precision is not None:
+            if self.args.precision < 0:
+                p = self.colored('{!r}'.format(self.args.precision), 'RED')
+                LOG.error("Invalid precision {}, it must not be less than zero.".format(p))
+                sys.stderr.write('\n')
+                self.arg_parser.print_help(sys.stderr)
+                self.exit(1)
+            self.precision = self.args.precision
+
+
     # -------------------------------------------------------------------------
     def _run(self):
         """The underlaying startpoint of the application."""