refactor(go): 'go test ...' commands

Better error handling and fewer side-effects (with match data).
This commit is contained in:
Henrik Lissner
2025-03-30 16:54:57 -04:00
parent 65d43ae472
commit 7827d32cc6

View File

@ -1,15 +1,19 @@
;;; lang/go/autoload.el -*- lexical-binding: t; -*- ;;; lang/go/autoload.el -*- lexical-binding: t; -*-
;;
;; Tests
(defvar +go-test-last nil
"The last test run.")
(defun +go--spawn (cmd) (defun +go--spawn (cmd)
(save-selected-window (save-selected-window
(compile cmd))) (compile cmd)))
(defun +go--assert-buffer-visiting ()
(unless buffer-file-name
(user-error "Not in a file-visiting buffer")))
;;; go test ...
(defvar +go-test-last nil
"The last test run.")
(defun +go--run-tests (args) (defun +go--run-tests (args)
(let ((cmd (concat "go test -test.v " args))) (let ((cmd (concat "go test -test.v " args)))
(setq +go-test-last (concat "cd " default-directory ";" cmd)) (setq +go-test-last (concat "cd " default-directory ";" cmd))
@ -39,24 +43,31 @@
(defun +go/test-single () (defun +go/test-single ()
"Run single test at point." "Run single test at point."
(interactive) (interactive)
(if (string-match "_test\\.go" buffer-file-name) (+go--assert-buffer-visiting)
(save-excursion (unless (string-match-p "_test\\.go$" buffer-file-name)
(re-search-backward "^func[ ]+\\(([[:alnum:]]*?[ ]?[*]?[[:alnum:]]+)[ ]+\\)?\\(Test[[:alnum:]_]+\\)(.*)") (user-error "Must be in a *_test.go file"))
(+go--run-tests (concat "-run" "='^\\Q" (match-string-no-properties 2) "\\E$'"))) (save-excursion
(error "Must be in a _test.go file"))) (save-match-data
(unless (re-search-backward "^func[ ]+\\(([[:alnum:]]*?[ ]?[*]?[[:alnum:]]+)[ ]+\\)?\\(Test[[:alnum:]_]+\\)(.*)" nil t)
(user-error "No detectable test at or after point"))
(+go--run-tests (concat "-run" "='^\\Q" (match-string-no-properties 2) "\\E$'")))))
;;;###autoload ;;;###autoload
(defun +go/test-file () (defun +go/test-file ()
"Run all tests in current file." "Run all tests in current file."
(interactive) (interactive)
(if (string-match "_test\\.go" buffer-file-name) (+go--assert-buffer-visiting)
(save-excursion (unless (string-match-p "_test\\.go$" buffer-file-name)
(goto-char (point-min)) (user-error "Must be in a *_test.go file"))
(let ((func-list)) (save-excursion
(while (re-search-forward "^func[ ]+\\(([[:alnum:]]*?[ ]?[*]?[[:alnum:]]+)[ ]+\\)?\\(Test[[:alnum:]_]+\\)(.*)" nil t) (save-match-data
(push (match-string-no-properties 2) func-list)) (goto-char (point-min))
(+go--run-tests (concat "-run" "='^(" (string-join func-list "|") ")$'")))) (let (func-list)
(error "Must be in a _test.go file"))) (while (re-search-forward "^func[ ]+\\(([[:alnum:]]*?[ ]?[*]?[[:alnum:]]+)[ ]+\\)?\\(Test[[:alnum:]_]+\\)(.*)" nil t)
(push (match-string-no-properties 2) func-list))
(unless func-list
(user-error "No detectable tests in this file"))
(+go--run-tests (concat "-run" "='^(" (string-join func-list "|") ")$'"))))))
;;;###autoload ;;;###autoload
(defun +go/bench-all () (defun +go/bench-all ()