SLOPSHOPPER

laravel-tooling

Runs Pint and Larastan after Claude edits PHP, and Pest or PHPUnit on demand, then shows the results in a live pane and the status line. /laravel-tooling opens…

paneguardcommandtoaststatusprocess
★ 1v0.2.0MITupdated 2026-10-22tomshaw/claude-code-plugins/mods/laravel-tooling
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · laravel-tooling
│ ┃ laravel-tooling ✕ › fix the failing auth test and add an audit log call │ ┃ ⚒ Laravel tooling waiting f │ ┃ ⏺ Read(src/auth.ts) │ ┃ ○ Pint not run yet ⎿ Read 6 lines │ ┃ ⏺ Update(src/auth.ts) │ ┃ ○ Larastan not run yet ⎿ Added 2 lines, removed 1 line │ ┃ ⏺ Bash(bun test) │ ┃ ○ Tests run from the pane or /laravel-to ⎿ 3 pass, 1 fail │ ┃ │ ┃ [ Run all ] [ Tests ] ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · laravel-tooling
⚒ Laravel tooling waiting for PHP edits ○ Pint not run yet ○ Larastan not run yet ○ Tests run from the pane or /laravel-tooling tests [ Run all ] [ Tests ]
README

<h1 align="center">Claude Code plugins</h1>

<a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-blue.svg" alt="MIT"></a> <a href="https://github.com/tomshaw/claude-code-plugins/actions/workflows/ci.yml"><img src="https://github.com/tomshaw/claude-code-plugins/actions/workflows/ci.yml/badge.svg?branch=main" alt="CI"></a>

<a href="#-install">Install</a> · <a href="#-mods">Mods</a> · <a href="#-skills">Skills</a> · <a href="docs/mods.md">Docs</a> · <a href="https://claude.dev/blog/getting-started-with-claude-code-mods/">What are mods?</a>

🚀 Install

Add the marketplace once, then install any plugin by name:

claude plugin marketplace add tomshaw/claude-code-plugins
claude plugin install proofread@tomshaw
claude plugin install work-journal@tomshaw
claude plugin install laravel-tooling@tomshaw
claude plugin install commit-msg@tomshaw
claude plugin install commit-summary@tomshaw
claude plugin install module-map@tomshaw
claude plugin install laymans-terms@tomshaw
claude plugin install five-ws@tomshaw
claude plugin install paper-trail@tomshaw
claude plugin install trust-me-bro@tomshaw
claude plugin install scrutinize@tomshaw

Or from inside Claude Code:

/plugin install proofread --marketplace tomshaw/claude-code-plugins

Restart Claude Code after installing. To try one without installing:

git clone https://github.com/tomshaw/claude-code-plugins && cd claude-code-plugins
claude --plugin-dir mods/proofread

Needs Claude Code 2.1.293+.

🧩 Mods

Plugins built on function hooks: they change what Claude Code shows and does, live. Click a name for the full guide.

ModWhy you want itCommand
✍️proofreadType fast, never get misread. Typos and grammar are fixed before Claude reads your prompt, with every fix highlighted. Code and paths are left alone/proofread
📓work-journalKnow what you did without writing it down. Your day, week or month, written up from your prompts: projects, threads, decisions and open items/journal week
⚒️laravel-toolingClaude's PHP, checked before you have to. Pint and Larastan run after every edit, tests on demand, results live in a pane, and one key turns failures into a fix prompt/laravel-tooling
📝commit-msgCommit messages that remember why. Written from the session that made the change, in your repo's style. You edit it, copy it and commit it yourself/commit-msg

🧠 Skills

Instructions Claude loads when your request matches them. Ask in plain words. paper-trail and scrutinize run only when you type their command. Click a name for the full guide.

