Home | History | Annotate | Download | only in load
      1 // Copyright 2017 The Go Authors. All rights reserved.
      2 // Use of this source code is governed by a BSD-style
      3 // license that can be found in the LICENSE file.
      4 
      5 package load
      6 
      7 import (
      8 	"bytes"
      9 	"encoding/json"
     10 	"errors"
     11 	"io/ioutil"
     12 )
     13 
     14 // DebugDeprecatedImportcfg is installed as the undocumented -debug-deprecated-importcfg build flag.
     15 // It is useful for debugging subtle problems in the go command logic but not something
     16 // we want users to depend on. The hope is that the "deprecated" will make that clear.
     17 // We intend to remove this flag in Go 1.11.
     18 var DebugDeprecatedImportcfg debugDeprecatedImportcfgFlag
     19 
     20 type debugDeprecatedImportcfgFlag struct {
     21 	enabled bool
     22 	Import  map[string]string
     23 	Pkg     map[string]*debugDeprecatedImportcfgPkg
     24 }
     25 
     26 type debugDeprecatedImportcfgPkg struct {
     27 	Dir    string
     28 	Import map[string]string
     29 }
     30 
     31 var (
     32 	debugDeprecatedImportcfgMagic = []byte("# debug-deprecated-importcfg\n")
     33 	errImportcfgSyntax            = errors.New("malformed syntax")
     34 )
     35 
     36 func (f *debugDeprecatedImportcfgFlag) String() string { return "" }
     37 
     38 func (f *debugDeprecatedImportcfgFlag) Set(x string) error {
     39 	if x == "" {
     40 		*f = debugDeprecatedImportcfgFlag{}
     41 		return nil
     42 	}
     43 	data, err := ioutil.ReadFile(x)
     44 	if err != nil {
     45 		return err
     46 	}
     47 
     48 	if !bytes.HasPrefix(data, debugDeprecatedImportcfgMagic) {
     49 		return errImportcfgSyntax
     50 	}
     51 	data = data[len(debugDeprecatedImportcfgMagic):]
     52 
     53 	f.Import = nil
     54 	f.Pkg = nil
     55 	if err := json.Unmarshal(data, &f); err != nil {
     56 		return errImportcfgSyntax
     57 	}
     58 	f.enabled = true
     59 	return nil
     60 }
     61 
     62 func (f *debugDeprecatedImportcfgFlag) lookup(parent *Package, path string) (dir, newPath string) {
     63 	newPath = path
     64 	if p := f.Import[path]; p != "" {
     65 		newPath = p
     66 	}
     67 	if parent != nil {
     68 		if p1 := f.Pkg[parent.ImportPath]; p1 != nil {
     69 			if p := p1.Import[path]; p != "" {
     70 				newPath = p
     71 			}
     72 		}
     73 	}
     74 	if p2 := f.Pkg[newPath]; p2 != nil {
     75 		return p2.Dir, newPath
     76 	}
     77 	return "", ""
     78 }
     79