-
-
Notifications
You must be signed in to change notification settings - Fork 8.7k
perf(hooks): optimize formatter hooks(x52 faster) — local binary, merged invocations, direct require() #359
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
pythonstrup
wants to merge
6
commits into
affaan-m:main
Choose a base branch
from
pythonstrup:feat/optimize-biome-hooks
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+4,437
−3,243
Open
Changes from 5 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
e66bddb
feat(hooks): add shared resolve-formatter utility with caching
pythonstrup 999c53d
perf(hooks): eliminate npx overhead and merge biome invocations
pythonstrup 5137ad5
perf(hooks): use direct require() instead of spawning child process
pythonstrup 34cd7b7
fix(hooks): add path traversal guard, timeouts, and error logging
pythonstrup 3cc66de
fix(hooks): address PR review feedback for biome optimization
pythonstrup 3abd3bf
fix(hooks): guard require() for legacy hooks, normalize filePath, fix…
pythonstrup File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -5,6 +5,11 @@ | |
| * Runs lightweight quality checks after file edits. | ||
| * - Targets one file when file_path is provided | ||
| * - Falls back to no-op when language/tooling is unavailable | ||
| * | ||
| * For JS/TS files with Biome, this hook is skipped because | ||
| * post-edit-format.js already runs `biome check --write`. | ||
| * This hook still handles .json/.md files for Biome, and all | ||
| * Prettier / Go / Python checks. | ||
| */ | ||
|
|
||
| 'use strict'; | ||
|
|
@@ -13,86 +18,149 @@ const fs = require('fs'); | |
| const path = require('path'); | ||
| const { spawnSync } = require('child_process'); | ||
|
|
||
| const { findProjectRoot, detectFormatter, resolveFormatterBin } = require('../lib/resolve-formatter'); | ||
|
|
||
| const MAX_STDIN = 1024 * 1024; | ||
| let raw = ''; | ||
|
|
||
| function run(command, args, cwd = process.cwd()) { | ||
| /** | ||
| * Execute a command synchronously, returning the spawnSync result. | ||
| * | ||
| * @param {string} command - Executable path or name | ||
| * @param {string[]} args - Arguments to pass | ||
| * @param {string} [cwd] - Working directory (defaults to process.cwd()) | ||
| * @returns {import('child_process').SpawnSyncReturns<string>} | ||
| */ | ||
| function exec(command, args, cwd = process.cwd()) { | ||
| return spawnSync(command, args, { | ||
| cwd, | ||
| encoding: 'utf8', | ||
| env: process.env, | ||
| timeout: 15000 | ||
| }); | ||
| } | ||
|
|
||
| /** | ||
| * Write a message to stderr for logging. | ||
| * | ||
| * @param {string} msg - Message to log | ||
| */ | ||
| function log(msg) { | ||
| process.stderr.write(`${msg}\n`); | ||
| } | ||
|
|
||
| /** | ||
| * Run quality-gate checks for a single file based on its extension. | ||
| * Skips JS/TS files when Biome is configured (handled by post-edit-format). | ||
| * | ||
| * @param {string} filePath - Path to the edited file | ||
| */ | ||
| function maybeRunQualityGate(filePath) { | ||
| if (!filePath || !fs.existsSync(filePath)) { | ||
| return; | ||
| } | ||
|
|
||
| // Resolve to absolute path so projectRoot-relative comparisons work | ||
| filePath = path.resolve(filePath); | ||
|
|
||
| const ext = path.extname(filePath).toLowerCase(); | ||
| const fix = String(process.env.ECC_QUALITY_GATE_FIX || '').toLowerCase() === 'true'; | ||
| const strict = String(process.env.ECC_QUALITY_GATE_STRICT || '').toLowerCase() === 'true'; | ||
|
|
||
| if (['.ts', '.tsx', '.js', '.jsx', '.json', '.md'].includes(ext)) { | ||
| // Prefer biome if present | ||
| if (fs.existsSync(path.join(process.cwd(), 'biome.json')) || fs.existsSync(path.join(process.cwd(), 'biome.jsonc'))) { | ||
| const args = ['biome', 'check', filePath]; | ||
| const projectRoot = findProjectRoot(path.dirname(path.resolve(filePath))); | ||
| const formatter = detectFormatter(projectRoot); | ||
|
|
||
| if (formatter === 'biome') { | ||
| // JS/TS already handled by post-edit-format via `biome check --write` | ||
| if (['.ts', '.tsx', '.js', '.jsx'].includes(ext)) { | ||
| return; | ||
| } | ||
coderabbitai[bot] marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| // .json / .md — still need quality gate | ||
| const resolved = resolveFormatterBin(projectRoot, 'biome'); | ||
| if (!resolved) return; | ||
| const args = [...resolved.prefix, 'check', filePath]; | ||
cubic-dev-ai[bot] marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| if (fix) args.push('--write'); | ||
| const result = run('npx', args); | ||
| const result = exec(resolved.bin, args, projectRoot); | ||
| if (result.status !== 0 && strict) { | ||
| log(`[QualityGate] Biome check failed for ${filePath}`); | ||
| } | ||
| return; | ||
| } | ||
|
|
||
| // Fallback to prettier when installed | ||
| const prettierArgs = ['prettier', '--check', filePath]; | ||
| if (fix) { | ||
| prettierArgs[1] = '--write'; | ||
| } | ||
| const prettier = run('npx', prettierArgs); | ||
| if (prettier.status !== 0 && strict) { | ||
| log(`[QualityGate] Prettier check failed for ${filePath}`); | ||
| if (formatter === 'prettier') { | ||
| const resolved = resolveFormatterBin(projectRoot, 'prettier'); | ||
| if (!resolved) return; | ||
| const args = [...resolved.prefix, fix ? '--write' : '--check', filePath]; | ||
| const result = exec(resolved.bin, args, projectRoot); | ||
| if (result.status !== 0 && strict) { | ||
| log(`[QualityGate] Prettier check failed for ${filePath}`); | ||
| } | ||
| return; | ||
| } | ||
|
|
||
| // No formatter configured — skip | ||
| return; | ||
| } | ||
|
|
||
| if (ext === '.go' && fix) { | ||
| run('gofmt', ['-w', filePath]); | ||
| if (ext === '.go') { | ||
| if (fix) { | ||
| const r = exec('gofmt', ['-w', filePath]); | ||
| if (r.status !== 0 && strict) { | ||
| log(`[QualityGate] gofmt failed for ${filePath}`); | ||
| } | ||
| } else if (strict) { | ||
| const r = exec('gofmt', ['-l', filePath]); | ||
| if (r.stdout && r.stdout.trim()) { | ||
| log(`[QualityGate] gofmt check failed for ${filePath}`); | ||
cubic-dev-ai[bot] marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
|
Comment on lines
+112
to
+118
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Treat Syntax errors and missing 💡 Proposed fix } else if (strict) {
const r = exec('gofmt', ['-l', filePath]);
- if (r.stdout && r.stdout.trim()) {
+ if (r.status !== 0 || (r.stdout && r.stdout.trim())) {
log(`[QualityGate] gofmt check failed for ${filePath}`);
}
}🤖 Prompt for AI Agents |
||
| } | ||
| return; | ||
| } | ||
|
|
||
| if (ext === '.py') { | ||
| const args = ['format']; | ||
| if (!fix) args.push('--check'); | ||
| args.push(filePath); | ||
| const r = run('ruff', args); | ||
| const r = exec('ruff', args); | ||
| if (r.status !== 0 && strict) { | ||
| log(`[QualityGate] Ruff check failed for ${filePath}`); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| process.stdin.setEncoding('utf8'); | ||
| process.stdin.on('data', chunk => { | ||
| if (raw.length < MAX_STDIN) { | ||
| const remaining = MAX_STDIN - raw.length; | ||
| raw += chunk.substring(0, remaining); | ||
| } | ||
| }); | ||
|
|
||
| process.stdin.on('end', () => { | ||
| /** | ||
| * Core logic — exported so run-with-flags.js can call directly. | ||
| * | ||
| * @param {string} rawInput - Raw JSON string from stdin | ||
| * @returns {string} The original input (pass-through) | ||
| */ | ||
| function run(rawInput) { | ||
| try { | ||
| const input = JSON.parse(raw); | ||
| const input = JSON.parse(rawInput); | ||
| const filePath = String(input.tool_input?.file_path || ''); | ||
| maybeRunQualityGate(filePath); | ||
| } catch { | ||
| // Ignore parse errors. | ||
| } | ||
| return rawInput; | ||
| } | ||
|
|
||
| // ── stdin entry point (backwards-compatible) ──────────────────── | ||
| if (require.main === module) { | ||
| let raw = ''; | ||
| process.stdin.setEncoding('utf8'); | ||
| process.stdin.on('data', chunk => { | ||
| if (raw.length < MAX_STDIN) { | ||
| const remaining = MAX_STDIN - raw.length; | ||
| raw += chunk.substring(0, remaining); | ||
| } | ||
| }); | ||
|
|
||
| process.stdin.on('end', () => { | ||
| const result = run(raw); | ||
| process.stdout.write(result); | ||
| }); | ||
| } | ||
|
|
||
| process.stdout.write(raw); | ||
| }); | ||
| module.exports = { run }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.