Skip to content

Commit

Permalink
Add pre-commit hook to check localStorage usage
Browse files Browse the repository at this point in the history
  • Loading branch information
chandel-aman committed Jan 25, 2024
1 parent 8471fe8 commit 97a858c
Show file tree
Hide file tree
Showing 3 changed files with 69 additions and 2 deletions.
3 changes: 2 additions & 1 deletion .lintstagedrc.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
{
"**/*.{ts,tsx,yml}": "eslint --fix",
"**/*.{ts,tsx,json,scss,css,yml}": "prettier --write"
"**/*.{ts,tsx,json,scss,css,yml}": "prettier --write",
"**/*.{ts,tsx}": "node scripts/githooks/check-localstorage-usage.js"
}
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,8 @@
"jest-preview": "jest-preview",
"update:toc": "node scripts/githooks/update-toc.js",
"lint-staged": "lint-staged --concurrent false",
"setup": "tsx setup.ts"
"setup": "tsx setup.ts",
"check-localstorage": "node scripts/githooks/check-localstorage-usage.js"
},
"eslintConfig": {
"extends": [
Expand Down
65 changes: 65 additions & 0 deletions scripts/githooks/check-localstorage-usage.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
#!/usr/bin/env node

import { readFileSync } from 'fs';
import path from 'path';

import { execSync } from 'child_process';

const getModifiedFiles = () => {
try {
const result = execSync('git diff --cached --name-only', {
encoding: 'utf-8',
});
return result.trim().split('\n');
} catch (error) {
console.error('Error fetching modified files:', error.message);
process.exit(1);
}
};

const files = getModifiedFiles();

const filesWithLocalStorage = [];

const checkLocalStorageUsage = (file) => {
if (!file) {
return;
}

const scriptPath = path.resolve(new URL(import.meta.url).pathname);

if (
file === scriptPath ||
path.basename(file) === 'check-localstorage-usage.js'
) {
return;
}

const content = readFileSync(file, 'utf-8');

if (
content.includes('localStorage.getItem') ||
content.includes('localStorage.setItem') ||
content.includes('localStorage.removeItem')
) {
filesWithLocalStorage.push(file);
}
};

files.forEach(checkLocalStorageUsage);

if (filesWithLocalStorage.length > 0) {
console.error('\x1b[31m%s\x1b[0m', '\nError: Found usage of localStorage');
console.error('\nFiles with localStorage usage:');
filesWithLocalStorage.forEach((file) => console.error(file));

console.info(
'\x1b[34m%s\x1b[0m',
'\nInfo: Consider using custom hook functions.'
);
console.info(
'Please use the getItem, setItem, and removeItem functions provided by the custom hook useLocalStorage.\n'
);

process.exit(1);
}

0 comments on commit 97a858c

Please sign in to comment.