Golang Environ示例

说明

golang environ示例是从最受好评的开源项目中提取的实现代码,你可以参考下面示例的使用方式。

编程语言: Golang

命名空间/包名称: os

示例#1
文件: main.go 项目: kjakapat/go-repl

func compile(w *World) *bytes.Buffer {
	ioutil.WriteFile(TEMPPATH+".go", []byte(w.source()), 0644)

	err := new(bytes.Buffer)

	re, e, _ := os.Pipe()

	attr := &os.ProcAttr{Env: os.Environ(), Files: []*os.File{nil, e, nil}}
	args := []string{bin + "/" + arch + "g", "-o", TEMPPATH + ".6", TEMPPATH + ".go"}
	os.StartProcess(bin+"/"+arch+"g", args, attr)

	e.Close()
	io.Copy(err, re)

	if err.Len() > 0 {
		return err
	}

	re, e, _ = os.Pipe()

	attr = &os.ProcAttr{Env: os.Environ(), Files: []*os.File{nil, e, nil}}
	args = []string{bin + "/" + arch + "l", "-o", TEMPPATH + "", TEMPPATH + ".6"}
	os.StartProcess(bin+"/"+arch+"l", args, attr)

	e.Close()
	io.Copy(err, re)

	return err
}

示例#2
文件: chromium_builds.go 项目: saltmueller/skia-buildbot

func buildChromium(chromiumDir, targetPlatform string) error {
	if err := os.Chdir(filepath.Join(chromiumDir, "src")); err != nil {
		return fmt.Errorf("Could not chdir to %s/src: %s", chromiumDir, err)
	}

	// Find the build target to use while building chromium.
	buildTarget := "chrome"
	if targetPlatform == "Android" {
		util.LogErr(
			ioutil.WriteFile(filepath.Join(chromiumDir, "chromium.gyp_env"), []byte("{ 'GYP_DEFINES': 'OS=android', }\n"), 0777))
		buildTarget = "chrome_public_apk"
	}

	// Restart Goma's compiler proxy right before building the checkout.
	err := ExecuteCmd("python", []string{filepath.Join(GomaDir, "goma_ctl.py"), "restart"},
		os.Environ(), GOMA_CTL_RESTART_TIMEOUT, nil, nil)
	if err != nil {
		return fmt.Errorf("Error while restarting goma compiler proxy: %s", err)
	}

	// Run "GYP_DEFINES='gomadir=/b/build/goma' GYP_GENERATORS='ninja' build/gyp_chromium -Duse_goma=1".
	env := []string{fmt.Sprintf("GYP_DEFINES=gomadir=%s", GomaDir), "GYP_GENERATORS=ninja"}
	err = ExecuteCmd(filepath.Join("build", "gyp_chromium"), []string{"-Duse_goma=1"}, env,
		GYP_CHROMIUM_TIMEOUT, nil, nil)
	if err != nil {
		return fmt.Errorf("Error while running gyp_chromium: %s", err)
	}
	// Run "ninja -C out/Release -j100 ${build_target}".
	// Use the full system env while building chromium.
	args := []string{"-C", "out/Release", "-j100", buildTarget}
	return ExecuteCmd("ninja", args, os.Environ(), NINJA_TIMEOUT, nil, nil)
}

示例#3
文件: listener.go 项目: sunjiahz/goproxy

func StartProcess() (*os.Process, error) {
	argv0, err := exec.LookPath(os.Args[0])
	if err != nil {
		return nil, err
	}

	files := make([]*os.File, 0)
	files = append(files, os.Stdin)
	files = append(files, os.Stdout)
	files = append(files, os.Stderr)

	for _, key := range os.Environ() {
		if strings.HasPrefix(key, ENV_PREFIX) {
			parts := strings.SplitN(key, "=", 2)
			if fd, err := strconv.Atoi(parts[1]); err == nil {
				if err = noCloseOnExec(uintptr(fd)); err != nil {
					files = append(files, os.NewFile(uintptr(fd), key))
				}
			}
		}
	}

	return os.StartProcess(argv0, os.Args, &os.ProcAttr{
		Dir:   path.Dir(argv0),
		Env:   os.Environ(),
		Files: files,
		Sys:   &syscall.SysProcAttr{},
	})
}

示例#4
文件: foundation.go 项目: sgoings/otto

