Using eslint for pre-commit hooks in Git

Is there a way to run eslint on files in the pre-commit script when they are in the add stage?

I've placed the .eslintrc file in the hooks folder.

Additionally, I have the following script:

#!/bin/sh
#
# An example hook script to verify what is about to be committed.
# Called by "git commit" with no arguments.  The hook should
# exit with non-zero status after issuing an appropriate message if
# it wants to stop the commit.
#
# To enable this hook, rename this file to "pre-commit".

function lintit () {
  a=("${(f)$(git diff --name-only | grep -E '(.js)$')}")
  e=$(eslint -c eslint.json $a)
  echo $e
  if [[ "$e" != *"0 problems"* ]]; then
    echo "ERROR: Check eslint hints."
    exit 1 # reject
  fi
}
lintit

However, the script doesn't seem to pick up the eslint configuration from the .eslintrc file.

Appreciate any assistance!

Answer №1

Here are two potential issues with your script:

  • The file may not have the executable flags set
  • Your sub shell expression seems to be incorrect

In order for Git to execute properly on unixoid systems, it requires the correct executable flags.

$ chmod ug+x .git/hooks/pre-commit

If you haven't encountered any error messages yet, this could be the reason for it.

Additionally, there is a syntax error in your script:

a=("${(f)$(git diff --name-only | grep -E '(.js)$')}")
e=$(eslint -c eslint.json $a)

A better approach would be:

a="$( git diff --name-only | grep -E '(.js)$' )"
e=$( eslint -c eslint.json $a )

Further Enhancements

Simplify result checking

When eslint finds an error, it exits with a non-zero exit code.

eslint ${ESLINT_CONF} $( ... )
if [ $? -ne 0 ]; then
    echo "eslint has detected errors."
    exit 1
fi

If no echo message is needed, simply having the eslint statement at the end will cause the shell to exit based on that command's exit code.

Keep in mind that using the exit code method does not allow you to detect warnings since eslint exits with a positive code (zero) for warnings.

Include New Files in Checks

The current git diff statement won't include newly added files. Consider using git status instead:

git status --porcelain | awk '{print $2}'  | grep -E '(.js)$'

Finalized Script

#!/bin/sh

ESLINT_CONF=".eslintrc.json"

eslint ${ESLINT_CONF} $( git status --porcelain | awk '{print $2}' | grep -E '(.js)$' ) >/dev/null
if [ $? -ne 0 ]; then
    echo "ERROR: Check eslint hints."
    exit 1
fi

exit 0

Alternatively, a simplified version...

#!/bin/sh

ESLINT_CONF=".eslintrc.json"

eslint ${ESLINT_CONF} $( git status --porcelain | awk '{print $2}' | grep -E '(.js)$' ) >/dev/null

Or, with warning checks implemented...

#!/bin/sh

ESLINT_CONF=".eslintrc.json"

RES="( eslint ${ESLINT_CONF} $( git status --porcelain | awk '{print $2}' | grep -E '(.js)$' ) )"

if [ $? -ne 0 ] || [[ "${RES}" != *"0 warning"* ]]; then
    echo "ERROR: Check eslint hints."
    exit 1
fi

Remove >/dev/null (scripts 1 and 2) or echo "${RES}" (script 3) to display the eslint output.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

AngularJS personalized date selector directive

Looking to create a unique datepicker directive with a personalized template. Feeling lost on where to begin constructing it... Any suggestions on incorporating date data into my directive? Your guidance or tips on how to approach this project more effe ...

Tips for incorporating HTML code within a select option value?

I am working with AngularJS to create a Visual Composer for a website. One feature I want to incorporate is the ability to add HTML code based on the selection made in a dropdown menu. However, I am struggling to figure out how to include the HTML within t ...

In certain environments, Express.js may fail to recognize specific endpoints during registration

This is the snippet from my index.ts file. I compiled it using TS with the following build command: "tsc -p ./tsconfig.json && cp -R ./src/adminUI ./dist" const db = mongoose.connection; const app = express(); // TODO: whitelist app.use(cors()); ...

Is it necessary to replace Tomcat with Node.js?

I'm exploring building a server with node.js and wondering if I need tomcat as well. I'm new to this, so any insight on these basic concepts would be greatly appreciated. Thank you in advance! ...

