Skip to content

Commit

Permalink
Made partially implemented mod parsing safe
Browse files Browse the repository at this point in the history
  • Loading branch information
benhalstead committed Sep 11, 2020
1 parent 5ccaeb3 commit 0fd29e5
Show file tree
Hide file tree
Showing 3 changed files with 84 additions and 0 deletions.
71 changes: 71 additions & 0 deletions cmd/grnc-bind/binder/gomod.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
package binder

import (
"encoding/json"
"fmt"
"github.com/graniticio/granitic/v2/logging"
"log"
"os"
"os/exec"
"path/filepath"
)

//ParseModFile tries to parse the mod file in the supplied directory and returns an error if parsing failed
func ParseModFile(d string, l logging.Logger) (*ModFile, error) {

cwd, _ := os.Getwd()
defer os.Chdir(cwd)

if err := os.Chdir(d); err != nil {
return nil, fmt.Errorf("unable to change directory to %s: %s", d, err.Error())
}

goExec, err := exec.LookPath("go")

if err != nil {
return nil, fmt.Errorf("could not find go on your path. Make sure it is available in your OS PATH environment variable")
}

cmd := exec.Command(goExec, "mod", "edit", "--json")

stdout, err := cmd.StdoutPipe()

if err != nil {
return nil, err
}

if err := cmd.Start(); err != nil {
log.Fatal(err)
}

m := make(map[string]interface{})

if err := json.NewDecoder(stdout).Decode(&m); err != nil {
log.Fatal(err)
}

fmt.Println(m)

mf := new(ModFile)

return mf, nil

}

// ModFile represents a mod file on disk
type ModFile struct {
}

// CheckModFileExists makes sure that a go.mod file exists in the supplied directory
func CheckModFileExists(d string) bool {

f := filepath.Join(d, "go.mod")

info, err := os.Stat(f)

if os.IsNotExist(err) || info.IsDir() {
return false
}

return true
}
11 changes: 11 additions & 0 deletions cmd/grnc-bind/binder/testdata/validmod/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
module github.com/my/thing

go 1.14

require (
github.com/some/dependency v1.2.3
github.com/another/dependency/v4 v4.0.0
)


replace github.com/some/dependency => ../some
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
module github.com/graniticio/granitic/v2

go 1.14

0 comments on commit 0fd29e5

Please sign in to comment.