Compare commits

...

32 commits
v0.2.3 ... main

Author SHA1 Message Date
6a3924cee5
feat: json2go (#130)
* feat(json2go): implement

* feat(json2go): support manual input

* chore(readme): add json2go

* chore(docs): add docs
2025-12-08 21:29:34 +02:00
4a2384ade8
Merge pull request #129 (v0.4.0) 2025-11-27 17:12:38 +02:00
7764f6e37f
revert: automatically restart lsp server (#128)
semi revert of 7c198a1b36
2025-11-25 17:02:38 +02:00
f599e75963
chore: mention repo mirrors on other forges 2025-11-20 17:35:37 +02:00
906e340b4f
chore: update config docs 2025-11-06 17:20:08 +02:00
fabdcc5fb3
fix: type annotation 2025-11-06 17:19:53 +02:00
03de1f5ffc
chore: fix formatting 2025-11-06 17:19:53 +02:00
7a18d9f7bd
feat(strct-tags): add support for tag options (#126)
* feat(struct_tags): add options support

* refactor(struct-tags): give input field better name

* feat(struct-tag): add default option

* refactor: make it work on neovim version below 0.12

* chore(struct-tags): update the demo

* refactor: unite struct_tags util with main logic
2025-11-06 14:58:21 +02:00
0de1892ca9
chore(vhs): improve iferr demo 2025-10-26 13:55:44 +02:00
399845fee2
tests: remove plenary from dependencies, since we dont use it 2025-09-28 15:19:22 +03:00
ef4a3a1c7a
fix: type annotation for logger 2025-09-28 15:19:22 +03:00
e8d53840d4
refactor(health): mark all bin deps as required, check if vim version is 0.10 or higher 2025-09-16 15:14:17 +03:00
f4809cd2ec
chore(readme): address the most common issue
there's been several issues related to not installed deps: #124, #111,
#108, and more
2025-09-16 15:14:17 +03:00
0b2c26ebbb
refactor(config): allow both and 'string', and 'nil' for optional params 2025-09-13 12:53:03 +03:00
d1eaebab6b
refactor: fix config type annotations 2025-09-12 20:25:09 +03:00
7c198a1b36
feat: automatically restart lsp server (opt-in) 2025-09-10 16:17:15 +03:00
440a7cc432
chore: add vim 0.11.4 to the suite 2025-09-04 22:54:58 +03:00
1e7af1b212
feat(comment): add support for: interface methods, struct fields, variables (#123)
* refactor(comment): dont use unnecessary function

* chore: quick way to open vim in dev mode

* feat(comment): add comment on on interface method

* feat(comment): add comment on a struct field

* feat(comment): add comment on a variable

* docs: add note about the generate function

* docs: gopher.TsResult

* fix(utils): handle case when indentation is wrong
2025-09-04 16:52:18 +03:00
295e21e637
chore: start demos in vim (#122) 2025-08-31 14:30:13 +03:00
Oleksandr Smirnov
7e8c6f41aa
Merge pull request #121 from olexsmir/develop
sync develop with main
2025-08-30 17:01:47 +03:00
b7ce5d1f35
chore: update readme 2025-08-30 16:59:50 +03:00
Oleksandr Smirnov
9bf72afc63 chore: add demos (#118)
* chore: add dataset for demos

* chore(demos): add demos

* chore: update CONTRIBUTING

* this copefully will fix comments gif
2025-08-30 16:59:50 +03:00
c0951c4769
chore: update CONTRIBUTING.md 2025-08-30 16:59:50 +03:00
d6b41494f1
fix(testutils): validate provided cursor position 2025-08-30 16:59:50 +03:00
Oleksandr Smirnov
b6d3815f9b feat(struct_tags): add range support (#117)
* feat(struct_tags): add range support

* refactor: use `start`, and `end_` naming for ranges
2025-08-30 16:58:32 +03:00
8c87952964
chore(ci): install go bins via gopher.nvim itself 2025-08-30 16:58:32 +03:00
92b0ebb6a7
fix(config): type annotations 2025-08-30 16:58:32 +03:00
e90f766ea3
refactor(test): make helper test function more ergonomic
In my opinion, requiring user to access tests via `T["module_name"]`
was too fragile and typos prone.
2025-08-27 22:00:52 +03:00
53ab4274c2
chore: update tasks, run tests on all recent versions 2025-08-27 21:20:36 +03:00
09696900a5
test: add test for config 2025-08-27 20:56:07 +03:00
6f9648805e
chore: remove unused rules from nvim selene setup 2025-08-27 20:51:30 +03:00
Smirnov Oleksandr
de585144eb
fix(config): use new vim.validate, and not old one (#114) 2025-06-12 17:16:26 +03:00
82 changed files with 1554 additions and 427 deletions

View file

@ -15,6 +15,13 @@ 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
- v0.11.4
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
steps: steps:
- name: Install Task - name: Install Task
@ -47,14 +54,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
``` ```

177
README.md
View file

@ -4,79 +4,49 @@
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.
## Table of content
* [How to install](#install-using-lazynvim)
* [Features](#features)
* [Configuration](#configuration)
* [Troubleshooting](#troubleshooting)
* [Contributing](#contributing)
## 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
> [!IMPORTANT]
> If you prefer using other forges, this repository is also mirrored at:
> - [tangled.org](https://tangled.org): [`https://tangled.org/olexsmir.xyz/gopher.nvim`](https://tangled.org/olexsmir.xyz/gopher.nvim)
> - [codeberg.org](https://codeberg.org): [`https://codeberg.org/olexsmir/gopher.nvim`](https://codeberg.org/olexsmir/gopher.nvim)
```lua ```lua
-- NOTE: this plugin is already lazy-loaded and adds only about 1ms
-- of load time to your config
{ {
"olexsmir/gopher.nvim", "olexsmir/gopher.nvim",
ft = "go", ft = "go",
-- branch = "develop" -- branch = "develop"
-- (optional) will update plugin's deps on every update -- (optional) updates the plugin's dependencies on each update
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>
@ -92,6 +62,7 @@ require("gopher").setup {
- [impl](https://github.com/josharian/impl) - [impl](https://github.com/josharian/impl)
- [gotests](https://github.com/cweill/gotests) - [gotests](https://github.com/cweill/gotests)
- [iferr](https://github.com/koron/iferr) - [iferr](https://github.com/koron/iferr)
- [json2go](https://github.com/olexsmir/json2go)
</details> </details>
<details> <details>
@ -99,12 +70,17 @@ 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
" add json tag " add json tag
:GoTagAdd json :GoTagAdd json
" add json tag with omitempty option
:GoTagAdd json=omitempty
" remove yaml tag " remove yaml tag
:GoTagRm yaml :GoTagRm yaml
``` ```
@ -176,6 +152,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 +177,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
@ -206,12 +186,32 @@ require("gopher").setup {
``` ```
</details> </details>
<details>
<summary>
<b>Convert json to Go types</b>
</summary>
![Convert JSON to Go types](./vhs/json2go.gif)
`:GoJson` opens a temporary buffer where you can paste or write JSON.
Saving the buffer (`:w` or `:wq`) automatically closes it and inserts the generated Go struct into the original buffer at the cursor position.
Alternatively, you can pass JSON directly as an argument:
```vim
:GoJson {"name": "Alice", "age": 30}
```
Additionally, `gopher.json2go` provides lua api, see `:h gopher.nvim-json2go` for details.
</details>
<details> <details>
<summary> <summary>
<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 +219,78 @@ 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,
-- timeout for running installer commands(e.g :GoDepsInstall, :GoDepsInstallSync)
installer_timeout = 999999,
-- user specified paths to binaries
commands = {
go = "go",
gomodifytags = "gomodifytags",
gotests = "gotests",
impl = "impl",
iferr = "iferr",
},
gotests = {
-- a default template that gotess will use.
-- gotets doesn't have template named `default`, we use it to represent absence of the provided template.
template = "default",
-- path to a directory containing custom test code templates
template_dir = nil,
-- use named tests(map with test name as key) in table tests(slice of structs by default)
named = false,
},
gotag = {
transform = "snakecase",
-- default tags to add to struct fields
default_tag = "json",
-- default tag option added struct fields, set to nil to disable
-- e.g: `option = "json=omitempty,xml=omitempty`
option = nil,
},
iferr = {
-- choose a custom error message, nil to use default
-- e.g: `message = 'fmt.Errorf("failed to %w", err)'`
message = nil,
},
json2go = {
-- command used to open interactive input.
-- e.g: `split`, `botright split`, `tabnew`
interactive_cmd = "vsplit",
-- name of autogenerated struct
-- e.g: "MySuperCoolName"
type_name = nil,
},
}
```
## Troubleshooting
The most common issue with the plugin is missing dependencies.
Run `:checkhealth gopher` to verify that the plugin is installed correctly.
If any binaries are missing, install them using `:GoInstallDeps`.
If the issue persists, feel free to [open a new issue](https://github.com/olexsmir/gopher.nvim/issues/new).
## 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,28 @@
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!"
nvim:
cmd: nvim --clean -u "./scripts/minimal_init.lua" {{ .CLI_ARGS }}
docgen: docgen:
desc: generate vimhelp desc: generate vimhelp
@ -32,3 +32,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

@ -13,6 +13,7 @@ Table of Contents
Config ................................................ |gopher.nvim-config| Config ................................................ |gopher.nvim-config|
Commands ............................................ |gopher.nvim-commands| Commands ............................................ |gopher.nvim-commands|
Modify struct tags ............................... |gopher.nvim-struct-tags| Modify struct tags ............................... |gopher.nvim-struct-tags|
json2go .............................................. |gopher.nvim-json2go|
Auto implementation of interface methods ................ |gopher.nvim-impl| Auto implementation of interface methods ................ |gopher.nvim-impl|
Generating unit tests boilerplate .................... |gopher.nvim-gotests| Generating unit tests boilerplate .................... |gopher.nvim-gotests|
Iferr .................................................. |gopher.nvim-iferr| Iferr .................................................. |gopher.nvim-iferr|
@ -36,11 +37,11 @@ Parameters ~
------------------------------------------------------------------------------ ------------------------------------------------------------------------------
*gopher.nvim-dependencies* *gopher.nvim-dependencies*
`gopher.install_deps` `gopher.install_deps`
Gopher.nvim implements most of its features using third-party tools.
To install these tools, you can run `:GoInstallDeps` command Gopher.nvim implements most of its features using third-party tools. To
or call `require("gopher").install_deps()` if you want to use lua api. install plugin's dependencies, you can run:
By default dependencies will be installed asynchronously, `:GoInstallDeps` or `:GoInstallDepsSync`
to install them synchronously pass `{sync = true}` as an argument. or use `require("gopher").install_deps()` if you prefer lua api.
============================================================================== ==============================================================================
@ -57,7 +58,8 @@ to install them synchronously pass `{sync = true}` as an argument.
---@type number ---@type number
timeout = 2000, timeout = 2000,
--- timeout for running installer commands(e.g :GoDepsInstall, :GoDepsInstallSync) -- timeout for running installer commands(e.g :GoDepsInstall, :GoDepsInstallSync)
---@type number
installer_timeout = 999999, installer_timeout = 999999,
-- user specified paths to binaries -- user specified paths to binaries
@ -68,15 +70,19 @@ to install them synchronously pass `{sync = true}` as an argument.
gotests = "gotests", gotests = "gotests",
impl = "impl", impl = "impl",
iferr = "iferr", iferr = "iferr",
json2go = "json2go",
}, },
---@class gopher.ConfigGotests ---@class gopher.ConfigGotests
gotests = { gotests = {
-- gotests doesn't have template named "default" so this plugin uses "default" to set the default template -- a default template that gotess will use.
-- gotets doesn't have template named `default`, we use it to represent absence of the provided template.
template = "default", template = "default",
-- path to a directory containing custom test code templates -- path to a directory containing custom test code templates
---@type string|nil ---@type string|nil
template_dir = nil, template_dir = nil,
-- switch table tests from using slice to map (with test name for the key)
-- use named tests(map with test name as key) in table tests(slice of structs by default)
named = false, named = false,
}, },
---@class gopher.ConfigGoTag ---@class gopher.ConfigGoTag
@ -86,16 +92,36 @@ to install them synchronously pass `{sync = true}` as an argument.
-- default tags to add to struct fields -- default tags to add to struct fields
default_tag = "json", default_tag = "json",
-- default tag option added struct fields, set to nil to disable
-- e.g: `option = "json=omitempty,xml=omitempty`
---@type string|nil
option = nil,
}, },
---@class gopher.ConfigIfErr
iferr = { iferr = {
-- choose a custom error message -- choose a custom error message, nil to use default
-- e.g: `message = 'fmt.Errorf("failed to %w", err)'`
---@type string|nil ---@type string|nil
message = nil, message = nil,
}, },
---@class gopher.ConfigJson2Go
json2go = {
-- command used to open interactive input.
-- e.g: `split`, `botright split`, `tabnew`
interactive_cmd = "vsplit",
-- name of autogenerated struct, if nil none, will the default one of json2go.
-- e.g: "MySuperCoolName"
---@type string|nil
type_name = nil,
},
} }
< <
Class ~ Class ~
{gopher.Config} {gopher.Config}
Fields ~
{setup} `(fun(user_config?: gopher.Config))`
============================================================================== ==============================================================================
@ -110,16 +136,21 @@ you can set `vim.g.gopher_register_commands` to `false`, before loading the plug
------------------------------------------------------------------------------ ------------------------------------------------------------------------------
*gopher.nvim-struct-tags* *gopher.nvim-struct-tags*
`struct_tags` is utilizing the `gomodifytags` tool to add or remove tags to struct fields. `struct_tags` is utilizing the `gomodifytags` tool to add or remove tags to
struct fields.
Usage ~ Usage ~
How to add/remove tags to struct fields: How to add/remove/clear tags to struct fields:
1. Place cursor on the struct 1. Place cursor on the struct
2. Run `:GoTagAdd json` to add json tags to struct fields 2. Run `:GoTagAdd json` to add json tags to struct fields
3. Run `:GoTagRm json` to remove json tags to struct fields 3. Run `:GoTagRm json` to remove json tags to struct fields
4. Run `:GoTagClear` to clear all tags from struct fields
If you want to add/remove tag with options, you can use `json=omitempty`
(where json is tag, and omitempty is its option).
Example: `:GoTagAdd xml json=omitempty`
To clear all tags from struct run: `:GoTagClear`
NOTE: if you dont specify the tag it will use `json` as default NOTE: if you dont specify the tag it will use `json` as default
@ -140,6 +171,42 @@ Example:
} }
< <
==============================================================================
------------------------------------------------------------------------------
*gopher.nvim-json2go*
Convert json to go type annotations.
Usage ~
`:GoJson` opens a temporary buffer where you can paste or write JSON.
Saving the buffer (`:w` or `:wq`) automatically closes it and inserts the
generated Go struct into the original buffer at the cursor position.
Alternatively, you can pass JSON directly as an argument:
>vim
:GoJson {"name": "Alice", "age": 30}
<
------------------------------------------------------------------------------
*json2go.transform()*
`json2go.transform`({json_str})
Parameters ~
{json_str} `(string)` Json string that is going to be converted to go type.
Return ~
`(string)` `(optional)` Go type, or nil if failed.
------------------------------------------------------------------------------
*json2go.json2go()*
`json2go.json2go`({json_str})
Converts json string to go type, and puts result under the cursor. If
[json_str] is nil, will open an interactive prompt (with cmd set in
config).
Parameters ~
{json_str} `(optional)` `(string)`
============================================================================== ==============================================================================
------------------------------------------------------------------------------ ------------------------------------------------------------------------------
*gopher.nvim-impl* *gopher.nvim-impl*
@ -147,6 +214,7 @@ Example:
Integration of `impl` tool to generate method stubs for interfaces. Integration of `impl` tool to generate method stubs for interfaces.
Usage ~ Usage ~
1. Automatically implement an interface for a struct: 1. Automatically implement an interface for a struct:
- Place your cursor on the struct where you want to implement the interface. - Place your cursor on the struct where you want to implement the interface.
- Run `:GoImpl io.Reader` - Run `:GoImpl io.Reader`
@ -193,8 +261,9 @@ Usage ~
- Generate unit tests *only* for *exported(public)* functions/methods: - Generate unit tests *only* for *exported(public)* functions/methods:
- run `:GoTestsExp` - run `:GoTestsExp`
You can also specify the template to use for generating the tests. See |gopher.nvim-config| You can also specify the template to use for generating the tests.
More details about templates can be found at: https://github.com/cweill/gotests See |gopher.nvim-config|.
More details about templates: https://github.com/cweill/gotests
If you prefer named tests, you can enable them in |gopher.nvim-config|. If you prefer named tests, you can enable them in |gopher.nvim-config|.
@ -217,7 +286,9 @@ Execute `:GoIfErr` near any `err` variable to insert the check
This module provides a way to generate comments for Go code. This module provides a way to generate comments for Go code.
Usage ~ Usage ~
Set cursor on line with function/method/struct/etc and run `:GoCmt` to generate a comment.
Set cursor on line with function/method/struct/etc and
run `:GoCmt` to generate a comment.
vim:tw=78:ts=8:noet:ft=help:norl: vim:tw=78:ts=8:noet:ft=help:norl:

View file

@ -1,51 +0,0 @@
local r = require "gopher._utils.runner"
local c = require("gopher.config").commands
local u = require "gopher._utils"
local gocmd = {}
---@param args string[]
---@return string[]
local function if_get(args)
for i, arg in ipairs(args) do
local m = string.match(arg, "^https://(.*)$") or string.match(arg, "^http://(.*)$") or arg
table.remove(args, i)
table.insert(args, i, m)
end
return args
end
---@param args unknown[]
---@return string[]
local function if_generate(args)
if #args == 1 and args[1] == "%" then
args[1] = vim.fn.expand "%"
end
return args
end
---@param subcmd string
---@param args string[]
---@return string
function gocmd.run(subcmd, args)
if #args == 0 and subcmd ~= "generate" then
error "please provide any arguments"
end
if subcmd == "get" then
args = if_get(args)
end
if subcmd == "generate" then
args = if_generate(args)
end
local rs = r.sync { c.go, subcmd, unpack(args) }
if rs.code ~= 0 then
error("go " .. subcmd .. " failed: " .. rs.stderr)
end
u.notify(c.go .. " " .. subcmd .. " ran successful")
return rs.stdout
end
return gocmd

View file

@ -3,7 +3,7 @@ local log = require "gopher._utils.log"
local utils = {} local utils = {}
---@param msg string ---@param msg string
---@param lvl? number by default `vim.log.levels.INFO` ---@param lvl? integer by default `vim.log.levels.INFO`
function utils.notify(msg, lvl) function utils.notify(msg, lvl)
lvl = lvl or vim.log.levels.INFO lvl = lvl or vim.log.levels.INFO
vim.notify(msg, lvl, { vim.notify(msg, lvl, {
@ -38,4 +38,35 @@ function utils.trimend(s)
return r return r
end end
-- Since indentation can be spaces or tabs, that's my hack around it
---@param line string
---@param indent integer
---@return string
function utils.indent(line, indent)
local char = string.sub(line, 1, 1)
if char ~= " " and char ~= "\t" then
char = " "
end
return string.rep(char, indent)
end
---@generic T
---@param tbl T[]
---@return T[]
function utils.list_unique(tbl)
if vim.fn.has "nvim-0.12" == 1 then
return vim.list.unique(tbl)
end
for i = #tbl, 1, -1 do
for j = 1, i - 1 do
if tbl[i] == tbl[j] then
table.remove(tbl, i)
break
end
end
end
return tbl
end
return utils return utils

View file

@ -3,7 +3,7 @@
-- for the code i have stolen(or have inspected by idk) -- for the code i have stolen(or have inspected by idk)
local c = require "gopher.config" local c = require "gopher.config"
---@class Gopher.Logger ---@class gopher.Logger
---@field get_outfile fun():string ---@field get_outfile fun():string
---@field trace fun(...) ---@field trace fun(...)
---@field fmt_trace fun(...) ---@field fmt_trace fun(...)
@ -44,7 +44,7 @@ local config = {
float_precision = 0.01, float_precision = 0.01,
} }
---@type Gopher.Logger ---@type gopher.Logger
---@diagnostic disable-next-line: missing-fields ---@diagnostic disable-next-line: missing-fields
local log = {} local log = {}

View file

@ -11,9 +11,13 @@ local queries = {
right: (expression_list (composite_literal right: (expression_list (composite_literal
type: (struct_type))))] type: (struct_type))))]
]], ]],
struct_field = [[
(field_declaration name: (field_identifier) @_name)
]],
func = [[ func = [[
[(function_declaration name: (identifier) @_name) [(function_declaration name: (identifier) @_name)
(method_declaration name: (field_identifier) @_name)] (method_declaration name: (field_identifier) @_name)
(method_elem name: (field_identifier) @_name)]
]], ]],
package = [[ package = [[
(package_identifier) @_name (package_identifier) @_name
@ -23,12 +27,17 @@ local queries = {
name: (type_identifier) @_name name: (type_identifier) @_name
type: (interface_type)) type: (interface_type))
]], ]],
var = [[
[(var_declaration (var_spec name: (identifier) @_name))
(short_var_declaration
left: (expression_list (identifier) @_name @_var))]
]],
} }
---@param parent_type string[] ---@param parent_type string[]
---@param node TSNode ---@param node TSNode
---@return TSNode? ---@return TSNode?
local function get_parrent_node(parent_type, node) local function get_parent_node(parent_type, node)
---@type TSNode? ---@type TSNode?
local current = node local current = node
while current do while current do
@ -64,10 +73,11 @@ local function get_captures(query, node, bufnr)
end end
---@class gopher.TsResult ---@class gopher.TsResult
---@field name string ---@field name string Name of the struct, function, etc
---@field start_line integer ---@field start integer Line number where the declaration starts
---@field end_line integer ---@field end_ integer Line number where the declaration ends
---@field is_varstruct boolean ---@field indent integer Number of spaces/tabs in the current cursor line
---@field is_varstruct boolean Is struct declared as `var S struct{}` or `s := struct{}{}`
---@param bufnr integer ---@param bufnr integer
---@param parent_type string[] ---@param parent_type string[]
@ -78,25 +88,24 @@ local function do_stuff(bufnr, parent_type, query)
error "No treesitter parser found for go" error "No treesitter parser found for go"
end end
local node = vim.treesitter.get_node { local node = vim.treesitter.get_node { bufnr = bufnr }
bufnr = bufnr,
}
if not node then if not node then
error "No nodes found under cursor" error "No nodes found under the cursor"
end end
local parent_node = get_parrent_node(parent_type, node) local parent_node = get_parent_node(parent_type, node)
if not parent_node then if not parent_node then
error "No parent node found under cursor" error "No parent node found under the cursor"
end end
local q = vim.treesitter.query.parse("go", query) local q = vim.treesitter.query.parse("go", query)
local res = get_captures(q, parent_node, bufnr) local res = get_captures(q, parent_node, bufnr)
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, start_col, end_row, _ = parent_node:range()
res["start_line"] = start_row + 1 res["indent"] = start_col
res["end_line"] = end_row + 1 res["start"] = start_row + 1
res["end_"] = end_row + 1
return res return res
end end
@ -104,11 +113,12 @@ end
---@param bufnr integer ---@param bufnr integer
function ts.get_struct_under_cursor(bufnr) function ts.get_struct_under_cursor(bufnr)
--- should be both type_spec and type_declaration --- should be both type_spec and type_declaration
--- because in cases like `type ( T struct{}, U strict{} )` --- because in cases like `type ( T struct{}, U struct{} )`
--- i will be choosing always last struct in the list
--- ---
--- var_declaration is for cases like `var x struct{}` --- var_declaration is for cases like `var x struct{}`
--- short_var_declaration is for cases like `x := struct{}{}` --- short_var_declaration is for cases like `x := struct{}{}`
---
--- it always chooses last struct type in the list
return do_stuff(bufnr, { return do_stuff(bufnr, {
"type_spec", "type_spec",
"type_declaration", "type_declaration",
@ -117,10 +127,19 @@ function ts.get_struct_under_cursor(bufnr)
}, queries.struct) }, queries.struct)
end end
---@param bufnr integer
function ts.get_struct_field_under_cursor(bufnr)
return do_stuff(bufnr, { "field_declaration" }, queries.struct_field)
end
---@param bufnr integer ---@param bufnr integer
function ts.get_func_under_cursor(bufnr) function ts.get_func_under_cursor(bufnr)
--- since this handles both and funcs and methods we should check for both parent nodes --- since this handles both and funcs and methods we should check for both parent nodes
return do_stuff(bufnr, { "function_declaration", "method_declaration" }, queries.func) return do_stuff(bufnr, {
"method_elem",
"function_declaration",
"method_declaration",
}, queries.func)
end end
---@param bufnr integer ---@param bufnr integer
@ -133,4 +152,9 @@ function ts.get_interface_under_cursor(bufnr)
return do_stuff(bufnr, { "type_declaration" }, queries.interface) return do_stuff(bufnr, { "type_declaration" }, queries.interface)
end end
---@param bufnr integer
function ts.get_variable_under_cursor(bufnr)
return do_stuff(bufnr, { "var_declaration", "short_var_declaration" }, queries.var)
end
return ts return ts

View file

@ -3,36 +3,46 @@
---@text ---@text
--- This module provides a way to generate comments for Go code. --- This module provides a way to generate comments for Go code.
--- ---
---@usage Set cursor on line with function/method/struct/etc and run `:GoCmt` to generate a comment. ---@usage
--- Set cursor on line with function/method/struct/etc and
--- run `:GoCmt` to generate a comment.
local ts = require "gopher._utils.ts" local ts = require "gopher._utils.ts"
local log = require "gopher._utils.log" local log = require "gopher._utils.log"
local u = require "gopher._utils"
local comment = {} local comment = {}
---@param name string --- NOTE: The order of functions executed inside this function is IMPORTANT.
--- This function is extremely fragile; run tests after making any changes.
---
---@param bufnr integer
---@param line string
---@return string ---@return string
---@dochide ---@dochide
local function template(name) local function generate(bufnr, line)
return "// " .. name .. " " local sf_ok, sf_res = pcall(ts.get_struct_field_under_cursor, bufnr)
if sf_ok then
return u.indent(line, sf_res.indent) .. "// " .. sf_res.name .. " "
end end
---@param bufnr integer
---@return string
---@dochide
local function generate(bufnr)
local s_ok, s_res = pcall(ts.get_struct_under_cursor, bufnr) local s_ok, s_res = pcall(ts.get_struct_under_cursor, bufnr)
if s_ok then if s_ok then
return template(s_res.name) return u.indent(line, s_res.indent) .. "// " .. s_res.name .. " "
end
local v_ok, v_res = pcall(ts.get_variable_under_cursor, bufnr)
if v_ok then
return u.indent(line, v_res.indent) .. "// " .. v_res.name .. " "
end end
local f_ok, f_res = pcall(ts.get_func_under_cursor, bufnr) local f_ok, f_res = pcall(ts.get_func_under_cursor, bufnr)
if f_ok then if f_ok then
return template(f_res.name) return u.indent(line, f_res.indent) .. "// " .. f_res.name .. " "
end end
local i_ok, i_res = pcall(ts.get_interface_under_cursor, bufnr) local i_ok, i_res = pcall(ts.get_interface_under_cursor, bufnr)
if i_ok then if i_ok then
return template(i_res.name) return u.indent(line, i_res.indent) .. "// " .. i_res.name .. " "
end end
local p_ok, p_res = pcall(ts.get_package_under_cursor, bufnr) local p_ok, p_res = pcall(ts.get_package_under_cursor, bufnr)
@ -45,12 +55,16 @@ end
function comment.comment() function comment.comment()
local bufnr = vim.api.nvim_get_current_buf() local bufnr = vim.api.nvim_get_current_buf()
local cmt = generate(bufnr) local lnum = vim.fn.getcurpos()[2]
log.debug("generated comment: " .. cmt) local line = vim.fn.getline(lnum)
local cmt = generate(bufnr, line)
log.debug("generated comment:", {
comment = cmt,
line = line,
})
local pos = vim.fn.getcurpos()[2] vim.fn.append(lnum - 1, cmt)
vim.fn.append(pos - 1, cmt) vim.fn.setpos(".", { bufnr, lnum, #cmt })
vim.fn.setpos(".", { 0, pos, #cmt })
vim.cmd "startinsert!" vim.cmd "startinsert!"
end end

View file

@ -1,3 +1,6 @@
---@type gopher.Config
---@dochide
---@diagnostic disable-next-line: missing-fields .setup() gets injected later
local config = {} local config = {}
---@tag gopher.nvim-config.ConfigGoTagTransform ---@tag gopher.nvim-config.ConfigGoTagTransform
@ -16,6 +19,7 @@ local config = {}
---@tag gopher.nvim-config ---@tag gopher.nvim-config
---@eval return MiniDoc.afterlines_to_code(MiniDoc.current.eval_section) ---@eval return MiniDoc.afterlines_to_code(MiniDoc.current.eval_section)
---@class gopher.Config ---@class gopher.Config
---@field setup fun(user_config?: gopher.Config)
local default_config = { local default_config = {
-- log level, you might consider using DEBUG or TRACE for debugging the plugin -- log level, you might consider using DEBUG or TRACE for debugging the plugin
---@type number ---@type number
@ -25,7 +29,8 @@ local default_config = {
---@type number ---@type number
timeout = 2000, timeout = 2000,
--- timeout for running installer commands(e.g :GoDepsInstall, :GoDepsInstallSync) -- timeout for running installer commands(e.g :GoDepsInstall, :GoDepsInstallSync)
---@type number
installer_timeout = 999999, installer_timeout = 999999,
-- user specified paths to binaries -- user specified paths to binaries
@ -36,15 +41,19 @@ local default_config = {
gotests = "gotests", gotests = "gotests",
impl = "impl", impl = "impl",
iferr = "iferr", iferr = "iferr",
json2go = "json2go",
}, },
---@class gopher.ConfigGotests ---@class gopher.ConfigGotests
gotests = { gotests = {
-- gotests doesn't have template named "default" so this plugin uses "default" to set the default template -- a default template that gotess will use.
-- gotets doesn't have template named `default`, we use it to represent absence of the provided template.
template = "default", template = "default",
-- path to a directory containing custom test code templates -- path to a directory containing custom test code templates
---@type string|nil ---@type string|nil
template_dir = nil, template_dir = nil,
-- switch table tests from using slice to map (with test name for the key)
-- use named tests(map with test name as key) in table tests(slice of structs by default)
named = false, named = false,
}, },
---@class gopher.ConfigGoTag ---@class gopher.ConfigGoTag
@ -54,12 +63,30 @@ local default_config = {
-- default tags to add to struct fields -- default tags to add to struct fields
default_tag = "json", default_tag = "json",
-- default tag option added struct fields, set to nil to disable
-- e.g: `option = "json=omitempty,xml=omitempty`
---@type string|nil
option = nil,
}, },
---@class gopher.ConfigIfErr
iferr = { iferr = {
-- choose a custom error message -- choose a custom error message, nil to use default
-- e.g: `message = 'fmt.Errorf("failed to %w", err)'`
---@type string|nil ---@type string|nil
message = nil, message = nil,
}, },
---@class gopher.ConfigJson2Go
json2go = {
-- command used to open interactive input.
-- e.g: `split`, `botright split`, `tabnew`
interactive_cmd = "vsplit",
-- name of autogenerated struct, if nil none, will the default one of json2go.
-- e.g: "MySuperCoolName"
---@type string|nil
type_name = nil,
},
} }
--minidoc_afterlines_end --minidoc_afterlines_end
@ -77,30 +104,32 @@ _config.___plugin_name = "gopher.nvim" ---@diagnostic disable-line: inject-field
---@param user_config? gopher.Config ---@param user_config? gopher.Config
---@dochide ---@dochide
function config.setup(user_config) function config.setup(user_config)
vim.validate { user_config = { user_config, "table", true } } vim.validate("user_config", user_config, "table", true)
_config = vim.tbl_deep_extend("force", vim.deepcopy(default_config), user_config or {}) _config = vim.tbl_deep_extend("force", vim.deepcopy(default_config), user_config or {})
vim.validate { vim.validate("log_level", _config.log_level, "number")
log_level = { _config.log_level, "number" }, vim.validate("timeout", _config.timeout, "number")
timeout = { _config.timeout, "number" }, vim.validate("installer_timeout", _config.timeout, "number")
installer_timeout = { _config.installer_timeout, "number" }, vim.validate("commands", _config.commands, "table")
["commands"] = { _config.commands, "table" }, vim.validate("commands.go", _config.commands.go, "string")
["commands.go"] = { _config.commands.go, "string" }, vim.validate("commands.gomodifytags", _config.commands.gomodifytags, "string")
["commands.gomodifytags"] = { _config.commands.gomodifytags, "string" }, vim.validate("commands.gotests", _config.commands.gotests, "string")
["commands.gotests"] = { _config.commands.gotests, "string" }, vim.validate("commands.impl", _config.commands.impl, "string")
["commands.impl"] = { _config.commands.impl, "string" }, vim.validate("commands.iferr", _config.commands.iferr, "string")
["commands.iferr"] = { _config.commands.iferr, "string" }, vim.validate("commands.json2go", _config.commands.json2go, "string")
["gotests"] = { _config.gotests, "table" }, vim.validate("gotests", _config.gotests, "table")
["gotests.template"] = { _config.gotests.template, "string" }, vim.validate("gotests.template", _config.gotests.template, "string")
["gotests.template_dir"] = { _config.gotests.template, "string", true }, vim.validate("gotests.template_dir", _config.gotests.template_dir, { "string", "nil" })
["gotests.named"] = { _config.gotests.named, "boolean" }, vim.validate("gotests.named", _config.gotests.named, "boolean")
["gotag"] = { _config.gotag, "table" }, vim.validate("gotag", _config.gotag, "table")
["gotag.transform"] = { _config.gotag.transform, "string" }, vim.validate("gotag.transform", _config.gotag.transform, "string")
["gotag.default_tag"] = { _config.gotag.default_tag, "string" }, vim.validate("gotag.default_tag", _config.gotag.default_tag, "string")
["iferr"] = { _config.iferr, "table" }, vim.validate("gotag.option", _config.gotag.option, { "string", "nil" })
["iferr.message"] = { _config.iferr.message, "string", true }, vim.validate("iferr", _config.iferr, "table")
} vim.validate("iferr.message", _config.iferr.message, { "string", "nil" })
vim.validate("json2go.installer_timeout", _config.json2go.interactive_cmd, "string")
vim.validate("json2go.type_name", _config.json2go.type_name, { "string", "nil" })
end end
setmetatable(config, { setmetatable(config, {
@ -110,5 +139,4 @@ setmetatable(config, {
}) })
---@dochide ---@dochide
---@return gopher.Config
return config return config

56
lua/gopher/go.lua Normal file
View file

@ -0,0 +1,56 @@
local c = require "gopher.config"
local u = require "gopher._utils"
local r = require "gopher._utils.runner"
local go = {}
local function run(subcmd, args)
local rs = r.sync { c.commands.go, subcmd, unpack(args) }
if rs.code ~= 0 then
error("go " .. subcmd .. " failed: " .. rs.stderr)
end
u.notify(c.commands.go .. " " .. subcmd .. " ran successful")
return rs.stdout
end
---@param args string[]
function go.get(args)
for i, arg in ipairs(args) do
local m = string.match(arg, "^https://(.*)$") or string.match(arg, "^http://(.*)$") or arg
table.remove(args, i)
table.insert(args, i, m)
end
run("get", args)
end
---@param args string[]
function go.mod(args)
run("mod", args)
end
---@param args string[]
function go.work(args)
-- TODO: use `gopls.tidy`
run("work", args)
end
---Executes `go generate`
---If only argument is `%` it's going to be equivalent to `go generate <path to current file>`
---@param args string[]
function go.generate(args)
-- TODO: use `gopls.generate`
if #args == 0 then
error "please provide arguments"
end
if #args == 1 and args[1] == "%" then
args[1] = vim.fn.expand "%"
end
run("generate", args)
end
return go

View file

@ -12,8 +12,9 @@
--- - Generate unit tests *only* for *exported(public)* functions/methods: --- - Generate unit tests *only* for *exported(public)* functions/methods:
--- - run `:GoTestsExp` --- - run `:GoTestsExp`
--- ---
--- You can also specify the template to use for generating the tests. See |gopher.nvim-config| --- You can also specify the template to use for generating the tests.
--- More details about templates can be found at: https://github.com/cweill/gotests --- See |gopher.nvim-config|.
--- More details about templates: https://github.com/cweill/gotests
--- ---
--- If you prefer named tests, you can enable them in |gopher.nvim-config|. --- If you prefer named tests, you can enable them in |gopher.nvim-config|.

View file

@ -1,62 +1,58 @@
local c = require("gopher.config").commands
local health = {} local health = {}
local cmd = require("gopher.config").commands
local deps = { local deps = {
vim_version = "nvim-0.10",
bin = { bin = {
{ {
bin = cmd.go, bin = c.go,
msg = "required for `:GoGet`, `:GoMod`, `:GoGenerate`, `:GoWork`, `:GoInstallDeps`, `:GoInstallDepsSync`", msg = "required for `:GoGet`, `:GoMod`, `:GoGenerate`, `:GoWork`, `:GoInstallDeps`, `:GoInstallDepsSync`",
optional = false,
},
{ bin = cmd.gomodifytags, msg = "required for `:GoTagAdd`, `:GoTagRm`", optional = true },
{ bin = cmd.impl, msg = "required for `:GoImpl`", optional = true },
{ bin = cmd.iferr, msg = "required for `:GoIfErr`", optional = true },
{
bin = cmd.gotests,
msg = "required for `:GoTestAdd`, `:GoTestsAll`, `:GoTestsExp`",
optional = true,
}, },
{ bin = c.gomodifytags, msg = "required for `:GoTagAdd`, `:GoTagRm`" },
{ bin = c.impl, msg = "required for `:GoImpl`" },
{ bin = c.iferr, msg = "required for `:GoIfErr`" },
{ bin = c.gotests, msg = "required for `:GoTestAdd`, `:GoTestsAll`, `:GoTestsExp`" },
}, },
treesitter = { treesitter = {
{ parser = "go", msg = "required for most of the parts of `gopher.nvim`" }, { parser = "go", msg = "required for most of the parts of `gopher.nvim`" },
}, },
} }
---@param bin string ---@param bin {bin:string, msg:string, optional:boolean}
---@return boolean local function check_binary(bin)
local function is_binary_found(bin) if vim.fn.executable(bin.bin) == 1 then
return vim.fn.executable(bin) == 1 vim.health.ok(bin.bin .. " is found oh PATH: `" .. vim.fn.exepath(bin.bin) .. "`")
else
vim.health.error(bin.bin .. " not found on PATH, " .. bin.msg)
end
end end
---@param ft string ---@param ts {parser:string, msg:string}
---@return boolean local function check_treesitter(ts)
local function is_treesitter_parser_available(ft) local ok, parser = pcall(vim.treesitter.get_parser, 0, ts.parser)
local ok, parser = pcall(vim.treesitter.get_parser, 0, ft) if ok and parser ~= nil then
return ok and parser ~= nil vim.health.ok("`" .. ts.parser .. "` parser is installed")
else
vim.health.error("`" .. ts.parser .. "` parser not found")
end
end end
function health.check() function health.check()
vim.health.start "required binaries" vim.health.start "Neovim version"
vim.health.info "all those binaries can be installed by `:GoInstallDeps`" if vim.fn.has(deps.vim_version) == 1 then
for _, bin in ipairs(deps.bin) do vim.health.ok "Neovim version is compatible"
if is_binary_found(bin.bin) then
vim.health.ok(bin.bin .. " installed")
else else
if bin.optional then vim.health.error(deps.vim_version .. " or newer is required")
vim.health.warn(bin.bin .. " not found, " .. bin.msg)
else
vim.health.error(bin.bin .. " not found, " .. bin.msg)
end
end
end end
vim.health.start "required treesitter parsers" vim.health.start "Required binaries (those can be installed with `:GoInstallDeps`)"
for _, parser in ipairs(deps.treesitter) do for _, bin in ipairs(deps.bin) do
if is_treesitter_parser_available(parser.parser) then check_binary(bin)
vim.health.ok(parser.parser .. " parser installed")
else
vim.health.error(parser.parser .. " parser not found, " .. parser.msg)
end end
vim.health.start "Treesitter"
for _, parser in ipairs(deps.treesitter) do
check_treesitter(parser)
end end
end end

View file

@ -42,7 +42,7 @@ function iferr.iferr()
vim.fn.append(pos, u.remove_empty_lines(vim.split(rs.stdout, "\n"))) vim.fn.append(pos, u.remove_empty_lines(vim.split(rs.stdout, "\n")))
vim.cmd [[silent normal! j=2j]] vim.cmd [[silent normal! j=2j]]
vim.fn.setpos(".", pos) vim.fn.setpos(".", pos --[[@as integer[] ]])
end end
return iferr return iferr

View file

@ -3,7 +3,8 @@
---@text ---@text
--- Integration of `impl` tool to generate method stubs for interfaces. --- Integration of `impl` tool to generate method stubs for interfaces.
--- ---
---@usage 1. Automatically implement an interface for a struct: ---@usage
--- 1. Automatically implement an interface for a struct:
--- - Place your cursor on the struct where you want to implement the interface. --- - Place your cursor on the struct where you want to implement the interface.
--- - Run `:GoImpl io.Reader` --- - Run `:GoImpl io.Reader`
--- - This will automatically determine the receiver and implement the `io.Reader` interface. --- - This will automatically determine the receiver and implement the `io.Reader` interface.

View file

@ -13,7 +13,7 @@
local log = require "gopher._utils.log" local log = require "gopher._utils.log"
local tags = require "gopher.struct_tags" local tags = require "gopher.struct_tags"
local tests = require "gopher.gotests" local tests = require "gopher.gotests"
local gocmd = require("gopher._utils.gocmd").run local go = require "gopher.go"
local gopher = {} local gopher = {}
---@toc_entry Setup ---@toc_entry Setup
@ -35,11 +35,11 @@ end
---@toc_entry Install dependencies ---@toc_entry Install dependencies
---@tag gopher.nvim-dependencies ---@tag gopher.nvim-dependencies
---@text Gopher.nvim implements most of its features using third-party tools. ---@text
--- To install these tools, you can run `:GoInstallDeps` command --- Gopher.nvim implements most of its features using third-party tools. To
--- or call `require("gopher").install_deps()` if you want to use lua api. --- install plugin's dependencies, you can run:
--- By default dependencies will be installed asynchronously, --- `:GoInstallDeps` or `:GoInstallDepsSync`
--- to install them synchronously pass `{sync = true}` as an argument. --- or use `require("gopher").install_deps()` if you prefer lua api.
gopher.install_deps = require("gopher.installer").install_deps gopher.install_deps = require("gopher.installer").install_deps
gopher.impl = require("gopher.impl").impl gopher.impl = require("gopher.impl").impl
@ -58,20 +58,9 @@ gopher.test = {
all = tests.all_tests, all = tests.all_tests,
} }
gopher.get = function(...) gopher.get = go.get
gocmd("get", ...) gopher.mod = go.mod
end gopher.work = go.work
gopher.generate = go.generate
gopher.mod = function(...)
gocmd("mod", ...)
end
gopher.generate = function(...)
gocmd("generate", ...)
end
gopher.work = function(...)
gocmd("work", ...)
end
return gopher return gopher

View file

@ -9,6 +9,7 @@ local urls = {
impl = "github.com/josharian/impl@latest", impl = "github.com/josharian/impl@latest",
gotests = "github.com/cweill/gotests/...@develop", gotests = "github.com/cweill/gotests/...@develop",
iferr = "github.com/koron/iferr@latest", iferr = "github.com/koron/iferr@latest",
json2go = "olexsmir.xyz/json2go/cmd/json2go@latest",
} }
---@param opt vim.SystemCompleted ---@param opt vim.SystemCompleted

137
lua/gopher/json2go.lua Normal file
View file

@ -0,0 +1,137 @@
---@toc_entry json2go
---@tag gopher.nvim-json2go
---@text
--- Convert json to go type annotations.
---
---@usage
--- `:GoJson` opens a temporary buffer where you can paste or write JSON.
--- Saving the buffer (`:w` or `:wq`) automatically closes it and inserts the
--- generated Go struct into the original buffer at the cursor position.
---
--- Alternatively, you can pass JSON directly as an argument:
--- >vim
--- :GoJson {"name": "Alice", "age": 30}
--- <
local c = require "gopher.config"
local log = require "gopher._utils.log"
local u = require "gopher._utils"
local r = require "gopher._utils.runner"
local json2go = {}
---@dochide
---@param bufnr integer
---@param cpos integer
---@param type_ string
local function apply(bufnr, cpos, type_)
local lines = vim.api.nvim_buf_get_lines(bufnr, 0, -1, false)
local input_lines = u.remove_empty_lines(vim.split(type_, "\n"))
for i, line in pairs(input_lines) do
table.insert(lines, cpos + i, line)
end
vim.api.nvim_buf_set_lines(bufnr, 0, -1, true, lines)
end
-- Convert json string to go type.
---
---@param json_str string Json string that is going to be converted to go type.
---@return string? Go type, or nil if failed.
function json2go.transform(json_str)
local cmd = { c.commands.json2go }
if c.json2go.type_name then
table.insert(cmd, "-type", c.json2go.type_name)
end
local rs = r.sync(cmd, { stdin = json_str })
if rs.code ~= 0 then
u.notify("json2go: got this error: " .. rs.stdout, vim.log.levels.ERROR)
log.error("json2go: got this error: " .. rs.stdout)
return
end
return rs.stdout
end
---@dochide
---@param ocpos integer
local function interactive(ocpos)
local obuf = vim.api.nvim_get_current_buf()
local owin = vim.api.nvim_get_current_win()
-- setup the input window
local buf = vim.api.nvim_create_buf(false, true)
vim.cmd(c.json2go.interactive_cmd)
local win = vim.api.nvim_get_current_win()
vim.api.nvim_win_set_buf(win, buf)
vim.api.nvim_buf_set_name(buf, "[GoJson input]")
vim.api.nvim_set_option_value("filetype", "jsonc", { buf = buf })
vim.api.nvim_set_option_value("buftype", "acwrite", { buf = buf })
vim.api.nvim_set_option_value("swapfile", false, { buf = buf })
vim.api.nvim_set_option_value("bufhidden", "delete", { buf = buf })
vim.api.nvim_buf_set_lines(buf, 0, -1, false, {
"// Write your json here.",
"// Writing and quitting (:wq), will generate go struct under the cursor.",
"",
"",
})
vim.api.nvim_create_autocmd("BufLeave", { buffer = buf, command = "stopinsert" })
vim.api.nvim_create_autocmd("BufWriteCmd", {
buffer = buf,
once = true,
callback = function()
local input = vim.api.nvim_buf_get_lines(buf, 0, -1, true)
local inp = table.concat(
vim
.iter(input)
:filter(function(line)
local found = string.find(line, "^//.*")
return (not found) or (line == "")
end)
:totable(),
"\n"
)
local go_type = json2go.transform(inp)
if not go_type then
error "cound't convert json to go type"
end
vim.api.nvim_set_option_value("modified", false, { buf = buf })
apply(obuf, ocpos, go_type)
vim.api.nvim_set_current_win(owin)
vim.api.nvim_win_set_cursor(owin, { ocpos + 1, 0 })
vim.schedule(function()
pcall(vim.api.nvim_win_close, win, true)
pcall(vim.api.nvim_buf_delete, buf, {})
end)
end,
})
vim.cmd "normal! G"
vim.cmd "startinsert"
end
--- Converts json string to go type, and puts result under the cursor. If
--- [json_str] is nil, will open an interactive prompt (with cmd set in
--- config).
---
---@param json_str? string
function json2go.json2go(json_str)
local cur_line = vim.api.nvim_win_get_cursor(0)[1]
if not json_str then
interactive(cur_line)
return
end
local go_type = json2go.transform(json_str)
if not go_type then
error "cound't convert json to go type"
end
apply(0, cur_line, go_type)
end
return json2go

View file

@ -1,15 +1,20 @@
---@toc_entry Modify struct tags ---@toc_entry Modify struct tags
---@tag gopher.nvim-struct-tags ---@tag gopher.nvim-struct-tags
---@text ---@text
--- `struct_tags` is utilizing the `gomodifytags` tool to add or remove tags to struct fields. --- `struct_tags` is utilizing the `gomodifytags` tool to add or remove tags to
--- struct fields.
--- ---
---@usage ---@usage
--- How to add/remove tags to struct fields: --- How to add/remove/clear tags to struct fields:
--- 1. Place cursor on the struct --- 1. Place cursor on the struct
--- 2. Run `:GoTagAdd json` to add json tags to struct fields --- 2. Run `:GoTagAdd json` to add json tags to struct fields
--- 3. Run `:GoTagRm json` to remove json tags to struct fields --- 3. Run `:GoTagRm json` to remove json tags to struct fields
--- 4. Run `:GoTagClear` to clear all tags from struct fields
---
--- If you want to add/remove tag with options, you can use `json=omitempty`
--- (where json is tag, and omitempty is its option).
--- Example: `:GoTagAdd xml json=omitempty`
--- ---
--- To clear all tags from struct run: `:GoTagClear`
--- ---
--- NOTE: if you dont specify the tag it will use `json` as default --- NOTE: if you dont specify the tag it will use `json` as default
--- ---
@ -37,11 +42,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 input 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 +69,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)
@ -90,49 +107,94 @@ local function handle_tags(fpath, bufnr, user_args)
) )
end end
---@dochide
---@param option string
local function option_to_tag(option)
return option:match "^(.-)="
end
---@dochide
---@param args string[] ---@param args string[]
---@return string local function unwrap_if_needed(args)
---@dochide local out = {}
local function handler_user_args(args) for _, v in pairs(args) do
if #args == 0 then for _, p in pairs(vim.split(v, ",")) do
return c.gotag.default_tag table.insert(out, p)
end end
return table.concat(args, ",") end
return out
end end
-- Adds tags to a struct under the cursor
-- See |gopher.nvim-struct-tags|
---@param ... string Tags to add to the struct fields. If not provided, it will use [config.gotag.default_tag]
---@dochide ---@dochide
function struct_tags.add(...) ---@class gopher.StructTagsArgs
local args = { ... } ---@field tags string
---@field options string
---@dochide
---@param args string[]
---@return gopher.StructTagsArgs
function struct_tags.parse_args(args)
args = unwrap_if_needed(args)
local tags, options = {}, {}
for _, v in pairs(args) do
if string.find(v, "=") then
table.insert(options, v)
table.insert(tags, option_to_tag(v))
else
table.insert(tags, v)
end
end
return {
tags = table.concat(u.list_unique(tags), ","),
options = table.concat(u.list_unique(options), ","),
}
end
-- Adds tags to a struct under the cursor. See `:h gopher.nvim-struct-tags`.
---@param opts gopher.StructTagInput
---@dochide
function struct_tags.add(opts)
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_args = struct_tags.parse_args(opts.input)
handle_tags(fpath, bufnr, { "-add-tags", user_tags }) handle_tags(fpath, bufnr, opts.range, {
"-add-tags",
(user_args.tags ~= "") and user_args.tags or c.gotag.default_tag,
(user_args.options ~= "" or c.gotag.option) and "-add-options" or nil,
(user_args.options ~= "") and user_args.options or c.gotag.option,
})
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_args = struct_tags.parse_args(opts.input)
handle_tags(fpath, bufnr, { "-remove-tags", user_tags }) handle_tags(fpath, bufnr, opts.range, {
"-remove-tags",
(user_args.tags ~= "") and user_args.tags or c.gotag.default_tag,
(user_args.options ~= "" or c.gotag.option ~= nil) and "-remove-options" or nil,
(user_args.options ~= "") and user_args.options or c.gotag.option,
})
end end
-- Removes all tags from a struct under the cursor -- Removes all tags from a struct under the cursor.
-- See `:h gopher.nvim-struct-tags` -- See `:h gopher.nvim-struct-tags`.
---@dochide ---@dochide
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,17 +47,35 @@ end)
-- :GoTag -- :GoTag
cmd("GoTagAdd", function(opts) cmd("GoTagAdd", function(opts)
require("gopher").tags.add(unpack(opts.fargs)) require("gopher").tags.add {
end, "*") input = 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, "*") input = 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()
end) end)
-- :GoJson
cmd("GoJson", function(opts)
local inp = ((opts.args ~= "" and opts.args) or nil)
require("gopher.json2go").json2go(inp)
end, "*")
-- :GoTest -- :GoTest
cmd("GoTestAdd", function() cmd("GoTestAdd", function()
require("gopher").test.add() require("gopher").test.add()
@ -74,7 +95,6 @@ cmd("GoMod", function(opts)
end, "*") end, "*")
cmd("GoGet", function(opts) cmd("GoGet", function(opts)
vim.print(opts)
require("gopher").get(opts.fargs) require("gopher").get(opts.fargs)
end, "*") end, "*")
@ -83,5 +103,5 @@ cmd("GoWork", function(opts)
end, "*") end, "*")
cmd("GoGenerate", function(opts) cmd("GoGenerate", function(opts)
require("gopher").generate(opts.fargs or "") require("gopher").generate(opts.fargs or { "" })
end, "?") end, "?")

View file

@ -12,6 +12,7 @@ local files = {
"lua/gopher/config.lua", "lua/gopher/config.lua",
"plugin/gopher.lua", "plugin/gopher.lua",
"lua/gopher/struct_tags.lua", "lua/gopher/struct_tags.lua",
"lua/gopher/json2go.lua",
"lua/gopher/impl.lua", "lua/gopher/impl.lua",
"lua/gopher/gotests.lua", "lua/gopher/gotests.lua",
"lua/gopher/iferr.lua", "lua/gopher/iferr.lua",

View file

@ -20,9 +20,9 @@ local function install_plug(plugin)
end end
end end
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 +32,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 +55,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", {

View file

@ -0,0 +1,6 @@
package main
type Testinger interface {
Get(id string) int
Set(id string, val int)
}

View file

@ -0,0 +1,7 @@
package main
type Testinger interface {
Get(id string) int
// Set
Set(id string, val int)
}

View file

@ -0,0 +1,5 @@
package main
type Testinger interface {
Method(input string) error
}

View file

@ -0,0 +1,6 @@
package main
type Testinger interface {
// Method
Method(input string) error
}

View file

@ -0,0 +1,18 @@
package main
type (
TestOne struct {
Asdf string
ID int
}
TestTwo struct {
Fesa int
A bool
}
TestThree struct {
Asufj int
Fs string
}
)

View file

@ -0,0 +1,19 @@
package main
type (
TestOne struct {
Asdf string
ID int
}
TestTwo struct {
// Fesa
Fesa int
A bool
}
TestThree struct {
Asufj int
Fs string
}
)

View file

@ -0,0 +1,7 @@
package main
type CommentStruct struct {
Name string
Address string
Aliases []string
}

View file

@ -0,0 +1,8 @@
package main
type CommentStruct struct {
Name string
// Address
Address string
Aliases []string
}

5
spec/fixtures/comment/svar_input.go vendored Normal file
View file

@ -0,0 +1,5 @@
package main
func varTest() {
s := "something"
}

6
spec/fixtures/comment/svar_output.go vendored Normal file
View file

@ -0,0 +1,6 @@
package main
func varTest() {
// s
s := "something"
}

5
spec/fixtures/comment/var_input.go vendored Normal file
View file

@ -0,0 +1,5 @@
package main
func test() {
var imAVar string
}

6
spec/fixtures/comment/var_output.go vendored Normal file
View file

@ -0,0 +1,6 @@
package main
func test() {
// imAVar
var imAVar string
}

View file

@ -0,0 +1,8 @@
package main
func main() {
var s struct {
API string
Key string
}
}

View file

@ -0,0 +1,9 @@
package main
func main() {
var s struct {
API string
// Key
Key string
}
}

View file

@ -0,0 +1,2 @@
package main

View file

@ -0,0 +1,5 @@
package main
type AutoGenerated struct {
Json bool `json:"json"`
}

2
spec/fixtures/json2go/manual_input.go vendored Normal file
View file

@ -0,0 +1,2 @@
package main

View file

@ -0,0 +1,7 @@
package main
type AutoGenerated struct {
User struct {
Name string `json:"name"`
} `json:"user"`
}

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,8 @@
package main
type Test struct {
ID int
Another struct {
Second string
}
}

View file

@ -0,0 +1,8 @@
package main
type Test struct {
ID int `xml:"id,otheroption"`
Another struct {
Second string `xml:"second,otheroption"`
} `xml:"another,otheroption"`
}

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

@ -0,0 +1,11 @@
package main
type Test struct {
ID int `json:"id,omitempty" xml:"id,someoption"`
Name string `json:"name,omitempty" xml:"name,someoption"`
Num int64 `json:"num,omitempty" xml:"num,someoption"`
Another struct {
First int `json:"first,omitempty" xml:"first,someoption"`
Second string `json:"second,omitempty" xml:"second,someoption"`
} `json:"another,omitempty" xml:"another,someoption"`
}

View file

@ -0,0 +1,11 @@
package main
type Test struct {
ID int `xml:"id,someoption"`
Name string `xml:"name,someoption"`
Num int64 `xml:"num,someoption"`
Another struct {
First int `xml:"first,someoption"`
Second string `xml:"second,someoption"`
} `xml:"another,someoption"`
}

View file

@ -0,0 +1,8 @@
package main
type Test struct {
ID int
Another struct {
Second string
}
}

View file

@ -0,0 +1,8 @@
package main
type Test struct {
ID int `xml:"id,theoption"`
Another struct {
Second string `xml:"second,theoption"`
} `xml:"another,theoption"`
}

11
spec/fixtures/tags/with_option_input.go vendored Normal file
View file

@ -0,0 +1,11 @@
package main
type Test struct {
ID int
Name string
Num int64
Another struct {
First int
Second string
}
}

View file

@ -0,0 +1,11 @@
package main
type Test struct {
ID int `json:"id,omitempty"`
Name string `json:"name,omitempty"`
Num int64 `json:"num,omitempty"`
Another struct {
First int `json:"first,omitempty"`
Second string `json:"second,omitempty"`
} `json:"another,omitempty"`
}

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,55 @@ 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 a comment on struct field"] = function()
do_the_test("struct_fields", { 5, 8 })
end
comment["should add a comment on var struct field"] = function()
do_the_test("var_struct_fields", { 6, 4 })
end
comment["should add a comment on one field of many structs"] = function()
do_the_test("many_structs_fields", { 10, 4 })
end
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["should add comment on interface method"] = function()
do_the_test("interface_method", { 4, 2 })
end
comment["should add a comment on interface with many method"] = function()
do_the_test("interface_many_method", { 5, 2 })
end
comment["should add a comment on a var"] = function()
do_the_test("var", { 4, 2 })
end
comment["should add a comment on a short declared var"] = function()
do_the_test("svar", { 4, 8 })
end
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,11 +10,12 @@ 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)' }
} ]] }
]]
local rs = t.setup_test("iferr/message", child, { 6, 2 }) local rs = t.setup_test("iferr/message", child, { 6, 2 })
child.cmd "GoIfErr" child.cmd "GoIfErr"

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

@ -0,0 +1,25 @@
local t = require "spec.testutils"
local child, T, json2go = t.setup "json2go"
json2go["should convert interativly"] = function()
local rs = t.setup_test("json2go/interativly", child, { 2, 0 })
child.cmd "GoJson"
child.type_keys [[{"json": true}]]
child.type_keys "<Esc>"
child.cmd "wq" -- quit prompt
child.cmd "write" -- the fixture file
t.eq(t.readfile(rs.tmp), rs.fixtures.output)
t.cleanup(rs)
end
json2go["should convert argument"] = function()
local rs = t.setup_test("json2go/manual", child, { 2, 0 })
child.cmd [[GoJson {"user": {"name": "user-ovic"}}]]
child.cmd "write"
t.eq(t.readfile(rs.tmp), rs.fixtures.output)
t.cleanup(rs)
end
return T

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,70 @@ 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
struct_tags["should add tags with option"] = function()
local rs = t.setup_test("tags/with_option", child, { 3, 6 })
child.cmd "GoTagAdd json=omitempty"
child.cmd "write"
t.eq(t.readfile(rs.tmp), rs.fixtures.output)
t.cleanup(rs)
end
struct_tags["should add tags with default option"] = function()
child.lua [[
require("gopher").setup {
gotag = { option = "xml=theoption" },
}
]]
local rs = t.setup_test("tags/with_default_option", child, { 3, 6 })
child.cmd "GoTagAdd xml"
child.cmd "write"
t.eq(t.readfile(rs.tmp), rs.fixtures.output)
t.cleanup(rs)
end
struct_tags["should add tags and overwrite default option"] = function()
child.lua [[
require("gopher").setup {
gotag = { option = "xml=theoption" },
}
]]
local rs = t.setup_test("tags/overwrite_default_option", child, { 3, 6 })
child.cmd "GoTagAdd xml=otheroption"
child.cmd "write"
t.eq(t.readfile(rs.tmp), rs.fixtures.output)
t.cleanup(rs)
end
struct_tags["should remove tag with specified option"] = function()
local rs = t.setup_test("tags/remove_with_option", child, { 3, 6 })
child.cmd "GoTagRm json=omitempty"
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

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

@ -0,0 +1,25 @@
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()
---@diagnostic disable-next-line: missing-fields
require("gopher").setup {}
end
config["should change option"] = function()
local log_level = 1234567890
---@diagnostic disable-next-line: missing-fields
require("gopher").setup {
log_level = log_level,
}
t.eq(log_level, require("gopher.config").log_level)
end
return T

View file

@ -0,0 +1,68 @@
local t = require "spec.testutils"
local _, T, st = t.setup "struct_tags"
st["should parse tags"] = function()
local out = require("gopher.struct_tags").parse_args { "json", "yaml", "etc" }
t.eq(out.tags, "json,yaml,etc")
t.eq(out.options, "")
end
st["should parse tags separated by commas"] = function()
local out = require("gopher.struct_tags").parse_args { "json,yaml,etc" }
t.eq(out.tags, "json,yaml,etc")
t.eq(out.options, "")
end
st["should parse tags separated by command and spaces"] = function()
local out = require("gopher.struct_tags").parse_args {
"json,yaml",
"json=omitempty",
"xml=something",
}
t.eq(out.tags, "json,yaml,xml")
t.eq(out.options, "json=omitempty,xml=something")
end
st["should parse tag with an option"] = function()
local out = require("gopher.struct_tags").parse_args {
"json=omitempty",
"xml",
"xml=theoption",
}
t.eq(out.tags, "json,xml")
t.eq(out.options, "json=omitempty,xml=theoption")
end
st["should parse tags with an option"] = function()
local out = require("gopher.struct_tags").parse_args { "json=omitempty", "yaml" }
t.eq(out.tags, "json,yaml")
t.eq(out.options, "json=omitempty")
end
st["should parse tags with an option separated with comma"] = function()
local out = require("gopher.struct_tags").parse_args { "json=omitempty,yaml" }
t.eq(out.tags, "json,yaml")
t.eq(out.options, "json=omitempty")
end
st["should parse tags with options specified separately"] = function()
local out = require("gopher.struct_tags").parse_args { "json", "yaml", "json=omitempty" }
t.eq(out.tags, "json,yaml")
t.eq(out.options, "json=omitempty")
end
st["should parse tags with options specified separately and separated by comma"] = function()
local out = require("gopher.struct_tags").parse_args { "json,yaml,json=omitempty" }
t.eq(out.tags, "json,yaml")
t.eq(out.options, "json=omitempty")
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,9 +17,43 @@ 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
utils["should add .indent() spaces"] = function()
local u = require "gopher._utils"
local line = " func Test() error {"
local indent = 4
t.eq(" ", u.indent(line, indent))
end
utils["should add .indent() a tab"] = function()
local u = require "gopher._utils"
local line = "\tfunc Test() error {"
local indent = 1
t.eq("\t", u.indent(line, indent))
end
utils["should add .indent() 2 tabs"] = function()
local u = require "gopher._utils"
local line = "\t\tfunc Test() error {"
local indent = 2
t.eq("\t\t", u.indent(line, indent))
end
utils["should .list_unique on list with duplicates"] = function()
local u = require "gopher._utils"
t.eq({ "json", "xml" }, u.list_unique { "json", "xml", "json" })
end
utils["should .list_unique on list with no duplicates"] = function()
local u = require "gopher._utils"
t.eq({ "json", "xml" }, u.list_unique { "json", "xml" })
end
return T return T

23
vhs/Taskfile.yml Normal file
View file

@ -0,0 +1,23 @@
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
json2go:
cmd: vhs json2go.tape

BIN
vhs/comment.gif Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 272 KiB

7
vhs/comment.go Normal file
View file

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

29
vhs/comment.tape Normal file
View file

@ -0,0 +1,29 @@
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 "./nvim.sh comment.go" Enter Show
# package
Type ":GoCmt" Enter Sleep 500ms Escape Sleep 700ms
# func
Type@400ms "jjj"
Type ":GoCmt" Enter Sleep 500ms Escape Sleep 700ms
# struct
Type@400ms "jjj"
Type ":GoCmt" Enter Sleep 500ms Escape Sleep 700ms
# interface
Type@400ms "jjj"
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: 93 KiB

11
vhs/iferr.go Normal file
View file

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

18
vhs/iferr.tape Normal file
View file

@ -0,0 +1,18 @@
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 "./nvim.sh iferr.go" Enter Show
Type "3j"
Type ":GoIfErr" Sleep 500ms Enter
Sleep 5s

BIN
vhs/impl.gif Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

3
vhs/impl.go Normal file
View file

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

18
vhs/impl.tape Normal file
View file

@ -0,0 +1,18 @@
Output impl.gif
Require nvim
Require impl
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 "./nvim.sh impl.go" Enter Show
Type "2j"
Type ":GoImpl c io.Reader" Sleep 700ms Enter
Sleep 5s

BIN
vhs/json2go.gif Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 282 KiB

2
vhs/json2go.go Normal file
View file

@ -0,0 +1,2 @@
package main

27
vhs/json2go.tape Normal file
View file

@ -0,0 +1,27 @@
Output json2go.gif
Require nvim
Require json2go
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 "./nvim.sh json2go.go" Enter Show
Type@0ms "G"
Type@400ms ":GoJson" Sleep 500ms Enter
Type@70ms "{" Enter
Type@70ms `"json": true,` Enter
Type@70ms `"user": {"name": "Name", "of_age": true}` Enter
Type@70ms "}"
Escape Type@500ms ":wq" Enter
Sleep 1s
Type@25ms "G2o" Escape
Type@120ms `:GoJson {"json": true}` 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: 280 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
}
}

31
vhs/tags.tape Normal file
View file

@ -0,0 +1,31 @@
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 "./nvim.sh tags.go" Enter Show
Type@400ms "jjj"
Type ":GoTagAdd json yaml" Sleep 500ms Enter
Type@120ms ":w" Enter
Sleep 1s
Type ":GoTagRm json" Sleep 500ms Enter
Type ":w" Enter
Sleep 1s
Type ":GoTagClear" Sleep 500ms Enter
Type ":w" Enter
Sleep 1s
Type@400ms "jVjj"
Type ":GoTagAdd json=omitempty" Sleep 500ms Enter
Sleep 5s