func (f *Foundation) Infra(ctx *foundation.Context) error {
	if ctx.Action == "" {
		appInfra := ctx.Appfile.ActiveInfrastructure()
		lookup := directory.Lookup{Infra: appInfra.Type}
		infra, err := ctx.Directory.GetInfra(&directory.Infra{Lookup: lookup})
		os.Setenv("DEISCTL_TUNNEL", infra.Outputs["ip"])

		fmt.Println("DEISCTL_TUNNEL is " + os.Getenv("DEISCTL_TUNNEL"))

		cmd := exec.Command("deisctl", "config", "platform", "set", "version=v1.11.1")
		cmd.Env = os.Environ()
		err = ottoExec.Run(ctx.Ui, cmd)

		cmd = exec.Command("deisctl", "config", "platform", "set", "sshPrivateKey=~/.ssh/deis-test")
		cmd.Env = os.Environ()
		err = ottoExec.Run(ctx.Ui, cmd)

		cmd = exec.Command("deisctl", "config", "platform", "set", "domain=goings.space")
		cmd.Env = os.Environ()
		err = ottoExec.Run(ctx.Ui, cmd)

		cmd = exec.Command("deisctl", "install", "platform")
		cmd.Env = os.Environ()
		err = ottoExec.Run(ctx.Ui, cmd)

		cmd = exec.Command("deisctl", "start", "platform")
		cmd.Env = os.Environ()
		err = ottoExec.Run(ctx.Ui, cmd)

		return err
	}
	return nil
}

示例#5
文件: server_test.go 项目: hivetech/judo.legacy

func (s *DebugHooksServerSuite) TestRunHookExceptional(c *C) {
	err := ioutil.WriteFile(s.ctx.ClientFileLock(), []byte{}, 0777)
	c.Assert(err, IsNil)
	session, err := s.ctx.FindSession()
	c.Assert(session, NotNil)
	c.Assert(err, IsNil)

	// Run the hook in debug mode with no exit flock held.
	// The exit flock will be acquired immediately, and the
	// debug-hooks server process killed.
	err = session.RunHook("myhook", s.tmpdir, os.Environ())
	c.Assert(err, ErrorMatches, "signal: killed")

	// Run the hook in debug mode with the exit flock held.
	// This simulates the client process starting but not
	// cleanly exiting (normally the .pid file is updated,
	// and the server waits on the client process' death).
	cmd := exec.Command("flock", s.ctx.ClientExitFileLock(), "-c", "sleep 1s")
	c.Assert(cmd.Start(), IsNil)
	expected := time.Now().Add(time.Second)
	err = session.RunHook("myhook", s.tmpdir, os.Environ())
	after := time.Now()
	c.Assert(after, checkers.TimeBetween(expected.Add(-100*time.Millisecond), expected.Add(100*time.Millisecond)))
	c.Assert(err, ErrorMatches, "signal: killed")
	c.Assert(cmd.Wait(), IsNil)
}

示例#6
文件: talk.go 项目: ZhiqinYang/2014-talks

func startAttachTag(tag string) {
	if *dockerFlag == "" {
		*dockerFlag, _ = exec.LookPath("docker")
	}
	var containers []string
	img := "gc14:" + tag
	foreachDockerPs(func(runningImage, containerID string) {
		if runningImage != img {
			return
		}
		containers = append(containers, containerID)
	})
	switch {
	case len(containers) > 1:
		for _, container := range containers {
			// Best effort:
			exec.Command(*dockerFlag, "kill", container).Run()
			exec.Command(*dockerFlag, "rm", container).Run()
		}
	case len(containers) == 1:
		if err := syscall.Exec(*dockerFlag,
			[]string{*dockerFlag, "attach", containers[0]},
			os.Environ()); err != nil {
			log.Fatalf("docker attach exec: %v", err)
		}
	}
	if err := syscall.Exec(*dockerFlag,
		[]string{*dockerFlag, "run", "-t", "-i", "-h", tag, "-w", "/home/gopher", img, "/bin/bash"},
		os.Environ()); err != nil {
		log.Fatalf("docker run exec: %v", err)
	}
}

示例#7
文件: main.go 项目: CodyGuo/Go-Cody

