# Copyright (c) 2016, Genevolv LLC.  All rights reserved.

'''The pylint assessment.'''

import logging
LOG = logging.getLogger(__name__)

import os
from freevolv.test.jenkins.common import job_parent

class Pylint(job_parent.JobParent):
    '''Executes a pylint assessment.'''

    help_banner = 'Pylint assessment'

    #-------------------------------------
    # All command line arguments go here.
    #-------------------------------------
    parse_args = {}
    parse_args['pkg'] = {
        'action':'store',
        'help':'Module or package to run pylint assessment against.',
    }
    parse_args['--exedir'] = {
        'action':'store',
        'default':'.',
        'dest':'exedir',
        'help':'Relative path of directory to execute pylint from.',
    }
    parse_args['--rcfile'] = {
        'action':'store',
        'help':'Relative path to a pylint configuration file.',
        'dest':'rcfile',
    }

    def __init__(self, args=None):
        super(Pylint, self).__init__(args)
        self.help_banner = Pylint.help_banner
        self.parse_args = Pylint.parse_args
        self.old_dir = os.path.realpath(os.getcwd())
        self.rcfile = None

    def cd_to_exedir(self):
        ''' Change to the directory where pylint should run.'''
        if self.arguments.exedir != '.':
            LOG.debug('exedir: ' + self.arguments.exedir)
            exedir = os.path.realpath(self.arguments.exedir)
            LOG.debug('changing directory to ' + exedir)
            os.chdir(exedir)

    def cd_to_orig(self):
        ''' Return to the directory where this script was called from.'''
        if self.arguments.exedir != '.':
            LOG.debug('returning to directory ' + self.old_dir)
            os.chdir(self.old_dir)

    def check_config(self):
        ''' Verify the path of the configuraiton file given.'''
        if self.arguments.rcfile != None:
            self.rcfile = os.path.realpath(self.arguments.rcfile)
            if not os.path.exists(self.rcfile):
                LOG.error('File not found: ' + self.rcfile + '.  Attempting '
                          'to continue.')

    def main(self):
        '''Run pylint in location specified.'''
        from freevolv.utils import shell

        self.argparse()
        self.check_config()
        self.cd_to_exedir()

        cmd = ['pylint', '--version']
        shell.exe_cmd(cmd)
        cmd = ['pylint', '-f', 'parseable', self.arguments.pkg]
        if self.rcfile != None:
            cmd.append('--rcfile=' + self.rcfile)
        rcode = shell.exe_cmd(cmd, 'pylint.out')
        rtn = rcode & 0x1

        self.cd_to_orig()

        return rtn


if __name__ == '__main__':
    import sys
    sys.exit(Pylint(sys.argv).main())


