1 file changed, +25, -10
ac72b8bHandle classes that are bigger than max_chunk_size
src/chunking/python_chunker.py
+25, -10
+25, -10
@@ -14,25 +14,40 @@ def build_line_starts(text: str) -> list[int]:
1414 return starts
1515
1616
17 -def split_python_blocks(text: str) -> list[Block]:
18 - line_starts = build_line_starts(text)
17+def node_blocks(nodes: list[ast.stmt], line_starts: list[int],
18+ previous_last_line: int, scope: str,
19+ max_chunk_size: int) -> list[Block]:
1920 blocks: list[Block] = []
20 - previous_last_line = 0
21 - for node in ast.parse(text).body:
21+ for node in nodes:
2222 last_line = node.end_lineno or node.lineno
2323 start = line_starts[previous_last_line]
2424 end = line_starts[last_line]
2525 if isinstance(node, DEFINITION_TYPES):
26 - blocks.append(Block(start, end, True, node.name))
26+ name = f"{scope}.{node.name}" if scope else node.name
27+ if isinstance(node, ast.ClassDef) and end - start > max_chunk_size:
28+ inner = node_blocks(node.body, line_starts, previous_last_line,
29+ name, max_chunk_size)
30+ inner[0].starts_section = True
31+ inner[0].context = inner[0].context or name
32+ blocks.extend(inner)
33+ else:
34+ blocks.append(Block(start, end, True, name))
2735 else:
28 - blocks.append(Block(start, end, False, ""))
36+ blocks.append(Block(start, end, False, scope))
2937 previous_last_line = last_line
30 - if line_starts[previous_last_line] < len(text):
31 - blocks.append(Block(line_starts[previous_last_line], len(text),
32 - False, ""))
38+ return blocks
39+
40+
41+def split_python_blocks(text: str, max_chunk_size: int) -> list[Block]:
42+ line_starts = build_line_starts(text)
43+ blocks = node_blocks(ast.parse(text).body, line_starts, 0, "",
44+ max_chunk_size)
45+ last_end = blocks[-1].end if blocks else 0
46+ if last_end < len(text):
47+ blocks.append(Block(last_end, len(text), False, ""))
3348 return blocks
3449
3550
3651 def chunk_python(source: SourceFile, max_chunk_size: int) -> list[Chunk]:
37 - blocks = split_python_blocks(source.text)
52+ blocks = split_python_blocks(source.text, max_chunk_size)
3853 return pack_blocks(source, blocks, max_chunk_size)