PyCQA / isort

A Python utility / library to sort imports.
https://pycqa.github.io/isort/
MIT License
6.45k stars 574 forks source link

Fix `sort_reexports` code mangling #2283

Open Helveg opened 1 month ago

Helveg commented 1 month ago

Fixes #2193 and fixes #2252,

The logic behind sort_reexports was keeping track of a point in the output_stream, and seeked to that point before writing the sorted reexports back in, in order to compensate for the first line of this code sorting section being written into the stream already.

The original code tried to track the position of the point with every iteration, but since the code is very branched, and contains ~10 .write statements, this fails, and this approach would never be easily maintained. So I opted to simplify the approach by instead rolling back the write position in the stream by the length of the segment that was written too much.

Additionally, when the input code sort section is longer than the sorted output (e.g., when there is a lot of trimmed whitespace), some previously written garbage remained, which I fixed by truncating the stream after writing to it during sort_reexport operations.

Helveg commented 1 month ago

It seems a bit unfair that DeepSource blocks this PR for cyclomatic complexity while it was already this high :)