Skip to content

🎥 Make videos programmatically with React

Optimize pre-commit hook to only format changed packages

Jonny Burgerddafc4d1ba69
diff --git a/.githooks/pre-commit b/.githooks/pre-commit
index 6c8ec2dddb..a5c959980e 100755
--- a/.githooks/pre-commit
+++ b/.githooks/pre-commit
@@ -1,2 +1,2 @@
#!/bin/sh
-bun run format
+bun pre-commit.ts
diff --git a/pre-commit.ts b/pre-commit.ts
new file mode 100644
index 0000000000..8adabec012
--- /dev/null
+++ b/pre-commit.ts
@@ -0,0 +1,42 @@
+import {readFileSync, existsSync} from 'fs';
+import path from 'path';
+import {$} from 'bun';
+
+const result = await $`git diff --cached --name-only --diff-filter=ACMR`.text();
+const stagedFiles = result.trim().split('\n').filter(Boolean);
+
+if (stagedFiles.length === 0) {
+ process.exit(0);
+}
+
+const packageNames = new Set<string>();
+
+for (const file of stagedFiles) {
+ const match = file.match(/^packages\/([^/]+)\//);
+ if (!match) {
+ continue;
+ }
+
+ const dir = match[1];
+ const pkgJsonPath = path.join('packages', dir, 'package.json');
+
+ if (!existsSync(pkgJsonPath)) {
+ continue;
+ }
+
+ const pkgJson = JSON.parse(readFileSync(pkgJsonPath, 'utf-8'));
+
+ if (!pkgJson.scripts?.format) {
+ continue;
+ }
+
+ packageNames.add(pkgJson.name);
+}
+
+if (packageNames.size === 0) {
+ process.exit(0);
+}
+
+const filters = [...packageNames].flatMap((name) => ['--filter', name]);
+
+await $`bun run ${filters} format`;