func main() {
	// 获取系统名字
	fmt.Println(os.Hostname())
	// 获取系统内存
	fmt.Println(os.Getpagesize())
	// 获取系统环境变量
	for index, env := range os.Environ() {
		fmt.Println(index, " : ", env)
	}
	// 获取指定key的环境变量,环境变量不区分大小写
	fmt.Println("当前系统目录为:", os.Getenv("windir"))
	// 设置环境变量
	fmt.Println("cody的环境变量为:", os.Getenv("cody"))
	os.Setenv("Cody", "guo")
	fmt.Println("cody的环境变量为:", os.Getenv("cody"))
	// 删除所有环境变量
	os.Clearenv()
	fmt.Println(os.Environ())

	// 如果存在os.Exit()就不会执行defer
	// defer fmt.Println("我在退出吗?")
	// os.Exit(0)
	fmt.Println("程序已退出,不打印了...")

	fmt.Println(os.Getuid(), os.Getgid())
	fmt.Println(os.Getgroups())
	fmt.Println(os.Getpid(), os.Getppid())

	fmt.Println(os.TempDir())

}

示例#8
文件: set_env_test.go 项目: zined/llconf

func TestSetNewEval(t *testing.T) {
	arguments := []Argument{
		Constant("/bin/bash"),
		Constant("-c"),
		Constant("echo $setenv"),
	}
	exec := ExecPromise{ExecTest, arguments}

	var sout bytes.Buffer
	ctx := NewContext()
	ctx.ExecOutput = &sout

	name := "setenv"
	value := "blafasel"
	s := SetEnv{Constant(name), Constant(value), exec}

	oldenv := fmt.Sprintf("%v", os.Environ())
	s.Eval([]Constant{}, &ctx, "setenv")
	newenv := fmt.Sprintf("%v", os.Environ())

	if oldenv != newenv {
		t.Errorf("(setenv) changed overall environment")
	}

	if sout.String() != "blafasel\n" {
		t.Errorf("env name not present during execution")
	}
}

示例#9
文件: axiom.go 项目: postfix/axiom

func Mousetrap(app *cli.App) {
	oldBefore := app.Before
	app.Before = func(c *cli.Context) error {
		if mousetrap.StartedByExplorer() {
			cmd := exec.Command(os.Args[0], os.Args[1:]...)
			cmd.Env = append(os.Environ(), "MOUSETRAP=1")
			cmd.Stdin = os.Stdin
			cmd.Stdout = os.Stdout
			cmd.Stderr = os.Stderr
			cmd.Run()
			cmd = exec.Command("cmd.exe", "/K")
			cmd.Env = os.Environ()
			cmd.Stdin = os.Stdin
			cmd.Stdout = os.Stdout
			cmd.Stderr = os.Stderr
			err := cmd.Run()
			if err != nil {
				fmt.Println("Failed to execute sub-process. Error:", err)
				os.Exit(1)
			}
			os.Exit(0)
		}
		if oldBefore == nil {
			return nil
		}
		return oldBefore(c)
	}
}

示例#10
文件: webservice.go 项目: FelixCao/GoSQL

func main() {
	m := martini.Classic()
	m.Map(SetupDB())
	m.Get("/", func() string { return "Welcome to GoSQL database" })
	m.Get("/var", func() string {
		for _, e := range os.Environ() {
			pair := strings.Split(e, "=")
			fmt.Println(pair[0])
		}
		return "hello"
	})
	m.Get("/show", ShowDB)
	m.Get("/print1", func() string { return os.Getenv("POSTGRESDB_SERVICE_HOST") })
	m.Get("/print4", func() string { return os.Getenv("OPENSHIFT_POSTGRESQL_PASSWORD") })
	m.Get("/print5", func() string { return os.Getenv("OPENSHIFT_POSTGRESQL_USER") })
	m.Get("/print6", func() string { return os.Getenv("POSTGRESQL_USER") })
	m.Get("/var", func() string {
		for _, e := range os.Environ() {
			pair := strings.Split(e, "=")
			fmt.Println(pair[0])
		}
		return "yo"
	})
	m.Post("/add", InsertPur)
	m.RunOnAddr(":8080")
}

示例#11
文件: main.go 项目: qrush/go-repl

func compile(w *World) *bytes.Buffer {
	ioutil.WriteFile(TEMPPATH+".go", []byte(w.source()), 0644)

	err := new(bytes.Buffer)

	re, e, _ := os.Pipe()

	os.ForkExec(
		bin+"/"+arch+"g",
		[]string{bin + "/" + arch + "g", "-o", TEMPPATH + ".6", TEMPPATH + ".go"},
		os.Environ(),
		"",
		[]*os.File{nil, e, nil})

	e.Close()
	io.Copy(err, re)

	if err.Len() > 0 {
		return err
	}

	re, e, _ = os.Pipe()
	os.ForkExec(
		bin+"/"+arch+"l",
		[]string{bin + "/" + arch + "l", "-o", TEMPPATH + "", TEMPPATH + ".6"},
		os.Environ(),
		"",
		[]*os.File{nil, e, nil})

	e.Close()
	io.Copy(err, re)

	return err
}

示例#12
文件: gopages.go 项目: santinopnipa/SUT_gopages

//to build the project with gobuild or make after generating .go source files
func build(b int, s string) (err os.Error) {
	p := strings.Fields(s)
	params := make([]string, len(p)+1)
	params[0] = ""
	for i, param := range p {
		params[i+1] = param
	}
	m := b == MAKE
	g := b == GOBUILD
	//fd := []*os.File{os.Stdin, os.Stdout, os.Stderr}
	if m {
		err = os.Exec("/usr/bin/make", params, os.Environ())
		if err != nil {
			panic("Cannot call make")
		}
	} else if g {
		gobuild := os.Getenv("GOBIN")
		if len(gobuild) == 0 {
			gobuild = path.Join(os.Getenv("HOME"), "bin", "gobuild")
		} else {
			gobuild = path.Join(gobuild, "gobuild")
		}
		err := os.Exec(gobuild, params, os.Environ())
		if err != nil {
			panic("Cannot call gobuild")
		}
	}
	return
}

示例#13
文件: server_test.go 项目: jameinel/core

func (s *DebugHooksServerSuite) TestRunHookExceptional(c *gc.C) {
	err := ioutil.WriteFile(s.ctx.ClientFileLock(), []byte{}, 0777)
	c.Assert(err, gc.IsNil)
	session, err := s.ctx.FindSession()
	c.Assert(session, gc.NotNil)
	c.Assert(err, gc.IsNil)

	// Run the hook in debug mode with no exit flock held.
	// The exit flock will be acquired immediately, and the
	// debug-hooks server process killed.
	err = session.RunHook("myhook", s.tmpdir, os.Environ())
	c.Assert(err, gc.ErrorMatches, "signal: [kK]illed")

	// Run the hook in debug mode, simulating the holding
	// of the exit flock. This simulates the client process
	// starting but not cleanly exiting (normally the .pid
	// file is updated, and the server waits on the client
	// process' death).
	ch := make(chan bool)
	var clientExited bool
	s.PatchValue(&waitClientExit, func(*ServerSession) {
		clientExited = <-ch
	})
	go func() { ch <- true }()
	err = session.RunHook("myhook", s.tmpdir, os.Environ())
	c.Assert(clientExited, jc.IsTrue)
	c.Assert(err, gc.ErrorMatches, "signal: [kK]illed")
}

示例#14
文件: server_test.go 项目: naoina/miyabi

func TestIsMaster(t *testing.T) {
	origEnv := make([]string, len(os.Environ()))
	copy(origEnv, os.Environ())
	for _, v := range []struct {
		env    string
		expect bool
	}{
		{miyabi.FDEnvKey, false},
		{"UNKNOWN_KEY", true},
	} {
		func() {
			defer func() {
				os.Clearenv()
				for _, v := range origEnv {
					env := strings.SplitN(v, "=", 2)
					os.Setenv(env[0], env[1])
				}
			}()
			if err := os.Setenv(v.env, "1"); err != nil {
				t.Error(err)
				return
			}
			actual := miyabi.IsMaster()
			expect := v.expect
			if !reflect.DeepEqual(actual, expect) {
				t.Errorf(`IsMaster() with %v=1 => %#v; want %#v`, v.env, actual, expect)
			}
		}()
	}
}

示例#15
文件: main.go 项目: nickbruun/coyote

// Emit error.
func emitError(cmd []string, err error, errorHandlers []errorhandlers.Handler) {
	// Construct the error.
	timestamp := time.Now().UTC()
	hostname, _ := os.Hostname()

	environ := make(map[string]string, len(os.Environ()))
	for _, env := range os.Environ() {
		var k, v string

		equalPos := strings.IndexByte(env, '=')
		if equalPos == -1 {
			k = env
		} else {
			k = env[:equalPos]
			v = env[equalPos+1:]
		}

		environ[k] = v
	}

	errMsg := &errorhandlers.Error{
		Cmd:       cmd,
		Desc:      err.Error(),
		Hostname:  hostname,
		Environ:   environ,
		Timestamp: timestamp,
	}

	// Emit the error.
	for _, h := range errorHandlers {
		if err := h.Handle(errMsg); err != nil {
			fmt.Fprintf(os.Stderr, "Failed to send error message: %s\n", err)
		}
	}
}

