Source

dotfiles / bin / sort-scala-imports

#!/usr/bin/env python

import sys
from operator import attrgetter


def next_line():
    return sys.stdin.readline().rstrip('\n')

l = next_line()

while not l.startswith('import '):
    sys.stdout.write(l + '\n')
    l = next_line()

class ImportGroup(object):
    def __init__(self, line):
        self.main_line = line.rstrip()
        self.guts = []

    def slurp(self):
        global l
        if self.main_line.endswith('}'):
            # This is a line like: import foo.{ a, b, c }
            prefix, rest = self.main_line.split('{', 1)
            guts = [item.strip() for item in
                    rest.rstrip('}, ').split(',')]
            guts.sort(key=lambda s: s.lower())
            self.main_line = '%s{ %s }' % (prefix, ', '.join(guts))
            l = next_line()
        elif self.main_line.endswith('{'):
            while True:
                l = next_line()
                if l.rstrip().endswith('}'):
                    l = next_line()
                    break
                else:
                    self.guts.append(l.strip().rstrip(','))
        else:
            l = next_line()

    def spit(self):
        sys.stdout.write(self.main_line + '\n')

        if self.guts:
            self.guts.sort(key=lambda g: g.lower())
            sys.stdout.write('  ' +
                             ',\n  '.join(self.guts) +
                             '\n}\n')

    def key(self):
        return self.main_line.lower().replace('{', '@')

imports = []
while l.startswith('import '):
    ig = ImportGroup(l)
    ig.slurp()
    imports.append(ig)

imports.sort(key=lambda ig: ig.key())

for i in imports:
    i.spit()

sys.stdout.write(l + '\n')

for l in sys.stdin.readlines():
    sys.stdout.write(l)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.