SkillWhy you want itTry
📊commit-summaryYour standup, written by your commits. Any day, week or month, for anyone, grouped by theme with line counts and highlights"what did I do this week?"
🗺️module-mapSee the shape of a change, not just its lines. Modules, dependencies and boundaries for code as it is, a branch, or a plan, with problems flagged"what did this branch change structurally?"
💬laymans-termsExplain it so anyone gets it. Everyday words, written for the reader you name, simplified but never wrong"explain this for a client"
🧭five-wsAsk what a good reporter would, before you start. Who, what, where, when, why and how, then where the answers don't add up"/five-ws add an export button"
🔬paper-trailStop taking Claude's word for it. Every decision logged with proof you can open, false claims caught, and a second model's review. Check the work in minutes instead of redoing it"/paper-trail start <task>"
🤙trust-me-broThe straight answer, right now. What changed and what it means for you, in plain words, with every claim marked checked, pretty sure or didn't check"did it work?"
🔎scrutinizeA second set of eyes that has to show its work. Another model reviews it blind, every finding is checked, and you get only what held up, ranked, with a report page"/scrutinize the latest changes"

📚 More

  • 📖 docs/mods.md: how the mods behave, setup notes and build your own
  • 🧠 docs/skills.md: what each skill does and how to ask for it
  • 🤝 CONTRIBUTING.md: where each kind of plugin goes, and how to add one