示例#16
文件: helper.go 项目: helgi/workflow-e2e

// Start executes the provided command (often a `deis` command of some sort) as the specified user
// (by selecting the corresponding profile). Optional arguments may also be supplied that will be
// substituted into the provided command using fmt.Sprintf(...).
func Start(cmdLine string, user *model.User, args ...interface{}) (*gexec.Session, error) {
	if user != nil {
		envVars := append(os.Environ(), fmt.Sprintf("DEIS_PROFILE=%s", user.Username))
		ourCommand := model.Cmd{Env: envVars, CommandLineString: fmt.Sprintf(cmdLine, args...)}
		return StartCmd(ourCommand)
	}
	ourCommand := model.Cmd{Env: os.Environ(), CommandLineString: fmt.Sprintf(cmdLine, args...)}
	return StartCmd(ourCommand)
}

示例#17
文件: handlers.go 项目: freakmac/adbfs

// appendToEnv returns os.Environ() with the name=value pairs from vars.
func appendToEnv(vars map[string]string) (env []string) {
	env = make([]string, len(os.Environ()))
	copy(env, os.Environ())

	for k, v := range vars {
		env = append(env, fmt.Sprintf("%s=%s", k, v))
	}

	return
}

示例#18
文件: webbrowser.go 项目: bryanl/webbrowser

func detectBrowsers(o string) (Opener, error) {
	switch o {
	case "windows":
		return registerWindows(os.Environ())
	case "linux":
		return registerLinux(os.Environ())
	case "darwin":
		return registerOSX(os.Environ())
	}
	return nil, &UnsupportedOSError{OS: o}
}

示例#19
文件: rc.go 项目: ChengShuY/ps-top

// There must be a better way of doing this. Fix me...
// Copied from github.com/sjmudd/mysql_defaults_file so I should share this common code or fix it.
// Return the environment value of a given name.
func getEnviron(name string) string {
	for i := range os.Environ() {
		s := os.Environ()[i]
		keyValue := strings.Split(s, "=")

		if keyValue[0] == name {
			return keyValue[1]
		}
	}
	return ""
}

示例#20
文件: main_test.go 项目: zqzca/back

// setup dumps the database schema and imports it into a temporary randomly
// generated test database so that tests can be run against it using the
// generated sqlboiler ORM package.
func (p *pgTester) setup() error {
	var err error

	p.dbName = viper.GetString("postgres.dbname")
	p.host = viper.GetString("postgres.host")
	p.user = viper.GetString("postgres.user")
	p.pass = viper.GetString("postgres.pass")
	p.port = viper.GetInt("postgres.port")
	p.sslmode = viper.GetString("postgres.sslmode")
	// Create a randomized db name.
	p.testDBName = randomize.StableDBName(p.dbName)

	if err = p.makePGPassFile(); err != nil {
		return err
	}

	if err = p.dropTestDB(); err != nil {
		return err
	}
	if err = p.createTestDB(); err != nil {
		return err
	}

	dumpCmd := exec.Command("pg_dump", "--schema-only", p.dbName)
	dumpCmd.Env = append(os.Environ(), p.pgEnv()...)
	createCmd := exec.Command("psql", p.testDBName)
	createCmd.Env = append(os.Environ(), p.pgEnv()...)

	r, w := io.Pipe()
	dumpCmd.Stdout = w
	createCmd.Stdin = newFKeyDestroyer(rgxPGFkey, r)

	if err = dumpCmd.Start(); err != nil {
		return errors.Wrap(err, "failed to start pg_dump command")
	}
	if err = createCmd.Start(); err != nil {
		return errors.Wrap(err, "failed to start psql command")
	}

	if err = dumpCmd.Wait(); err != nil {
		fmt.Println(err)
		return errors.Wrap(err, "failed to wait for pg_dump command")
	}

	w.Close() // After dumpCmd is done, close the write end of the pipe

	if err = createCmd.Wait(); err != nil {
		fmt.Println(err)
		return errors.Wrap(err, "failed to wait for psql command")
	}

	return nil
}

