Skip to content

Commit

Permalink
when there is no module cache and no network connection, use fmt pack…
Browse files Browse the repository at this point in the history
…age for pritty print
  • Loading branch information
itchyny committed Jan 11, 2020
1 parent 857bd19 commit 7456f6c
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 3 deletions.
37 changes: 34 additions & 3 deletions gomod.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,14 @@ import (
"go/build"
"io"
"io/ioutil"
"net"
"net/url"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"time"
)

func (s *Session) initGoMod() error {
Expand All @@ -23,10 +26,11 @@ func (s *Session) initGoMod() error {

func listModuleDirectives() []string {
var directives []string
for _, pp := range printerPkgs {
for i, pp := range printerPkgs {
if pp.path == "fmt" {
continue
}
// Check local module caches.
found := lookupGoModule(pp.path, pp.version)
if found {
for _, r := range pp.requires {
Expand All @@ -36,16 +40,19 @@ func listModuleDirectives() []string {
}
}
}
if found {
if found || canAccessGoproxy() {
// Specifying the version of the printer package improves startup
// performance by skipping module version fetching. Also allows to
// use gore in offline environment.
directives = append(directives, "require "+pp.path+" "+pp.version)
for _, r := range pp.requires {
directives = append(directives, "require "+r.path+" "+r.version)
}
break
} else {
// If there is no module cache and no network connection, use fmt package.
printerPkgs = printerPkgs[i+1:]
}
break
}
modules, err := goListAll()
if err != nil {
Expand Down Expand Up @@ -90,3 +97,27 @@ func lookupGoModule(pkg, version string) bool {
fi, err := os.Stat(modDir)
return err == nil && fi.IsDir()
}

func canAccessGoproxy() bool {
var host string
if url, err := url.Parse(getGoproxy()); err != nil {
host = "proxy.golang.org"
} else {
host = url.Hostname()
}
addr := net.JoinHostPort(host, "80")
dialer := net.Dialer{Timeout: 5 * time.Second}
conn, err := dialer.Dial("tcp", addr)
if err != nil {
return false
}
defer conn.Close()
return true
}

func getGoproxy() string {
if goproxy := os.Getenv("GOPROXY"); goproxy != "" {
return goproxy
}
return "https://proxy.golang.org/"
}
1 change: 1 addition & 0 deletions session.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ func main() {
`

// printerPkgs is a list of packages that provides pretty printing function
// when changing this, read listModuleDirectives carefully
var printerPkgs = []struct {
path, version string
requires []pathVersion
Expand Down

0 comments on commit 7456f6c

Please sign in to comment.