From 97a858c45703907fd71b3b5998a9faa97c5f7343 Mon Sep 17 00:00:00 2001 From: chandel-aman Date: Fri, 26 Jan 2024 02:45:32 +0530 Subject: [PATCH] Add pre-commit hook to check localStorage usage --- .lintstagedrc.json | 3 +- package.json | 3 +- scripts/githooks/check-localstorage-usage.js | 65 ++++++++++++++++++++ 3 files changed, 69 insertions(+), 2 deletions(-) create mode 100755 scripts/githooks/check-localstorage-usage.js diff --git a/.lintstagedrc.json b/.lintstagedrc.json index 564fc70d3f..36195c0491 100644 --- a/.lintstagedrc.json +++ b/.lintstagedrc.json @@ -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" } diff --git a/package.json b/package.json index 6b6a3acbfe..9c11c567a7 100644 --- a/package.json +++ b/package.json @@ -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": [ diff --git a/scripts/githooks/check-localstorage-usage.js b/scripts/githooks/check-localstorage-usage.js new file mode 100755 index 0000000000..a53d28d401 --- /dev/null +++ b/scripts/githooks/check-localstorage-usage.js @@ -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); +}