示例#21
文件: main.go 项目: ivanwyc/google-go

// run runs the command argv, resolving argv[0] if necessary by searching $PATH.
// It provides input on standard input to the command.
func run(argv []string, input []byte) (out string, err os.Error) {
	if len(argv) < 1 {
		err = os.EINVAL
		goto Error
	}
	prog, ok := lookPathCache[argv[0]]
	if !ok {
		prog, err = exec.LookPath(argv[0])
		if err != nil {
			goto Error
		}
		lookPathCache[argv[0]] = prog
	}
	// fmt.Fprintf(os.Stderr, "%v\n", argv);
	var cmd *exec.Cmd
	if len(input) == 0 {
		cmd, err = exec.Run(prog, argv, os.Environ(), "", exec.DevNull, exec.Pipe, exec.MergeWithStdout)
		if err != nil {
			goto Error
		}
	} else {
		cmd, err = exec.Run(prog, argv, os.Environ(), "", exec.Pipe, exec.Pipe, exec.MergeWithStdout)
		if err != nil {
			goto Error
		}
		go func() {
			cmd.Stdin.Write(input)
			cmd.Stdin.Close()
		}()
	}
	defer cmd.Close()
	var buf bytes.Buffer
	_, err = io.Copy(&buf, cmd.Stdout)
	out = buf.String()
	if err != nil {
		cmd.Wait(0)
		goto Error
	}
	w, err := cmd.Wait(0)
	if err != nil {
		goto Error
	}
	if !w.Exited() || w.ExitStatus() != 0 {
		err = w
		goto Error
	}
	return

Error:
	err = &runError{copy(argv), err}
	return
}

示例#22
文件: repl.go 项目: lunixbochs/usercorn

func main() {
	c := cmd.NewUsercornRawCmd()
	c.NoExe = true
	c.NoArgs = true

	c.RunUsercorn = func(args, env []string) error {
		u := c.Usercorn
		mem, err := u.Mmap(u.Entry(), 0x10000)
		if err != nil {
			return err
		}
		mem.Desc = "repl"

		status := models.StatusDiff{U: u}
		fmt.Printf("%s", status.Changes(false).String("", c.Config.Color))
		addr := mem.Addr
		end := addr
		input := bufio.NewScanner(os.Stdin)
		for {
			fmt.Printf("%s", status.Changes(true).String("", c.Config.Color))
			fmt.Printf("0x%x: ", addr)
			if !input.Scan() {
				break
			}
			text := input.Text()
			if len(text) > 0 && text[0] == '.' {
				if handleCmd(c, text) {
					continue
				}
			}
			sc, err := u.Assemble(text, addr)
			if err != nil {
				fmt.Printf("asm err: %s\n", err)
				continue
			}
			if err := u.MemWrite(addr, sc); err != nil {
				fmt.Printf("write err: %s\n", err)
				continue
			}
			end = addr + uint64(len(sc))
			u.SetEntry(addr)
			u.SetExit(end)
			if err := u.Run(os.Args, os.Environ()); err != nil {
				fmt.Printf("exec err: %s\n", err)
			}
			addr = end
		}
		fmt.Printf("\n%s", status.Changes(false).String("", c.Config.Color))
		return nil
	}
	c.Run(os.Args, os.Environ())
}

示例#23
文件: env.go 项目: pokerG/GoBeginner

func main() {
	os.Setenv("FOO", "1")
	fmt.Println("FOO:", os.Getenv("FOO"))
	fmt.Println("BAR:", os.Getenv("BAR"))
	fmt.Println()
	fmt.Println(os.Environ())
	for b, e := range os.Environ() {
		fmt.Println(b)
		fmt.Println(e)
		pair := strings.Split(e, "=")
		fmt.Println(pair[0])
	}
}

示例#24
文件: constants.go 项目: kumaranff/GoLang

func main() {
	// Print envrironment information
	fmt.Println(os.Environ())

	// Print envrironment information one per line
	for _, env := range os.Environ() {
		fmt.Println(env)
	}

	name := os.Getenv("USERNAME")

	fmt.Println(name)
}

示例#25
文件: doall_cmd_test.go 项目: abec/srclib

