github.com/getgauge/gauge@v1.6.9/api/lang/format.go (about) 1 /*---------------------------------------------------------------- 2 * Copyright (c) ThoughtWorks, Inc. 3 * Licensed under the Apache License, Version 2.0 4 * See LICENSE in the project root for license information. 5 *----------------------------------------------------------------*/ 6 7 package lang 8 9 import ( 10 "encoding/json" 11 "fmt" 12 "strings" 13 14 "github.com/getgauge/gauge/formatter" 15 "github.com/getgauge/gauge/gauge" 16 "github.com/getgauge/gauge/parser" 17 "github.com/getgauge/gauge/util" 18 "github.com/sourcegraph/go-langserver/pkg/lsp" 19 "github.com/sourcegraph/jsonrpc2" 20 ) 21 22 func format(request *jsonrpc2.Request) (interface{}, error) { 23 var params lsp.DocumentFormattingParams 24 if err := json.Unmarshal(*request.Params, ¶ms); err != nil { 25 return nil, err 26 } 27 logDebug(request, "LangServer: request received : Type: Format Document URI: %s", params.TextDocument.URI) 28 file := util.ConvertURItoFilePath(params.TextDocument.URI) 29 if util.IsValidSpecExtension(file) { 30 spec, parseResult, err := new(parser.SpecParser).Parse(getContent(params.TextDocument.URI), gauge.NewConceptDictionary(), file) 31 if err != nil { 32 return nil, err 33 } 34 if !parseResult.Ok { 35 return nil, fmt.Errorf("failed to format document. Fix all the problems first") 36 } 37 newString := formatter.FormatSpecification(spec) 38 oldString := getContent(params.TextDocument.URI) 39 textEdit := createTextEdit(newString, 0, 0, len(strings.Split(oldString, "\n")), len(oldString)) 40 return []lsp.TextEdit{textEdit}, nil 41 } 42 return nil, fmt.Errorf("failed to format document. %s is not a valid spec file", file) 43 }