Skip to content

Commit e2f6d2c

Browse files
committed
Don't insert duplicate imports
1 parent adcdb8a commit e2f6d2c

File tree

2 files changed

+45
-2
lines changed

2 files changed

+45
-2
lines changed

pyimport.el

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,24 @@ To terminate the loop early, throw 'break."
7979
(string= keyword2 "from")
8080
(string= mod1 mod2))))
8181

82+
(defun pyimport--insert-from-symbol (symbol)
83+
"When point is a on an import line, add SYMBOL."
84+
;; Assumes the current line is of the form 'from foo import bar, baz'.
85+
86+
;; Step past the 'from '.
87+
(goto-char (line-beginning-position))
88+
(while (not (looking-at "import "))
89+
(forward-char 1))
90+
(forward-char (length "import "))
91+
92+
(insert
93+
(->> (delete-and-extract-region (point) (line-end-position))
94+
(s-split ", ")
95+
(cons symbol)
96+
(-sort #'string<)
97+
(-uniq)
98+
(s-join ", "))))
99+
82100
(defun pyimport--insert-import (line)
83101
"Insert LINE, a python import statement, in the current buffer."
84102
(let* ((current-lines (pyimport--import-lines (current-buffer)))
@@ -87,9 +105,8 @@ To terminate the loop early, throw 'break."
87105
;; Find the first matching line, and append there
88106
(pyimport--for-each-line
89107
(when (pyimport--same-module (pyimport--current-line) line)
90-
(goto-char (point-at-eol))
91108
(-let [(_ _module _ name) (s-split " " line)]
92-
(insert ", " name))
109+
(pyimport--insert-from-symbol name))
93110
;; Break from this loop.
94111
(throw 'break nil)))
95112

test/pyimport-test.el

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,3 +117,29 @@
117117
(setq result-lines (nreverse result-lines))
118118
(should
119119
(equal result-lines '("a" "b" "c" "d")))))
120+
121+
(ert-deftest insert-import-simple ()
122+
"Test inserting an import."
123+
(with-temp-buffer
124+
(pyimport--insert-import "from foo import x")
125+
(should
126+
(equal (buffer-string)
127+
"from foo import x\n"))))
128+
129+
(ert-deftest insert-import-with-existing ()
130+
"Test inserting an import when we already have imports from that module."
131+
(with-temp-buffer
132+
(insert "from foo import x\n")
133+
(pyimport--insert-import "from foo import y")
134+
(should
135+
(equal (buffer-string)
136+
"from foo import x, y\n"))))
137+
138+
(ert-deftest insert-import-duplicate ()
139+
"Test inserting an import when we already have that symbol imported"
140+
(with-temp-buffer
141+
(insert "from foo import x\n")
142+
(pyimport--insert-import "from foo import x")
143+
(should
144+
(equal (buffer-string)
145+
"from foo import x\n"))))

0 commit comments

Comments
 (0)