Skip to content
This repository has been archived by the owner on May 29, 2024. It is now read-only.

Commit

Permalink
Support formatting using gofmt and gofumpt
Browse files Browse the repository at this point in the history
  • Loading branch information
harry-hov committed Sep 22, 2023
1 parent eac5918 commit 394dd10
Show file tree
Hide file tree
Showing 3 changed files with 73 additions and 0 deletions.
46 changes: 46 additions & 0 deletions internal/lsp/format.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package lsp

import (
"context"
"encoding/json"
"errors"
"log/slog"
"math"

"github.com/harry-hov/gnopls/internal/tools"

"go.lsp.dev/jsonrpc2"
"go.lsp.dev/protocol"
)

func (s *server) Formatting(ctx context.Context, reply jsonrpc2.Replier, req jsonrpc2.Request) error {
var params protocol.DocumentFormattingParams
if err := json.Unmarshal(req.Params(), &params); err != nil {
return sendParseError(ctx, reply, err)
}

uri := params.TextDocument.URI
file, ok := s.snapshot.Get(uri.Filename())
if !ok {
return reply(ctx, nil, errors.New("snapshot not found"))
}

formatted, err := tools.Format(string(file.Src), s.formatOpt)
if err != nil {
return reply(ctx, nil, err)
}

slog.Info("format " + string(params.TextDocument.URI.Filename()))
return reply(ctx, []protocol.TextEdit{
{
Range: protocol.Range{
Start: protocol.Position{Line: 0, Character: 0},
End: protocol.Position{
Line: math.MaxInt32,
Character: math.MaxInt32,
},
},
NewText: string(formatted),
},
}, nil)
}
2 changes: 2 additions & 0 deletions internal/lsp/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@ func (s *server) ServerHandler(ctx context.Context, reply jsonrpc2.Replier, req
return s.DidOpen(ctx, reply, req)
case "textDocument/didSave":
return s.DidSave(ctx, reply, req)
case "textDocument/formatting":
return s.Formatting(ctx, reply, req)
default:
return jsonrpc2.MethodNotFoundHandler(ctx, reply, req)
}
Expand Down
25 changes: 25 additions & 0 deletions internal/tools/format.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,34 @@
package tools

import (
"errors"
"go/format"

gofumpt "mvdan.cc/gofumpt/format"
)

type FormattingOption int

const (
Gofmt FormattingOption = iota
Gofumpt
)

func Format(data string, opt FormattingOption) ([]byte, error) {
switch opt {
case Gofmt:
return RunGofmt(data)
case Gofumpt:
return RunGofumpt(data)
default:
return nil, errors.New("gnopls: invalid formatting option")
}
}

func RunGofmt(data string) ([]byte, error) {
return format.Source([]byte(data))
}

func RunGofumpt(data string) ([]byte, error) {
return gofumpt.Source([]byte(data), gofumpt.Options{})
}

0 comments on commit 394dd10

Please sign in to comment.