|
| 1 | +# 338 - Git Diff Word Frequency |
| 2 | + |
| 3 | +```rig |
| 4 | +import { agent, p, s, defineTool } from "rig"; |
| 5 | +
|
| 6 | +const countWordChanges = defineTool("countWordChanges", { |
| 7 | + description: "Count added and deleted words from a git word-diff porcelain output", |
| 8 | + parameters: s.object({ diffOutput: s.string }), |
| 9 | + handler: ({ diffOutput }: { diffOutput: string }) => { |
| 10 | + const lines = diffOutput.split("\n"); |
| 11 | + const addedWords: Record<string, number> = {}; |
| 12 | + const deletedWords: Record<string, number> = {}; |
| 13 | + for (const line of lines) { |
| 14 | + if (line.startsWith("+") && !line.startsWith("+++")) { |
| 15 | + line.slice(1).split(/\s+/).filter(Boolean).forEach((w: string) => { |
| 16 | + addedWords[w] = (addedWords[w] ?? 0) + 1; |
| 17 | + }); |
| 18 | + } else if (line.startsWith("-") && !line.startsWith("---")) { |
| 19 | + line.slice(1).split(/\s+/).filter(Boolean).forEach((w: string) => { |
| 20 | + deletedWords[w] = (deletedWords[w] ?? 0) + 1; |
| 21 | + }); |
| 22 | + } |
| 23 | + } |
| 24 | + const sortByCount = (m: Record<string, number>) => |
| 25 | + Object.entries(m).sort((a, b) => b[1] - a[1]).slice(0, 10).map(([w]) => w); |
| 26 | + return { |
| 27 | + topAddedWords: sortByCount(addedWords), |
| 28 | + topDeletedWords: sortByCount(deletedWords), |
| 29 | + totalAdditions: Object.values(addedWords).reduce((a, b) => a + b, 0), |
| 30 | + totalDeletions: Object.values(deletedWords).reduce((a, b) => a + b, 0), |
| 31 | + }; |
| 32 | + }, |
| 33 | +}); |
| 34 | +
|
| 35 | +// Agent role: analyze word-level changes in the last git diff and report top added/deleted words. |
| 36 | +const gitDiffWordFrequency = agent({ |
| 37 | + model: "small", |
| 38 | + instructions: p`Word diff output: ${p.bash("git diff --word-diff=porcelain HEAD~1 HEAD 2>/dev/null || git diff --word-diff=porcelain HEAD 2>/dev/null || echo 'no diff'")} |
| 39 | +Call countWordChanges with the diff output and return the word frequency analysis.`, |
| 40 | + output: s.object({ |
| 41 | + topAddedWords: s.array(s.string), |
| 42 | + topDeletedWords: s.array(s.string), |
| 43 | + totalAdditions: s.int, |
| 44 | + totalDeletions: s.int, |
| 45 | + mostFrequentAddition: s.optional(s.string), |
| 46 | + }), |
| 47 | + tools: [countWordChanges], |
| 48 | + maxTurns: 4, |
| 49 | +}); |
| 50 | +
|
| 51 | +export default gitDiffWordFrequency; |
| 52 | +``` |
0 commit comments