Skip to content
Closed
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
remove duplicate imports
  • Loading branch information
lixy committed Jan 9, 2017
commit 4836d93e8bca545fbd3a166473dd2d00d5ed8669
30 changes: 16 additions & 14 deletions ImportExtension/AddImportOperation.swift
Original file line number Diff line number Diff line change
Expand Up @@ -29,17 +29,20 @@ class AddImportOperation {

func execute() {
let selection = self.buffer.selections.firstObject as! XCSourceTextRange
let selectionLine = selection.start.line
let importString = (self.buffer.lines[selectionLine] as! String).trimmingCharacters(in: CharacterSet.whitespaces)
var selectionLine = selection.start.line

var importString = (self.buffer.lines[selectionLine] as! String).trimmingCharacters(in: CharacterSet.whitespaces)
importString = importString.trimmingCharacters(in: CharacterSet.init(charactersIn: " \t\n"))

guard isValid(importString: importString) else {
return
}

//remove duplicate imports
removeDuplicate(importString: importString)
let removeNum = removeDuplicate(importString: importString)
selectionLine = selectionLine-removeNum

let line = appropriateLine(ignoringLine: selectionLine)
let line = appropriateLine()
guard line != NSNotFound else {
return
}
Expand All @@ -52,15 +55,21 @@ class AddImportOperation {
self.buffer.selections.insert(selectionPosition, at: 0)
}

func removeDuplicate(importString: String) -> Void {
func removeDuplicate(importString: String) -> Int {

//do not forget itself
var lineNumber = -1;

let tempLines = NSMutableArray.init(array: buffer.lines)
tempLines.enumerateObjects(options: .reverse) { (line, index, stop) in
if line as! String == importString {
let string = (line as! String).trimmingCharacters(in: CharacterSet.init(charactersIn: " \t\n"))
if string == importString {
buffer.lines.removeObject(at: index)
lineNumber += 1
}
}

return lineNumber
}

func isValid(importString: String) -> Bool {
Expand All @@ -79,15 +88,12 @@ class AddImportOperation {
return numberOfMatches > 0
}

func appropriateLine(ignoringLine: Int) -> Int {
func appropriateLine() -> Int {
var lineNumber = NSNotFound
let lines = buffer.lines as NSArray as! [String]

//Find the line that is first after all the imports
for (index, line) in lines.enumerated() {
if index == ignoringLine {
continue
}

if isValid(importString: line) {
lineNumber = index
Expand All @@ -100,10 +106,6 @@ class AddImportOperation {

//if a line is not found, find first free line after comments
for (index, line) in lines.enumerated() {
if index == ignoringLine {
continue
}

lineNumber = index
if line.isWhitespaceOrNewline() {
break
Expand Down