Skip to content

Add eslint precommit#96

Merged
adithya-naik merged 10 commits into
developfrom
add-eslint-precommit
Jun 28, 2026
Merged

Add eslint precommit#96
adithya-naik merged 10 commits into
developfrom
add-eslint-precommit

Conversation

@adithya-naik

@adithya-naik adithya-naik commented Jun 28, 2026

Copy link
Copy Markdown
Owner

What this PR does

closes #95

This PR adds a complete ESLint v9 setup with pre-commit hooks and CI linting to enforce code quality across the project.

Changes made

1. ESLint v9 with Flat Config

  • Migrated from .eslintrc.json (deprecated in v9) to modern eslint.config.js (flat config)
  • Added caughtErrors: "none" to ignore unused variables in catch blocks (avoids unnecessary code changes)
  • Rules enforced: single quotes, semicolons, 2-space indentation, no unused variables

2. Pre-commit Hook (Husky + lint-staged)

  • Added Husky v9 for Git hooks management
  • Added lint-staged to run ESLint only on staged .js files
  • Pre-commit hook automatically runs eslint --fix on staged files before committing
  • Bad commits are blocked if lint errors exist

3. CI/CD Integration

  • Added lint job to .github/workflows/ci.yml
  • Runs npm run lint on every PR
  • PRs with lint errors will show and cannot be merged (once branch protection is enabled)

4. Fixed All Existing Lint Errors

  • 640+ errors auto-fixed using npm run lint:fix (quotes, indentation, semicolons)
  • 1 manual fix for an empty catch block in src/utils/hook.js
  • Codebase now 100% lint-clean

5. Developer Experience

  • Added "prepare": "husky install" script to package.json
  • Other developers get Husky automatically when they run npm install
  • Updated lint-staged config to remove deprecated git add command

Commands added

bash
npm run lint        # Check for lint errors
npm run lint:fix    # Auto-fix lint errors

Summary by CodeRabbit

  • New Features

    • Added linting checks in the CI pipeline and a pre-commit hook to catch formatting issues earlier.
    • Added project lint commands for checking and auto-fixing code.
  • Bug Fixes

    • Improved initialization feedback with clearer messages for permission, disk space, and setup issues.
    • Refined export, search, list, stats, favorites, and hook command messages for clearer user output.
  • Chores

    • Updated project version and added developer tooling for code quality and commit-time checks.

@coderabbitai

coderabbitai Bot commented Jun 28, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@adithya-naik, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 53 minutes and 25 seconds. Learn how PR review limits work.

Your organization has used up its prepaid credits, and credit purchases are no longer available. Enable the review add-on in the billing tab to keep reviews running — you're only billed for reviews past your plan's rate limits ($0.25/file).

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based credits.

🚦 How do rate limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: f238560e-6a98-4699-ac45-bb90d5a5167a

📥 Commits

Reviewing files that changed from the base of the PR and between ada2bfa and d36b1b9.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (2)
  • package.json
  • src/commands/clear.js
📝 Walkthrough

Walkthrough

Adds ESLint flat configuration, husky pre-commit hook with lint-staged, and a CI lint job. Applies the resulting single-quote style rule across all source files. src/commands/clear.js was accidentally replaced with a copy of the ESLint config, removing clearCommand. export.js gains actual file-writing implementation for JSON and CSV exports.

Changes

ESLint Setup and Single-Quote Style Enforcement

Layer / File(s) Summary
ESLint config, package scripts, and CI lint job
eslint.config.js, package.json, .husky/pre-commit, .github/workflows/ci.yml
Adds eslint.config.js with flat config (single quotes, semicolons, 2-space indent, Node/ES2021 globals). package.json gains lint, lint:fix, prepare scripts and eslint/husky/lint-staged devDependencies. .husky/pre-commit runs npx lint-staged. CI gains a lint job running npm run lint on PRs.
clear.js accidentally replaced with ESLint config
src/commands/clear.js
The entire clearCommand implementation was removed and the file now exports a duplicate ESLint configuration array, breaking the clear CLI command.
export.js JSON/CSV file writing
src/commands/export.js
Implements fs.writeFileSync for tracker-export.json and tracker-export.csv, adds success logging with file paths, an Excel/Sheets hint for CSV, and dedicated catch blocks for write failures.
Single-quote style across all source files
bin/tracker.js, src/commands/..., src/utils/..., src/index.js
Applies single-quote string literals uniformly across all source files. init.js also adds EACCES/ENOSPC specific error handling in the catch block.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

  • adithya-naik/cmd-tracker#92: Modifies .github/workflows/ci.yml around the same validate job structure that this PR also edits when adding the lint job.

Poem

🐇 A rabbit tidied up the quotes one day,
Single marks where double used to stay.
ESLint now watches every line,
Husky guards commits — all looks fine!
But clear.js got a curious swap,
Its commands replaced — a config mishap! 🪄

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title matches the main change: adding ESLint with a pre-commit hook.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch add-eslint-precommit

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/commands/export.js (1)

69-80: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Escape embedded quotes before writing CSV.

item.command can legitimately contain ". Right now Line 75 wraps the field in quotes but never doubles embedded quotes, so commands like git commit -m "msg" produce malformed CSV that Excel/Sheets and other parsers won't round-trip correctly.