Source 3 files
hooks/register.tsx 440 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { CheckName, CheckResult, Checks, Issue } from '../types'
5import { parsePhpstan, parsePint, parseTests } from './parse'
6
7const PANE = 'laravel-tooling'
8const PROGRESS_EVERY = 500
9
10const idle = (summary: string): CheckResult => ({ status: 'idle', summary, issues: [], durationMs: 0, ranAt: 0 })
11
12const checks = atom({ plugin: 'laravel-tooling', key: 'checks' } as const, {
13  pint: idle('not run yet'),
14  phpstan: idle('not run yet'),
15  tests: idle('run from the pane or /laravel-tooling tests'),
16} satisfies Checks)
17const pending = atom({ plugin: 'laravel-tooling', key: 'pending' } as const, [] as string[])
18
19const LABELS: Record<CheckName, string> = { pint: 'Pint', phpstan: 'Larastan', tests: 'Tests' }
20const SHORT: Record<CheckName, string> = { pint: 'Pint', phpstan: 'Stan', tests: 'Tests' }
21const ORDER: CheckName[] = ['pint', 'phpstan', 'tests']
22
23const ICONS: Record<CheckResult['status'], string> = { idle: '○', running: '◐', pass: '✓', fail: '✗', error: '!' }
24const COLORS: Record<CheckResult['status'], string> = {
25  idle: 'inactive',
26  running: 'suggestion',
27  pass: 'success',
28  fail: 'error',
29  error: 'warning',
30}
31
32const EDIT_TOOLS = new Set(['Edit', 'Write', 'MultiEdit'])
33
34const settings = { autoTests: false, testFilter: '' }
35const session = {
36  root: '',
37  isLaravel: false,
38  phpstanConfig: undefined as string | undefined,
39  installed: { pint: false, phpstan: false, tests: false } as Record<CheckName, boolean>,
40  testRunner: 'pest' as 'pest' | 'phpunit',
41}
42const runner = { isRunning: false, queued: undefined as CheckName[] | undefined, queuedFilter: '' }
43
44const seconds = (ms: number): string => (ms < 1000 ? `${ms}ms` : `${(ms / 1000).toFixed(1)}s`)
45
46const clock = (at: number): string => {
47  const date = new Date(at)
48  const pad = (value: number): string => String(value).padStart(2, '0')
49
50  return `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
51}
52
53const statusLine = (all: Checks): string =>
54  ORDER.map(name => {
55    const check = all[name]
56    if (name === 'tests' && check.status === 'pass') {
57      return `${SHORT[name]} ${check.summary.split(' ')[0]}`
58    }
59    if (check.status === 'fail' && name === 'phpstan') {
60      return `${SHORT[name]} ${check.issues.length}${ICONS.fail}`
61    }
62
63    return `${SHORT[name]} ${ICONS[check.status]}`
64  }).join(' · ')
65
66const commandFor = (name: CheckName, filter: string): string[] => {
67  if (name === 'pint') {
68    return ['vendor/bin/pint', '--dirty', '--format=json']
69  }
70  if (name === 'phpstan') {
71    const config = session.phpstanConfig === undefined ? [] : [`--configuration=${session.phpstanConfig}`]
72
73    return ['vendor/bin/phpstan', 'analyse', '--memory-limit=2G', ...config, '--error-format=json', '--no-progress']
74  }
75
76  return [`vendor/bin/${session.testRunner}`, '--teamcity', ...(filter === '' ? [] : [`--filter=${filter}`])]
77}
78
79const parse = (name: CheckName, stdout: string, stderr: string) =>
80  name === 'pint'
81    ? parsePint(stdout, stderr, session.root)
82    : name === 'phpstan'
83      ? parsePhpstan(stdout, stderr, session.root)
84      : parseTests(stdout, stderr, session.root)
85
86const setCheck = async ($: EngineInterface, name: CheckName, result: CheckResult): Promise<Checks> => {
87  let after = await read($, checks)
88  await update($, checks, all => {
89    after = { ...all, [name]: result }
90
91    return after
92  })
93  $.ui.status(statusLine(after))
94
95  return after
96}
97
98const progressOf = (output: string): string => {
99  const finished = output.split('##teamcity[testFinished').length - 1
100  const failed = output.split('##teamcity[testFailed').length - 1
101
102  return `running… ${finished} done${failed > 0 ? `, ${failed} failed` : ''}`
103}
104
105const capture = async (
106  $: EngineInterface,
107  argv: string[],
108  onOutput: (stdout: string) => Promise<void>,
109): Promise<{ stdout: string; stderr: string }> => {
110  let stdout = ''
111  let stderr = ''
112  for await (const chunk of $.process.spawn({ argv, cwd: session.root, input: '' })) {
113    if (chunk.stream === 'stdout') {
114      stdout += chunk.text
115      await onOutput(stdout)
116    } else {
117      stderr += chunk.text
118    }
119  }
120
121  return { stdout, stderr }
122}
123
124const runOne = async ($: EngineInterface, name: CheckName, filter: string): Promise<void> => {
125  const before = (await read($, checks))[name]
126  const startedAt = await $.clock.now()
127  const running: CheckResult = { ...before, status: 'running', summary: 'running…' }
128  await setCheck($, name, running)
129
130  let shownAt = startedAt
131  const showProgress = async (stdout: string): Promise<void> => {
132    const now = await $.clock.now()
133    if (name !== 'tests' || now - shownAt < PROGRESS_EVERY) {
134      return
135    }
136    shownAt = now
137    await setCheck($, name, { ...running, summary: progressOf(stdout) })
138  }
139
140  let result: CheckResult
141  try {
142    const ran = await capture($, commandFor(name, filter), showProgress)
143    result = { ...parse(name, ran.stdout, ran.stderr), durationMs: (await $.clock.now()) - startedAt, ranAt: startedAt }
144  } catch (error) {
145    const message = error instanceof Error ? error.message : String(error)
146    $.ui.log(`laravel-tooling: ${LABELS[name]} could not run: ${message}`, { to: 'debug' })
147    result = {
148      status: 'error',
149      summary: 'could not run',
150      issues: [{ file: '', message }],
151      durationMs: (await $.clock.now()) - startedAt,
152      ranAt: startedAt,
153    }
154  }
155
156  await setCheck($, name, result)
157
158  if (result.status === 'fail' && before.status !== 'fail') {
159    $.ui.toast(`${LABELS[name]}: ${result.summary}`)
160  }
161}
162
163const runChecks = async ($: EngineInterface, wanted: CheckName[], filter: string): Promise<void> => {
164  const names = wanted.filter(name => session.installed[name])
165  if (names.length === 0) {
166    return
167  }
168  if (runner.isRunning) {
169    runner.queued = [...new Set([...(runner.queued ?? []), ...names])]
170    runner.queuedFilter = filter
171
172    return
173  }
174
175  runner.isRunning = true
176  try {
177    for (const name of ORDER.filter(one => names.includes(one))) {
178      await runOne($, name, filter)
179    }
180  } finally {
181    runner.isRunning = false
182  }
183
184  const next = runner.queued
185  if (next !== undefined) {
186    runner.queued = undefined
187    await runChecks($, next, runner.queuedFilter)
188  }
189}
190
191const start = ($: EngineInterface, names: CheckName[], filter = settings.testFilter): void => {
192  $.clock.after(0, () => {
193    void runChecks($, names, filter)
194  })
195}
196
197const fixPrompt = (all: Checks): string => {
198  const sections = ORDER.filter(name => all[name].status === 'fail' || all[name].status === 'error').map(name => {
199    const lines = all[name].issues
200      .slice(0, 40)
201      .map(issue => `- ${issue.file}${issue.line === undefined ? '' : `:${issue.line}`} ${issue.message}`.trim())
202
203    return `${LABELS[name]} (${all[name].summary}):\n${lines.join('\n')}`
204  })
205
206  return `Fix these Laravel tooling failures:\n\n${sections.join('\n\n')}\n`
207}
208
209const byFile = (issues: Issue[]): [string, Issue[]][] => {
210  const groups = new Map<string, Issue[]>()
211  for (const issue of issues) {
212    groups.set(issue.file, [...(groups.get(issue.file) ?? []), issue])
213  }
214
215  return [...groups.entries()]
216}
217
218const testLabel = (): string => (session.testRunner === 'pest' ? 'Pest' : 'PHPUnit')
219
220const openPane = ($: EngineInterface) => $.ui.open({ id: PANE, title: 'Laravel tooling' })
221
222export const register: Register = (on, options) => {
223  settings.autoTests = options.autoTests === true
224  settings.testFilter = String(options.testFilter ?? '').trim()
225
226  on('session.start', async ($, e, next) => {
227    const started = await next(e)
228    session.root = started.cwd
229    const has = (path: string) => $.fs.exists(`${session.root}/${path}`)
230    session.isLaravel = await has('artisan')
231    if (!session.isLaravel) {
232      return started
233    }
234
235    const hasPest = await has('vendor/bin/pest')
236    session.testRunner = hasPest ? 'pest' : 'phpunit'
237    session.installed = {
238      pint: await has('vendor/bin/pint'),
239      phpstan: await has('vendor/bin/phpstan'),
240      tests: hasPest || (await has('vendor/bin/phpunit')),
241    }
242    session.phpstanConfig = undefined
243    for (const config of ['phpstan.neon', 'phpstan.neon.dist', 'phpstan.dist.neon']) {
244      if (session.phpstanConfig === undefined && (await has(config))) {
245        session.phpstanConfig = config
246      }
247    }
248    await update($, checks, all => {
249      const missing = ORDER.filter(name => !session.installed[name])
250
251      return { ...all, ...Object.fromEntries(missing.map(name => [name, idle('not installed')])) }
252    })
253
254    try {
255      await $.command.register({
256        name: 'laravel-tooling',
257        description: 'Laravel tooling: open the pane, `run` every check, or `tests [filter]` to run the tests',
258        argumentHint: '[run | tests [filter] | pint | stan]',
259      })
260    } catch (error) {
261      $.ui.log(`laravel-tooling: /laravel-tooling not registered: ${String(error)}`, { to: 'debug' })
262    }
263    $.ui.status(statusLine(await read($, checks)))
264
265    return started
266  })
267
268  on('command.run', { command: 'laravel-tooling' }, async ($, e) => {
269    if (!session.isLaravel) {
270      return { text: 'This is not a Laravel project (no artisan file).' }
271    }
272
273    const [action = '', ...rest] = e.args.trim().split(/\s+/)
274    const filter = rest.join(' ')
275    await openPane($)
276
277    if (action === 'run') {
278      start($, ORDER)
279
280      const names = ORDER.filter(name => session.installed[name]).map(name => (name === 'tests' ? testLabel() : LABELS[name]))
281
282      return { text: names.length === 0 ? 'None of Pint, Larastan, Pest or PHPUnit is installed.' : `Running ${names.join(', ')}.` }
283    }
284    if (action === 'tests') {
285      start($, ['tests'], filter === '' ? settings.testFilter : filter)
286
287      if (!session.installed.tests) {
288        return { text: 'Neither Pest nor PHPUnit is installed (vendor/bin/pest, vendor/bin/phpunit).' }
289      }
290
291      return { text: filter === '' ? `Running ${testLabel()}.` : `Running ${testLabel()} with --filter=${filter}.` }
292    }
293    if (action === 'pint' || action === 'stan') {
294      const name: CheckName = action === 'pint' ? 'pint' : 'phpstan'
295      if (!session.installed[name]) {
296        return { text: `${LABELS[name]} is not installed (vendor/bin/${name}).` }
297      }
298      start($, [name])
299
300      return { text: `Running ${action === 'pint' ? 'Pint' : 'Larastan'}.` }
301    }
302
303    return { text: 'Laravel tooling pane opened.' }
304  })
305
306  on('tool.call', async ($, e, next) => {
307    const ran = await next(e)
308    if (!session.isLaravel || !EDIT_TOOLS.has(String(e.tool)) || ran.isError === true) {
309      return ran
310    }
311
312    const path = (e as { file_path?: unknown }).file_path
313    if (typeof path === 'string' && path.endsWith('.php')) {
314      await update($, pending, list => (list.includes(path) ? list : [...list, path]))
315    }
316
317    return ran
318  }).catch(($, e, next) => next(e))
319
320  on('turn.complete', async ($, e, next) => {
321    const done = await next(e)
322    if (!session.isLaravel || e.agentId !== undefined) {
323      return done
324    }
325
326    const edited = await read($, pending)
327    if (edited.length === 0) {
328      return done
329    }
330
331    await update($, pending, () => [])
332    start($, settings.autoTests ? ORDER : ['pint', 'phpstan'])
333
334    return done
335  })
336
337  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
338    const { Box, Text, Button, Link } = $.ui.resolve(e)
339    const all = await read($, checks)
340    const width = e.props.bodyColumns ?? e.viewport?.columns ?? 80
341    const room = Math.max(4, (e.viewport?.rows ?? 30) - 12)
342    const hasFailures = ORDER.some(name => all[name].status === 'fail' || all[name].status === 'error')
343    const isBusy = ORDER.some(name => all[name].status === 'running')
344    const lastRan = Math.max(...ORDER.map(name => all[name].ranAt))
345    let budget = room
346
347    const issueRows = (name: CheckName) => {
348      const issues = all[name].issues
349      if (issues.length === 0 || budget <= 0) {
350        return []
351      }
352
353      let shownCount = 0
354      const rows = byFile(issues).flatMap(([file, list]) => {
355        if (budget <= 0) {
356          return []
357        }
358        budget -= 1
359        const header =
360          file === '' ? null : (
361            <Box key={`${name}:${file}`} paddingLeft={4}>
362              <Link href={`file://${session.root}/${file}`} label={file} />
363            </Box>
364          )
365        const shown = list.slice(0, Math.max(0, budget))
366        budget -= shown.length
367        shownCount += shown.length
368
369        return [
370          header,
371          ...shown.map((issue, index) => (
372            <Box key={`${name}:${file}:${index}`} paddingLeft={file === '' ? 4 : 6} flexDirection="row" gap={1}>
373              {issue.line !== undefined && (
374                <Text color="warning">{String(issue.line).padStart(4)}</Text>
375              )}
376              <Text color="subtle" wrap="wrap">
377                {issue.message}
378              </Text>
379            </Box>
380          )),
381        ]
382      })
383      const hidden = issues.length - shownCount
384
385      return hidden > 0
386        ? [
387            ...rows,
388            <Box key={`${name}:more`} paddingLeft={4}>
389              <Text dimColor>…and {hidden} more</Text>
390            </Box>,
391          ]
392        : rows
393    }
394
395    return (
396      <Box flexDirection="column" width={width}>
397        <Box flexDirection="row" justifyContent="space-between" marginBottom={1}>
398          <Text bold color="claude">
399            ⚒ Laravel tooling
400          </Text>
401          <Text dimColor>{lastRan > 0 ? `last run ${clock(lastRan)}` : 'waiting for PHP edits'}</Text>
402        </Box>
403        {ORDER.map(name => {
404          const check = all[name]
405
406          return (
407            <Box key={name} flexDirection="column" marginBottom={1}>
408              <Box flexDirection="row" justifyContent="space-between">
409                <Box flexDirection="row" gap={1}>
410                  <Text color={COLORS[check.status]} bold>
411                    {ICONS[check.status]}
412                  </Text>
413                  <Text bold>{LABELS[name].padEnd(9)}</Text>
414                  <Text color={check.status === 'idle' ? 'inactive' : COLORS[check.status]}>{check.summary}</Text>
415                </Box>
416                {check.durationMs > 0 && check.status !== 'running' && <Text dimColor>{seconds(check.durationMs)}</Text>}
417              </Box>
418              {issueRows(name)}
419            </Box>
420          )
421        })}
422        <Box flexDirection="row" gap={1}>
423          <Button key="run" label={isBusy ? 'Running…' : 'Run all'} hotkey="r" variant="primary" onPress={() => start($, ORDER)} />
424          <Button key="tests" label="Tests" hotkey="t" onPress={() => start($, ['tests'])} />
425          {hasFailures && (
426            <Button
427              key="fix"
428              label="Ask Claude to fix"
429              hotkey="f"
430              onPress={async () => {
431                await $.prompt.fill({ text: fixPrompt(await read($, checks)), mode: 'replace' })
432              }}
433            />
434          )}
435        </Box>
436      </Box>
437    )
438  })
439}
440
hooks/parse.ts 166 lines
1import type { CheckResult, Issue } from '../types'
2
3type Parsed = Pick<CheckResult, 'status' | 'summary' | 'issues'>
4
5const plural = (count: number, word: string): string => `${count} ${word}${count === 1 ? '' : 's'}`
6
7export const relativeTo = (root: string, path: string): string => {
8  const base = root.endsWith('/') ? root : `${root}/`
9
10  return path.startsWith(base) ? path.slice(base.length) : path
11}
12
13const firstJsonObject = (text: string): unknown => {
14  const start = text.indexOf('{')
15  const end = text.lastIndexOf('}')
16  if (start === -1 || end <= start) {
17    return undefined
18  }
19  try {
20    return JSON.parse(text.slice(start, end + 1))
21  } catch {
22    return undefined
23  }
24}
25
26const failure = (summary: string, stderr: string): Parsed => ({
27  status: 'error',
28  summary,
29  issues: stderr.trim() === '' ? [] : [{ file: '', message: stderr.trim().split('\n').slice(0, 6).join('\n') }],
30})
31
32type PintJson = { result?: string; files?: { path: string; fixers?: string[] }[] }
33
34export const parsePint = (stdout: string, stderr: string, root: string): Parsed => {
35  const json = firstJsonObject(stdout) as PintJson | undefined
36  if (json === undefined || json.result === undefined) {
37    return failure('Pint did not report', stderr || stdout)
38  }
39
40  const files = json.files ?? []
41  if (files.length === 0) {
42    return { status: 'pass', summary: 'clean', issues: [] }
43  }
44
45  const verb = json.result === 'fail' ? 'needs' : 'fixed'
46
47  return {
48    status: json.result === 'fail' ? 'fail' : 'pass',
49    summary: `${verb} ${plural(files.length, 'file')}`,
50    issues: files.map(file => ({
51      file: relativeTo(root, file.path),
52      message: (file.fixers ?? []).join(', '),
53    })),
54  }
55}
56
57type StanJson = {
58  totals?: { errors: number; file_errors: number }
59  files?: Record<string, { messages: { message: string; line?: number | null }[] }>
60  errors?: string[]
61}
62
63export const parsePhpstan = (stdout: string, stderr: string, root: string): Parsed => {
64  const json = firstJsonObject(stdout) as StanJson | undefined
65  if (json === undefined || json.totals === undefined) {
66    return failure('Larastan did not report', stderr || stdout)
67  }
68
69  const issues: Issue[] = [
70    ...(json.errors ?? []).map(message => ({ file: '', message })),
71    ...Object.entries(json.files ?? {}).flatMap(([path, file]) =>
72      file.messages.map(item => ({
73        file: relativeTo(root, path),
74        line: item.line ?? undefined,
75        message: item.message,
76      })),
77    ),
78  ]
79  const count = json.totals.file_errors + json.totals.errors
80  if (count === 0) {
81    return { status: 'pass', summary: 'no errors', issues: [] }
82  }
83
84  const files = Object.keys(json.files ?? {}).length
85
86  return {
87    status: 'fail',
88    summary: files > 0 ? `${plural(count, 'error')} in ${plural(files, 'file')}` : plural(count, 'error'),
89    issues,
90  }
91}
92
93const unescapeTeamcity = (value: string): string =>
94  value.replace(/\|(['nr|\[\]])/g, (_, char: string) =>
95    char === 'n' ? '\n' : char === 'r' ? '' : char,
96  )
97
98const attributes = (line: string): Record<string, string> => {
99  const found: Record<string, string> = {}
100  for (const match of line.matchAll(/(\w+)='((?:\|.|[^'|])*)'/g)) {
101    found[match[1]!] = unescapeTeamcity(match[2]!)
102  }
103
104  return found
105}
106
107const LOCATIONS = /([^\s:'"()]+\.php):(\d+)/g
108
109const projectLocation = (text: string, root: string): { file: string; line: number } | undefined => {
110  for (const match of text.matchAll(LOCATIONS)) {
111    const file = relativeTo(root, match[1]!)
112    if (!file.startsWith('vendor/') && !file.includes('/vendor/')) {
113      return { file, line: Number(match[2]) }
114    }
115  }
116
117  return undefined
118}
119
120export const parseTests = (stdout: string, stderr: string, root: string): Parsed => {
121  let passed = 0
122  let skipped = 0
123  const issues: Issue[] = []
124  let failing = new Set<string>()
125
126  for (const piece of stdout.split('##teamcity[').slice(1)) {
127    const line = piece.split('\n')[0] ?? ''
128    const event = line.match(/^(\w+)/)?.[1]
129    if (event === undefined) {
130      continue
131    }
132    const fields = attributes(line)
133    const name = fields.name ?? ''
134
135    if (event === 'testFailed') {
136      failing.add(name)
137      const location = projectLocation(fields.details ?? '', root)
138      const hintFile = relativeTo(root, (fields.locationHint ?? '').replace(/^\w+_qn:\/\//, '').split('::')[0] ?? '')
139      issues.push({
140        file: location?.file ?? hintFile,
141        line: location?.line,
142        message: `${name}: ${(fields.message ?? '').trim()}`,
143      })
144    } else if (event === 'testIgnored') {
145      skipped += 1
146      failing.add(name)
147    } else if (event === 'testFinished' && !failing.has(name)) {
148      passed += 1
149    } else if (event === 'testSuiteFinished') {
150      failing = new Set()
151    }
152  }
153
154  const failed = issues.length
155  const total = passed + failed
156  if (total === 0 && skipped === 0) {
157    return failure('no tests ran', stderr || stdout.split('\n').slice(-8).join('\n'))
158  }
159
160  const tail = skipped > 0 ? `, ${skipped} skipped` : ''
161
162  return failed === 0
163    ? { status: 'pass', summary: `${passed}/${total} passed${tail}`, issues: [] }
164    : { status: 'fail', summary: `${plural(failed, 'failure')}, ${passed}/${total} passed${tail}`, issues }
165}
166
types/index.d.ts 22 lines
1export type CheckName = 'pint' | 'phpstan' | 'tests'
2
3export type CheckStatus = 'idle' | 'running' | 'pass' | 'fail' | 'error'
4
5export type Issue = { file: string; line?: number; message: string }
6
7export type CheckResult = {
8  status: CheckStatus
9  summary: string
10  issues: Issue[]
11  durationMs: number
12  ranAt: number
13}
14
15export type Checks = Record<CheckName, CheckResult>
16
17declare module 'claude-code' {
18  interface PluginState {
19    'laravel-tooling': { checks: Checks; pending: string[] }
20  }
21}
22