Update tools to generic template

Resolves openbmc/openbmc-test-automation#1232

Change-Id: I572c52c52ab9896dd6420bba119da61af371b5d4
Signed-off-by: manasarm <manashsarma@in.ibm.com>
diff --git a/tools/oem/ibm/gen_csv_results.py b/tools/oem/ibm/gen_csv_results.py
index 483a2c5..6236a97 100755
--- a/tools/oem/ibm/gen_csv_results.py
+++ b/tools/oem/ibm/gen_csv_results.py
@@ -1,25 +1,123 @@
-#!/usr/bin/python
+#!/usr/bin/env python
+
 r"""
-#############################################################
-#    @brief   Uses robot framework API to extract test result
-#             data from output.xml generated by robot tests.
-#             For more information on the Robot Framework API
-#             http://robot-framework.readthedocs.io/en/3.0
-#             /autodoc/robot.result.html
-#############################################################
+Use robot framework API to extract test result data from output.xml generated
+by robot tests. For more information on the Robot Framework API, see
+http://robot-framework.readthedocs.io/en/3.0/autodoc/robot.result.html
 """
-import sys
+
+import sys, os
 import getopt
 import csv
-from datetime import datetime
 import robot.errors
+import re
+from datetime import datetime
 from robot.api import ExecutionResult
 from robot.result.visitor import ResultVisitor
 from xml.etree import ElementTree
-import re
+
+# Remove the python library path to restore with local project path later.
+save_path_0 = sys.path[0]
+del sys.path[0]
+sys.path.append(os.path.join(os.path.dirname(__file__), "../../../lib"))
+
+from gen_arg import *
+from gen_print import *
+from gen_valid import *
+
+# Restore sys.path[0].
+sys.path.insert(0, save_path_0)
+
+parser = argparse.ArgumentParser(
+    usage='%(prog)s [OPTIONS]',
+    description="%(prog)s uses a robot framework API to extract test result\
+    data from output.xml generated by robot tests. For more information on the\
+    Robot Framework API, see\
+    http://robot-framework.readthedocs.io/en/3.0/autodoc/robot.result.html and\
+    https://gerrit.openbmc-project.xyz/#/c/8885/15/tools/oem/ibm/\
+    gen_csv_results.py",
+    formatter_class=argparse.ArgumentDefaultsHelpFormatter,
+    prefix_chars='-+')
+
+parser.add_argument(
+    '--source',
+    '-s',
+    help='The output.xml robot test result file path.')
+
+parser.add_argument(
+    '--dest',
+    '-d',
+    help='The directory path where the generated .csv files will go.')
+
+# Populate stock_list with options we want.
+stock_list = [("test_mode", 0), ("quiet", 0), ("debug", 0)]
+
+
+def exit_function(signal_number=0,
+                  frame=None):
+
+    r"""
+    Execute whenever the program ends normally or with the signals that we
+    catch (i.e. TERM, INT).
+    """
+
+    dprint_executing()
+
+    dprint_var(signal_number)
+
+    qprint_pgm_footer()
+
+
+def signal_handler(signal_number,
+                   frame):
+
+    r"""
+    Handle signals.  Without a function to catch a SIGTERM or SIGINT, the
+    program would terminate immediately with return code 143 and without
+    calling the exit_function.
+    """
+
+    # Our convention is to set up exit_function with atexit.register() so
+    # there is no need to explicitly call exit_function from here.
+
+    dprint_executing()
+
+    # Calling exit prevents us from returning to the code that was running
+    # when the signal was received.
+    exit(0)
+
+
+def validate_parms():
+
+    r"""
+    Validate program parameters, etc.  Return True or False (i.e. pass/fail)
+    accordingly.
+    """
+
+    if not valid_file_path(source):
+        return False
+
+    if not valid_dir_path(dest):
+        return False
+
+    gen_post_validation(exit_function, signal_handler)
+
+    return True
 
 
 def parse_output_xml(xml_file_path, csv_dir_path):
+
+    r"""
+    Parse the robot-generated output.xml file and extract various test
+    output data. Put the extracted information into a csv file in the "dest"
+    folder.
+
+    Description of argument(s):
+    xml_file_path  The path to a Robot-generated output.xml file.
+    csv_dir_path   The path to the directory that is to contain the .csv files
+                   generated by this function.
+    """
+
     result = ExecutionResult(xml_file_path)
     result.configure(stat_config={'suite_stat_level': 2,
                                   'tag_stat_combine': 'tagANDanother'})
@@ -112,16 +210,18 @@
 
 
 def xml_to_csv_time(xml_datetime):
+
     r"""
     Convert the time from %Y%m%d %H:%M:%S.%f format to %Y-%m-%d-%H-%M-%S format
     and return it.
 
-    Description of arguments:
-        datetime  The date in the following format: %Y%m%d %H:%M:%S.%f
-                  (This is the format typically found in an XML file.)
+    Description of argument(s):
+    datetime  The date in the following format: %Y%m%d %H:%M:%S.%f
+              (This is the format typically found in an XML file.)
 
     The date returned will be in the following format: %Y-%m-%d-%H-%M-%S
     """
+
     # 20170206 05:05:19.342
     l_str = datetime.strptime(xml_datetime, "%Y%m%d %H:%M:%S.%f")
     # 2017-02-06-05-05-19
@@ -130,13 +230,15 @@
 
 
 def get_system_details(xml_file_path):
+
     r"""
     Get the system data from output.xml generated by robot and return it.
     The list returned will be in the following order: [driver,platform]
 
-    Description of arguments:
-        xml_file_path  The relative or absolute path to the output.xml file.
+    Description of argument(s):
+    xml_file_path  The relative or absolute path to the output.xml file.
     """
+
     bmc_version = ""
     bmc_platform = ""
     with open(xml_file_path, 'rt') as output:
@@ -159,41 +261,22 @@
     return [str(bmc_version), str(bmc_platform)]
 
 
-def usage():
-    name = 'gen_csv_results.py'
-    print 'Usage: '
-    print name, '-s <source path> -d <destination path>'
-    print '\t-s | --source=  : output.xml robot test result file path'
-    print '\t-d | --dest=    : Where the *.csv file will be generated'
-    sys.exit()
+def main():
 
+    if not gen_get_options(parser, stock_list):
+        return False
 
-def main(argv):
+    if not validate_parms():
+        return False
 
-    source = ''
-    dest = ''
-    try:
-        opts, args = getopt.getopt(argv, "h:s:d:", ["source=", "dest="])
-    except getopt.GetoptError:
-        usage()
-
-    for opt, arg in opts:
-        if opt == '-h':
-            usage()
-        elif opt in ("-s", "--source"):
-            source = arg
-        elif opt in ("-d", "--dest"):
-            dest = arg
-
-    if source == '':
-        usage()
-        print 'ERROR: Provide input file path to robot generated output.xml '
-
-    if dest == '':
-        usage()
-        print 'ERROR: Destination directory where *.csv file will be generated'
+    qprint_pgm_header()
 
     parse_output_xml(source, dest)
 
-if __name__ == "__main__":
-    main(sys.argv[1:])
+    return True
+
+
+# Main
+
+if not main():
+    exit(1)