Difference between revisions of "LR fmt.py"

From PeformIQ Upgrade
Jump to navigation Jump to search
 
Line 294: Line 294:
[[Category:Python]]
[[Category:Python]]
[[Category:LoadRunner]]
[[Category:LoadRunner]]
[[Category:Examples]]

Latest revision as of 17:10, 19 July 2009

#!/usr/bin/env python
#
#-------------------------------------------------------------------------------

import os
import re
import sys
import getopt

#-------------------------------------------------------------------------------

from datetime import datetime

#-------------------------------------------------------------------------------
"""
  Reformat  LoadRuner scripts:

    Pass 1 - put selective logic around resources
    Pass 2 - Rejig spacing of ITEM data in requests

"""
#-------------------------------------------------------------------------------

debug_flg   = False
verbose_flg = False
debug_flg   = True

separator1  = '#' + 79 * '-'
separator2  = '\t#' + 76 * '-'

pass1_file  = None
pass2_file  = None

#-------------------------------------------------------------------------------

def replace(action):
   bak_file = 'bak/%s_%s.c' % (action, datetime.now().strftime('%Y%m%d%H%M%S'))

   if not os.path.exists('bak'):
      os.mkdir('bak')

   os.rename(src_file, bak_file)

   if pass2_file:
      os.rename(pass2_file, src_file)
   elif pass1_file:
      os.rename(pass1_file, src_file)

#-------------------------------------------------------------------------------

def rejig_item_data(action):
   global pass2_file

   spacer      = None
   block       = None
   l_name      = 0
   l_value     = 0
   in_ITEMDATA = False

   pass2_file = '%s.pass2' % action

   try:
      f_in = open(pass1_file, 'r')
   except:
      sys.exit(1)

   try:
      f_out = open(pass2_file, 'w')
   except:
      sys.exit(1)

   p   = re.compile('(  *)("Name=[^"]*") *, *("Value=[^"]*") *, *ENDITEM,(.*)')

   for line in f_in.readlines():
      line = line[:-1]
      line = line.replace('\t', '   ')

      if re.search('ITEMDATA', line):
         block   = []
         l_name  = 0
         l_value = 0
         spacer  = ''
         if debug_flg: print 'ITEMDATA Start'
         in_ITEMDATA = True
         f_out.write("%s\n" % line)
         continue

      if in_ITEMDATA and re.search('LAST', line):
         if debug_flg: print 'ITEMDATA End ========================================='
         in_ITEMDATA = False
         if debug_flg: print 'len block = %d' % len(block)
         block_txt = ''
         for b in block:
            line = "%s%s,%s%s,%sENDITEM,%s\n" % (
                spacer,
                b[1],
                (' '*(l_name - len(b[1]) + 2)),
                b[2],
                (' '*(l_value - len(b[2]) + 2)),
                b[3])
            block_txt += line
         f_out.write("%s" % block_txt)
         f_out.write("%sLAST);\n" % spacer)
         if debug_flg: print 'ITEMDATA End ========================================='
         spacer = None
         continue

      if in_ITEMDATA:
         if debug_flg: print line
         m = p.search(line)
         if m:
            if debug_flg: print '[%s][%s][%s][%s]' % (m.group(1), m.group(2), m.group(3), m.group(4))

            if not spacer:
               spacer = m.group(1)
            name   = m.group(2)
            value  = m.group(3)
            extra  = m.group(4)

            l = len(name)
            if l > l_name:
               l_name = l

            l = len(value)
            if l > l_value:
               l_value = l

            block.append((spacer, name, value, extra))
            continue

      f_out.write("%s\n" % line)

   f_in.close()
   f_out.close()

#-------------------------------------------------------------------------------

def reformat(action):
   global src_file, pass1_file

   indent      = False
   in_block    = False;
   is_resource = False;
   padding     = ''

   src_file    = '%s.c' % action
   pass1_file  = '%s.pass1' % action

   try:
      f_in = open(src_file, 'r')
   except:
      sys.exit(1)

   try:
      f_out = open(pass1_file, 'w')
   except:
      sys.exit(1)

   for line in f_in.readlines():
      line = line[:-1]

      # l = l.replace('\t','   ')

      if re.search('_[0-9][0-9]*"', line):
         l = re.sub('_[0-9][0-9]*"', '"', line)

      if re.search('^{$', line):
         f_out.write("{\n")
         f_out.write("%s\n\n" % separator2)
         continue

      if re.search('^}$', line):
         f_out.write("}  // %s\n" % action)
         continue

      if re.search('web_concurrent_end\(', line):
         in_block = False;
         padding  = ''
         f_out.write("\t%s\n" % line)
         f_out.write("\t}\n")
         f_out.write("\n%s\n" % separator2)
         continue

      if re.search('web_concurrent_start\(', line):
         in_block = True;
         if is_resource:
            is_resource = False
            # f_out.write("\t}\n")
            # f_out.write("\n%s\n" % separator2)
         else:
            padding  = '\t'
            f_out.write("%s\n\n" % separator2)
            f_out.write("\tif (resource_flg) {\n")
            f_out.write("\t%s\n" % line)
         continue

      if not in_block:
         if re.search('web_url\(', line):
            if re.search(r'\.[Gg][Ii][Ff]', line):
               new_resource = True
            elif re.search(r'\.[Jj][Ss]', line):
               new_resource = True
            elif re.search(r'\.[Cc][Ss][Ss]', line):
               new_resource = True
            else:
               new_resource = False
               if is_resource:
                  is_resource = False
                  padding     = ''
                  f_out.write("\t}\n")
                  f_out.write("\n%s\n\n" % separator2)

            if  new_resource and not is_resource:
               is_resource = True
               padding     = '\t'
               f_out.write("%s\n\n" % separator2)
               f_out.write("\tif (resource_flg) {\n")

         if re.search('web_submit_data\(', line):
            if is_resource:
               is_resource = False
               padding     = ''
               f_out.write("\t}\n")
               f_out.write("\n%s\n" % separator2)

      if len(line) > 0:
         f_out.write("%s%s\n" % (padding, line))
      else:
         f_out.write("\n")

   f_in.close()
   f_out.close()

#-------------------------------------------------------------------------------

def usage():
   USAGE = """
   
     Usage:
     
       $ lr__fmt.py -s Action
       
   """
   
   sys.stderr.write(USAGE)
   
#-------------------------------------------------------------------------------

def main(argv):
   global debug_flg, verbose_flg
   
   action      = None
   replace_flg = False

   #----- Process command line arguments ---------------------------------------

   try:
      opts, args = getopt.getopt(argv, "a:dhf:rs:v",
              ["action=", "debug", "help", "file=", "replace", "script=", "verbose"])
   except getopt.GetoptError:
      usage()
      sys.exit(2)
   else:
      for opt, arg in opts:
         if opt in ("-h", "--help"):
            usage()
            sys.exit(0)
         elif opt in ("-a", "--action"):
            action = arg
         elif opt in ("-f", "--file"):
            action = arg
         elif opt in ("-r", "--replace"):
            replace_flg = True
         elif opt in ("-s", "--script"):
            action = arg
         elif opt in ("-v", "--verbose"):
            verbose_flg = True

   reformat(action)
   rejig_item_data()

   if replace_flg:
      replace(action)

#-------------------------------------------------------------------------------

if __name__ == "__main__":
   main(sys.argv[1:])

#-------------------------------------------------------------------------------