Skip to content

Instantly share code, notes, and snippets.

@el-ethan
Created January 6, 2019 20:16
Show Gist options
  • Save el-ethan/74bb0b3a17b10daca90a67224c82757d to your computer and use it in GitHub Desktop.
Save el-ethan/74bb0b3a17b10daca90a67224c82757d to your computer and use it in GitHub Desktop.
Lint js files with changes before commit.

Place the following in .git/hooks/pre-commit:

#!/bin/sh

node ./pre-commit.js

exit $?

Place the following in pre-commit.js in the root of your repo:

const { exec } = require('child-process-promise');
const process = require('process');

async function getFilesToLint() {
    const filesToLint = await exec('git diff HEAD --name-only').then(({stdout}) => {
        const files = stdout.split('\n');
        const filesToOmit = ['app.js'];
        const filesToLint = files.filter(thisFile => {
            return thisFile.endsWith('.js') && !filesToOmit.includes(thisFile);
        });
        return filesToLint;
    });
    return filesToLint;
}

async function lintFiles() {
    const lintingOutput = [];
    const filesToLint = await getFilesToLint();
    return exec(`eslint ${filesToLint.join(' ')}`)
        .then(({stdout}) => {
            return {exitCode: 0, output: stdout};
        })
        .catch(({stdout}) => {
            return {exitCode: 1, output:stdout};
        });
}

async function main() {
    const results = await lintFiles();
    if (results.exitCode === 1 && results.output) {
        console.log(results.output);
        console.log('You have some linting errors. Please see the output above and fix the errors our ignore them and commit using XXXX');
    }
    process.exit(results.exitCode);
}

main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment