Merge pull request #121 from olexsmir/develop

sync develop with main
This commit is contained in:
Oleksandr Smirnov 2025-08-30 17:01:47 +03:00 committed by GitHub
commit 7e8c6f41aa
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
37 changed files with 472 additions and 188 deletions

View file

@ -15,6 +15,12 @@ jobs:
version: version:
- stable - stable
- nightly - nightly
- v0.10.0
- v0.10.4
- v0.11.0
- v0.11.1
- v0.11.2
- v0.11.3
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
steps: steps:
- name: Install Task - name: Install Task
@ -47,14 +53,9 @@ jobs:
key: ${{ runner.os }}-tests-${{ hashFiles('${{ github.workspace }}/.tests') }} key: ${{ runner.os }}-tests-${{ hashFiles('${{ github.workspace }}/.tests') }}
- name: Install Go bins - name: Install Go bins
run: | run: task install-deps
# TODO: install with :GoInstallDeps
go install github.com/fatih/gomodifytags@latest
go install github.com/josharian/impl@latest
go install github.com/cweill/gotests/...@latest
go install github.com/koron/iferr@latest
- name: Run Tests - name: Run Tests
run: | run: |
nvim --version nvim --version
task tests task test

View file

@ -1,17 +1,14 @@
# Contributing to `gopher.nvim` # Contributing to `gopher.nvim`
Thank you for taking the time to submit some code to gopher.nvim. It means a lot! Thank you for taking the time to submit some code to gopher.nvim. It means a lot!
### Task running ### Task running
In this codebase for running tasks is used [Taskfile](https://taskfile.dev). In this codebase for running tasks is used [Taskfile](https://taskfile.dev).
You can install it with: You can install it with:
```bash ```bash
go install github.com/go-task/task/v3/cmd/task@latest go install github.com/go-task/task/v3/cmd/task@latest
``` ```
### Styling and formatting ### Formatting and linting
Code is formatted by [stylua](https://github.com/JohnnyMorganz/StyLua) and linted using [selene](https://github.com/Kampfkarren/selene). Code is formatted by [stylua](https://github.com/JohnnyMorganz/StyLua) and linted using [selene](https://github.com/Kampfkarren/selene).
You can install these with: You can install these with:
@ -22,30 +19,31 @@ sudo pacman -S selene stylua
For formatting use this following commands, or setup your editor to integrate with selene/stylua: For formatting use this following commands, or setup your editor to integrate with selene/stylua:
```bash ```bash
task stylua task format
task lint # lintering and format chewing task lint
``` ```
### Documentation ### Documentation
Here we're using [mini.doc](https://github.com/echasnovski/mini.nvim/blob/main/readmes/mini-doc.md)
for generating vimhelp files based on [LuaCats](https://luals.github.io/wiki/annotations/) annotations in comments.
Here we are using [mini.doc](https://github.com/echasnovski/mini.nvim/blob/main/readmes/mini-doc.md) For demo gifs in [readme](./README.md) we're using [vhs](https://github.com/charmbracelet/vhs).
for generating help files based on EmmyLua-like annotations in comments All files related to demos live in [/vhs](./vhs) dir.
You can generate docs with: You can generate docs with:
```bash ```bash
task docgen task docgen # generates vimhelp
task vhs:generate # generates demo gifs
``` ```
### Commit messages ### Commit messages
We use [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/), please follow it. We use [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/), please follow it.
### Testing ### Testing
For testing this plugins uses [mini.test](https://github.com/echasnovski/mini.nvim/blob/main/readmes/mini-test.md). For testing this plugins uses [mini.test](https://github.com/echasnovski/mini.nvim/blob/main/readmes/mini-test.md).
All tests live in [/spec](./spec) dir. All tests live in [/spec](./spec) dir.
You can run tests with: You can run tests with:
```bash ```bash
task tests task test
``` ```

112
README.md
View file

@ -4,19 +4,21 @@
Minimalistic plugin for Go development in Neovim written in Lua. Minimalistic plugin for Go development in Neovim written in Lua.
It's **NOT** an LSP tool, the main goal of this plugin is to add go tooling support in Neovim. It's **NOT** an LSP tool, the goal of this plugin is to add go tooling support in Neovim.
> If you want to use new and maybe undocumented, and unstable features you might use [develop](https://github.com/olexsmir/gopher.nvim/tree/develop) branch. > All development of new and maybe undocumented, and unstable features is happening on [develop](https://github.com/olexsmir/gopher.nvim/tree/develop) branch.
## Install (using [lazy.nvim](https://github.com/folke/lazy.nvim)) ## Install (using [lazy.nvim](https://github.com/folke/lazy.nvim))
Requirements: Requirements:
- **Neovim 0.10** or later - **Neovim 0.10** or later
- Treesitter `go` parser(`:TSInstall go` if you use [nvim-treesitter](https://github.com/nvim-treesitter/nvim-treesitter)) - Treesitter parser for `go`(`:TSInstall go` if you use [nvim-treesitter](https://github.com/nvim-treesitter/nvim-treesitter))
- [Go](https://github.com/golang/go) installed (tested on 1.23) - [Go](https://github.com/golang/go) installed
```lua ```lua
-- NOTE: this plugin is already lazy-loaded, it adds only about 1ms of load
-- time to your config
{ {
"olexsmir/gopher.nvim", "olexsmir/gopher.nvim",
ft = "go", ft = "go",
@ -25,58 +27,14 @@ Requirements:
build = function() build = function()
vim.cmd.GoInstallDeps() vim.cmd.GoInstallDeps()
end, end,
---@module "gopher"
---@type gopher.Config ---@type gopher.Config
opts = {}, opts = {},
} }
``` ```
## Configuration
> [!IMPORTANT]
>
> If you need more info look `:h gopher.nvim`
**Take a look at default options (might be a bit outdated, look `:h gopher.nvim-config`)**
```lua
require("gopher").setup {
-- log level, you might consider using DEBUG or TRACE for debugging the plugin
log_level = vim.log.levels.INFO,
-- timeout for running internal commands
timeout = 2000,
commands = {
go = "go",
gomodifytags = "gomodifytags",
gotests = "gotests",
impl = "impl",
iferr = "iferr",
},
gotests = {
-- gotests doesn't have template named "default" so this plugin uses "default" to set the default template
template = "default",
-- path to a directory containing custom test code templates
template_dir = nil,
-- switch table tests from using slice to map (with test name for the key)
named = false,
},
gotag = {
transform = "snakecase",
-- default tags to add to struct fields
default_tag = "json",
},
iferr = {
-- choose a custom error message
message = nil,
},
}
```
## Features ## Features
<!-- markdownlint-disable -->
<details> <details>
<summary> <summary>
<b>Install plugin's go deps</b> <b>Install plugin's go deps</b>
@ -99,6 +57,8 @@ require("gopher").setup {
<b>Add and remove tags for structs via <a href="https://github.com/fatih/gomodifytags">gomodifytags</a></b> <b>Add and remove tags for structs via <a href="https://github.com/fatih/gomodifytags">gomodifytags</a></b>
</summary> </summary>
![Add tags demo](./vhs/tags.gif)
By default `json` tag will be added/removed, if not set: By default `json` tag will be added/removed, if not set:
```vim ```vim
@ -176,6 +136,8 @@ require("gopher").setup {
<b>Interface implementation via <a href="https://github.com/josharian/impl">impl<a></b> <b>Interface implementation via <a href="https://github.com/josharian/impl">impl<a></b>
</summary> </summary>
![Auto interface implementation demo](./vhs/impl.gif)
Syntax of the command: Syntax of the command:
```vim ```vim
:GoImpl [receiver] [interface] :GoImpl [receiver] [interface]
@ -199,6 +161,8 @@ require("gopher").setup {
<b>Generate boilerplate for doc comments</b> <b>Generate boilerplate for doc comments</b>
</summary> </summary>
![Generate comments](./vhs/comment.gif)
First set a cursor on **public** package/function/interface/struct and execute: First set a cursor on **public** package/function/interface/struct and execute:
```vim ```vim
@ -212,6 +176,8 @@ require("gopher").setup {
<b>Generate <code>if err != nil {</code> via <a href="https://github.com/koron/iferr">iferr</a></b> <b>Generate <code>if err != nil {</code> via <a href="https://github.com/koron/iferr">iferr</a></b>
</summary> </summary>
![Generate if err != nil {](./vhs/iferr.gif)
Set the cursor on the line with `err` and execute Set the cursor on the line with `err` and execute
```vim ```vim
@ -219,11 +185,49 @@ require("gopher").setup {
``` ```
</details> </details>
## Configuration
> [!IMPORTANT]
>
> If you need more info look `:h gopher.nvim`
**Take a look at default options (might be a bit outdated, look `:h gopher.nvim-config`)**
```lua
require("gopher").setup {
-- log level, you might consider using DEBUG or TRACE for debugging the plugin
log_level = vim.log.levels.INFO,
-- timeout for running internal commands
timeout = 2000,
commands = {
go = "go",
gomodifytags = "gomodifytags",
gotests = "gotests",
impl = "impl",
iferr = "iferr",
},
gotests = {
-- gotests doesn't have template named "default" so this plugin uses "default" to set the default template
template = "default",
-- path to a directory containing custom test code templates
template_dir = nil,
-- switch table tests from using slice to map (with test name for the key)
named = false,
},
gotag = {
transform = "snakecase",
-- default tags to add to struct fields
default_tag = "json",
},
iferr = {
-- choose a custom error message
message = nil,
},
}
```
## Contributing ## Contributing
PRs are always welcome. See [CONTRIBUTING.md](./CONTRIBUTING.md) PRs are always welcome. See [CONTRIBUTING.md](./CONTRIBUTING.md)
## Thanks
- [go.nvim](https://github.com/ray-x/go.nvim)
- [iferr](https://github.com/koron/iferr)

View file

@ -1,28 +1,26 @@
version: "3" version: "3"
includes:
vhs:
taskfile: ./vhs/Taskfile.yml
dir: ./vhs
tasks: tasks:
lint: lint:
desc: runs all linters
cmds:
- task: selene
- stylua --check .
selene:
desc: runs lua linter(selene)
cmds: cmds:
- selene . - selene .
- stylua --check .
stylua: format:
desc: runs lua formatter cmd: stylua .
cmds:
- stylua .
tests: test:
desc: run all tests
cmds: cmds:
- | - |
nvim --clean --headless \ nvim --clean --headless \
-u ./scripts/minimal_init.lua \ -u ./scripts/minimal_init.lua \
-c "lua MiniTest.run()" -c "lua MiniTest.run()" \
-c ":qa!"
docgen: docgen:
desc: generate vimhelp desc: generate vimhelp
@ -32,3 +30,11 @@ tasks:
-u "./scripts/minimal_init.lua" \ -u "./scripts/minimal_init.lua" \
-c "luafile ./scripts/docgen.lua" \ -c "luafile ./scripts/docgen.lua" \
-c ":qa!" -c ":qa!"
install-deps:
desc: installs go bin (used in CI)
cmds:
- |
nvim --clean --headless \
-u "./scripts/minimal_init.lua" \
+GoInstallDepsSync +qa

View file

@ -65,8 +65,8 @@ end
---@class gopher.TsResult ---@class gopher.TsResult
---@field name string ---@field name string
---@field start_line integer ---@field start integer
---@field end_line integer ---@field end_ integer
---@field is_varstruct boolean ---@field is_varstruct boolean
---@param bufnr integer ---@param bufnr integer
@ -95,8 +95,8 @@ local function do_stuff(bufnr, parent_type, query)
assert(res.name ~= nil, "No capture name found") assert(res.name ~= nil, "No capture name found")
local start_row, _, end_row, _ = parent_node:range() local start_row, _, end_row, _ = parent_node:range()
res["start_line"] = start_row + 1 res["start"] = start_row + 1
res["end_line"] = end_row + 1 res["end_"] = end_row + 1
return res return res
end end

View file

@ -109,4 +109,4 @@ setmetatable(config, {
---@dochide ---@dochide
---@return gopher.Config ---@return gopher.Config
return config return config --[[ @as gopher.Config ]]

View file

@ -37,11 +37,22 @@ local u = require "gopher._utils"
local log = require "gopher._utils.log" local log = require "gopher._utils.log"
local struct_tags = {} local struct_tags = {}
---@dochide
---@class gopher.StructTagInput
---@field tags string[] User provided tags
---@field range? gopher.StructTagRange (optional)
---@dochide
---@class gopher.StructTagRange
---@field start number
---@field end_ number
---@param fpath string ---@param fpath string
---@param bufnr integer ---@param bufnr integer
---@param range? gopher.StructTagRange
---@param user_args string[] ---@param user_args string[]
---@dochide ---@dochide
local function handle_tags(fpath, bufnr, user_args) local function handle_tags(fpath, bufnr, range, user_args)
local st = ts.get_struct_under_cursor(bufnr) local st = ts.get_struct_under_cursor(bufnr)
-- stylua: ignore -- stylua: ignore
@ -53,9 +64,10 @@ local function handle_tags(fpath, bufnr, user_args)
"-w", "-w",
} }
if st.is_varstruct then -- `-struct` and `-line` cannot be combined, setting them separately
if range or st.is_varstruct then
table.insert(cmd, "-line") table.insert(cmd, "-line")
table.insert(cmd, string.format("%d,%d", st.start_line, st.end_line)) table.insert(cmd, string.format("%d,%d", (range or st).start, (range or st).end_))
else else
table.insert(cmd, "-struct") table.insert(cmd, "-struct")
table.insert(cmd, st.name) table.insert(cmd, st.name)
@ -93,7 +105,7 @@ end
---@param args string[] ---@param args string[]
---@return string ---@return string
---@dochide ---@dochide
local function handler_user_args(args) local function handler_user_tags(args)
if #args == 0 then if #args == 0 then
return c.gotag.default_tag return c.gotag.default_tag
end end
@ -102,28 +114,30 @@ end
-- Adds tags to a struct under the cursor -- Adds tags to a struct under the cursor
-- See |gopher.nvim-struct-tags| -- See |gopher.nvim-struct-tags|
---@param ... string Tags to add to the struct fields. If not provided, it will use [config.gotag.default_tag] ---@param opts gopher.StructTagInput
---@dochide ---@dochide
function struct_tags.add(...) function struct_tags.add(opts)
local args = { ... } log.debug("adding tags", opts)
local fpath = vim.fn.expand "%" local fpath = vim.fn.expand "%"
local bufnr = vim.api.nvim_get_current_buf() local bufnr = vim.api.nvim_get_current_buf()
local user_tags = handler_user_args(args) local user_tags = handler_user_tags(opts.tags)
handle_tags(fpath, bufnr, { "-add-tags", user_tags }) handle_tags(fpath, bufnr, opts.range, { "-add-tags", user_tags })
end end
-- Removes tags from a struct under the cursor -- Removes tags from a struct under the cursor
-- See `:h gopher.nvim-struct-tags` -- See `:h gopher.nvim-struct-tags`
---@dochide ---@dochide
---@param ... string Tags to add to the struct fields. If not provided, it will use [config.gotag.default_tag] ---@param opts gopher.StructTagInput
function struct_tags.remove(...) function struct_tags.remove(opts)
local args = { ... } log.debug("removing tags", opts)
local fpath = vim.fn.expand "%" local fpath = vim.fn.expand "%"
local bufnr = vim.api.nvim_get_current_buf() local bufnr = vim.api.nvim_get_current_buf()
local user_tags = handler_user_args(args) local user_tags = handler_user_tags(opts.tags)
handle_tags(fpath, bufnr, { "-remove-tags", user_tags }) handle_tags(fpath, bufnr, opts.range, { "-remove-tags", user_tags })
end end
-- Removes all tags from a struct under the cursor -- Removes all tags from a struct under the cursor
@ -132,7 +146,7 @@ end
function struct_tags.clear() function struct_tags.clear()
local fpath = vim.fn.expand "%" local fpath = vim.fn.expand "%"
local bufnr = vim.api.nvim_get_current_buf() local bufnr = vim.api.nvim_get_current_buf()
handle_tags(fpath, bufnr, { "-clear-tags" }) handle_tags(fpath, bufnr, nil, { "-clear-tags" })
end end
return struct_tags return struct_tags

View file

@ -3,43 +3,3 @@ any = true
[MiniTest] [MiniTest]
any = true any = true
[describe]
any = true
[[describe.args]]
type = "string"
[[describe.args]]
type = "function"
[it]
any = true
[[it.args]]
type = "string"
[[it.args]]
type = "function"
[before_each]
any = true
[[before_each.args]]
type = "function"
[[after_each.args]]
type = "function"
[assert]
any = true
[assert.is_not]
any = true
[[assert.equals.args]]
type = "any"
[[assert.equals.args]]
type = "any"
[[assert.equals.args]]
type = "any"
required = false
[[assert.same.args]]
type = "any"
[[assert.same.args]]
type = "any"

View file

@ -11,10 +11,13 @@ end
---@param name string ---@param name string
---@param fn fun(args: table) ---@param fn fun(args: table)
---@param nargs? number|"*"|"?" ---@param nargs? number|"*"|"?"
---@param range? boolean
---@private ---@private
local function cmd(name, fn, nargs) local function cmd(name, fn, nargs, range)
nargs = nargs or 0 vim.api.nvim_create_user_command(name, fn, {
vim.api.nvim_create_user_command(name, fn, { nargs = nargs }) nargs = nargs or 0,
range = range or false,
})
end end
cmd("GopherLog", function() cmd("GopherLog", function()
@ -44,12 +47,24 @@ end)
-- :GoTag -- :GoTag
cmd("GoTagAdd", function(opts) cmd("GoTagAdd", function(opts)
require("gopher").tags.add(unpack(opts.fargs)) require("gopher").tags.add {
end, "*") tags = opts.fargs,
range = (opts.count ~= -1) and {
start = opts.line1,
end_ = opts.line2,
} or nil,
}
end, "*", true)
cmd("GoTagRm", function(opts) cmd("GoTagRm", function(opts)
require("gopher").tags.rm(unpack(opts.fargs)) require("gopher").tags.rm {
end, "*") tags = opts.fargs,
range = (opts.count ~= -1) and {
start = opts.line1,
end_ = opts.line2,
} or nil,
}
end, "*", true)
cmd("GoTagClear", function() cmd("GoTagClear", function()
require("gopher").tags.clear() require("gopher").tags.clear()

View file

@ -23,6 +23,7 @@ end
install_plug "nvim-lua/plenary.nvim" install_plug "nvim-lua/plenary.nvim"
install_plug "nvim-treesitter/nvim-treesitter" install_plug "nvim-treesitter/nvim-treesitter"
install_plug "echasnovski/mini.doc" -- used for docs generation install_plug "echasnovski/mini.doc" -- used for docs generation
install_plug "folke/tokyonight.nvim" -- theme for generating demos
install_plug "echasnovski/mini.test" install_plug "echasnovski/mini.test"
vim.env.XDG_CONFIG_HOME = root ".tests/config" vim.env.XDG_CONFIG_HOME = root ".tests/config"
@ -32,6 +33,8 @@ vim.env.XDG_CACHE_HOME = root ".tests/cache"
vim.opt.runtimepath:append(root()) vim.opt.runtimepath:append(root())
vim.opt.packpath:append(root ".tests/site") vim.opt.packpath:append(root ".tests/site")
vim.o.swapfile = false
vim.o.writebackup = false
vim.notify = vim.print vim.notify = vim.print
-- install go treesitter parse -- install go treesitter parse
@ -53,6 +56,13 @@ if #vim.api.nvim_list_uis() == 0 then
} }
end end
-- set colorscheme only when running ui
if #vim.api.nvim_list_uis() == 1 then
vim.cmd.colorscheme "tokyonight-night"
vim.o.cursorline = true
vim.o.number = true
end
-- needed for tests, i dont know the reason why, but on start -- needed for tests, i dont know the reason why, but on start
-- vim is not able to use treesitter for go by default -- vim is not able to use treesitter for go by default
vim.api.nvim_create_autocmd("FileType", { vim.api.nvim_create_autocmd("FileType", {

14
spec/fixtures/tags/add_range_input.go vendored Normal file
View file

@ -0,0 +1,14 @@
package main
type Test struct {
ID int
Name string
Num int64
Cost int
Thingy []string
Testing int
Another struct {
First int
Second string
}
}

14
spec/fixtures/tags/add_range_output.go vendored Normal file
View file

@ -0,0 +1,14 @@
package main
type Test struct {
ID int
Name string `gopher:"name"`
Num int64 `gopher:"num"`
Cost int `gopher:"cost"`
Thingy []string
Testing int
Another struct {
First int
Second string
}
}

View file

@ -0,0 +1,14 @@
package main
type Test struct {
ID int `asdf:"id"`
Name string `asdf:"name"`
Num int64 `asdf:"num"`
Cost int `asdf:"cost"`
Thingy []string `asdf:"thingy"`
Testing int `asdf:"testing"`
Another struct {
First int `asdf:"first"`
Second string `asdf:"second"`
} `asdf:"another"`
}

View file

@ -0,0 +1,14 @@
package main
type Test struct {
ID int `asdf:"id"`
Name string `asdf:"name"`
Num int64
Cost int
Thingy []string
Testing int `asdf:"testing"`
Another struct {
First int `asdf:"first"`
Second string `asdf:"second"`
} `asdf:"another"`
}

View file

@ -1,5 +1,5 @@
local t = require "spec.testutils" local t = require "spec.testutils"
local child, T = t.setup "comment" local child, T, comment = t.setup "comment"
local function do_the_test(fixture, pos) local function do_the_test(fixture, pos)
local rs = t.setup_test("comment/" .. fixture, child, pos) local rs = t.setup_test("comment/" .. fixture, child, pos)
@ -10,27 +10,27 @@ local function do_the_test(fixture, pos)
t.cleanup(rs) t.cleanup(rs)
end end
T["comment"]["should add comment to package"] = function() comment["should add comment to package"] = function()
do_the_test("package", { 1, 1 }) do_the_test("package", { 1, 1 })
end end
T["comment"]["should add comment to struct"] = function() comment["should add comment to struct"] = function()
do_the_test("struct", { 4, 1 }) do_the_test("struct", { 4, 1 })
end end
T["comment"]["should add comment to function"] = function() comment["should add comment to function"] = function()
do_the_test("func", { 3, 1 }) do_the_test("func", { 3, 1 })
end end
T["comment"]["should add comment to method"] = function() comment["should add comment to method"] = function()
do_the_test("method", { 5, 1 }) do_the_test("method", { 5, 1 })
end end
T["comment"]["should add comment to interface"] = function() comment["should add comment to interface"] = function()
do_the_test("interface", { 3, 6 }) do_the_test("interface", { 3, 6 })
end end
T["comment"]["otherwise should add // above cursor"] = function() comment["otherwise should add // above cursor"] = function()
do_the_test("empty", { 1, 1 }) do_the_test("empty", { 1, 1 })
end end

View file

@ -1,5 +1,5 @@
local t = require "spec.testutils" local t = require "spec.testutils"
local child, T = t.setup "gotests" local child, T, gotests = t.setup "gotests"
--- NOTE: :GoTestAdd is the only place that has actual logic --- NOTE: :GoTestAdd is the only place that has actual logic
--- All other parts are handled `gotests` itself. --- All other parts are handled `gotests` itself.
@ -10,7 +10,7 @@ local function read_testfile(fpath)
return t.readfile(fpath:gsub(".go", "_test.go")) return t.readfile(fpath:gsub(".go", "_test.go"))
end end
T["gotests"]["should add test for function under cursor"] = function() gotests["should add test for function under cursor"] = function()
local rs = t.setup_test("tests/function", child, { 3, 5 }) local rs = t.setup_test("tests/function", child, { 3, 5 })
child.cmd "GoTestAdd" child.cmd "GoTestAdd"
@ -18,7 +18,7 @@ T["gotests"]["should add test for function under cursor"] = function()
t.cleanup(rs) t.cleanup(rs)
end end
T["gotests"]["should add test for method under cursor"] = function() gotests["should add test for method under cursor"] = function()
local rs = t.setup_test("tests/method", child, { 5, 19 }) local rs = t.setup_test("tests/method", child, { 5, 19 })
child.cmd "GoTestAdd" child.cmd "GoTestAdd"

View file

@ -1,7 +1,7 @@
local t = require "spec.testutils" local t = require "spec.testutils"
local child, T = t.setup "iferr" local child, T, iferr = t.setup "iferr"
T["iferr"]["should add if != nil {"] = function() iferr["should add if != nil {"] = function()
local rs = t.setup_test("iferr/iferr", child, { 8, 2 }) local rs = t.setup_test("iferr/iferr", child, { 8, 2 })
child.cmd "GoIfErr" child.cmd "GoIfErr"
child.cmd "write" child.cmd "write"
@ -10,7 +10,7 @@ T["iferr"]["should add if != nil {"] = function()
t.cleanup(rs) t.cleanup(rs)
end end
T["iferr"]["should add if err with custom message"] = function() iferr["should add if err with custom message"] = function()
child.lua [[ child.lua [[
require("gopher").setup { require("gopher").setup {
iferr = { message = 'fmt.Errorf("failed to %w", err)' } iferr = { message = 'fmt.Errorf("failed to %w", err)' }

View file

@ -1,7 +1,7 @@
local t = require "spec.testutils" local t = require "spec.testutils"
local child, T = t.setup "impl" local child, T, impl = t.setup "impl"
T["impl"]["should do impl with 'w io.Writer'"] = function() impl["should do impl with 'w io.Writer'"] = function()
local rs = t.setup_test("impl/writer", child, { 3, 0 }) local rs = t.setup_test("impl/writer", child, { 3, 0 })
child.cmd "GoImpl w io.Writer" child.cmd "GoImpl w io.Writer"
child.cmd "write" child.cmd "write"
@ -12,7 +12,7 @@ T["impl"]["should do impl with 'w io.Writer'"] = function()
t.cleanup(rs) t.cleanup(rs)
end end
T["impl"]["should work with full input, 'r Read io.Reader'"] = function() impl["should work with full input, 'r Read io.Reader'"] = function()
local rs = t.setup_test("impl/reader", child) local rs = t.setup_test("impl/reader", child)
child.cmd "GoImpl r Read io.Reader" child.cmd "GoImpl r Read io.Reader"
child.cmd "write" child.cmd "write"
@ -22,7 +22,7 @@ T["impl"]["should work with full input, 'r Read io.Reader'"] = function()
t.cleanup(rs) t.cleanup(rs)
end end
T["impl"]["should work with minimal input 'io.Closer'"] = function() impl["should work with minimal input 'io.Closer'"] = function()
local rs = t.setup_test("impl/closer", child, { 3, 6 }) local rs = t.setup_test("impl/closer", child, { 3, 6 })
child.cmd "GoImpl io.Closer" child.cmd "GoImpl io.Closer"
child.cmd "write" child.cmd "write"

View file

@ -1,7 +1,7 @@
local t = require "spec.testutils" local t = require "spec.testutils"
local child, T = t.setup "struct_tags" local child, T, struct_tags = t.setup "struct_tags"
T["struct_tags"]["should add tag"] = function() struct_tags["should add tag"] = function()
local rs = t.setup_test("tags/add", child, { 3, 6 }) local rs = t.setup_test("tags/add", child, { 3, 6 })
child.cmd "GoTagAdd json" child.cmd "GoTagAdd json"
child.cmd "write" child.cmd "write"
@ -10,7 +10,7 @@ T["struct_tags"]["should add tag"] = function()
t.cleanup(rs) t.cleanup(rs)
end end
T["struct_tags"]["should remove tag"] = function() struct_tags["should remove tag"] = function()
local rs = t.setup_test("tags/remove", child, { 4, 6 }) local rs = t.setup_test("tags/remove", child, { 4, 6 })
child.cmd "GoTagRm json" child.cmd "GoTagRm json"
child.cmd "write" child.cmd "write"
@ -19,7 +19,7 @@ T["struct_tags"]["should remove tag"] = function()
t.cleanup(rs) t.cleanup(rs)
end end
T["struct_tags"]["should be able to handle many structs"] = function() struct_tags["should be able to handle many structs"] = function()
local rs = t.setup_test("tags/many", child, { 10, 3 }) local rs = t.setup_test("tags/many", child, { 10, 3 })
child.cmd "GoTagAdd testing" child.cmd "GoTagAdd testing"
child.cmd "write" child.cmd "write"
@ -28,7 +28,7 @@ T["struct_tags"]["should be able to handle many structs"] = function()
t.cleanup(rs) t.cleanup(rs)
end end
T["struct_tags"]["should clear struct"] = function() struct_tags["should clear struct"] = function()
local rs = t.setup_test("tags/clear", child, { 3, 1 }) local rs = t.setup_test("tags/clear", child, { 3, 1 })
child.cmd "GoTagClear" child.cmd "GoTagClear"
child.cmd "write" child.cmd "write"
@ -37,7 +37,7 @@ T["struct_tags"]["should clear struct"] = function()
t.cleanup(rs) t.cleanup(rs)
end end
T["struct_tags"]["should add more than one tag"] = function() struct_tags["should add more than one tag"] = function()
local tmp = t.tmpfile() local tmp = t.tmpfile()
local fixtures = t.get_fixtures "tags/add_many" local fixtures = t.get_fixtures "tags/add_many"
t.writefile(tmp, fixtures.input) t.writefile(tmp, fixtures.input)
@ -60,7 +60,7 @@ T["struct_tags"]["should add more than one tag"] = function()
t.cleanup { tmp = tmp } t.cleanup { tmp = tmp }
end end
T["struct_tags"]["should add tags on var"] = function() struct_tags["should add tags on var"] = function()
local rs = t.setup_test("tags/var", child, { 5, 6 }) local rs = t.setup_test("tags/var", child, { 5, 6 })
child.cmd "GoTagAdd yaml" child.cmd "GoTagAdd yaml"
child.cmd "write" child.cmd "write"
@ -69,7 +69,7 @@ T["struct_tags"]["should add tags on var"] = function()
t.cleanup(rs) t.cleanup(rs)
end end
T["struct_tags"]["should add tags on short declr var"] = function() struct_tags["should add tags on short declr var"] = function()
local rs = t.setup_test("tags/svar", child, { 4, 3 }) local rs = t.setup_test("tags/svar", child, { 4, 3 })
child.cmd "GoTagAdd xml" child.cmd "GoTagAdd xml"
child.cmd "write" child.cmd "write"
@ -78,4 +78,22 @@ T["struct_tags"]["should add tags on short declr var"] = function()
t.cleanup(rs) t.cleanup(rs)
end end
struct_tags["should add tag with range"] = function()
local rs = t.setup_test("tags/add_range", child, { 5, 1 })
child.cmd ".,+2GoTagAdd gopher"
child.cmd "write"
t.eq(t.readfile(rs.tmp), rs.fixtures.output)
t.cleanup(rs)
end
struct_tags["should remove tag with range"] = function()
local rs = t.setup_test("tags/remove_range", child, { 6, 1 })
child.cmd ".,+2GoTagRm asdf"
child.cmd "write"
t.eq(t.readfile(rs.tmp), rs.fixtures.output)
t.cleanup(rs)
end
return T return T

View file

@ -6,9 +6,11 @@ local testutils = {}
testutils.mininit_path = vim.fs.joinpath(base_dir, "scripts", "minimal_init.lua") testutils.mininit_path = vim.fs.joinpath(base_dir, "scripts", "minimal_init.lua")
testutils.fixtures_dir = vim.fs.joinpath(base_dir, "spec/fixtures") testutils.fixtures_dir = vim.fs.joinpath(base_dir, "spec/fixtures")
---@param name string ---@param mod string Module name for which to create a nested test set.
---@return MiniTest.child, table ---@return MiniTest.child child nvim client.
function testutils.setup(name) ---@return table T root test set created by `MiniTest.new_set()`.
---@return table mod_name nested set of tests in `T[mod]`.
function testutils.setup(mod)
local child = MiniTest.new_child_neovim() local child = MiniTest.new_child_neovim()
local T = MiniTest.new_set { local T = MiniTest.new_set {
hooks = { hooks = {
@ -19,8 +21,8 @@ function testutils.setup(name)
}, },
} }
T[name] = MiniTest.new_set {} T[mod] = MiniTest.new_set {}
return child, T return child, T, T[mod]
end end
---@generic T ---@generic T
@ -76,6 +78,8 @@ end
---@param pos? number[] ---@param pos? number[]
---@return gopher.TestUtilsSetup ---@return gopher.TestUtilsSetup
function testutils.setup_test(fixture, child, pos) function testutils.setup_test(fixture, child, pos)
vim.validate("pos", pos, "table", true)
local tmp = testutils.tmpfile() local tmp = testutils.tmpfile()
local fixtures = testutils.get_fixtures(fixture) local fixtures = testutils.get_fixtures(fixture)
@ -84,6 +88,8 @@ function testutils.setup_test(fixture, child, pos)
local bufnr = child.fn.bufnr(tmp) local bufnr = child.fn.bufnr(tmp)
if pos then if pos then
assert(#pos == 2, "invalid cursor position")
child.fn.setpos(".", { bufnr, unpack(pos) }) child.fn.setpos(".", { bufnr, unpack(pos) })
end end

22
spec/unit/config_test.lua Normal file
View file

@ -0,0 +1,22 @@
local t = require "spec.testutils"
local _, T, config = t.setup "config"
config["can be called without any arguments passed"] = function()
---@diagnostic disable-next-line: missing-parameter
require("gopher").setup()
end
config["can be called with empty table"] = function()
require("gopher").setup {}
end
config["should change option"] = function()
local log_level = 1234567890
require("gopher").setup {
log_level = log_level,
}
t.eq(log_level, require("gopher.config").log_level)
end
return T

View file

@ -1,14 +1,14 @@
local t = require "spec.testutils" local t = require "spec.testutils"
local _, T = t.setup "utils" local _, T, utils = t.setup "utils"
T["utils"]["should .remove_empty_lines()"] = function() utils["should .remove_empty_lines()"] = function()
local u = require "gopher._utils" local u = require "gopher._utils"
local inp = { "hi", "", "a", "", "", "asdf" } local inp = { "hi", "", "a", "", "", "asdf" }
t.eq(u.remove_empty_lines(inp), { "hi", "a", "asdf" }) t.eq(u.remove_empty_lines(inp), { "hi", "a", "asdf" })
end end
T["utils"]["should .readfile_joined()"] = function() utils["should .readfile_joined()"] = function()
local data = "line1\nline2\nline3" local data = "line1\nline2\nline3"
local tmp = t.tmpfile() local tmp = t.tmpfile()
local u = require "gopher._utils" local u = require "gopher._utils"
@ -17,7 +17,7 @@ T["utils"]["should .readfile_joined()"] = function()
t.eq(u.readfile_joined(tmp), data) t.eq(u.readfile_joined(tmp), data)
end end
T["utils"]["should .trimend()"] = function() utils["should .trimend()"] = function()
local u = require "gopher._utils" local u = require "gopher._utils"
t.eq(u.trimend " hi ", " hi") t.eq(u.trimend " hi ", " hi")
end end

20
vhs/Taskfile.yml Normal file
View file

@ -0,0 +1,20 @@
version: "3"
tasks:
generate:
deps:
- comment
- iferr
- tags
- impl
comment:
cmd: vhs comment.tape
iferr:
cmd: vhs iferr.tape
tags:
cmd: vhs tags.tape
impl:
cmd: vhs impl.tape

BIN
vhs/comment.gif Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 220 KiB

7
vhs/comment.go Normal file
View file

@ -0,0 +1,7 @@
package demos
func doSomethingImportant() {}
type User struct{}
type DataProvider interface{}

34
vhs/comment.tape Normal file
View file

@ -0,0 +1,34 @@
Output comment.gif
Require nvim
Set FontFamily "JetBrains Mono"
Set Height 800
Set Width 1500
Set Padding 20
Set Shell "bash"
Set Theme "tokyonight"
Set TypingSpeed 250ms
Hide
Type@0ms "alias nvim='./nvim.sh'" Enter
Type@0ms "clear" Enter
Show
Type "nvim comment.go" Sleep 150ms Enter
# package
Type ":GoCmt" Enter Sleep 500ms Escape Sleep 700ms
# func
Type "3j"
Type ":GoCmt" Enter Sleep 500ms Escape Sleep 700ms
# struct
Type "3j"
Type ":GoCmt" Enter Sleep 500ms Escape Sleep 700ms
# interface
Type "3j"
Type ":GoCmt" Enter Sleep 500ms Escape Sleep 700ms
Sleep 5s

3
vhs/go.mod Normal file
View file

@ -0,0 +1,3 @@
module demos
go 1.25.0

BIN
vhs/iferr.gif Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 98 KiB

11
vhs/iferr.go Normal file
View file

@ -0,0 +1,11 @@
package demos
func ifErr() {
out, err := doSomething()
_ = out
}
func doSomething() (string, error) {
return "", nil
}

23
vhs/iferr.tape Normal file
View file

@ -0,0 +1,23 @@
Output iferr.gif
Require nvim
Require iferr
Set FontFamily "JetBrains Mono"
Set Height 800
Set Width 1500
Set Padding 20
Set Shell "bash"
Set Theme "tokyonight"
Set TypingSpeed 250ms
Hide
Type@0ms "alias nvim='./nvim.sh'" Enter
Type@0ms "clear" Enter
Show
Type "nvim iferr.go" Sleep 150ms Enter
Type "3j"
Type ":GoIfErr" Sleep 500ms Enter
Sleep 5s

BIN
vhs/impl.gif Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 87 KiB

3
vhs/impl.go Normal file
View file

@ -0,0 +1,3 @@
package demos
type CloserExample struct{}

23
vhs/impl.tape Normal file
View file

@ -0,0 +1,23 @@
Output impl.gif
Require nvim
Require iferr
Set FontFamily "JetBrains Mono"
Set Height 800
Set Width 1500
Set Padding 20
Set Shell "bash"
Set Theme "tokyonight"
Set TypingSpeed 250ms
Hide
Type@0ms "alias nvim='./nvim.sh'" Enter
Type@0ms "clear" Enter
Show
Type "nvim impl.go" Sleep 150ms Enter
Type "2j"
Type ":GoImpl io.Reader" Sleep 500ms Enter
Sleep 5s

2
vhs/nvim.sh Executable file
View file

@ -0,0 +1,2 @@
#!/usr/bin/env bash
nvim --clean -u "../scripts/minimal_init.lua" $@

BIN
vhs/tags.gif Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 246 KiB

12
vhs/tags.go Normal file
View file

@ -0,0 +1,12 @@
package demos
type AddTagsToMe struct {
Name string
ID int
Address string
Aliases []string
Nested struct {
Foo string
Bar float32
}
}

36
vhs/tags.tape Normal file
View file

@ -0,0 +1,36 @@
Output tags.gif
Require nvim
Require gomodifytags
Set FontFamily "JetBrains Mono"
Set Height 800
Set Width 1500
Set Padding 20
Set Shell "bash"
Set Theme "tokyonight"
Set TypingSpeed 250ms
Hide
Type@0ms "alias nvim='./nvim.sh'" Enter
Type@0ms "clear" Enter
Show
Type "nvim tags.go" Sleep 150ms Enter
Type "3j"
Type ":GoTagAdd json yaml" Sleep 500ms Enter
Type@120ms ":w" Enter
Sleep 1s
Type ":GoTagRm json" Sleep 500ms Enter
Type@120ms ":w" Enter
Sleep 1s
Type ":GoTagClear" Sleep 500ms Enter
Type@120ms ":w" Enter
Sleep 1s
Type "jV2j"
Type ":GoTagAdd xml" Sleep 500ms Enter
Sleep 5s