func TestCrossCompile(t *testing.T) { if strings.HasPrefix(runtime.Version(), "go1.4") { t.Skip("skipping cross compile test, not supported on", runtime.Version()) } gb := T{T: t} defer gb.cleanup() gb.tempDir("src/p") gb.tempFile("src/p/main.go", `package main func main() { println("hello world") } `) gb.cd(gb.tempdir) tmpdir := gb.tempDir("tmp") goos := "windows" if runtime.GOOS == goos { goos = "linux" } gb.setenv("TMP", tmpdir) gb.setenv("GOOS", goos) gb.run("build") gb.mustBeEmpty(tmpdir) name := fmt.Sprintf("p-%s-%s", goos, runtime.GOARCH) if goos == "windows" { name += ".exe" } gb.mustExist(gb.path("bin", name)) gb.wantExecutable(gb.path("bin", name), "expected $PROJECT/bin/p-$GOOS-$GOARCH") }
func (env *TravisEnvironment) Prepare() { msg("preparing environment for Travis CI\n") run("go", "get", "golang.org/x/tools/cmd/cover") run("go", "get", "github.com/mattn/goveralls") run("go", "get", "github.com/mitchellh/gox") if runtime.GOOS == "darwin" { // install the libraries necessary for fuse run("brew", "install", "caskroom/cask/brew-cask") run("brew", "cask", "install", "osxfuse") } // only test cross compilation on linux with Travis if runtime.GOOS == "linux" { env.goxArch = []string{"386", "amd64"} if !strings.HasPrefix(runtime.Version(), "go1.3") { env.goxArch = append(env.goxArch, "arm") } env.goxOS = []string{"linux", "darwin", "freebsd", "openbsd", "windows"} } else { env.goxArch = []string{runtime.GOARCH} env.goxOS = []string{runtime.GOOS} } msg("gox: OS %v, ARCH %v\n", env.goxOS, env.goxArch) if !strings.HasPrefix(runtime.Version(), "go1.5") { run("gox", "-build-toolchain", "-os", strings.Join(env.goxOS, " "), "-arch", strings.Join(env.goxArch, " ")) } }
func main() { flag.Parse() if *flagVersion { fmt.Fprintf(os.Stderr, "publisher version: %s\nGo version: %s (%s/%s)\n", buildinfo.Version(), runtime.Version(), runtime.GOOS, runtime.GOARCH) return } logf("Starting publisher version %s; Go %s (%s/%s)", buildinfo.Version(), runtime.Version(), runtime.GOOS, runtime.GOARCH) listenAddr, err := app.ListenAddress() if err != nil { logger.Fatalf("Listen address: %v", err) } conf := appConfig() ph := newPublishHandler(conf) if err := ph.initRootNode(); err != nil { logf("%v", err) } ws := webserver.New() ws.Logger = logger ws.Handle("/", ph) if conf.HTTPSCert != "" && conf.HTTPSKey != "" { ws.SetTLS(conf.HTTPSCert, conf.HTTPSKey) } if err := ws.Listen(listenAddr); err != nil { logger.Fatalf("Listen: %v", err) } ws.Serve() }
// New constructs a new AirbrakeHandler. // // The projectId & key parameters should be obtained from airbrake. The // environment parameter is the name of the environment to report errors under. func New(projectId int64, key string, environment string) *AirbrakeHandler { repoRoot, _, repoVersion := util.RepoInfo() context := &AirbrakeContext{ OS: runtime.GOOS + " " + runtime.GOARCH, //TODO syscall.Uname() when in linux Language: "go " + runtime.Version(), Environment: environment, RootDirectory: repoRoot, Version: repoVersion, } env := map[string]string{} env["_"] = os.Args[0] env["GOVERSION"] = runtime.Version() env["GOMAXPROCS"] = fmt.Sprintf("%d", runtime.GOMAXPROCS(0)) env["GOROOT"] = runtime.GOROOT() env["HOSTNAME"], _ = os.Hostname() aURL, _ := url.Parse(fmt.Sprintf("%s/api/v3/projects/%d/notices?key=%s", airbrakeURL, projectId, key)) return &AirbrakeHandler{ AirbrakeURL: aURL, projectId: projectId, key: key, Context: context, Env: env, } }
func main() { flag.Parse() if *flagVersion { fmt.Fprintf(os.Stderr, "hello version: %s\nGo version: %s (%s/%s)\n", buildinfo.Version(), runtime.Version(), runtime.GOOS, runtime.GOARCH) return } log.Printf("Starting hello version %s; Go %s (%s/%s)", buildinfo.Version(), runtime.Version(), runtime.GOOS, runtime.GOARCH) listenAddr, err := app.ListenAddress() if err != nil { log.Fatalf("Listen address: %v", err) } conf := appConfig() ws := webserver.New() ws.Handle("/", &helloHandler{who: conf.Word}) // TODO(mpl): handle status requests too. Camlistore will send an auth // token in the extra config that should be used as the "password" for // subsequent status requests. if err := ws.Listen(listenAddr); err != nil { log.Fatalf("Listen: %v", err) } ws.Serve() }
func TestTestGoCommand(t *testing.T) { var buf bytes.Buffer oldStderr := stderr stderr = &buf defer func() { stderr = oldStderr }() var devel = false if runtime.Version()[:5] == "devel" { devel = true } cmdPath := getCommandPath("go") if err := testGoCommand(cmdPath); err != nil { t.Fatal("Unexptected error testing go command: ", err.Error()) } if !devel { if got := buf.String(); got != "" { t.Fatal("Didn't expect a message to stderr, but got one: " + got) } } else { expected := fmt.Sprintf("Warning running with development build: go "+ "version %s %s/%s\n", runtime.Version(), runtime.GOOS, runtime.GOARCH) if got := buf.String(); got != expected { t.Fatalf("Expected the warning message to be %q, but got %q", expected, got) } } }
// Prepare installs dependencies and starts services in order to run the tests. func (env *TravisEnvironment) Prepare() error { env.env = make(map[string]string) msg("preparing environment for Travis CI\n") for _, pkg := range []string{ "golang.org/x/tools/cmd/cover", "github.com/pierrre/gotestcover", } { err := run("go", "get", pkg) if err != nil { return err } } if err := env.getMinio(); err != nil { return err } if err := env.runMinio(); err != nil { return err } if *runCrossCompile && !(runtime.Version() < "go1.7") { // only test cross compilation on linux with Travis if err := run("go", "get", "github.com/mitchellh/gox"); err != nil { return err } if runtime.GOOS == "linux" { env.goxOSArch = []string{ "linux/386", "linux/amd64", "windows/386", "windows/amd64", "darwin/386", "darwin/amd64", "freebsd/386", "freebsd/amd64", "opendbsd/386", "opendbsd/amd64", } if !strings.HasPrefix(runtime.Version(), "go1.3") { env.goxOSArch = append(env.goxOSArch, "linux/arm", "freebsd/arm") } } else { env.goxOSArch = []string{runtime.GOOS + "/" + runtime.GOARCH} } msg("gox: OS/ARCH %v\n", env.goxOSArch) if runtime.Version() < "go1.5" { err := run("gox", "-build-toolchain", "-osarch", strings.Join(env.goxOSArch, " ")) if err != nil { return err } } } return nil }
func TestAirbrakeHandler(t *testing.T) { ah := New(123456, "0123456789abcdef0123456789abcdef", "testing") ah.Context.URL = "http://example.com/airbrake" ah.Context.UserId = "johndoe" ah.Context.UserName = "******" ah.Context.UserEmail = "*****@*****.**" logEvent := event.New(1, event.Warning, "test AirbrakeHandler", map[string]interface{}{"foo": "bar"}, true) err := ah.Event(logEvent) require.NoError(t, err) notice := testAirbrakeServer.notices[len(testAirbrakeServer.notices)-1] nNotifier := notice["notifier"].(map[string]interface{}) assert.Equal(t, notifier.Name, nNotifier["name"]) assert.Equal(t, notifier.Version, nNotifier["version"]) assert.Equal(t, notifier.Url, nNotifier["url"]) _, selfFile, _, _ := runtime.Caller(0) nErrors := notice["errors"].([]interface{}) nError := nErrors[0].(map[string]interface{}) nBacktrace := nError["backtrace"].([]interface{}) nBacktrace0 := nBacktrace[0].(map[string]interface{}) assert.Equal(t, "warning", nError["type"]) assert.Equal(t, "test AirbrakeHandler", nError["message"]) assert.Equal(t, selfFile, nBacktrace0["file"]) assert.NotEmpty(t, nBacktrace0["line"]) assert.Equal(t, "TestAirbrakeHandler", nBacktrace0["function"]) var repoVersion string execCmd := exec.Command("git", "describe", "--dirty", "--tags", "--always") output, err := execCmd.Output() if err == nil { repoVersion = string(bytes.TrimRight(output, "\n")) } nContext := notice["context"].(map[string]interface{}) assert.Equal(t, runtime.GOOS+" "+runtime.GOARCH, nContext["os"]) assert.Equal(t, "go "+runtime.Version(), nContext["language"]) assert.Equal(t, "testing", nContext["environment"]) assert.Equal(t, repoVersion, nContext["version"]) assert.Equal(t, "http://example.com/airbrake", nContext["url"]) assert.Equal(t, "johndoe", nContext["userId"]) assert.Equal(t, "john doe", nContext["userName"]) assert.Equal(t, "*****@*****.**", nContext["userEmail"]) hostname, _ := os.Hostname() nEnvironment := notice["environment"].(map[string]interface{}) assert.Equal(t, fmt.Sprintf("%d", runtime.GOMAXPROCS(0)), nEnvironment["GOMAXPROCS"]) assert.Equal(t, runtime.Version(), nEnvironment["GOVERSION"]) assert.Equal(t, runtime.GOROOT(), nEnvironment["GOROOT"]) assert.Equal(t, hostname, nEnvironment["HOSTNAME"]) nParams := notice["params"].(map[string]interface{}) assert.Equal(t, "bar", nParams["foo"]) }
func getSupportedPlatforms() []Platform { if strings.HasPrefix(runtime.Version(), "go1.4") { return SUPPORTED_PLATFORMS_1_4 } if strings.HasPrefix(runtime.Version(), "go1.3") { return SUPPORTED_PLATFORMS_1_3 } // otherwise default to <= go1.2 return SUPPORTED_PLATFORMS_1_1 }
func TestVersion(t *testing.T) { r := &g2z.AgentRequest{} s, err := Version(r) if err != nil { t.Error(err.Error()) } if s != runtime.Version() { t.Errorf("Expected Version() to return '%s', got '%s'", runtime.Version(), s) } }
func main() { ftmdLog.Info("//////////////////////// Copyright 2015 Factom Foundation") ftmdLog.Info("//////////////////////// Use of this source code is governed by the MIT") ftmdLog.Info("//////////////////////// license that can be found in the LICENSE file.") ftmdLog.Warning("Go compiler version:", runtime.Version()) fmt.Println("Go compiler version:", runtime.Version()) cp.CP.AddUpdate("gocompiler", "system", fmt.Sprintln("Go compiler version: ", runtime.Version()), "", 0) cp.CP.AddUpdate("copyright", "system", "Legal", "Copyright 2015 Factom Foundation\n"+ "Use of this source code is governed by the MIT\n"+ "license that can be found in the LICENSE file.", 0) if !isCompilerVersionOK() { for i := 0; i < 30; i++ { fmt.Println("!!! !!! !!! ERROR: unsupported compiler version !!! !!! !!!") } time.Sleep(time.Second) os.Exit(1) } // Load configuration file and send settings to components loadConfigurations() // create the $home/.factom directory if it does not exist os.Mkdir(homeDir, 0755) // Initialize db initDB() // Use all processor cores. runtime.GOMAXPROCS(runtime.NumCPU()) //Up some limits. if err := limits.SetLimits(); err != nil { os.Exit(1) } // Work around defer not working after os.Exit() if err := factomdMain(); err != nil { os.Exit(1) } }
func NewBuildContext(archSuffix string) *build.Context { if strings.HasPrefix(runtime.Version(), "go1.") && runtime.Version()[4] < '3' { panic("GopherJS requires Go 1.3. Please upgrade.") } return &build.Context{ GOROOT: build.Default.GOROOT, GOPATH: build.Default.GOPATH, GOOS: build.Default.GOOS, GOARCH: archSuffix, Compiler: "gc", BuildTags: []string{"netgo"}, ReleaseTags: build.Default.ReleaseTags, } }
func TestCGONext(t *testing.T) { // Test if one can do 'next' in a cgo binary // On OSX with Go < 1.5 CGO is not supported due to: https://github.com/golang/go/issues/8973 if runtime.GOOS == "darwin" && strings.Contains(runtime.Version(), "1.4") { return } withTestProcess("cgotest", t, func(p *Process, fixture protest.Fixture) { pc, err := p.FindFunctionLocation("main.main", true, 0) if err != nil { t.Fatal(err) } _, err = p.SetBreakpoint(pc) if err != nil { t.Fatal(err) } err = p.Continue() if err != nil { t.Fatal(err) } err = p.Next() if err != nil { t.Fatal(err) } }) }
// check that go test -race builds and runs a racy binary, and that it finds the race. func TestTestRace(t *testing.T) { if !canRace { t.Skip("skipping because race detector not supported") } if strings.HasPrefix(runtime.Version(), "go1.4") { t.Skipf("skipping race test as Go version %v incorrectly marks race failures as success", runtime.Version()) } gb := T{T: t} defer gb.cleanup() gb.tempDir("src/race") gb.tempFile("src/race/map_test.go", `package race import "testing" func TestRaceMapRW(t *testing.T) { m := make(map[int]int) ch := make(chan bool, 1) go func() { _ = m[1] ch <- true }() m[1] = 1 <-ch } `) gb.cd(gb.tempdir) tmpdir := gb.tempDir("tmp") gb.setenv("TMP", tmpdir) gb.runFail("test", "-race") gb.mustBeEmpty(tmpdir) }
func getPlatformInfo() keybase1.PlatformInfo { return keybase1.PlatformInfo{ Os: runtime.GOOS, Arch: runtime.GOARCH, GoVersion: runtime.Version(), } }
func init() { if Version != "unknown-dev" { // If not a generic dev build, version string should come from git describe exp := regexp.MustCompile(`^v\d+\.\d+\.\d+(-[a-z0-9]+)*(\+\d+-g[0-9a-f]+)?(-dirty)?$`) if !exp.MatchString(Version) { l.Fatalf("Invalid version string %q;\n\tdoes not match regexp %v", Version, exp) } } // Check for a clean release build. A release is something like "v0.1.2", // with an optional suffix of letters and dot separated numbers like // "-beta3.47". If there's more stuff, like a plus sign and a commit hash // and so on, then it's not a release. If there's a dash anywhere in // there, it's some kind of beta or prerelease version. exp := regexp.MustCompile(`^v\d+\.\d+\.\d+(-[a-z]+[\d\.]+)?$`) IsRelease = exp.MatchString(Version) IsBeta = strings.Contains(Version, "-") stamp, _ := strconv.Atoi(BuildStamp) BuildDate = time.Unix(int64(stamp), 0) date := BuildDate.UTC().Format("2006-01-02 15:04:05 MST") LongVersion = fmt.Sprintf("syncthing %s (%s %s-%s %s) %s@%s %s", Version, runtime.Version(), runtime.GOOS, runtime.GOARCH, BuildEnv, BuildUser, BuildHost, date) if os.Getenv("STTRACE") != "" { logFlags = log.Ltime | log.Ldate | log.Lmicroseconds | log.Lshortfile } }
func servePage(w http.ResponseWriter, title, subtitle, query string, content []byte) { d := struct { Title string Subtitle string PkgRoots []string SearchBox bool Query string Version string Menu []byte Content []byte }{ title, subtitle, fsMap.PrefixList(), *indexEnabled, query, runtime.Version(), nil, content, } if err := godocHTML.Execute(w, &d); err != nil { log.Printf("godocHTML.Execute: %s", err) } }
func TestNewAWSLogsClientUserAgentHandler(t *testing.T) { ctx := logger.Context{ Config: map[string]string{ regionKey: "us-east-1", }, } client, err := newAWSLogsClient(ctx) if err != nil { t.Fatal(err) } realClient, ok := client.(*cloudwatchlogs.CloudWatchLogs) if !ok { t.Fatal("Could not cast client to cloudwatchlogs.CloudWatchLogs") } buildHandlerList := realClient.Handlers.Build request := &request.Request{ HTTPRequest: &http.Request{ Header: http.Header{}, }, } buildHandlerList.Run(request) expectedUserAgentString := fmt.Sprintf("Docker %s (%s) %s/%s (%s; %s; %s)", dockerversion.Version, runtime.GOOS, aws.SDKName, aws.SDKVersion, runtime.Version(), runtime.GOOS, runtime.GOARCH) userAgent := request.HTTPRequest.Header.Get("User-Agent") if userAgent != expectedUserAgentString { t.Errorf("Wrong User-Agent string, expected \"%s\" but was \"%s\"", expectedUserAgentString, userAgent) } }
func init() { stamp, _ := strconv.Atoi(BuildStamp) BuildDate = time.Unix(int64(stamp), 0) date := BuildDate.UTC().Format("2006-01-02 15:04:05 MST") LongVersion = fmt.Sprintf(`strelaysrv %s (%s %s-%s) %s@%s %s`, Version, runtime.Version(), runtime.GOOS, runtime.GOARCH, BuildUser, BuildHost, date) }
func run() int { // If there is no explicit number of Go threads to use, then set it if os.Getenv("GOMAXPROCS") == "" { runtime.GOMAXPROCS(runtime.NumCPU()) } // log.Printf("[INFO] Packer version: %s %s %s", Version, VersionPrerelease, GitCommit) log.Printf("Packer Target OS/Arch: %s %s", runtime.GOOS, runtime.GOARCH) log.Printf("Built with Go Version: %s", runtime.Version()) Ui = &ui.BasicUi{ Reader: os.Stdin, Writer: os.Stdout, ErrorWriter: os.Stdout, } args := os.Args[1:] cli := &cli.CLI{ Args: args, Commands: Commands, //HelpFunc: excludeHelpFunc(Commands, []string{"plugin"}), HelpWriter: os.Stdout, Version: version, } exitCode, err := cli.Run() if err != nil { fmt.Fprintf(os.Stderr, "Error executing CLI: %s\n", err) return 1 } return exitCode }
// rotateFile closes the syncBuffer's file and starts a new one. func (sb *syncBuffer) rotateFile(now time.Time) error { if sb.file != nil { if err := sb.Flush(); err != nil { return err } if err := sb.file.Close(); err != nil { return err } } var err error sb.file, _, err = create(sb.sev, now) sb.nbytes = 0 if err != nil { return err } sb.Writer = bufio.NewWriterSize(sb.file, bufferSize) // Write header. var buf bytes.Buffer fmt.Fprintf(&buf, "Log file created at: %s\n", now.Format("2006/01/02 15:04:05")) fmt.Fprintf(&buf, "Running on machine: %s\n", host) fmt.Fprintf(&buf, "Binary: Built with %s %s for %s/%s\n", runtime.Compiler, runtime.Version(), runtime.GOOS, runtime.GOARCH) fmt.Fprintf(&buf, "Log line format: [IWEF]yymmdd hh:mm:ss.uuuuuu file:line msg\n") var n int n, err = sb.file.Write(buf.Bytes()) sb.nbytes += uint64(n) return err }
func (srv *Server) DockerVersion() APIVersion { return APIVersion{ Version: VERSION, GitCommit: GITCOMMIT, GoVersion: runtime.Version(), } }
func getSystemTags() (map[string]string, error) { tags := make(map[string]string) tags["connector-version"] = lib.BuildDate hostname, err := os.Hostname() if err == nil { tags["system-hostname"] = hostname } tags["system-arch"] = runtime.GOARCH tags["system-golang-version"] = runtime.Version() sysname, nodename, release, version, machine, err := uname() if err != nil { return nil, fmt.Errorf("CUPS failed to call uname while initializing: %s", err) } tags["system-uname-sysname"] = sysname tags["system-uname-nodename"] = nodename tags["system-uname-release"] = release tags["system-uname-version"] = version tags["system-uname-machine"] = machine tags["connector-cups-client-version"] = fmt.Sprintf("%d.%d.%d", C.CUPS_VERSION_MAJOR, C.CUPS_VERSION_MINOR, C.CUPS_VERSION_PATCH) return tags, nil }
// ServerInfo - get server info. func (web *webAPIHandlers) ServerInfo(r *http.Request, args *WebGenericArgs, reply *ServerInfoRep) error { if !isJWTReqAuthenticated(r) { return toJSONError(errAuthentication) } host, err := os.Hostname() if err != nil { host = "" } memstats := &runtime.MemStats{} runtime.ReadMemStats(memstats) mem := fmt.Sprintf("Used: %s | Allocated: %s | Used-Heap: %s | Allocated-Heap: %s", humanize.Bytes(memstats.Alloc), humanize.Bytes(memstats.TotalAlloc), humanize.Bytes(memstats.HeapAlloc), humanize.Bytes(memstats.HeapSys)) platform := fmt.Sprintf("Host: %s | OS: %s | Arch: %s", host, runtime.GOOS, runtime.GOARCH) goruntime := fmt.Sprintf("Version: %s | CPUs: %s", runtime.Version(), strconv.Itoa(runtime.NumCPU())) reply.MinioEnvVars = os.Environ() reply.MinioVersion = Version reply.MinioMemory = mem reply.MinioPlatform = platform reply.MinioRuntime = goruntime reply.UIVersion = miniobrowser.UIVersion return nil }
func servePage(w http.ResponseWriter, tabtitle, title, subtitle, query string, content []byte) { if tabtitle == "" { tabtitle = title } d := struct { Tabtitle string Title string Subtitle string SearchBox bool Query string Version string Menu []byte Content []byte }{ tabtitle, title, subtitle, *indexEnabled, query, runtime.Version(), nil, content, } if err := godocHTML.Execute(w, &d); err != nil { log.Printf("godocHTML.Execute: %s", err) } }
func runVersion(cmd *Command, args []string) { if len(args) != 0 { cmd.Usage() } fmt.Printf("go version %s %s/%s (with experimental changes)\n", runtime.Version(), runtime.GOOS, runtime.GOARCH) }
func runVersion(cmd *cobra.Command, args []string) (exit int) { stdout.Printf("rkt Version: %s", version.Version) stdout.Printf("appc Version: %s", schema.AppContainerVersion) stdout.Printf("Go Version: %s", runtime.Version()) stdout.Printf("Go OS/Arch: %s/%s", runtime.GOOS, runtime.GOARCH) return }
func main() { if len(os.Args) == 1 { cmd := exec.Command(os.Args[0], "-test.bench=.*", "-test.benchmem=true", "-test.benchtime=2s") cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr cmd.Run() return } fmt.Printf("Build: %s %s-%s\n", runtime.Version(), runtime.GOOS, runtime.GOARCH) hashers := []struct { name string hash hash.Hash }{ {"SHA256", sha256.New()}, {"SHAKE256", shakeAdapter{sha3.NewShake256(), 64}}, } benchmarks := []testing.InternalBenchmark{} for _, h := range hashers { benchmarks = append(benchmarks, testing.InternalBenchmark{ Name: h.name, F: wrap(h.hash), }) } testing.Main(func(pat, str string) (bool, error) { return true, nil }, nil, benchmarks, nil) }
func main() { var filename string var v bool flag.StringVar(&filename, "cfg", "", "path to config file") flag.BoolVar(&v, "v", false, "show version") flag.Parse() if v { fmt.Println(version) return } cfg, err := config.Load(filename) if err != nil { log.Fatalf("[FATAL] %s. %s", version, err) } log.Printf("[INFO] Runtime config\n" + toJSON(cfg)) log.Printf("[INFO] Version %s starting", version) log.Printf("[INFO] Go runtime is %s", runtime.Version()) initRuntime(cfg) initMetrics(cfg) initBackend(cfg) go watchBackend() startAdmin(cfg) startListeners(cfg.Listen, cfg.Proxy.ShutdownWait, newProxy(cfg)) registry.Default.Deregister() }
func LogRuntime() string { n := runtime.NumCPU() v := runtime.Version() m := runtime.GOMAXPROCS(-1) fmsg := "%v %v; cpus: %v; GOMAXPROCS: %v; version: %v" return fmt.Sprintf(fmsg, runtime.GOARCH, runtime.GOOS, n, m, v) }