In a large JavaScript/TypeScript codebase, maintaining code quality while ensuring rapid development can be a daunting task. One of the widely used tools is a linter, which helps to enforce coding standards and avoid common issues. However, running a linter on an entire codebase can be time-consuming and often unproductive like on a legacy project. Thus, running a liter for only changed files lead to quicker CI jobs, which will enhance the overall development workflow.
This blog post will guide you on how to run a linter for only the changed files in a Node.js project.
The first step is to identify which files have been changed. You can use Git commands to achieve this.
For example, to list all modified files in comparison to main
branch we can use the following command:
git --no-pager diff --name-only --diff-filter=d origin/master...$(git rev-parse --abbrev-ref HEAD)
Let’s break it down step by step:
--no-pager
flag runs the Git command without invoking the pager, which means the output will be printed directly to the terminal.
diff
command is used here to show differences between commits, branches, or the working directory.
--name-only
modifies the git diff
output to show only the names of the files that have changed, instead of the full diff.
--diff-filter=d
filters the output of diff
to exclude deleted files. The d
stands for deleted.
origin/master...$(git rev-parse --abbrev-ref HEAD)
specifies the range for the git diff
command. In this case it compares the current branch to the main
branch.
Furthermore we can add one more command to it, and that’s to include only specific files, eg: typescript or javascript files.
git --no-pager diff --name-only --diff-filter=d origin/master...$(git rev-parse --abbrev-ref HEAD) -- '*.ts'
This later modification of the initial command is that, we can pass only specific file types to the linter.
If we were using eslint
, the full command could look like this:
eslint --quiet $(git --no-pager diff --name-only --diff-filter=d origin/master...$(git rev-parse --abbrev-ref HEAD) -- '*.ts')
When this command gets executed in CI/CD tool, it will run the linter only for the changed file.