Skip to content

Instantly share code, notes, and snippets.

@chmouel
Created November 29, 2024 10:04
Show Gist options
  • Save chmouel/2011b6fb3c7466ba67dd06a748a74f20 to your computer and use it in GitHub Desktop.
Save chmouel/2011b6fb3c7466ba67dd06a748a74f20 to your computer and use it in GitHub Desktop.
Use treesitter to get gotest subtests and function name
(defvar my-gotest-get-subtest-key "name")
(defun my-gotest-get-subtest-ts ()
(let* ((struct-node (treesit-parent-until
(treesit-node-at (point))
(lambda (n)
(string-equal (treesit-node-type n) "literal_value"))))
(funcname
(substring-no-properties
(treesit-node-text
(treesit-node-child-by-field-name (treesit-defun-at-point) "name"))))
(children (when struct-node
(treesit-node-children struct-node)))
(subtest nil))
(when struct-node
(dolist (child children)
(when (and (string-equal (treesit-node-type child) "keyed_element")
(string-match (concat "^" my-gotest-get-subtest-key ":\\s-*\"\\(.*\\)\"$") (treesit-node-text child)))
(setq subtest
(shell-quote-argument
(replace-regexp-in-string " " "_" (match-string-no-properties 1 (treesit-node-text child))))))))
(concat (format "^%s%s$" funcname (if subtest (concat "/" subtest) "")))))
(defun my-gotest-maybe-ts-run()
"Run the test function at point or the subtest at point if it is a subtest."
(interactive)
(when (string-match "_test\\.go" (buffer-file-name))
(let ((gotest (my-gotest-get-subtest-ts)))
(go-test--go-test (concat "-run " gotest " .")))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment