Skip to content

Commit

Permalink
Merge pull request #63 from juliosueiras/features/tcp-server
Browse files Browse the repository at this point in the history
Features/tcp server
  • Loading branch information
juliosueiras authored Feb 26, 2020
2 parents 569bb8a + 98502e3 commit 3626372
Show file tree
Hide file tree
Showing 10 changed files with 178 additions and 71 deletions.
10 changes: 5 additions & 5 deletions helper/file.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,11 +88,11 @@ func FindOffset(fileText string, line, column int) int {
}

func DumpLog(res interface{}) {
result := spew.Sdump(res)
strSlice:=strings.Split(result, "\n")
for _, s := range strSlice {
log.Debug(s)
}
result := spew.Sdump(res)
strSlice := strings.Split(result, "\n")
for _, s := range strSlice {
log.Debug(s)
}
}

func ParseVariables(vars hcl.Traversal, configVars map[string]*configs.Variable, completionItems []lsp.CompletionItem) []lsp.CompletionItem {
Expand Down
8 changes: 4 additions & 4 deletions langserver/did_change.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,9 @@ func TextDocumentDidChange(ctx context.Context, vs lsp.DidChangeTextDocumentPara

DiagsFiles[fileURL] = tfstructs.GetDiagnostics(tempFile.Name(), fileURL)

TextDocumentPublishDiagnostics(Server, ctx, lsp.PublishDiagnosticsParams{
URI: vs.TextDocument.URI,
Diagnostics: DiagsFiles[fileURL],
})
TextDocumentPublishDiagnostics(ctx, lsp.PublishDiagnosticsParams{
URI: vs.TextDocument.URI,
Diagnostics: DiagsFiles[fileURL],
})
return nil
}
8 changes: 4 additions & 4 deletions langserver/did_open.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,10 @@ func TextDocumentDidOpen(ctx context.Context, vs lsp.DidOpenTextDocumentParams)

DiagsFiles[fileURL] = tfstructs.GetDiagnostics(fileURL, fileURL)

TextDocumentPublishDiagnostics(Server, ctx, lsp.PublishDiagnosticsParams{
URI: vs.TextDocument.URI,
Diagnostics: DiagsFiles[fileURL],
})
TextDocumentPublishDiagnostics(ctx, lsp.PublishDiagnosticsParams{
URI: vs.TextDocument.URI,
Diagnostics: DiagsFiles[fileURL],
})
tempFile.Write([]byte(vs.TextDocument.Text))
return nil
}
50 changes: 25 additions & 25 deletions langserver/document_link.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,42 +2,42 @@ package langserver

import (
"context"
lsp "github.com/sourcegraph/go-lsp"
log "github.com/sirupsen/logrus"
lsp "github.com/sourcegraph/go-lsp"
)

type documentLinkParams struct {
TextDocument lsp.TextDocumentItem `json:"textDocument"`
TextDocument lsp.TextDocumentItem `json:"textDocument"`
}

type DocumentLink struct {
Range lsp.Range `json:"range"`
Range lsp.Range `json:"range"`

/**
* The uri this link points to. If missing a resolve request is sent later.
*/
Target string `json:"target"`
/**
* The uri this link points to. If missing a resolve request is sent later.
*/
Target string `json:"target"`

Tooltip string `json:"tooltip"`
Tooltip string `json:"tooltip"`
}

func TextDocumentDocumentLink(ctx context.Context, vs documentLinkParams) ([]DocumentLink, error) {
log.Info(vs)
log.Info(vs)

return []DocumentLink{
DocumentLink{
Range: lsp.Range{
Start: lsp.Position{
Line: 1,
Character: 1,
},
End: lsp.Position{
Line: 1,
Character: 10,
},
},
Target: "https://github.com",
Tooltip: "https://github.com",
},
}, nil
return []DocumentLink{
DocumentLink{
Range: lsp.Range{
Start: lsp.Position{
Line: 1,
Character: 1,
},
End: lsp.Position{
Line: 1,
Character: 10,
},
},
Target: "https://github.com",
Tooltip: "https://github.com",
},
}, nil
}
14 changes: 7 additions & 7 deletions langserver/initialize.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,18 @@ import (
)

type DocumentLinkOptions struct {
ResolveProvider bool `json:"resolveProvider,omitempty"`
ResolveProvider bool `json:"resolveProvider,omitempty"`
}

type ExtendedServerCapabilities struct {
TextDocumentSync *lsp.TextDocumentSyncOptionsOrKind `json:"textDocumentSync,omitempty"`
CompletionProvider *lsp.CompletionOptions `json:"completionProvider,omitempty"`
HoverProvider bool `json:"hoverProvider,omitempty"`
DocumentLinkProvider *DocumentLinkOptions `json:"documentLinkProvider,omitempty"`
TextDocumentSync *lsp.TextDocumentSyncOptionsOrKind `json:"textDocumentSync,omitempty"`
CompletionProvider *lsp.CompletionOptions `json:"completionProvider,omitempty"`
HoverProvider bool `json:"hoverProvider,omitempty"`
DocumentLinkProvider *DocumentLinkOptions `json:"documentLinkProvider,omitempty"`
}

type ExtendedInitializeResult struct {
Capabilities ExtendedServerCapabilities `json:"capabilities"`
Capabilities ExtendedServerCapabilities `json:"capabilities"`
}

func Initialize(ctx context.Context, vs lsp.InitializeParams) (ExtendedInitializeResult, error) {
Expand All @@ -45,7 +45,7 @@ func Initialize(ctx context.Context, vs lsp.InitializeParams) (ExtendedInitializ
},
HoverProvider: false,
DocumentLinkProvider: &DocumentLinkOptions{
ResolveProvider: false,
ResolveProvider: false,
},
},
}, nil
Expand Down
11 changes: 11 additions & 0 deletions langserver/initialized.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package langserver

import (
"context"
)

type InitializedParams struct {}

func Initialized(ctx context.Context, vs InitializedParams) error {
return nil
}
89 changes: 77 additions & 12 deletions langserver/main.go
Original file line number Diff line number Diff line change
@@ -1,27 +1,92 @@
package langserver

import (
"context"
"fmt"
"github.com/creachadair/jrpc2"
"github.com/creachadair/jrpc2/channel"
"github.com/creachadair/jrpc2/handler"
"github.com/creachadair/jrpc2/server"
log "github.com/sirupsen/logrus"
oldLog "log"
"net"
"os"
)