func TestDoAll_cached_sample(t *testing.T) {
	cleanup("go-cache")

	var gitCmd *exec.Cmd
	var srcCmd *exec.Cmd
	gitCmd = exec.Command("git", "checkout", "071610bf3a597bc41aae05e27c5407444b7ea0d1")
	gitCmd.Dir = filepath.Join(testdataPath, "go-cached")
	if o, err := gitCmd.CombinedOutput(); err != nil {
		t.Fatal(string(o), err)
	}
	srcCmd = exec.Command("src", "do-all")
	srcCmd.Dir = filepath.Join(testdataPath, "go-cached")
	srcCmd.Env = append([]string{"SRCLIBPATH=" + srclibPath}, os.Environ()...)
	if o, err := srcCmd.CombinedOutput(); err != nil {
		t.Fatal(string(o), err)
	}
	gitCmd = exec.Command("git", "checkout", "34dd0f240fe12cdd8c9c6e24620cc0013518a55e")
	gitCmd.Dir = filepath.Join(testdataPath, "go-cached")
	if o, err := gitCmd.CombinedOutput(); err != nil {
		t.Fatal(string(o), err)
	}
	srcCmd = exec.Command("src", "do-all")
	srcCmd.Dir = filepath.Join(testdataPath, "go-cached")
	srcCmd.Env = append([]string{"SRCLIBPATH=" + srclibPath}, os.Environ()...)
	if o, err := srcCmd.CombinedOutput(); err != nil {
		t.Fatal(string(o), err)
	}
	firstOne, err := ioutil.ReadFile(filepath.Join(testdataPath, "go-cached", buildstore.BuildDataDirName, "071610bf3a597bc41aae05e27c5407444b7ea0d1", "one", "sample.graph.json"))
	if err != nil {
		t.Fatal(err)
	}
	secondOne, err := ioutil.ReadFile(filepath.Join(testdataPath, "go-cached", buildstore.BuildDataDirName, "34dd0f240fe12cdd8c9c6e24620cc0013518a55e", "one", "sample.graph.json"))
	if err != nil {
		t.Fatal(err)
	}
	if string(firstOne) != string(secondOne) {
		t.Error("Source unit \"one\" should have been cached: string(firstOne) != string(secondOne)")
	}
	firstTwo, err := ioutil.ReadFile(filepath.Join(testdataPath, "go-cached", buildstore.BuildDataDirName, "071610bf3a597bc41aae05e27c5407444b7ea0d1", "two", "sample.graph.json"))
	if err != nil {
		t.Fatal(err)
	}
	secondTwo, err := ioutil.ReadFile(filepath.Join(testdataPath, "go-cached", buildstore.BuildDataDirName, "34dd0f240fe12cdd8c9c6e24620cc0013518a55e", "two", "sample.graph.json"))
	if err != nil {
		t.Fatal(err)
	}
	if string(firstTwo) == string(secondTwo) {
		t.Error("Source unit \"two\" should not be cached: string(firstTwo) == string(secondTwo)")
	}
	cleanup("go-cache")
}

示例#26
文件: env_test.go 项目: Fiery/go-run

func TestEnvCombination(t *testing.T) {
	// set to os defaults
	Env = makeEnvMap(os.Environ(), false)
	Env = Env.combine([]string{"USER=$USER:$USER:func"})

	assert.Equal(t, user+":"+user+":func", (*Env)["USER"], "Should have been overriden by func environment")

	assert.Equal(t, len(os.Environ()), len(*Env), "Consolidated environment length changed.")

	Env = Env.combine([]string{"GOSU_NEW_VAR=foo"})
	assert.Equal(t, "foo", (*Env)["GOSU_NEW_VAR"], "Should have conslidated Env set")
	assert.Equal(t, len(os.Environ())+1, len(*Env), "Consolidated environment length should have increased by 1")

}

示例#27
文件: templates.go 项目: trek10inc/configo

func processTemplatedEnvs(environ []string) error {
	envMap := make(map[string]string)

	// Calculate fresh map of environment variables
	fromEnviron(os.Environ()).All(func(kv T) (bool, error) {
		envMap[kv.(env).key] = kv.(env).value
		return true, nil
	})

	count, err := fromEnviron(environ).
		Where(func(kv T) (bool, error) { return strings.HasPrefix(kv.(env).value, configoPrefix), nil }).
		CountBy(func(kv T) (bool, error) {
			tmpl, err := template.New(kv.(env).key).Funcs(customFuncs).Parse(strings.TrimPrefix(kv.(env).value, configoPrefix))

			if err != nil {
				return false, err
			}

			var buffer bytes.Buffer
			if err = tmpl.Execute(&buffer, envMap); err != nil {
				return false, err
			}

			key := kv.(env).key
			value := buffer.String()

			log.Infof("Setting templated variable `%s` to `%#v`", key, value)

			err = os.Setenv(key, value)

			if err != nil {
				return false, err
			}

			return true, nil
		})

	if err != nil {
		return err
	}

	if count > 0 {
		if log.IsEnabledFor(logging.DEBUG) {
			log.Debugf("Environment variables after templates:\n\t%s", strings.Join(os.Environ(), "\n\t"))
		}
	}

	return nil
}

