Although our IDE comes with plugins to check linting, sometimes in development, we rush to commit files to meet dateline and forgot about linting.

In a previous post, you can see how to setup a precommit code that automatically trigger lint checker in only 10 minutes with full source code.

The problem with that is in angular development, when we run the following code

ng lint

we will run lint check for all the files. This will take a while. As you commit , you might wonder, why the check runs all the files?
It should only check the files i commit staged for push.

Fret not, this post will show a way , we can do that. Of course there are other ways to achieve same things.

Find the source code here.

Checkout the 2 files


In this approach we will do the following in sequence
I) configure command to trigger node program during precommit
II) invoke a node program that invoke commands
III) use commands of git to check what is staged files
IV) using the file list, trigger command of ng lint to check each of that specific file

First we we write a git command to check committed / staged files

git diff --name-only --cached

This will give you all the list of files you commit but not yet pushed.

Then we we write a cross-compatible platform command for linux,macos,windows checking lint of that specific file.

ng lint | findstr [yourfilename]

ng lint | grep [yourfilename]

This will do lint check specifically on the specific file.

Finally , we write the node program here. To access commands in node program, repl, we install shelljs for our program to invoke commands

npm i --save shelljs

const { exec } = require('child_process');
const fs = require('fs');

function execCommand(command, errorCallback, successCallback) { 

    const shell = require('shelljs');
    shell.exec(command, { silent: true }, function (code, stdout, stderr) { 
        if (stderr) { 	

const callbackLintFiles = function (response) {
const callBackListFiles = function (response) {
    const listFiles = response.split('\n');

    for (let i = 0; i < listFiles.length; i++) {
        if (listFiles[i]) {
            let command = `ng lint | findstr ${listFiles[i]}`; 
            execCommand(command, callbackLintFiles, callbackLintFiles);

            command = `ng lint | grep ${listFiles[i]}`; 
            execCommand(command, callbackLintFiles, callbackLintFiles);
const cmd = 'git diff --name-only --cached';
execCommand(cmd, callBackListFiles, callBackListFiles);

Be sure to checkout the full git source code here.

Leave a Reply

Your email address will not be published. Required fields are marked *