Skip to content

Commit

Permalink
refactoring using gofumpt
Browse files Browse the repository at this point in the history
  • Loading branch information
LinceMathew committed Sep 7, 2024
1 parent 5546ba1 commit 514cc88
Show file tree
Hide file tree
Showing 28 changed files with 87 additions and 104 deletions.
6 changes: 2 additions & 4 deletions cmdexec/cmdexec.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import (
"errors"
"os"
"strings"

"time"

"github.com/HexmosTech/httpie-go"
Expand All @@ -23,18 +22,17 @@ import (
// to stdout.
// Once execution finishes, previous CWD is restored,
// and the command output is returned as a string
func ExecCommand(cmdSlice []string, stdinBody string, apiDir string) (httpie.ExResponse, int64, error) {
func ExecCommand(cmdSlice []string, stdinBody string, apiDir string) (httpie.ExResponse, int64, error) {
oldDir, _ := os.Getwd()
utils.ChangeWorkingDir(apiDir)
start := time.Now()
resp, err := httpie.Lama2Entry(cmdSlice, strings.NewReader(stdinBody))
if err != nil {
return httpie.ExResponse{}, 0, errors.New("Error from API executor: " + err.Error())

}
elapsed := time.Since(start)
utils.ChangeWorkingDir(oldDir)
responseTime := elapsed.Milliseconds()
responseTime := elapsed.Milliseconds()

return resp, responseTime, nil
}
1 change: 0 additions & 1 deletion cmdexec/cmdexec.wasm.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import (
"errors"
"fmt"
"os"

"strings"

"github.com/HexmosTech/httpie-go"
Expand Down
1 change: 0 additions & 1 deletion cmdexec/js.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
//go:build cli


package cmdexec

import (
Expand Down
3 changes: 2 additions & 1 deletion cmdgen/cmdgen.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ import (
// The assembleCmdString function constructs a httpie
// command string for an HTTP request based on the provided
// HTTP method, URL, JSON object, headers, and options. It also
// handle multipart and form data.
//
// handle multipart and form data.
func assembleCmdString(httpv string, url string, jsonObj *gabs.Container, headers *gabs.Container, multipart bool, form bool, o *lama2cmd.Opts) ([]string, string) {
command := make([]string, 0)
var files *gabs.Container
Expand Down
2 changes: 1 addition & 1 deletion codegen/codegen.cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ func generateConvertedSippet(targetLangLib string, parsedAPI *gabs.Container) st
log.Debug().Str("Processor block incoming block", block.String()).Msg("")
convertedSnippetList = append(convertedSnippetList, snippet)
} else if blockType == "Lama2File" {
harRequest, flag := GetRequestHARString(block,targetLangLib)
harRequest, flag := GetRequestHARString(block, targetLangLib)
snippetArgs := SnippetArgs{}
lang, lib := SplitLangLib(targetLangLib)
snippetArgs.Language = lang
Expand Down
26 changes: 13 additions & 13 deletions codegen/codegen.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ type SnippetArgs struct {

func GetRequestHARString(block *gabs.Container, targetLang string) (string, int) {
httpv := block.S("verb", "value").String()
httpv = strings.Trim(httpv, `"`)
httpv = strings.Trim(httpv, `"`)
httpv = strings.Trim(httpv, `'`)
url := block.S("url", "value")
flag := preprocessURL(url)
Expand All @@ -28,9 +28,9 @@ func GetRequestHARString(block *gabs.Container, targetLang string) (string, int)
harObj := gabs.New()

if strings.Contains(strings.ToLower(targetLang), "python") || strings.Contains(strings.ToLower(targetLang), "shell") || strings.Contains(strings.ToLower(targetLang), "php") {
httpv = strings.ToUpper(httpv)
}
httpv = strings.ToUpper(httpv)
}

if jsonObj != nil {
postData := gabs.New()
postData.Set("application/json", "mimeType")
Expand Down Expand Up @@ -109,12 +109,12 @@ func preprocessURL(url *gabs.Container) int {
urls := url.String()
flag := 0
fmt.Println("URL:", urls)
urls = strings.Trim(urls, `"`)
urls = strings.Trim(urls, `'`)
urls = strings.Trim(urls, `"`)
urls = strings.Trim(urls, `'`)
fmt.Println("URL Updated:", urls)
if !strings.HasPrefix(urls, "https://") && !strings.HasPrefix(urls, "http://") {
fmt.Println("URL does not start with 'https://' or 'http://'")
newURL := "https://" + urls
fmt.Println("URL does not start with 'https://' or 'http://'")
newURL := "https://" + urls
// if !strings.Contains(newURL, ".com") {
// parts := strings.SplitN(newURL, "://", 2)
// protocol = parts[0] + "://"
Expand All @@ -125,10 +125,10 @@ func preprocessURL(url *gabs.Container) int {
// newURL += ".com"
// }
// }
url.Set(newURL)
flag = 1
}
url.Set(newURL)
flag = 1
}

// Remove the outermost "${}" to isolate the placeholder content
fmt.Print("URL:", urls)
return flag
Expand All @@ -144,7 +144,7 @@ func postprocessURL(convertedSnippet string, flag int) string {
fmt.Println("Error decoding URL:", err)
return convertedSnippet
}
// decodedURL = strings.Replace(decodedURL, `""`, `"`, -1) removed for python
// decodedURL = strings.Replace(decodedURL, `""`, `"`, -1) removed for python
return decodedURL
// return convertedSnippet
}
Expand Down
2 changes: 1 addition & 1 deletion codegen/codegen.wasm.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ func generateConvertedSippet(targetLangLib string, parsedAPI *gabs.Container) st
snippetArgs.SnippetCore = snippetcore
fmt.Println("Snippet args:", snippetArgs)
httpsnippetCode := PrepareHTTPSnippetGenerator(snippetArgs)
//fmt.Println("httpsnippetCode:", httpsnippetCode)
// fmt.Println("httpsnippetCode:", httpsnippetCode)
convertedSnippet := js.Global().Call("eval", httpsnippetCode)
fmt.Println("convertedSnippet data:", convertedSnippet.String())
// convertedSnippet, err := evaluateJSCode(httpsnippetCode)
Expand Down
4 changes: 2 additions & 2 deletions controller/controller.cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ import (
)

func HandleParsedFile(parsedAPI *gabs.Container, o *lama2cmd.Opts, dir string) (httpie.ExResponse, *lama2cmd.Opts, []outputmanager.ResponseTime, []outputmanager.StatusCode, []outputmanager.ContentSize, error) {
vm := cmdexec.GetJSVm()
return HandleParsedFileHelper(parsedAPI, o, dir, vm)
vm := cmdexec.GetJSVm()
return HandleParsedFileHelper(parsedAPI, o, dir, vm)
}

// Process initiates the following tasks in the given order:
Expand Down
10 changes: 4 additions & 6 deletions controller/controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,10 @@ import (
)

func HandleParsedFileHelper(parsedAPI *gabs.Container, args ...interface{}) (httpie.ExResponse, *lama2cmd.Opts, []outputmanager.ResponseTime, []outputmanager.StatusCode, []outputmanager.ContentSize, error) {
parsedAPIblocks := GetParsedAPIBlocks(parsedAPI)
o, dir := extractArgs(args)
resp, opts, responseTimes, statusCode, contentSize := processBlocks(parsedAPIblocks, o, dir)
return resp, opts, responseTimes, statusCode, contentSize, nil
parsedAPIblocks := GetParsedAPIBlocks(parsedAPI)
o, dir := extractArgs(args)
resp, opts, responseTimes, statusCode, contentSize := processBlocks(parsedAPIblocks, o, dir)
return resp, opts, responseTimes, statusCode, contentSize, nil
}

func GetParsedAPIBlocks(parsedAPI *gabs.Container) []*gabs.Container {
Expand Down Expand Up @@ -76,5 +76,3 @@ func processLama2FileBlock(block *gabs.Container, vm interface{}, o *lama2cmd.Op
// }
// return resp, o
// }


3 changes: 1 addition & 2 deletions controller/controller.wasm.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,12 @@ import (
"fmt"
"os"
"strings"
"syscall/js"

"github.com/HexmosTech/gabs/v2"
"github.com/HexmosTech/httpie-go"
"github.com/rs/zerolog/log"

"syscall/js"

"github.com/HexmosTech/lama2/codegen"
"github.com/HexmosTech/lama2/lama2cmd"
"github.com/HexmosTech/lama2/parser"
Expand Down
8 changes: 5 additions & 3 deletions l2.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,15 @@ import (
"github.com/HexmosTech/lama2/lama2cmd"
)

var version string
var lamawasm string
var (
version string
lamawasm string
)

func main() {
if len(version) == 0 {
version = "vUnset"
}
lama2cmd.SetLSPServer(&l2lsp.DefaultLSPServer{})
controller.Process(version)
}
}
4 changes: 2 additions & 2 deletions l2.wasm.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ func init() {
}

func main() {
//Set the global JavaScript property "goWebRequestFunc" to the result of wasmLamaPromise
// Set the global JavaScript property "goWebRequestFunc" to the result of wasmLamaPromise
js.Global().Set("goWebRequestFunc", wasmLamaPromise())
js.Global().Set("goCmdConvertFunc", wasmCodeConverter())

Expand Down Expand Up @@ -57,7 +57,7 @@ func wasmCodeConverter() js.Func {
handler := js.FuncOf(func(this js.Value, args []js.Value) interface{} {
resolve := args[0]
go func() {
result, _ := controller.ProcessConverterInput(inputdata,convertLang)
result, _ := controller.ProcessConverterInput(inputdata, convertLang)
resolve.Invoke(js.ValueOf(result))
}()
return nil
Expand Down
12 changes: 5 additions & 7 deletions l2lsp/methods/lsp_execute.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,10 @@ import (
)

/*
ExecuteCommand is the LSP method that handles the execution of the API file
filePath: the path to the API file
ExecuteCommand is the LSP method that handles the execution of the API file
filePath: the path to the API file
*/
func ExecuteCommand(req request.JSONRPCRequest) response.JSONRPCResponse {

jsonResponse, err := ProcessForLSP(req.Params.FilePath)
if err != nil {
return response.ErrorResp(req, 500, err.Error())
Expand All @@ -29,11 +28,10 @@ func ExecuteCommand(req request.JSONRPCRequest) response.JSONRPCResponse {
}

/*
ProcessForLSP is the method that processes the API file
filePath: the path to the API file
ProcessForLSP is the method that processes the API file
filePath: the path to the API file
*/
func ProcessForLSP(filePath string) (*gabs.Container, error) {

apiContent, err := preprocess.GetLamaFileAsString(filePath)
if err != nil {
return nil, err
Expand Down Expand Up @@ -63,4 +61,4 @@ func ProcessForLSP(filePath string) (*gabs.Container, error) {
return jsonResponse, nil
}

// {"jsonrpc":"2.0","id":12,"method":"executeCommand","params":{"filePath":"/home/lince/hexmos/apihub/apihub/fb_backend_v3/search.l2"}}
// {"jsonrpc":"2.0","id":12,"method":"executeCommand","params":{"filePath":"/home/lince/hexmos/apihub/apihub/fb_backend_v3/search.l2"}}
1 change: 0 additions & 1 deletion l2lsp/methods/lsp_suggestEnv.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,6 @@ func getRequestURI(req request.JSONRPCRequest) (string, int, error) {
return "", response.ErrUnsupportedFeature, errors.New("Windows is not supported as of now. To contribute visit here: https://github.com/HexmosTech/Lama2")
}
return "", response.ErrUnexpectedURIScheme, errors.New("encountered unexpected URI scheme. Ex: 'file:///path/to/workspace/myapi.l2'")

}

func SuggestEnvironmentVariables(req request.JSONRPCRequest) response.JSONRPCResponse {
Expand Down
2 changes: 1 addition & 1 deletion l2lsp/request/general_request.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ type Params struct {
WorkspaceFolders *[]WorkspaceFolder `json:"workspaceFolders,omitempty"`
SearchQuery *string `json:"searchQuery,omitempty"`
TextDocument *Uri `json:"textDocument,omitempty"`
FilePath string `json:"filePath,omitempty"`
FilePath string `json:"filePath,omitempty"`
}

type ClientInfo struct {
Expand Down
3 changes: 2 additions & 1 deletion l2lsp/response/suggestenv_response.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,5 @@ func CreateEnvironmentVariablesResp(req request.JSONRPCRequest, envs interface{}
Result: envs,
}
}
// {"jsonrpc":"2.0","id":12,"method":"executeCommand","params":{"filePath":"/home/lince/hexmos/apihub/apihub/fb_backend_v3/search.l2"}}

// {"jsonrpc":"2.0","id":12,"method":"executeCommand","params":{"filePath":"/home/lince/hexmos/apihub/apihub/fb_backend_v3/search.l2"}}
2 changes: 1 addition & 1 deletion l2lsp/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ func init() {
}

// DefaultLSPServer is the default implementation of LSPServer
type DefaultLSPServer struct {}
type DefaultLSPServer struct{}

func (s *DefaultLSPServer) StartLspServer() {
log.Info().Msg("Started process")
Expand Down
1 change: 0 additions & 1 deletion lama2cmd/lama2cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ func SetLSPServer(server LSPServer) {
lspServer = server
}


// The Opts structure stores user preferences, and is used throughout
// the module to make various decisions.
type Opts struct {
Expand Down
1 change: 0 additions & 1 deletion outputManager/output_manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@ type ContentSize struct {
SizeInBytes int `json:"sizeInBytes"`
}


func setupLogger(consoleOut io.Writer) {
consoleWriter := zerolog.ConsoleWriter{Out: consoleOut}
consoleWriter2 := zerolog.ConsoleWriter{Out: &LogBuff}
Expand Down
1 change: 0 additions & 1 deletion preprocess/expandvar.cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import (
"github.com/rs/zerolog/log"
)


// Expand replaces ${var} or $var in the string based on the mapping function.
// For example, os.ExpandEnv(s) is equivalent to os.Expand(s, os.Getenv).
func Expand(s string, vm interface{}, mapping map[string]string) string {
Expand Down
5 changes: 1 addition & 4 deletions preprocess/expandvar.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

// Copyright 2010 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
Expand All @@ -10,10 +9,8 @@ package preprocess
import (
"os"
"strings"

)


// isShellSpecialVar reports whether the character identifies a special
// shell variable such as $*.
func isShellSpecialVar(c uint8) bool {
Expand Down Expand Up @@ -71,4 +68,4 @@ func getEnvironMap() map[string]string {
}
}
return m
}
}
31 changes: 16 additions & 15 deletions preprocess/expandvar.wasm.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,21 +53,22 @@ func Expand(s string, vm interface{}, mapping map[string]string) string {
res2 := utils.RemoveUnquotedValueMarker(res)
return res2
}

func getJsValue(name string, mapping map[string]string, buf []byte) []byte {
log.Debug().Str("WW Getting from worker", name).Msg("");
jsVal := GetFromWorker(name)
fmt.Println("WW: getjsvalue",name,jsVal)
log.Debug().Str("WW JavaScript Variable Value:", jsVal).Msg("");
log.Debug().Str("WW Getting from worker", name).Msg("")
jsVal := GetFromWorker(name)
fmt.Println("WW: getjsvalue", name, jsVal)
log.Debug().Str("WW JavaScript Variable Value:", jsVal).Msg("")
if jsVal != "" {
buf = append(buf, []byte(jsVal)...)
} else {
val, ok := mapping[name]
if ok {
buf = append(buf, val...)
} else {
buf = append(buf, ""...)
log.Warn().Str("Couldn't find the variable `"+name+"`, in both Javascript processor block and environment variables. Replacing with empty string", "").Msg("")
}
}
return buf
buf = append(buf, []byte(jsVal)...)
} else {
val, ok := mapping[name]
if ok {
buf = append(buf, val...)
} else {
buf = append(buf, ""...)
log.Warn().Str("Couldn't find the variable `"+name+"`, in both Javascript processor block and environment variables. Replacing with empty string", "").Msg("")
}
}
return buf
}
Loading

0 comments on commit 514cc88

Please sign in to comment.