#!/usr/bin/env python
from __future__ import print_function

import subprocess
import sys

from hooksettings import no_ci_triggered  # File extensions that don't trigger Travis CI

output       = subprocess.check_output(['git', 'diff', '--name-only',
                                                       '--cached'])
changedFiles = output.decode('utf-8').splitlines()

# Determine if a filename should trigger CI
def triggers_CI(filename):
    if filename.count('.') > 0:
        # Do CI if any file extensions are anything other than those in no_ci_trigged 
        #   (which might be something like ['md', 'text'])
        #   ie If all of the changed files are either markdown or text, skip CI. Otherwise, do CI as normal
        extension = filename.rsplit('.', 1)[1]
        print('Extension: %s' % extension)
        if extension in no_ci_triggered:
            return False # If the extensions is something like .md or .txt (no_ci_triggered)
        else:
            return True # If the extension is something like .py, (other than, for example, .md or .txt)
    else:
        return True # Do CI for files with no extension

print('%s files changed:' % len(changedFiles))
doCI = any([triggers_CI(filename) for filename in changedFiles]) # If any of the changed files triggers CI

# Load default commit into memory
with open(sys.argv[1], 'r') as defaultcommit:
    defaultMsg = defaultcommit.read()

# Overwrite it:
with open(sys.argv[1], 'w') as commit:
    commit.write(defaultMsg)
    if not doCI:
        commit.write(
            '# The line below will skip Travis CI.\n' + 
            '# If this is not what you want, delete it.\n' + 
            '[ci skip]\n')

