# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
# Copyright (C) 2013 Canonical Ltd.
# Author: Loïc Minier <loic.minier@ubuntu.com>

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 3 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

"""Static checkers against source files."""

import subprocess
import testtools

from setup import PYTHON_SCRIPTS, SH_SCRIPTS


# external script which is only pyflakes-clean, not pep8-clean
PEP8_EXCLUDES = ["repo", ]


def has_command(command):
    """Returns whether a command is in  the PATH or not."""
    returncode = subprocess.call(['which', command],
                                 stdout=open('/dev/null', 'w'))
    return returncode == 0


def get_output(command):
        proc = subprocess.Popen(command,
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE)
        return proc.communicate()


class TestStaticCheckers(testtools.TestCase):
    @testtools.skipUnless(has_command("checkbashisms"),
                          "checkbashisms not found")
    def test_bashisms(self):
        (stdout, stderr) = get_output(['checkbashisms', ] + SH_SCRIPTS)
        self.assertEquals('', stdout)
        self.assertEquals('', stderr)

    @testtools.skipUnless(has_command("pep8"), "pep8 not found")
    def test_pep8(self):
        scripts = [p for p in PYTHON_SCRIPTS if p not in PEP8_EXCLUDES]
        (stdout, stderr) = get_output(['pep8', '.'] + scripts)
        self.assertEquals('', stdout)
        self.assertEquals('', stderr)

    @testtools.skipUnless(has_command("pyflakes"), "pyflakes not found")
    def test_pyflakes(self):
        (stdout, stderr) = get_output(['pyflakes', '.'] + PYTHON_SCRIPTS)
        self.assertEquals('', stdout)
        self.assertEquals('', stderr)

    def test_sh_syntax(self):
        (stdout, stderr) = get_output(['sh', '-n'] + SH_SCRIPTS)
        self.assertEquals('', stdout)
        self.assertEquals('', stderr)