func CreateServer() *jrpc2.Server {
Server = jrpc2.NewServer(handler.Map{
"initialize": handler.New(Initialize),
"textDocument/completion": handler.New(TextDocumentComplete),
"textDocument/didChange": handler.New(TextDocumentDidChange),
"textDocument/didOpen": handler.New(TextDocumentDidOpen),
"textDocument/didClose": handler.New(TextDocumentDidClose),
func RunStdioServer(oldLogInstance *oldLog.Logger) {
isTCP = false

StdioServer = jrpc2.NewServer(ServiceMap, &jrpc2.ServerOptions{
AllowPush: true,
Logger: oldLogInstance,
})

StdioServer.Start(channel.Header("")(os.Stdin, os.Stdout))

log.Info("Server started")

// Wait for the server to exit, and report any errors.
if err := StdioServer.Wait(); err != nil {
log.Printf("Server exited: %v", err)
}

log.Info("Server Finish")
}

func RunTCPServer(address string, port int, oldLogInstance *oldLog.Logger) {
isTCP = true

lst, err := net.Listen("tcp", fmt.Sprintf("%s:%d", address, port))
if err != nil {
log.Fatalf("Listen: %v", err)
}

newChan := channel.Header("")

ctx := context.Background()

ctx, cancelFunc := context.WithCancel(ctx)

go func() {
if err := server.Loop(lst, ServiceMap, &server.LoopOptions{
Framing: newChan,
ServerOptions: &jrpc2.ServerOptions{
AllowPush: true,
Logger: oldLogInstance,
},
}); err != nil {
log.Errorf("Loop: unexpected failure: %v", err)
cancelFunc()
return
}
}()

select {
case <-ctx.Done():
log.Info("Server Finish")
err := lst.Close()
if err != nil {
log.Info("Server Finish")
log.Info(ctx.Err())
return
}
}
}

func InitializeServiceMap() {
ServiceMap = handler.Map{
"initialize": handler.New(Initialize),
"initialized": handler.New(Initialized),
"textDocument/completion": handler.New(TextDocumentComplete),
"textDocument/didChange": handler.New(TextDocumentDidChange),
"textDocument/didOpen": handler.New(TextDocumentDidOpen),
"textDocument/didClose": handler.New(TextDocumentDidClose),
"textDocument/documentLink": handler.New(TextDocumentDocumentLink),
//"textDocument/hover": handler.New(TextDocumentHover),
//"textDocument/references": handler.New(TextDocumentReferences),
//"textDocument/codeLens": handler.New(TextDocumentCodeLens),
"exit": handler.New(Exit),
"shutdown": handler.New(Shutdown),
"$/cancelRequest": handler.New(CancelRequest),
}, &jrpc2.ServerOptions{
AllowPush: true,
})

return Server
}
}
12 changes: 10 additions & 2 deletions langserver/publish_diagnostics.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,15 @@ import (
lsp "github.com/sourcegraph/go-lsp"
)

func TextDocumentPublishDiagnostics(server *jrpc2.Server, ctx context.Context, vs lsp.PublishDiagnosticsParams) error {
func TextDocumentPublishDiagnostics(ctx context.Context, vs lsp.PublishDiagnosticsParams) error {

return server.Push(ctx, "textDocument/publishDiagnostics", vs)
var resultedError error

if isTCP {
resultedError = jrpc2.ServerPush(ctx, "textDocument/publishDiagnostics", vs)
} else {
resultedError = StdioServer.Push(ctx, "textDocument/publishDiagnostics", vs)
}

return resultedError
}
4 changes: 3 additions & 1 deletion langserver/temp.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,6 @@ import (

var tempFile afero.File
var DiagsFiles = make(map[string][]lsp.Diagnostic)
var Server *jrpc2.Server
var StdioServer *jrpc2.Server
var ServiceMap jrpc2.Assigner
var isTCP bool
43 changes: 32 additions & 11 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,26 @@ import (
"flag"
"fmt"
log "github.com/sirupsen/logrus"
"io/ioutil"
oldLog "log"
"os"
"strings"

"github.com/creachadair/jrpc2/channel"
"github.com/juliosueiras/terraform-lsp/langserver"
"io/ioutil"
)

var tcp = flag.Bool("tcp", false, "Use TCP instead of Stdio(which is default)")
var port = flag.Int("port", 9900, "Port for TCP Server")
var address = flag.String("address", "127.0.0.1", "Address for TCP Server")

var location = flag.String("log-location", "", "Location of the lsp log")
var locationJRPC2 = flag.String("log-jrpc2-location", "", "Location of the lsp log for jrpc2")

var debug = flag.Bool("debug", false, "Enable debug output")
var debugJRPC2 = flag.Bool("debug-jrpc2", false, "Enable debug output for jrpc2")

var enableLogFile = flag.Bool("enable-log-file", false, "Enable log file")
var enableLogFileJRPC2 = flag.Bool("enable-log-jrpc2-file", false, "Enable log file for JRPC2")

var Version string
var GitCommit string
Expand All @@ -34,8 +42,6 @@ func main() {
return
}

Server := langserver.CreateServer()

log.Infof("Log Level is Debug: %t", *debug)

if *debug {
Expand All @@ -53,14 +59,29 @@ func main() {
log.SetOutput(f)
}

// Start the server on a channel comprising stdin/stdout.
Server.Start(channel.Header("")(os.Stdin, os.Stdout))
log.Info("Server started")
var oldLogInstance *oldLog.Logger

if *debugJRPC2 {
if !*tcp && !*enableLogFileJRPC2 {
log.Fatal("Debug for JRPC2 has to be set for log file location if is set to use stdio")
}

// Wait for the server to exit, and report any errors.
if err := Server.Wait(); err != nil {
log.Printf("Server exited: %v", err)
oldLogInstance = oldLog.New(os.Stdout, "", 0)
if *enableLogFileJRPC2 {
f, err := os.OpenFile(fmt.Sprintf("%stf-lsp-jrpc2.log", *locationJRPC2), os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
log.Fatalf("error opening file: %v", err)
}
defer f.Close()
oldLogInstance.SetOutput(f)
}
}

log.Info("Server Finish")
langserver.InitializeServiceMap()

if *tcp {
langserver.RunTCPServer(*address, *port, oldLogInstance)
} else {
langserver.RunStdioServer(oldLogInstance)
}
}

0 comments on commit 3626372

Please sign in to comment.