2929
3030CodeType = enum .Enum ('CodeType' , 'PRE_IMPORT_CODE IMPORT NON_CODE CODE' )
3131
32+ NON_COMBINABLE = (CodeType .IMPORT , CodeType .PRE_IMPORT_CODE )
33+
3234
3335class CodePartition (NamedTuple ):
3436 code_type : CodeType
@@ -45,9 +47,6 @@ def _partitions_to_src(partitions: Iterable[CodePartition]) -> str:
4547
4648
4749def partition_source (src : str ) -> list [CodePartition ]:
48- """Partitions source into a list of `CodePartition`s for import
49- refactoring.
50- """
5150 lines = src .splitlines (True )
5251
5352 chunks = []
@@ -115,22 +114,16 @@ def partition_source(src: str) -> list[CodePartition]:
115114 chunks .append (CodePartition (CodeType .CODE , srctext ))
116115 break
117116
118- return [chunk for chunk in chunks if chunk .src ]
119-
120-
121- def combine_trailing_code_chunks (
122- partitions : Iterable [CodePartition ],
123- ) -> list [CodePartition ]:
124- chunks = list (partitions )
125-
126- NON_COMBINABLE = (CodeType .IMPORT , CodeType .PRE_IMPORT_CODE )
127- if chunks and chunks [- 1 ].code_type not in NON_COMBINABLE :
128- src = chunks .pop ().src
129- while chunks and chunks [- 1 ].code_type not in NON_COMBINABLE :
130- src = chunks .pop ().src + src
117+ # combine any trailing code chunks
118+ ret = [chunk for chunk in chunks if chunk .src ]
119+ code = []
120+ while ret and ret [- 1 ].code_type not in NON_COMBINABLE :
121+ code .append (ret .pop ())
122+ if code :
123+ code_src = _partitions_to_src (reversed (code ))
124+ ret .append (CodePartition (CodeType .CODE , code_src ))
131125
132- chunks .append (CodePartition (CodeType .CODE , src ))
133- return chunks
126+ return ret
134127
135128
136129def separate_comma_imports (
@@ -387,7 +380,6 @@ def fix_file_contents(
387380 return ''
388381
389382 partitioned = partition_source (contents )
390- partitioned = combine_trailing_code_chunks (partitioned )
391383 partitioned = add_imports (partitioned , to_add = to_add )
392384 partitioned = separate_comma_imports (partitioned )
393385 partitioned = replace_imports (partitioned , to_replace = to_replace )
0 commit comments