Skip to content

hookCode quality

Warn Long Files

A Claude Code hook that flags any edited source file longer than 500 lines, so the agent splits the code before the file gets unwieldy.

npx workspacetemplates add warn-long-files --tool claude-code

Writes 1 file to .claude/

.claude/settings.jsonmerge into your file16 lines · 1.1 KBFile
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "node -e \"process.on('uncaughtException',()=>process.exit(0));let d='';process.stdin.on('data',c=>d+=c).on('end',()=>{let j={};try{j=JSON.parse(d)||{}}catch(e){process.exit(0)}const i=j.tool_input||{};const f=String(i.file_path||'');const fs=require('fs');const rd=()=>{try{return fs.readFileSync(f,'utf8')}catch(e){return null}};const e=require('path').extname(f).toLowerCase();const ok=['.js','.jsx','.ts','.tsx','.mjs','.cjs','.py','.rb','.go','.rs','.java','.kt','.cs','.php','.swift','.c','.cpp','.h','.vue','.svelte'];if(!ok.includes(e)||f.includes('.min.'))process.exit(0);const t=rd();if(t===null)process.exit(0);const max=Number(process.env.WARN_LINES)||500;const n=t.split('\\n').length-(t.endsWith('\\n')?1:0);if(n>max){console.error(f+' now has '+n+' lines (limit '+max+'). Split it into smaller modules by responsibility, or tell the user why it stays long.');process.exit(2)}process.exit(0)})\"",
            "timeout": 15
          }
        ]
      }
    ]
  }
}

What it does

Agents tend to keep adding to the same file. This PostToolUse hook counts the lines of each edited source file and speaks up once the count passes the limit, which is 500 unless you set WARN_LINES.

Only code extensions are counted, and minified files are skipped. The message asks for a split by responsibility or a reason to leave it.

Example

you › Add CSV export to the report service.

agent › After the edit the hook notes that report.ts has 640 lines. The agent moves the exporter into its own module.

Questions

Can I change the limit?
Yes. Set WARN_LINES to your number in the environment before starting Claude Code.
Does it count blank lines?
Yes, it counts every line in the file, so the number matches what an editor shows.
  • Block Generated File Edits

    HookCode quality

    Free
  • Block Large Writes

    HookCode quality

    Free
  • Block Vendor Edits

    HookCode quality

    Free
  • Ensure Final Newline

    HookCode quality

    Free