What is the best way to keep track of choices made in 'mat-list-option' while using 'cdk-virtual-scroll-viewport'?

I have been working on implementing mat-list-option within cdk-virtual-scroll-viewport in an Angular 14 project. I came across a demo project in Angular 11 that helped me set up this implementation. In the Angular 11 demo, scrolling functions perfectly an ...

JSplumb - retrieve a connection targeting a particular endpoint

There are multiple endpoints on my elements. By using the following code snippet, I am able to retrieve all the connections linked to a specific element: // My JSPlumb instance object is named plumber connSet = plumber.getConnections({target:eltID}); Th ...

Placing an object to the right side

I'm currently developing an app using React Native and I need to position something on the right side of the screen. <View style={searchDrop}> <TextInput style={textInput} placeholder="Search Coin ...

Don't select the next letter when the right arrow key is pressed in JavaScript

When using a textarea with a keydown event, I noticed that when typing and then moving the cursor to the middle and pressing the right arrow key, the next letter gets highlighted. Is there a way to prevent this highlighting from occurring? Interestingly, ...

Access the document on the desktop and open it in a new popup window

As a novice in html coding, I'm wondering if it's possible to write window size and other properties directly into the page. Let me explain. I'm currently working on a calculator and I want to run the HTML file on my desktop. Everything wor ...

Most effective method for integrating a JS module across all browsers

I have created a robust library that I want to integrate into a different web project. This library handles all its dependencies and consists of js, css, and html files. My ideal scenario would be to package it as an npm module and simply use import to in ...

Issues with Await and Async functionality in Angular and Ionic 4 causing unexpected behavior

Struggling to show error messages during the sign-up process? Constantly encountering the same issue in your code? The error TS1308 is throwing you off: 'await' expression is only allowed within an async function. Take a look at this problemati ...

HTML element resizing unexpectedly due to browser interactions

I recently created a sleek HTML transparent header bar using the following CSS: #head-bar{ position:fixed; top: 0px; width:100%; left:0px; min-height:25%; z-index:2; background-color:#000; background: rgba(0, 0, 0, 0.5); } ...

Creating a soft focus effect in a specific region (behind the text)

While working on my homepage created with HTML/CSS/Javascript, I have text positioned at the top left corner of the screen. The challenge arises from the fact that I am using different backgrounds sourced from Reddit, and a script randomly selects one duri ...

Possible solutions for AngularJS using ng- tags

I absolutely love incorporating AngularJs into my Multiple Pages Laravel Application. However, using the Laravel Blade Template Engine has made me reconsider adding Angular Tags to clutter my blade templates. For instance <div ng-controller="TodoCont ...

Is there a method to use media queries to dynamically switch JavaScript files based on the user's device?

I've been working on optimizing the mobile layout of my website, and while I have successfully implemented a media query with a different stylesheet for mobile devices, I'm struggling to determine if it's feasible to also load a separate Jav ...

What is the best way to assign multiple values to a single key without replacing the existing value?

My goal is to store multiple values for a single key by utilizing arrays within my main object. I've been struggling with this and feeling discouraged, questioning why I thought I could accomplish it. Can someone provide guidance on the best approach ...

Is Socket.io exclusive to browsers?

Similar Question: Using socket.io standalone without node.js How to run socket.io (client side only) on apache server My website is hosted on a Linux server with shared hosting. Since I don't have the ability to install node.js, I am looking ...

jQuery scripts were not loaded, resulting in an uncaught type error

Hey there! I am currently using jQuery Tablesorter to handle pagination on my website, but it seems to be throwing an error in the browser console. The specific error message reads: Uncaught TypeError: undefined is not a function viewTags:24 (anonymous fu ...

What could be causing the format to be incorrect?

docker run -it -v "%cd%":/e2e -w /e2e cypress/included:6.2.1 --browser chrome When attempting to execute this command within Visual Studio Code, an error is encountered: docker: invalid reference format. See 'docker run --help' Vario ...

Unable to fulfill all the promises in JavaScript

As I develop a filter feature, I have categories and cities in the format: ['New York'], ['Cars']. The goal is to iterate through them to retrieve products based on each city or category. My approach involves storing these products in t ...