all repos

gopher.nvim @ 096bc8e7ee4c8c85c0c07d63f8d6c224c593800a

Minimalistic plugin for Go development

gopher.nvim/lua/gopher/gotests.lua(view raw)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
local Job = require "plenary.job"
local ts_utils = require "gopher._utils.ts"
local u = require "gopher._utils"
local M = {}

---@param cmd_args table
local function run(cmd_args)
  Job
    :new({
      command = "gotests",
      args = cmd_args,
      on_exit = function(_, retval)
        if retval ~= 0 then
          u.notify("command 'go " .. unpack(cmd_args) .. "' exited with code " .. retval, "error")
          return
        end

        u.notify("unit test(s) generated", "info")
      end,
    })
    :start()
end

---@param args table
local function add_test(args)
  local fpath = vim.fn.expand "%" ---@diagnostic disable-line: missing-parameter
  table.insert(args, "-w")
  table.insert(args, fpath)
  run(args)
end

---generate unit test for one function
---@param parallel boolean
function M.func_test(parallel)
  local ns = ts_utils.get_func_method_node_at_pos(unpack(vim.api.nvim_win_get_cursor(0)))
  if ns == nil or ns.name == nil then
    print "cursor on func/method and execute the command again"
    return
  end

  local cmd_args = { "-only", ns.name }
  if parallel then
    table.insert(cmd_args, "-parallel")
  end

  add_test(cmd_args)
end

---generate unit tests for all functions in current file
---@param parallel boolean
function M.all_tests(parallel)
  local cmd_args = { "-all" }
  if parallel then
    table.insert(cmd_args, "-parallel")
  end

  add_test(cmd_args)
end

---generate unit tests for all exported functions
---@param parallel boolean
function M.all_exported_tests(parallel)
  local cmd_args = {}
  if parallel then
    table.insert(cmd_args, "-parallel")
  end

  table.insert(cmd_args, "-exported")
  add_test(cmd_args)
end

return M