Proposed fix
 function exportAsCSV(data, total) {
 
   try {
+    const escapeCsv = (value) => `"${String(value).replace(/"/g, '""')}"`;
     let csvContent = 'category,command,date\n';
 
     for (const [category, commands] of Object.entries(data)) {
       for (const item of commands) {
         const date = new Date(item.time).toLocaleDateString();
-        csvContent += `${category},"${item.command}",${date}\n`;
+        csvContent += [
+          escapeCsv(category),
+          escapeCsv(item.command),
+          escapeCsv(date)
+        ].join(',') + '\n';
       }
     }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/commands/export.js` around lines 69 - 80, The CSV export in export.js
writes item.command directly inside quoted fields, so embedded double quotes can
break the output. Update the CSV generation inside the loop that builds
csvContent to escape/double any quotes in item.command before concatenating it,
keeping the rest of the export flow and filePath/writeFileSync logic unchanged.
🧹 Nitpick comments (1)
.github/workflows/ci.yml (1)

14-31: 🩺 Stability & Availability | 🔵 Trivial

Broaden CI beyond lint-only coverage.

npm run lint plus the current --version smoke test still won't execute subcommand handlers, so regressions like the src/commands/clear.js replacement can merge unnoticed. Adding one lightweight invocation per command module here would catch that class of breakage much earlier.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @.github/workflows/ci.yml around lines 14 - 31, The CI workflow is only
running linting, so it can miss regressions in command handlers like the recent
clear command change. Update the lint job in the workflow to add at least one
lightweight execution for each command module, alongside the existing npm run
lint step, so the handlers are actually exercised during CI. Use the existing
command entry points and module names such as clear and the other subcommand
modules to wire in these smoke invocations.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/commands/clear.js`:
- Around line 1-30: The module currently exports ESLint config instead of the
clear command, so restore the command implementation in clearCommand and keep
this file exporting that handler again; move the ESLint array into
eslint.config.js (or equivalent config entry) so bin/tracker.js can still import
clearCommand and invoke tracker clear without runtime failure. Locate the
affected export by the clearCommand symbol and replace the config export with
the original command logic.

In `@src/commands/init.js`:
- Around line 148-149: The fallback .gitignore guidance in the init flow is
incomplete because it only mentions .tracker/ while the init command also treats
tracker-export.json and tracker-export.csv as local-only artifacts. Update the
warning message in the init command’s fallback logging so it tells users to
ignore all three paths, keeping the guidance consistent with the rest of the
export handling in init.js and preventing accidental commits of exported
history.
- Around line 128-135: The init flow is appending duplicate .gitignore content
because `entriesToAdd` is already written in the `init.js` logic and then
`trackerEntry` is appended again immediately after. Remove the second
`fs.appendFileSync(gitignorePath, trackerEntry)` in this block so the
`entriesToAdd` write is the only .gitignore update, keeping the existing log
messages tied to the single append.

In `@src/commands/search.js`:
- Around line 79-81: The search highlighting in the command matching flow builds
a RegExp directly from user input, which can break on special characters and
produce incorrect matches. Update the logic in the search command path around
the item.command replace call to escape the searchTerm before passing it to new
RegExp, keeping isValidQuery as-is and ensuring the highlighted output still
uses the escaped pattern safely.

In `@src/commands/stats.js`:
- Around line 52-71: The package-managers category key is inconsistent across
statsCommand and the shared category contract, so the icon lookup falls back to
the default. Update the icons map in statsCommand to use the same lowercase key
as src/utils/validator.js and src/commands/list.js (the packagemanagers symbol)
so the category resolves to the intended icon instead of others. Use the
existing statsCommand icons object as the place to align the key name.

---

Outside diff comments:
In `@src/commands/export.js`:
- Around line 69-80: The CSV export in export.js writes item.command directly
inside quoted fields, so embedded double quotes can break the output. Update the
CSV generation inside the loop that builds csvContent to escape/double any
quotes in item.command before concatenating it, keeping the rest of the export
flow and filePath/writeFileSync logic unchanged.

---

Nitpick comments:
In @.github/workflows/ci.yml:
- Around line 14-31: The CI workflow is only running linting, so it can miss
regressions in command handlers like the recent clear command change. Update the
lint job in the workflow to add at least one lightweight execution for each
command module, alongside the existing npm run lint step, so the handlers are
actually exercised during CI. Use the existing command entry points and module
names such as clear and the other subcommand modules to wire in these smoke
invocations.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 2d89fedb-905c-4962-bd8d-55f3290ef666

📥 Commits

Reviewing files that changed from the base of the PR and between 31f4f35 and ada2bfa.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (19)
  • .github/workflows/ci.yml
  • .husky/pre-commit
  • bin/tracker.js
  • eslint.config.js
  • package.json
  • src/commands/clear.js
  • src/commands/export.js
  • src/commands/favorite.js
  • src/commands/hook.js
  • src/commands/init.js
  • src/commands/list.js
  • src/commands/save.js
  • src/commands/search.js
  • src/commands/stats.js
  • src/index.js
  • src/utils/categorizer.js
  • src/utils/hook.js
  • src/utils/storage.js
  • src/utils/validator.js

Comment thread src/commands/clear.js Outdated
Comment thread src/commands/init.js
Comment thread src/commands/init.js
Comment thread src/commands/search.js
Comment thread src/commands/stats.js
@adithya-naik adithya-naik merged commit d756187 into develop Jun 28, 2026
4 checks passed
@sonarqubecloud

Copy link
Copy Markdown

adithya-naik added a commit that referenced this pull request Jun 28, 2026
* chore: bump version to 1.0.1 [skip ci]

* chore: trigger publish workflow

* chore: bump version to 1.0.2 [skip ci]

* chore: add ESLint v9 with flat config, pre-commit hook, and CI lint job

* test hook

* chore: add prepare script for Husky auto-install

* remove : git add from lint

* chore: clean up husky pre-commit hook for v10 compatibility

* refactor: get clear.js back

* fix: add missing @eslint/js dev dep

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Run eslint on pre-commit & required job on merge

1 participant