surshar / claude-code
Claude Code is an agentic coding tool that lives in your terminal, understands your codebase, and helps you code faster by executing routine tasks, explaining complex code, and handling git workflows - all through natural language commands.
Built by Anthropic · github.com/anthropics
| 1 | import Git from '../../../git' |
| 2 | import { hunkSourceOf } from '../hunk-source-of' |
| 3 | import { leadingHunkOf } from '../leading-hunk-of' |
| 4 | import { MAX_CODE_CHARS } from '../max-code-chars' |
| 5 | import { subHunksOf } from '../sub-hunks-of' |
| 6 | import type Types from '../types' |
| 7 | import { drawnLineOf } from './drawn-line-of' |
| 8 | |
| 9 | /** |
| 10 | * A file's hunks as the sources of `Code` blocks, one a hunk, stacked with |
| 11 | * nothing between as the built-in stacks a file's hunks. |
| 12 | * |
| 13 | * A hunk longer than MAX_CODE_CHARS is split (subHunksOf) into several. The |
| 14 | * body stops, truncated, at the whole lines the room holds as the host |
| 15 | * counts, a block a node; the room left comes back. |
| 16 | * |
| 17 | * @param hunks the file's hunks |
| 18 | * @param room the characters and nodes the pane's bodies have left |
| 19 | * @returns the sources in order, whether any line was left out or cut, and |
| 20 | * the room after them |
| 21 | */ |
| 22 | export function codeBlocksOf( |
| 23 | hunks: readonly Git.Hunk[], |
| 24 | room: Types.BodyRoom, |
| 25 | ): Types.CodeBody { |
| 26 | const sources: string[] = [] |
| 27 | |
| 28 | let chars = 0 |
| 29 | let isTruncated = false |
| 30 | |
| 31 | const left = (): Types.BodyRoom => ({ |
| 32 | chars: room.chars - chars, |
| 33 | nodes: room.nodes - sources.length, |
| 34 | }) |
| 35 | |
| 36 | for (const hunk of hunks) { |
| 37 | const lines = hunk.lines.filter(Git.isBodyLine).map(drawnLineOf) |
| 38 | const split = subHunksOf({ ...hunk, lines }, MAX_CODE_CHARS) |
| 39 | isTruncated ||= split.isTruncated |
| 40 | |
| 41 | for (const piece of split.hunks) { |
| 42 | const fits = room.chars - chars |
| 43 | const isWhole = hunkSourceOf(piece).length <= fits |
| 44 | const fitted = isWhole ? piece : leadingHunkOf(piece, fits) |
| 45 | const isOverNodes = sources.length + 1 > room.nodes |
| 46 | |
| 47 | if (isOverNodes || fitted.lines.length === 0) { |
| 48 | return { sources, isTruncated: true, room: left() } |
| 49 | } |
| 50 | |
| 51 | const text = hunkSourceOf(fitted) |
| 52 | sources.push(text) |
| 53 | chars += text.length |
| 54 | |
| 55 | if (fitted.lines.length < piece.lines.length) { |
| 56 | return { sources, isTruncated: true, room: left() } |
| 57 | } |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | return { sources, isTruncated, room: left() } |
| 62 | } |