Skip to content

Instantly share code, notes, and snippets.

@jubishop
Created April 11, 2009 09:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jubishop/93512 to your computer and use it in GitHub Desktop.
Save jubishop/93512 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require "#{ENV['TM_SUPPORT_PATH']}/lib/exit_codes.rb"
lines = STDIN.readlines
doc = lines.join
importRegex = /^\s*import /
classCapture = /\.(\w+)\s*;$/
packageCapture = /^\s*import\s+(\w+)/
lines.delete_if { |line|
if (line.match(importRegex))
matches = line.match(classCapture)
(matches && doc.scan(matches.captures.first).length <= 1)
end
false
}
firstImport = false
lastImport = false
lines.each_with_index{|line, i|
if (line.match(importRegex))
firstImport ||= i
lastImport = i
end
}
TextMate::exit_show_tool_tip("No imports") unless (firstImport && lastImport)
importLines = lines.slice!(firstImport..lastImport).delete_if{|line| line.strip.empty?};
TextMate::exit_show_tool_tip("Imports mixed") if (importLines.any?{|line| !line.match(importRegex)})
importLines.uniq!
importLines.sort!
lastPackage = importLines.first.match(packageCapture).captures.first
importLines.map!{|line|
retArray = [line];
newPackage = line.match(packageCapture).captures.first
retArray.unshift("\n") if (newPackage != lastPackage)
lastPackage = newPackage
retArray
}.flatten!
puts lines.insert(firstImport, importLines).join
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment