Ejemplo n.º 1
0
//TODO fulfil all defaults
func FillSettingsDefaults(settings *Settings, workingDirectory string) {
	if settings.AppName == "" {
		settings.AppName = core.GetAppName(settings.AppName, workingDirectory)
	}
	if settings.OutPath == "" {
		settings.OutPath = core.OUTFILE_TEMPLATE_DEFAULT
	}
	if settings.ResourcesInclude == "" {
		settings.ResourcesInclude = core.RESOURCES_INCLUDE_DEFAULT
	}
	if settings.ResourcesExclude == "" {
		settings.ResourcesExclude = core.RESOURCES_EXCLUDE_DEFAULT
	}
	if settings.MainDirsExclude == "" {
		settings.MainDirsExclude = core.MAIN_DIRS_EXCLUDE_DEFAULT
	}
	if settings.PackageVersion == "" {
		settings.PackageVersion = core.PACKAGE_VERSION_DEFAULT
	}
	if settings.BuildSettings == nil {
		bs := BuildSettings{}
		FillBuildSettingsDefaults(&bs)
		settings.BuildSettings = &bs
	}
	if settings.GoRoot == "" {
		if settings.IsVerbose() {
			log.Printf("Defaulting GoRoot to runtime.GOROOT (%s)", runtime.GOROOT())
		}
		settings.GoRoot = runtime.GOROOT()
	}
}
Ejemplo n.º 2
0
// Per golang.org/issue/14937, check that every .gz file
// in the tree has a zero mtime.
func TestGZIPFilesHaveZeroMTimes(t *testing.T) {
	if testing.Short() && testenv.Builder() == "" {
		t.Skip("skipping in short mode")
	}
	var files []string
	err := filepath.Walk(runtime.GOROOT(), func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}
		if !info.IsDir() && strings.HasSuffix(path, ".gz") {
			files = append(files, path)
		}
		return nil
	})
	if err != nil {
		if os.IsNotExist(err) {
			t.Skipf("skipping: GOROOT directory not found: %s", runtime.GOROOT())
		}
		t.Fatal("error collecting list of .gz files in GOROOT: ", err)
	}
	if len(files) == 0 {
		t.Fatal("expected to find some .gz files under GOROOT")
	}
	for _, path := range files {
		checkZeroMTime(t, path)
	}
}
Ejemplo n.º 3
0
func TestFixedGOROOT(t *testing.T) {
	if runtime.GOOS == "plan9" {
		t.Skipf("skipping plan9, it is inconsistent by allowing GOROOT to be updated by Setenv")
	}

	// Restore both the real GOROOT environment variable, and runtime's copies:
	if orig, ok := syscall.Getenv("GOROOT"); ok {
		defer syscall.Setenv("GOROOT", orig)
	} else {
		defer syscall.Unsetenv("GOROOT")
	}
	envs := runtime.Envs()
	oldenvs := append([]string{}, envs...)
	defer runtime.SetEnvs(oldenvs)

	// attempt to reuse existing envs backing array.
	want := runtime.GOROOT()
	runtime.SetEnvs(append(envs[:0], "GOROOT="+want))

	if got := runtime.GOROOT(); got != want {
		t.Errorf(`initial runtime.GOROOT()=%q, want %q`, got, want)
	}
	if err := syscall.Setenv("GOROOT", "/os"); err != nil {
		t.Fatal(err)
	}
	if got := runtime.GOROOT(); got != want {
		t.Errorf(`after setenv runtime.GOROOT()=%q, want %q`, got, want)
	}
	if err := syscall.Unsetenv("GOROOT"); err != nil {
		t.Fatal(err)
	}
	if got := runtime.GOROOT(); got != want {
		t.Errorf(`after unsetenv runtime.GOROOT()=%q, want %q`, got, want)
	}
}
Ejemplo n.º 4
0
// subdir determines the package based on the current working directory,
// and returns the path to the package source relative to $GOROOT (or $GOPATH).
func subdir() (pkgpath string, underGoRoot bool, err error) {
	cwd, err := os.Getwd()
	if err != nil {
		return "", false, err
	}
	if root := runtime.GOROOT(); strings.HasPrefix(cwd, root) {
		subdir, err := filepath.Rel(root, cwd)
		if err != nil {
			return "", false, err
		}
		return subdir, true, nil
	}

	for _, p := range filepath.SplitList(build.Default.GOPATH) {
		if !strings.HasPrefix(cwd, p) {
			continue
		}
		subdir, err := filepath.Rel(p, cwd)
		if err == nil {
			return subdir, false, nil
		}
	}
	return "", false, fmt.Errorf(
		"working directory %q is not in either GOROOT(%q) or GOPATH(%q)",
		cwd,
		runtime.GOROOT(),
		build.Default.GOPATH,
	)
}
Ejemplo n.º 5
0
// subdir determines the package based on the current working directory,
// and returns the path to the package source relative to $GOROOT (or $GOPATH).
func subdir() (pkgpath string, underGoRoot bool) {
	cwd, err := os.Getwd()
	if err != nil {
		log.Fatal(err)
	}
	if root := runtime.GOROOT(); strings.HasPrefix(cwd, root) {
		subdir, err := filepath.Rel(root, cwd)
		if err != nil {
			log.Fatal(err)
		}
		return subdir, true
	}

	for _, p := range filepath.SplitList(build.Default.GOPATH) {
		if !strings.HasPrefix(cwd, p) {
			continue
		}
		subdir, err := filepath.Rel(p, cwd)
		if err == nil {
			return subdir, false
		}
	}
	log.Fatalf("the current path %q is not in either GOROOT(%q) or GOPATH(%q)",
		cwd, runtime.GOROOT(), build.Default.GOPATH)
	return "", false
}
Ejemplo n.º 6
0
Archivo: gc.go Proyecto: torfuzx/gb
func (t *gcToolchain) Asm(pkg *Package, srcdir, ofile, sfile string) error {
	args := []string{"-o", ofile, "-D", "GOOS_" + pkg.gotargetos, "-D", "GOARCH_" + pkg.gotargetarch}
	switch {
	case goversion == 1.4:
		includedir := filepath.Join(runtime.GOROOT(), "pkg", pkg.gotargetos+"_"+pkg.gotargetarch)
		args = append(args, "-I", includedir)
	case goversion > 1.4:
		odir := filepath.Join(filepath.Dir(ofile))
		includedir := filepath.Join(runtime.GOROOT(), "pkg", "include")
		args = append(args, "-I", odir, "-I", includedir)
	default:
		return fmt.Errorf("unsupported Go version: %v", runtime.Version)
	}
	args = append(args, sfile)
	if err := mkdir(filepath.Dir(ofile)); err != nil {
		return fmt.Errorf("gc:asm: %v", err)
	}
	var buf bytes.Buffer
	err := runOut(&buf, srcdir, nil, t.as, args...)
	if err != nil {
		fmt.Fprintf(os.Stderr, "# %s\n", pkg.ImportPath)
		io.Copy(os.Stderr, &buf)
	}
	return err
}
Ejemplo n.º 7
0
// StdPkg returns all lists of Go standard packages.
// Usually pass "/usr/local/go".
// There is an alternative way: https://github.com/golang/tools/blob/master/imports/mkstdlib.go
func StdPkg(goRootPath string) (map[string]bool, error) {
	if goRootPath == "" {
		goRootPath = runtime.GOROOT()
		if goRootPath == "" {
			goRootPath = os.Getenv("GOROOT")
			if goRootPath == "" {
				return nil, errors.New("can't find GOROOT: try to set it to /usr/local/go")
			}
		}
	}
	stdpkgPath := filepath.Join(goRootPath, "src")
	rmap, err := walkDir(stdpkgPath)

	if err != nil {
		log.Println("trying to find the runtime `GOROOT`")
		goRootPath = runtime.GOROOT()
		stdpkgPath = filepath.Join(goRootPath, "src")
		log.Println("try with:", stdpkgPath)
		rmap, err = walkDir(stdpkgPath)

		if err != nil {
			log.Println("trying to find the environment variable `GOROOT`")
			goRootPath = os.Getenv("GOROOT")
			stdpkgPath = filepath.Join(goRootPath, "src")
			log.Println("try with:", stdpkgPath)
			rmap, err = walkDir(stdpkgPath)

			if err != nil {
				return nil, err
			}

		}
	}

	smap := make(map[string]bool)
	for _, val := range rmap {
		stdName := strings.Replace(val, stdpkgPath, "", -1)
		stdName = filepath.Clean(stdName)
		if strings.HasPrefix(stdName, "/") {
			stdName = stdName[1:]
		}
		if strings.HasPrefix(stdName, "cmd") {
			continue
		}
		if strings.Contains(stdName, "testdata") {
			continue
		}
		if strings.Contains(stdName, "internal") {
			continue
		}
		if len(stdName) < 2 {
			continue
		}
		if _, ok := smap[stdName]; !ok {
			smap[stdName] = true
		}
	}
	return smap, nil
}
Ejemplo n.º 8
0
Archivo: go.go Proyecto: npchp110/wide
// GetAPIPath gets the Go source code path.
//
//  1. before Go 1.4: $GOROOT/src/pkg
//  2. Go 1.4 and after: $GOROOT/src
func (*mygo) GetAPIPath() string {
	ret := runtime.GOROOT() + "/src/pkg" // before Go 1.4
	if !File.IsExist(ret) {
		ret = runtime.GOROOT() + "/src" // Go 1.4 and after
	}

	return filepath.FromSlash(path.Clean(ret))
}
Ejemplo n.º 9
0
// FullGoSearchPath gets the search paths for finding packages
func FullGoSearchPath() string {
	allPaths := os.Getenv(GOPATHKey)
	if allPaths != "" {
		allPaths = strings.Join([]string{allPaths, runtime.GOROOT()}, ":")
	} else {
		allPaths = runtime.GOROOT()
	}
	return allPaths
}
Ejemplo n.º 10
0
func generate(pkg string, deps ...*dependency) *dependency {
	var wg dependency
	if exclude(pkg) {
		return &wg
	}
	wg.Add(1)
	all.Add(1)
	go func() {
		defer wg.Done()
		defer all.Done()
		// Wait for dependencies to finish.
		for _, d := range deps {
			d.Wait()
			if d.hasErrors && !*force {
				fmt.Printf("--- ABORT: %s\n", pkg)
				wg.hasErrors = true
				return
			}
		}
		vprintf("=== GENERATE %s\n", pkg)
		args := []string{"generate"}
		if *verbose {
			args = append(args, "-v")
		}
		args = append(args, "./"+pkg)
		cmd := exec.Command(filepath.Join(runtime.GOROOT(), "bin", "go"), args...)
		w := &bytes.Buffer{}
		cmd.Stderr = w
		cmd.Stdout = w
		if err := cmd.Run(); err != nil {
			fmt.Printf("--- FAIL: %s:\n\t%v\n\tError: %v\n", pkg, indent(w), err)
			hasErrors = true
			wg.hasErrors = true
			return
		}

		vprintf("=== TEST %s\n", pkg)
		args[0] = "test"
		cmd = exec.Command(filepath.Join(runtime.GOROOT(), "bin", "go"), args...)
		wt := &bytes.Buffer{}
		cmd.Stderr = wt
		cmd.Stdout = wt
		if err := cmd.Run(); err != nil {
			fmt.Printf("--- FAIL: %s:\n\t%v\n\tError: %v\n", pkg, indent(wt), err)
			hasErrors = true
			wg.hasErrors = true
			return
		}
		vprintf("--- SUCCESS: %s\n\t%v\n", pkg, indent(w))
		fmt.Print(wt.String())
	}()
	return &wg
}
Ejemplo n.º 11
0
// pkgpath returns the destination for object cached for this Package.
func pkgpath(pkg *Package) string {
	importpath := filepath.FromSlash(pkg.ImportPath) + ".a"
	switch {
	case pkg.isCrossCompile():
		return filepath.Join(pkg.Pkgdir(), importpath)
	case pkg.Standard && pkg.race:
		// race enabled standard lib
		return filepath.Join(runtime.GOROOT(), "pkg", pkg.gotargetos+"_"+pkg.gotargetarch+"_race", importpath)
	case pkg.Standard:
		// standard lib
		return filepath.Join(runtime.GOROOT(), "pkg", pkg.gotargetos+"_"+pkg.gotargetarch, importpath)
	default:
		return filepath.Join(pkg.Pkgdir(), importpath)
	}
}
Ejemplo n.º 12
0
func TestInfoWithArgs(t *testing.T) {
	gb := T{T: t}
	defer gb.cleanup()

	gb.tempDir("src")
	gb.cd(gb.tempdir)
	gb.run("info", "GB_PROJECT_DIR", "GB_MISSING", "GB_GOROOT")
	gb.grepStdout(`^`+regexp.QuoteMeta(gb.tempdir), "missing "+regexp.QuoteMeta(gb.tempdir))
	gb.grepStdout(`^`+regexp.QuoteMeta(runtime.GOROOT()), "missing "+regexp.QuoteMeta(runtime.GOROOT()))
	// second line should be empty
	lines := bytes.Split(gb.stdout.Bytes(), []byte{'\n'})
	if len(lines[1]) != 0 {
		t.Fatal("want 0, got", len(lines[1]))
	}
}
Ejemplo n.º 13
0
func TestBug3486(t *testing.T) { // http://code.google.com/p/go/issues/detail?id=3486
	root, err := filepath.EvalSymlinks(runtime.GOROOT())
	if err != nil {
		t.Fatal(err)
	}
	lib := filepath.Join(root, "lib")
	src := filepath.Join(root, "src")
	seenSrc := false
	filepath.Walk(root, func(pth string, info os.FileInfo, err error) error {
		if err != nil {
			t.Fatal(err)
		}

		switch pth {
		case lib:
			return filepath.SkipDir
		case src:
			seenSrc = true
		}
		return nil
	})
	if !seenSrc {
		t.Fatalf("%q not seen", src)
	}
}
Ejemplo n.º 14
0
func TestBug3486(t *testing.T) { // http://code.google.com/p/go/issues/detail?id=3486
	root, err := filepath.EvalSymlinks(runtime.GOROOT())
	if err != nil {
		t.Fatal(err)
	}
	lib := filepath.Join(root, "lib")
	src := filepath.Join(root, "src")
	seenSrc := false
	walker := fs.Walk(root)
	for walker.Step() {
		if walker.Err() != nil {
			t.Fatal(walker.Err())
		}

		switch walker.Path() {
		case lib:
			walker.SkipDir()
		case src:
			seenSrc = true
		}
	}
	if !seenSrc {
		t.Fatalf("%q not seen", src)
	}
}
Ejemplo n.º 15
0
func (suite *SerialRunnerTestSuite) TestEnvVars() {
	makeEnvVarPrintBuildFile := func(path, varname string) {
		fmtStatement := fmt.Sprintf(`print(os.environ['%s'], file=sys.stdout)`, varname)
		suite.makeTestBuildFile(path, []string{fmtStatement})
	}

	type testCase struct {
		path, varname, expected string
	}
	env := Env{
		"PATH":                os.Getenv("PATH"),
		"GOPATH":              os.Getenv("GOPATH"),
		"NOMS_CHECKOUT_PATH":  "/where/noms/is",
		"ATTIC_CHECKOUT_PATH": "/where/attic/is",
	}
	tests := []testCase{}
	for n, v := range env {
		tc := testCase{suite.uniqueBuildFile(), n, v}
		makeEnvVarPrintBuildFile(tc.path, tc.varname)
		tests = append(tests, tc)
	}
	gorootTestCase := testCase{suite.uniqueBuildFile(), "GOROOT", runtime.GOROOT()}
	makeEnvVarPrintBuildFile(gorootTestCase.path, gorootTestCase.varname)
	tests = append(tests, gorootTestCase)

	log := &bytes.Buffer{}
	if suite.True(Serial(log, log, env, suite.dir, buildFileBasename), "Serial() should have succeeded! logs:\n%s", string(log.Bytes())) {
		logText := string(log.Bytes())
		for _, tc := range tests {
			suite.Contains(logText, tc.expected)
		}
	}
}
Ejemplo n.º 16
0
// setEnvironment assembles the configuration for gotest and its subcommands.
func setEnvironment() {
	// Basic environment.
	GOROOT = runtime.GOROOT()
	addEnv("GOROOT", GOROOT)
	GOARCH = os.Getenv("GOARCH")
	if GOARCH == "" {
		GOARCH = runtime.GOARCH
	}
	addEnv("GOARCH", GOARCH)
	O = theChar[GOARCH]
	if O == "" {
		Fatalf("unknown architecture %s", GOARCH)
	}

	// Commands and their flags.
	gc := os.Getenv("GC")
	if gc == "" {
		gc = O + "g"
	}
	XGC = []string{gc, "-I", "_test", "-o", "_xtest_." + O}
	GC = []string{gc, "-I", "_test", "_testmain.go"}
	gl := os.Getenv("GL")
	if gl == "" {
		gl = O + "l"
	}
	GL = []string{gl, "-L", "_test", "_testmain." + O}

	// Silence make on Linux
	addEnv("MAKEFLAGS", "")
	addEnv("MAKELEVEL", "")
}
Ejemplo n.º 17
0
func init() {
	flag.Parse()

	if *debug {
		logger = log.New(os.Stdout, "godev", log.LstdFlags)
	} else {
		logger = log.New(ioutil.Discard, "godev", log.LstdFlags)
	}

	goroot = runtime.GOROOT() + string(os.PathSeparator)

	dirs := build.Default.SrcDirs()

	for i := len(dirs) - 1; i >= 0; i-- {
		srcDir := dirs[i]

		if !strings.HasPrefix(srcDir, goroot) {
			srcDirs = append(srcDirs, srcDir)
		}

		if bundle_root_dir == "" {
			_, err := os.Stat(srcDir + "/github.com/sirnewton01/godev/bundles")

			if err == nil {
				bundle_root_dir = srcDir + "/github.com/sirnewton01/godev/bundles"
				break
			}
		}
	}

	// Try the location provided by the srcdir flag
	if bundle_root_dir == "" && *godev_src_dir != "" {
		_, err := os.Stat(*godev_src_dir + "/bundles")

		if err == nil {
			bundle_root_dir = *godev_src_dir + "/bundles"
		}
	}

	if bundle_root_dir == "" {
		log.Fatal("GOPATH variable doesn't contain the godev source.\nEither add the location to the godev source to your GOPATH or set the srcdir flag to the location.")
	}

	if os.Getenv("GOHOST") != "" {
		hostName = os.Getenv("GOHOST")

		certFile = os.Getenv("GOCERTFILE")
		keyFile = os.Getenv("GOKEYFILE")

		// If the host name is not loopback then we must use a secure connection
		//  with certificatns
		if certFile == "" || keyFile == "" {
			log.Fatal("When using a public port a certificate file (GOCERTFILE) and key file (GOKEYFILE) environment variables must be provided to secure the connection.")
		}

		// Initialize the random magic key for this session
		rand.Seed(time.Now().UTC().UnixNano())
		magicKey = strconv.FormatInt(rand.Int63(), 16)
	}
}
Ejemplo n.º 18
0
func TestStdFixed(t *testing.T) {
	testTestDir(t, filepath.Join(runtime.GOROOT(), "test", "fixedbugs"),
		"bug248.go", "bug302.go", "bug369.go", // complex test instructions - ignore
		"bug459.go",    // likely incorrect test - see issue 6793 (pending spec clarification)
		"issue3924.go", // likely incorrect test - see issue 6671 (pending spec clarification)
	)
}
Ejemplo n.º 19
0
func main() {
	var err error
	args := os.Args[1:]

	if len(args) == 0 {
		fmt.Fprintln(os.Stderr, "Usage: "+path.Base(os.Args[0])+" <sourcefile> [args]")
		os.Exit(1)
	}

	_, err = os.Stat(filepath.Join(runtime.GOROOT(), "bin", "go"))
	if err != nil {
		fmt.Fprintln(os.Stderr, "Error: can't access GO lang executable")
		os.Exit(1)
	}

	_, err = exec.LookPath("go")
	if err != nil {
		fmt.Fprintln(os.Stderr, "Error: can't find GO lang tools in PATH")
		os.Exit(1)
	}

	err = Run(args)
	if err != nil {
		fmt.Fprintln(os.Stderr, "Error: "+err.Error())
		os.Exit(1)
	}
}
Ejemplo n.º 20
0
Archivo: test.go Proyecto: xland/qt
func main() {
	var (
		ending      string
		buildTarget = "desktop"
	)
	if len(os.Args) > 1 {
		buildTarget = os.Args[1]
	}
	if runtime.GOOS == "windows" {
		ending = ".exe"
	}

	fmt.Printf("_________________________Test-%v__________________________\n", buildTarget)

	runCmd(exec.Command("go", "build", "-o", path.Join(runtime.GOROOT(), "bin", fmt.Sprintf("qtdeploy%v", ending)), utils.GetQtPkgPath("internal", "deploy", "deploy.go")), "qtdeploy")

	for _, example := range []string{"widgets", path.Join("quick", "calc"), path.Join("quick", "dialog"), path.Join("quick", "view"), path.Join("qml", "application"), path.Join("qml", "prop")} {
		var before = time.Now()

		fmt.Print(example)

		runCmd(exec.Command(fmt.Sprintf("qtdeploy%v", ending), "test", buildTarget, path.Join(utils.GetQtPkgPath("internal", "examples"), example)), fmt.Sprintf("test.%v", example))

		var sep = "\t"
		if len(example) < 8 {
			sep += "\t\t"
		}
		if len(example) >= 8 && len(example) < 17 {
			sep += "\t"
		}

		fmt.Printf("%v\t\t%v\n", sep, time.Since(before)/time.Second*time.Second)
	}

}
Ejemplo n.º 21
0
func testDir(t *testing.T, dir string, endTime time.Time) (nimports int) {
	dirname := filepath.Join(runtime.GOROOT(), "pkg", runtime.GOOS+"_"+runtime.GOARCH, dir)
	list, err := ioutil.ReadDir(dirname)
	if err != nil {
		t.Errorf("testDir(%s): %s", dirname, err)
	}
	for _, f := range list {
		if time.Now().After(endTime) {
			t.Log("testing time used up")
			return
		}
		switch {
		case !f.IsDir():
			// try extensions
			for _, ext := range pkgExts {
				if strings.HasSuffix(f.Name(), ext) {
					name := f.Name()[0 : len(f.Name())-len(ext)] // remove extension
					if testPath(t, filepath.Join(dir, name)) {
						nimports++
					}
				}
			}
		case f.IsDir():
			nimports += testDir(t, filepath.Join(dir, f.Name()), endTime)
		}
	}
	return
}
Ejemplo n.º 22
0
func TestStdTest(t *testing.T) {
	testTestDir(t, filepath.Join(runtime.GOROOT(), "test"),
		"cmplxdivide.go", // also needs file cmplxdivide1.go - ignore
		"sigchld.go",     // don't work on Windows; testTestDir should consult build tags
		"float_lit2.go",  // TODO(gri) enable for releases 1.4 and higher
	)
}
Ejemplo n.º 23
0
func TestFindImportInternal(t *testing.T) {
	withEmptyGoPath(func() {
		// Check for src/internal/race, not just src/internal,
		// so that we can run this test also against go1.5
		// (which doesn't contain that file).
		_, err := os.Stat(filepath.Join(runtime.GOROOT(), "src/internal/race"))
		if err != nil {
			t.Skip(err)
		}

		got, rename, err := findImportGoPath("race", map[string]bool{"Acquire": true}, filepath.Join(runtime.GOROOT(), "src/math/x.go"))
		if err != nil {
			t.Fatal(err)
		}
		if got != "internal/race" || rename {
			t.Errorf(`findImportGoPath("race", Acquire ...) = %q, %t; want "internal/race", false`, got, rename)
		}

		// should not be able to use internal from outside that tree
		got, rename, err = findImportGoPath("race", map[string]bool{"Acquire": true}, filepath.Join(runtime.GOROOT(), "x.go"))
		if err != nil {
			t.Fatal(err)
		}
		if got != "" || rename {
			t.Errorf(`findImportGoPath("race", Acquire ...)=%q, %t, want "", false`, got, rename)
		}
	})
}
Ejemplo n.º 24
0
func GcToolchain(opts ...func(*gcoption)) func(c *Context) error {
	defaults := []func(*gcoption){
		func(opt *gcoption) {
			opt.goos = runtime.GOOS
		},
		func(opt *gcoption) {
			opt.goarch = runtime.GOARCH
		},
	}
	var options gcoption
	for _, opt := range append(defaults, opts...) {
		opt(&options)
	}

	return func(c *Context) error {
		goroot := runtime.GOROOT()
		goos := options.goos
		goarch := options.goarch
		tooldir := filepath.Join(goroot, "pkg", "tool", goos+"_"+goarch)
		c.tc = &gcToolchain{
			goos:   goos,
			goarch: goarch,
			gc:     filepath.Join(tooldir, "compile"),
			ld:     filepath.Join(tooldir, "link"),
			as:     filepath.Join(tooldir, "asm"),
			pack:   filepath.Join(tooldir, "pack"),
		}
		return nil
	}
}
Ejemplo n.º 25
0
// Test for correctly identifying the name of a vendored package when it
// differs from its directory name. In this test, the import line
// "mypkg.com/mypkg.v1" would be removed if goimports wasn't able to detect
// that the package name is "mypkg".
func TestFixImportsVendorPackage(t *testing.T) {
	// Skip this test on go versions with no vendor support.
	if _, err := os.Stat(filepath.Join(runtime.GOROOT(), "src/vendor")); err != nil {
		t.Skip(err)
	}
	testConfig{
		gopathFiles: map[string]string{
			"mypkg.com/outpkg/vendor/mypkg.com/mypkg.v1/f.go": "package mypkg\nvar Foo = 123\n",
		},
	}.test(t, func(t *goimportTest) {
		input := `package p

import (
	"fmt"

	"mypkg.com/mypkg.v1"
)

var (
	_ = fmt.Print
	_ = mypkg.Foo
)
`
		buf, err := Process(filepath.Join(t.gopath, "src/mypkg.com/outpkg/toformat.go"), []byte(input), &Options{})
		if err != nil {
			t.Fatal(err)
		}
		if got := string(buf); got != input {
			t.Fatalf("results differ\nGOT:\n%s\nWANT:\n%s\n", got, input)
		}
	})
}
Ejemplo n.º 26
0
func TestBug3486(t *testing.T) { // http://code.google.com/p/go/issues/detail?id=3486
	root, err := filepath.EvalSymlinks(runtime.GOROOT() + "/test")
	if err != nil {
		t.Fatal(err)
	}
	bugs := filepath.Join(root, "bugs")
	ken := filepath.Join(root, "ken")
	seenBugs := false
	seenKen := false
	filepath.Walk(root, func(pth string, info os.FileInfo, err error) error {
		if err != nil {
			t.Fatal(err)
		}

		switch pth {
		case bugs:
			seenBugs = true
			return filepath.SkipDir
		case ken:
			if !seenBugs {
				t.Fatal("filepath.Walk out of order - ken before bugs")
			}
			seenKen = true
		}
		return nil
	})
	if !seenKen {
		t.Fatalf("%q not seen", ken)
	}
}
Ejemplo n.º 27
0
func defaultContext() Context {
	var c Context

	c.GOARCH = envOr("GOARCH", runtime.GOARCH)
	c.GOOS = envOr("GOOS", runtime.GOOS)
	c.GOROOT = pathpkg.Clean(runtime.GOROOT())
	c.GOPATH = envOr("GOPATH", "")
	c.Compiler = runtime.Compiler

	// Each major Go release in the Go 1.x series should add a tag here.
	// Old tags should not be removed. That is, the go1.x tag is present
	// in all releases >= Go 1.x. Code that requires Go 1.x or later should
	// say "+build go1.x", and code that should only be built before Go 1.x
	// (perhaps it is the stub to use in that case) should say "+build !go1.x".
	c.ReleaseTags = []string{"go1.1", "go1.2", "go1.3", "go1.4", "go1.5", "go1.6"}

	switch os.Getenv("CGO_ENABLED") {
	case "1":
		c.CgoEnabled = true
	case "0":
		c.CgoEnabled = false
	default:
		// cgo must be explicitly enabled for cross compilation builds
		if runtime.GOARCH == c.GOARCH && runtime.GOOS == c.GOOS {
			c.CgoEnabled = cgoEnabled[c.GOOS+"/"+c.GOARCH]
			break
		}
		c.CgoEnabled = false
	}

	return c
}
Ejemplo n.º 28
0
func main() {
	flag.Usage = usage
	flag.Parse()
	if runtime.GOROOT() == "" {
		fmt.Fprintf(os.Stderr, "%s: no $GOROOT\n", argv0)
		os.Exit(1)
	}
	readPackageList()

	// special case - "unsafe" is already installed
	visit["unsafe"] = done

	args := flag.Args()
	if len(args) == 0 {
		usage()
	}
	for _, path := range args {
		if s := schemeRe.FindString(path); s != "" {
			errorf("%q used in import path, try %q\n", s, path[len(s):])
			continue
		}
		document(path)
	}
	if errors_ {
		os.Exit(1)
	}
}
Ejemplo n.º 29
0
// Run this shell script, but do it in Go so it can be run by "go test".
// 	go build -o testvet
// 	$(GOROOT)/test/errchk ./testvet -shadow -printfuncs='Warn:1,Warnf:1' testdata/*.go testdata/*.s
// 	rm testvet
//
func TestVet(t *testing.T) {
	// Plan 9 and Windows systems can't be guaranteed to have Perl and so can't run errchk.
	switch runtime.GOOS {
	case "plan9", "windows":
		t.Skip("skipping test; no Perl on %q", runtime.GOOS)
	}

	// go build
	cmd := exec.Command("go", "build", "-o", binary)
	run(cmd, t)

	// defer removal of vet
	defer os.Remove(binary)

	// errchk ./testvet
	gos, err := filepath.Glob(filepath.Join(dataDir, "*.go"))
	if err != nil {
		t.Fatal(err)
	}
	asms, err := filepath.Glob(filepath.Join(dataDir, "*.s"))
	if err != nil {
		t.Fatal(err)
	}
	files := append(gos, asms...)
	errchk := filepath.Join(runtime.GOROOT(), "test", "errchk")
	flags := []string{
		"./" + binary,
		"-printfuncs=Warn:1,Warnf:1",
		"-test", // TODO: Delete once -shadow is part of -all.
	}
	cmd = exec.Command(errchk, append(flags, files...)...)
	if !run(cmd, t) {
		t.Fatal("vet command failed")
	}
}
Ejemplo n.º 30
0
func newDoc() *doc {
	d := doc{}

	// build an fs including GOROOT and GOPATH
	d.fs = vfs.NameSpace{}
	fsGate := make(chan bool, 20)
	d.fs.Bind("/", gatefs.New(vfs.OS(runtime.GOROOT()), fsGate), "/", vfs.BindReplace)

	box, err := rice.FindBox("templates")
	if err != nil {
		log.Fatalln(err)
	}

	// create a presentation based on the fs
	corpus := godoc.NewCorpus(d.fs)
	d.pres = godoc.NewPresentation(corpus)
	packageText, err := box.String("package.txt")
	if err != nil {
		log.Fatalln(err)
	}
	d.pres.PackageText, err = template.New("package.txt").Funcs(d.pres.FuncMap()).Delims("[", "]").Parse(packageText)
	if err != nil {
		log.Fatalln(err)
	}

	return &d
}