lang/java: fix java namespace resolution #1098

Now uses slightly more sophisticated namespace resolution when
populating the *.java file template.
This commit is contained in:
Henrik Lissner 2019-01-21 03:44:21 -05:00
parent 4b8c21a34b
commit 99e916348a
No known key found for this signature in database
GPG key ID: 5F6C0EA160557395
3 changed files with 66 additions and 8 deletions

View file

@ -30,3 +30,42 @@
(android-mode +1)
(doom/set-build-command "./gradlew %s" "build.gradle")))
;;;###autoload
(defun +java-current-package ()
"Converts the current file's path into a namespace.
For example: ~/some/project/src/net/lissner/game/MyClass.java
Is converted to: net.lissner.game
It does this by ignoring everything before the nearest package root (see
`+java-project-package-roots' to control what this function considers a package
root)."
(unless (eq major-mode 'java-mode)
(user-error "Not in a java-mode buffer"))
(let* ((project-root (file-truename (doom-project-root)))
(file-path (file-name-sans-extension
(file-truename (or buffer-file-name
default-directory))))
(src-root (cl-loop for root in +java-project-package-roots
if (and (stringp root)
(locate-dominating-file file-path root))
return (file-name-directory (file-relative-name file-path (expand-file-name root it)))
if (and (integerp root)
(> root 0)
(let* ((parts (split-string (file-relative-name file-path project-root) "/"))
(fixed-parts (reverse (nbutlast (reverse parts) root))))
(when fixed-parts
(string-join fixed-parts "/"))))
return it)))
(when src-root
(string-remove-suffix "." (replace-regexp-in-string "/" "." src-root)))))
;;;###autoload
(defun +java-current-class ()
"Get the class name for the current file."
(unless (eq major-mode 'java-mode)
(user-error "Not in a java-mode buffer"))
(unless buffer-file-name
(user-error "This buffer has no filepath; cannot guess its class name"))
(or (file-name-sans-extension (file-name-base (buffer-file-name)))
"ClassName"))