示例#28
文件: start.go 项目: jweslley/procker

func parseEnv(filepath string) []string {
	file, err := os.Open(filepath)
	if err != nil {
		if filepath == defaultEnvfile {
			return os.Environ()
		} else {
			failIf(err)
		}
	}
	defer file.Close()

	env, err := procker.ParseEnv(file)
	failIf(err)
	return append(os.Environ(), env...)
}

示例#29
文件: build.go 项目: npe9/harvey

func link(b *build) {
	if len(b.SourceFilesCmd) > 0 {
		for _, n := range b.SourceFilesCmd {
			// Split off the last element of the file
			var ext = filepath.Ext(n)
			if len(ext) == 0 {
				log.Fatalf("refusing to overwrite extension-less source file %v", n)
				continue
			}
			n = n[0 : len(n)-len(ext)]
			args := []string{"-o", n}
			f := path.Base(n)
			o := f[:len(f)] + ".o"
			args = append(args, []string{o}...)
			args = append(args, b.Oflags...)
			args = append(args, adjust([]string{"-L", "/amd64/lib"})...)
			args = append(args, b.Libs...)
			cmd := exec.Command(toolprefix+"ld", args...)
			cmd.Env = append(os.Environ(), b.Env...)

			cmd.Stdin = os.Stdin
			cmd.Stderr = os.Stderr
			cmd.Stdout = os.Stdout
			log.Printf("%v", cmd.Args)
			err := cmd.Run()
			if err != nil {
				log.Fatalf("%v\n", err)
			}
		}
	} else {
		args := []string{"-o", b.Program}
		args = append(args, b.ObjectFiles...)
		args = append(args, b.Oflags...)
		args = append(args, adjust([]string{"-L", "/amd64/lib"})...)
		args = append(args, b.Libs...)
		cmd := exec.Command(toolprefix+"ld", args...)
		cmd.Env = append(os.Environ(), b.Env...)

		cmd.Stdin = os.Stdin
		cmd.Stderr = os.Stderr
		cmd.Stdout = os.Stdout
		log.Printf("%v", cmd.Args)
		err := cmd.Run()
		if err != nil {
			log.Fatalf("%v\n", err)
		}
	}
}

示例#30
文件: build.go 项目: ChrisMcKenzie/caddy

func build(cmd *cobra.Command, args []string) {
	p, err := pkg.ReadCaddyJSON()
	if err != nil {
		log.Fatal(err)
		return
	}

	if build, ok := p.Scripts["build"]; ok {
		fmt.Printf("Running script \"build\"\n%s", build)
		fields := strings.Fields(build)

		cmd := exec.Command(fields[0], fields[1:]...)
		cmd.Env = append(os.Environ(), "GO15VENDOREXPERIMENT=1")
		var buf bytes.Buffer
		cmd.Stderr = &buf
		cmd.Stdout = &buf
		err := cmd.Run()
		out := buf.String()
		fmt.Println(out)
		if err != nil {
			fmt.Println(err)
		}
	} else {
		if strings.Contains(runtime.Version(), "go1.5") {
			// add GO15VENDOREXPERIMENT=1 env var so it uses local "vendor""
			var goArgs []string

			if output != "" {
				goArgs = []string{"-o", output}
			}

			goArgs = append(goArgs, args...)
			goArgs = append([]string{"build"}, goArgs...)

			cmd := exec.Command("go", goArgs...)
			cmd.Env = append(os.Environ(), "GO15VENDOREXPERIMENT=1")
			var buf bytes.Buffer
			cmd.Stderr = &buf
			cmd.Stdout = &buf
			err := cmd.Run()
			out := buf.String()
			fmt.Println(out)
			if err != nil {
				fmt.Println(err)
			}
		}
	}
}

展开阅读全文