Categories
Git Uncategorized

Sorting Imports in the Whole Repository

Recently I was about to create an initial release for a project I have been working on for a while, and I wanted to change the package names to resemble the new context that had changed over the last two years. Using git-filter-repo it was almost trivial to change both the directory structure and every single mention of the package name. However, one of my disorders did absolutely not agree with imports now being in an incorrect order, so I sat down with git-filter-repo again and came up with the following script. This is what it does:

  1. Checking the filename. Does it end with “.kt”? If not, return, don’t change anything.
  2. Get the file’s content as a blob, turn into text, split it into lines.
  3. Go through all lines, store the package line, and store all imports.
  4. If there are no imports in this file, return the unchanged file.
  5. Sort the imports.
  6. Delete all lines from after the package line until the last import line.
  7. Now, go through the lines that are left, and once the package line is encountered, write it out, followed by an empty line, and the sorted imports; otherwise just write out the line.
  8. Join all the lines, encode them as UTF-8, create a new blob, return it.
git filter-repo --file-info-callback '
if not filename.endswith(b".kt"):
    return (filename, mode, blob_id)

text = value.get_contents_by_identifier(blob_id).decode("utf-8", errors="ignore")
lines = text.splitlines()

package_line = None
last_import = None
imports = []

for line in lines:
    if line.startswith("package "):
        package_line = line
    if line.startswith("import "):
        imports.append(line)
        last_import = line

if not imports:
    return (filename, mode, blob_id)

imports = sorted(set(imports))

package_index = lines.index(package_line)
last_import_index = lines.index(last_import)
del lines[package_index + 1:last_import_index + 1]

result = []
for line in lines:
    result.append(line)
    if line == package_line:
        result.append("")
        result.extend(imports)

final_data = ("\n".join(result) + "\n").encode("utf-8")
return (filename, mode, value.insert_file_with_contents(final_data))
'

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.