#!/usr/bin/env python3
# Copyright (c) 2007-2011 Arastra, Inc.  All rights reserved.
# Arastra, Inc. Confidential and Proprietary.

# Generate a pylint-able fdl and run pylint over it.

from __future__ import absolute_import, division, print_function

import argparse
import Tac

parser = argparse.ArgumentParser(
   description="Generate a pylint-able fdl called '*.fdl.pylint' from <fdlpath> " \
      "and run pylint over it. The '*.fdl.pylint' is created in the current " \
      "directory." )
parser.add_argument( 'fdlpath', type=str, help='path to the fdl')
parser.add_argument( '--py3k', action='store_true',
                     help='Check pylint --py3k in addition to normal pylint' )

args = parser.parse_args()

def replaceHeader( lineStr ):
   if ":" not in lineStr:
      return None
   ( name, value ) = lineStr.split( ":", 1 )
   name = name.strip()
   value = value.strip()
   return name + " = " + '"' + value + '"\n'

dummyVars = """
system = None
chassis = None
supe = None
cardplane = None
card = None

Value = lambda *args, **kwargs:None
Type = lambda *args, **kwargs:None
MacAddrAdd = lambda *args, **kwargs:None

"""

disableMsgs = [
   # dummyVars is inserted before the imports, and multi-fin fdls are unlikely to
   # have all imports at the top anyway.
   "wrong-import-position",
   "misplaced-future",
]

# pylint: disable-next=consider-using-f-string
disableStr = "\n".join( "# pylint: disable=%s" % m for m in disableMsgs ) + "\n\n"

with open( args.fdlpath, 'r' ) as fdlIn, \
       open ( args.fdlpath + ".pylint", 'w' ) as fdlOut:
   # Header.
   for line in fdlIn:
      if line == "\n":
         inHeader = False
         fdlOut.write( dummyVars )
         fdlOut.write( disableStr )
         break
      out = replaceHeader( line )
      if not out:
         continue
      fdlOut.write( out )

   # Fdl.
   for line in fdlIn:
      fdlOut.write( line )

def runPylint( fdlpath, py3k ):
   cmd = [ "a4", "pylint" ]
   if py3k:
      cmd.append( "--py3k" )
   cmd.append( fdlpath + ".pylint" )

   # Catch the exception so we exit more gracefully and don't drop into pdb.
   try:
      Tac.run( cmd )
   except Tac.SystemCommandError:
      return True

   return False

err = runPylint( args.fdlpath, False )
if args.py3k:
   err |= runPylint( args.fdlpath, True )

if err:
   print( "pylint failed. See errors above." )
   exit( 1 ) # pylint: disable=consider-using-sys-exit
