Skip to content

Commit

Permalink
rustic-cargo-add-missing-imports (brotzeit#161)
Browse files Browse the repository at this point in the history
* Extract crate name from error message

* Build list from missing imports

* update name

* Add all missing imports in current buffer

* Let the user select one import with prefix arg

* Check for cargo-edit and handle no missing imports

* Mention function in readme
  • Loading branch information
samhedin authored and brotzeit committed Aug 15, 2022
1 parent baef1fa commit b296d30
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -464,6 +464,7 @@ modify the parameters of a command.
- `rustic-cargo-add` Add crate to Cargo.toml using 'cargo add'
- `rustic-cargo-rm` Remove crate from Cargo.toml using 'cargo rm'
- `rustic-cargo-upgrade` Upgrade dependencies as specified in the local manifest file using 'cargo upgrade'
- `rustic-cargo-add-missing-imports ` Add the missing imports for the current buffer to `cargo.toml`. This function requires `lsp-mode`.

### Test

Expand Down
19 changes: 19 additions & 0 deletions rustic-cargo.el
Original file line number Diff line number Diff line change
Expand Up @@ -709,6 +709,25 @@ If running with prefix command `C-u', read whole command from minibuffer."
(read-from-minibuffer "Crate: ")))))
(rustic-run-cargo-command command))))

(defun rustic-cargo-add-missing-imports ()
"Add missing imports to Cargo.toml.
Adds all missing imports by default.
Use with 'prefix-arg` to select imports to add."
(interactive)
(when (rustic-cargo-edit-installed-p)
(let ((missing-imports (delete-dups
(seq-reduce (lambda (missing-crates errortable)
(if (string= "E0432" (gethash "code" errortable))
(cons (nth 3 (split-string (gethash "message" errortable) "`")) missing-crates)
missing-crates))
(gethash (buffer-file-name) (lsp-diagnostics t)) '()))))
(if missing-imports
(rustic-run-cargo-command (format "cargo add %s"
(if current-prefix-arg
(completing-read "Select import to add to Cargo.toml" missing-imports)
(mapconcat 'identity missing-imports " "))))
(message "Couldn't find any imports to add. If this was a mistake, make sure your language server is running properly.")))))

;;;###autoload
(defun rustic-cargo-rm (&optional arg)
"Remove crate from Cargo.toml using 'cargo rm'.
Expand Down

0 comments on commit b296d30

Please sign in to comment.