Golang Chdir示例

说明

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

编程语言: Golang

命名空间/包名称: os

示例#1
文件: writers.go 项目: jumanjiman/eris-cli

func pullRepo(location string, alreadyAsked bool) error {
	if alreadyAsked || askToPull(location) {
		prevDir, _ := os.Getwd()

		if err := os.Chdir(location); err != nil {
			return fmt.Errorf("Error:\tCould not move into the directory (%s)\n", location)
		}

		logger.Printf("Pulling origin master.\n")
		c := exec.Command("git", "pull", "origin", "master")

		// XXX [csk]: we squelch this output to provide a nicer newb interface... may need to change later
		//c.Stdout = config.GlobalConfig.Writer

		c.Stderr = config.GlobalConfig.ErrorWriter
		if err := c.Run(); err != nil {
			logger.Printf("err: %v\n", err)
			return err
		}

		if err := os.Chdir(prevDir); err != nil {
			return fmt.Errorf("Error:\tCould not move into the directory (%s)\n", prevDir)
		}
	}

	return nil
}

示例#2
文件: bot.go 项目: stunti/camlistore

func camputMany() error {
	if *fast {
		gofast(1)
		return nil
	}
	err := os.Chdir(camliRoot)
	if err != nil {
		log.Fatal(err)
	}
	defer func() {
		err := os.Chdir(defaultDir)
		if err != nil {
			panic(err)
		}
	}()
	// upload the full camli pkg tree
	setCurrentTask(NameToCmd["camput3"])
	tsk := getCurrentTask()
	_, err = runCmd(tsk.Cmd)
	addRun(tsk, err)
	if err != nil {
		return err
	}
	return nil
}

示例#3
文件: fmt_test.go 项目: RezaDKhan/terraform

func TestFmt_workingDirectory(t *testing.T) {
	tempDir, err := fmtFixtureWriteDir()
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	defer os.RemoveAll(tempDir)

	cwd, err := os.Getwd()
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	err = os.Chdir(tempDir)
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	defer os.Chdir(cwd)

	ui := new(cli.MockUi)
	c := &FmtCommand{
		Meta: Meta{
			ContextOpts: testCtxConfig(testProvider()),
			Ui:          ui,
		},
	}

	args := []string{}
	if code := c.Run(args); code != 0 {
		t.Fatalf("wrong exit code. errors: \n%s", ui.ErrorWriter.String())
	}

	expected := fmt.Sprintf("%s\n", fmtFixture.filename)
	if actual := ui.OutputWriter.String(); actual != expected {
		t.Fatalf("got: %q\nexpected: %q", actual, expected)
	}
}

示例#4
文件: show_test.go 项目: devendraPSL/terraform-api

func TestShow_noArgsNoState(t *testing.T) {
	// Create the default state
	td, err := ioutil.TempDir("", "tf")
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	statePath := filepath.Join(td, DefaultStateFilename)

	// Change to the temporary directory
	cwd, err := os.Getwd()
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	if err := os.Chdir(filepath.Dir(statePath)); err != nil {
		t.Fatalf("err: %s", err)
	}
	defer os.Chdir(cwd)

	ui := new(cli.MockUi)
	c := &ShowCommand{
		Meta: Meta{
			ContextOpts: testCtxConfig(testProvider()),
			Ui:          ui,
		},
	}

	args := []string{}
	if code := c.Run(args); code != 0 {
		t.Fatalf("bad: \n%s", ui.OutputWriter.String())
	}
}

示例#5
文件: nex_test.go 项目: infogulch/nex

// Test the reverse-Polish notation calculator rp.{nex,y}.
func TestNexPlusYacc(t *testing.T) {
	tmpdir, err := ioutil.TempDir("", "nex")
	dieErr(t, err, "TempDir")
	defer func() {
		dieErr(t, os.RemoveAll(tmpdir), "RemoveAll")
	}()
	run := func(s string) {
		v := strings.Split(s, " ")
		err := exec.Command(v[0], v[1:]...).Run()
		dieErr(t, err, s)
	}
	run("cp rp.nex rp.y " + tmpdir)
	wd, err := os.Getwd()
	dieErr(t, err, "Getwd")
	dieErr(t, os.Chdir(tmpdir), "Chdir")
	defer func() {
		dieErr(t, os.Chdir(wd), "Chdir")
	}()
	run(nexBin + " rp.nex")
	run("go tool yacc rp.y")
	run("go build y.go rp.nn.go")
	cmd := exec.Command("./y")
	cmd.Stdin = strings.NewReader(
		`1 2 3 4 + * -
9 8 * 7 * 3 2 * 1 * / n
`)
	want := "-13\n-84\n"
	got, err := cmd.CombinedOutput()
	dieErr(t, err, "CombinedOutput")
	if want != string(got) {
		t.Fatalf("want %q, got %q", want, string(got))
	}
}

示例#6
文件: path_test.go 项目: TomHoenderdos/go-sunos

func TestAbs(t *testing.T) {
	oldwd, err := os.Getwd()
	if err != nil {
		t.Fatal("Getwd failed: ", err)
	}
	defer os.Chdir(oldwd)

	root, err := ioutil.TempDir("", "TestAbs")
	if err != nil {
		t.Fatal("TempDir failed: ", err)
	}
	defer os.RemoveAll(root)

	wd, err := os.Getwd()
	if err != nil {
		t.Fatal("getwd failed: ", err)
	}
	err = os.Chdir(root)
	if err != nil {
		t.Fatal("chdir failed: ", err)
	}
	defer os.Chdir(wd)

	for _, dir := range absTestDirs {
		err = os.Mkdir(dir, 0777)
		if err != nil {
			t.Fatal("Mkdir failed: ", err)
		}
	}

	err = os.Chdir(absTestDirs[0])
	if err != nil {
		t.Fatal("chdir failed: ", err)
	}

	for _, path := range absTests {
		path = strings.Replace(path, "$", root, -1)
		info, err := os.Stat(path)
		if err != nil {
			t.Errorf("%s: %s", path, err)
			continue
		}

		abspath, err := filepath.Abs(path)
		if err != nil {
			t.Errorf("Abs(%q) error: %v", path, err)
			continue
		}
		absinfo, err := os.Stat(abspath)
		if err != nil || !os.SameFile(absinfo, info) {
			t.Errorf("Abs(%q)=%q, not the same file", path, abspath)
		}
		if !filepath.IsAbs(abspath) {
			t.Errorf("Abs(%q)=%q, not an absolute path", path, abspath)
		}
		if filepath.IsAbs(path) && abspath != filepath.Clean(path) {
			t.Errorf("Abs(%q)=%q, isn't clean", path, abspath)
		}
	}
}

示例#7
文件: build_test.go 项目: jkary/core

func (b *buildSuite) SetUpTest(c *gc.C) {
	b.BaseSuite.SetUpTest(c)

	dir1 := c.MkDir()
	dir2 := c.MkDir()

	c.Log(dir1)
	c.Log(dir2)

	path := os.Getenv("PATH")
	os.Setenv("PATH", fmt.Sprintf("%s:%s:%s", dir1, dir2, path))

	// Make an executable file called "juju-test" in dir2.
	b.filePath = filepath.Join(dir2, "juju-test")
	err := ioutil.WriteFile(
		b.filePath,
		[]byte("doesn't matter, we don't execute it"),
		0755)
	c.Assert(err, gc.IsNil)

	cwd, err := os.Getwd()
	c.Assert(err, gc.IsNil)

	b.cwd = c.MkDir()
	err = os.Chdir(b.cwd)
	c.Assert(err, gc.IsNil)

	b.restore = func() {
		os.Setenv("PATH", path)
		os.Chdir(cwd)
	}
}

示例#8
文件: main.go 项目: ZCLanner/manhua8_fetcher

func downloadComicBook(bookName, url string) {
	os.Mkdir(bookName, 0755|os.ModeDir)
	os.Chdir(bookName)
	urlArray := getImageUrls(url)
	if urlArray == nil {
		return
	}

	fmt.Printf("Downloading %s\n", bookName)
	channel := make(chan int)
	i := 0
	for i < len(urlArray) && i < 10 {
		imageUrl := urlArray[i]
		i++
		go downloadImage(imageUrl, getImageFilePath(imageUrl), channel)
	}

	successCount := 0
	for successCount < len(urlArray) {
		success := <-channel
		if success == 1 {
			successCount++
			fmt.Printf("%d/%d\r", successCount, len(urlArray))
			if i < len(urlArray) {
				imageUrl := urlArray[i]
				i++
				go downloadImage(imageUrl, getImageFilePath(imageUrl), channel)
			}
		}
	}
	fmt.Printf("Complete downloading %s\n", bookName)
	os.Chdir("..")
}

示例#9
文件: wpress.go 项目: Mechador/wpress-archiver

func compress(src string) {
	archiver, _ := wpress.NewWriter(fmt.Sprintf("%s.wpress", src))

	// Get current working folder
	cwd, _ := os.Getwd()

	// Go to destination folder
	os.Chdir(src)

	// List folder
	folder := ""
	files, _ := ioutil.ReadDir(".")
	for _, f := range files {
		if folder != "" {
			folder = ""
			break
		} else {
			folder = f.Name()
		}
	}

	// Go to nested directory if necessary
	if folder != "" {
		os.Chdir(folder)
	}

	// Add directory recursively
	archiver.AddDirectory(".")
	archiver.Close()

	// Go to previous folder
	os.Chdir(cwd)
}

示例#10
文件: zglob_test.go 项目: moul/advanced-ssh-config

func TestZGlobAbs(t *testing.T) {
	tmpdir := setup(t)
	defer os.RemoveAll(tmpdir)

	curdir, err := os.Getwd()
	if err != nil {
		t.Fatal(err)
	}
	err = os.Chdir(tmpdir)
	if err != nil {
		t.Fatal(err)
	}
	defer os.Chdir(curdir)

	for _, test := range testZGlobs {
		test.pattern = filepath.ToSlash(filepath.Join(tmpdir, test.pattern))
		for i, expected := range test.expected {
			test.expected[i] = filepath.ToSlash(filepath.Join(tmpdir, expected))
		}
		got, err := Glob(test.pattern)
		if err != nil {
			if test.err != err {
				t.Error(err)
			}
			continue
		}
		if !check(test.expected, got) {
			t.Errorf(`zglob failed: pattern %q: expected %v but got %v`, test.pattern, test.expected, got)
		}
	}
}

示例#11
文件: diskio.go 项目: robbassi/tulva

func (diskio *DiskIO) Init() {
	log.Println("DiskIO : Init : Started")
	defer log.Println("DiskIO : Init : Completed")

	if len(diskio.metaInfo.Info.Files) > 0 {
		// Multiple File Mode
		directory := diskio.metaInfo.Info.Name
		// Create the directory if it doesn't exist
		if _, err := os.Stat(directory); os.IsNotExist(err) {
			err = os.Mkdir(directory, os.ModeDir|os.ModePerm)
			checkError(err)
		}
		err := os.Chdir(directory)
		checkError(err)
		for _, file := range diskio.metaInfo.Info.Files {
			// Create any sub-directories if required
			if len(file.Path) > 1 {
				directory = filepath.Join(file.Path[1:]...)
				if _, err := os.Stat(directory); os.IsNotExist(err) {
					err = os.MkdirAll(directory, os.ModeDir|os.ModePerm)
					checkError(err)
				}
			}
			// Create the file if it doesn't exist
			name := filepath.Join(file.Path...)
			diskio.files = append(diskio.files, openOrCreateFile(name))
		}
		err = os.Chdir("..")
		checkError(err)
	} else {
		// Single File Mode
		diskio.files = append(diskio.files, openOrCreateFile(diskio.metaInfo.Info.Name))
	}
}

示例#12
文件: zglob_test.go 项目: moul/advanced-ssh-config

func TestZGlob(t *testing.T) {
	tmpdir := setup(t)
	defer os.RemoveAll(tmpdir)

	curdir, err := os.Getwd()
	if err != nil {
		t.Fatal(err)
	}
	err = os.Chdir(tmpdir)
	if err != nil {
		t.Fatal(err)
	}
	defer os.Chdir(curdir)

	tmpdir = "."
	for _, test := range testZGlobs {
		got, err := Glob(test.pattern)
		if err != nil {
			if test.err != err {
				t.Error(err)
			}
			continue
		}
		if !check(test.expected, got) {
			t.Errorf(`zglob failed: pattern %q: expected %v but got %v`, test.pattern, test.expected, got)
		}
	}
}

示例#13
文件: init_test.go 项目: AssertSelenium/terraform

func TestInit_cwd(t *testing.T) {
	dir := tempDir(t)
	if err := os.MkdirAll(dir, 0755); err != nil {
		t.Fatalf("err: %s", err)
	}

	// Change to the temporary directory
	cwd, err := os.Getwd()
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	if err := os.Chdir(dir); err != nil {
		t.Fatalf("err: %s", err)
	}
	defer os.Chdir(cwd)

	ui := new(cli.MockUi)
	c := &InitCommand{
		Meta: Meta{
			ContextOpts: testCtxConfig(testProvider()),
			Ui:          ui,
		},
	}

	args := []string{
		testFixturePath("init"),
	}
	if code := c.Run(args); code != 0 {
		t.Fatalf("bad: \n%s", ui.ErrorWriter.String())
	}

	if _, err := os.Stat("hello.tf"); err != nil {
		t.Fatalf("err: %s", err)
	}
}

示例#14
文件: plan_test.go 项目: JasonGiedymin/terraform

func TestPlan_stateDefault(t *testing.T) {
	originalState := &terraform.State{
		Resources: map[string]*terraform.ResourceState{
			"test_instance.foo": &terraform.ResourceState{
				ID:   "bar",
				Type: "test_instance",
			},
		},
	}

	// Write the state file in a temporary directory with the
	// default filename.
	td, err := ioutil.TempDir("", "tf")
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	statePath := filepath.Join(td, DefaultStateFilename)

	f, err := os.Create(statePath)
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	err = terraform.WriteState(originalState, f)
	f.Close()
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	// Change to that directory
	cwd, err := os.Getwd()
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	if err := os.Chdir(filepath.Dir(statePath)); err != nil {
		t.Fatalf("err: %s", err)
	}
	defer os.Chdir(cwd)

	p := testProvider()
	ui := new(cli.MockUi)
	c := &PlanCommand{
		Meta: Meta{
			ContextOpts: testCtxConfig(p),
			Ui:          ui,
		},
	}

	args := []string{
		testFixturePath("plan"),
	}
	if code := c.Run(args); code != 0 {
		t.Fatalf("bad: %d\n\n%s", code, ui.ErrorWriter.String())
	}

	// Verify that the provider was called with the existing state
	expectedState := originalState.Resources["test_instance.foo"]
	if !reflect.DeepEqual(p.DiffState, expectedState) {
		t.Fatalf("bad: %#v", p.DiffState)
	}
}

示例#15
文件: main.go 项目: nicolas-brousse/rack

func extractTarball(r io.Reader, base string) error {
	cwd, err := os.Getwd()

	if err != nil {
		return err
	}

	defer os.Chdir(cwd)

	err = os.MkdirAll(base, 0755)

	if err != nil {
		return err
	}

	err = os.Chdir(base)

	if err != nil {
		return err
	}

	cmd := exec.Command("tar", "xz")
	cmd.Stdin = r
	err = cmd.Run()

	if err != nil {
		return err
	}

	return nil
}

示例#16
文件: hls.go 项目: youxidev/HLSWebServer

func (this *hlsFile) write(data []byte) {
	if this.fileHandler == nil {
		this.fileName = this.generateFileName()
		var err error
		wd, _ := os.Getwd()
		os.Chdir("../../")
		this.fileHandler, err = os.OpenFile(this.fileName, os.O_CREATE|os.O_RDWR, 0777)
		os.Chdir(wd)
		if err != nil {
			fmt.Println("write", err)
			return
		}
	}
	if this.begTime == 0 {
		this.begTime = uint32(time.Now().UnixNano() / 1000 / 1000 / 1000)
	}
	now := uint32(time.Now().UnixNano() / 1000 / 1000 / 1000)

	this.fileHandler.Write(data)
	this.fileSize += uint32(len(data))
	now -= this.begTime
	if now >= TSFILEMAX_DURATION {
		this.fileHandler.Close()
		this.fileHandler = nil
		this.begTime = 0
		this.m3u8.Update(m3u8Tag{duration: now, url: this.fileName})
	}
}

示例#17
文件: utils.go 项目: giorgil/caddy-hugo

// Run is used to run the static website generator
func Run(c *config.Config) {
	cwd, err := os.Getwd()

	if err != nil {
		log.Print("Can't get working directory.")
	}

	err = os.Chdir(c.Path)

	if err != nil {
		log.Print("Can't get working directory.")
	}

	viper.Reset()
	commands.HugoCmd.ParseFlags(c.Args)
	err = commands.HugoCmd.RunE(nil, nil)

	if err != nil {
		log.Print(err)
	}

	err = os.Chdir(cwd)

	if err != nil {
		log.Print("Can't get working directory.")
	}
}

示例#18
文件: buildpack.go 项目: naaman/bp

func (b *Buildpack) Run(appdir string) error {
	b.env = newBuildEnv(appdir)

	wd, _ := os.Getwd()
	os.Chdir(b.env.buildDir)

	detectCmd := exec.Command(b.detect, b.env.buildDir)
	if err := execCmd(detectCmd, os.Stdout, os.Stderr); err != nil {
		return nil
	}

	compileCmd := exec.Command(b.compile, b.env.buildDir, b.env.cacheDir, b.env.envFile)
	if err := execCmd(compileCmd, os.Stdout, os.Stderr); err != nil {
		return err
	}

	releaseCmd := exec.Command(b.release, b.env.buildDir)
	releaseOut := new(bytes.Buffer)
	if err := execCmd(releaseCmd, releaseOut, os.Stderr); err != nil {
		return err
	}
	writeProcfile(b.env, releaseOut.Bytes())

	os.Chdir(wd)

	return nil
}

示例#19
文件: chroot-child.go 项目: dgonyeo/acbuild

func runChroot(cmd *cobra.Command, args []string) {
	runtime.LockOSThread()
	err := syscall.Chroot(flagChroot)
	if err != nil {
		errAndExit("couldn't chroot: %v", err)
	}
	err = os.Chdir("/")
	if err != nil {
		errAndExit("couldn't cd: %v", err)
	}

	if flagWorkingDir != "" {
		err = os.Chdir(flagWorkingDir)
		if err != nil {
			errAndExit("couldn't cd: %v", err)
		}
	}

	execCmd := exec.Command(flagCmd, flagArgs...)
	execCmd.Env = flagEnv
	execCmd.Stdin = os.Stdin
	execCmd.Stdout = os.Stdout
	execCmd.Stderr = os.Stderr
	err = execCmd.Run()
	if err != nil {
		if exitErr, ok := err.(*exec.ExitError); ok {
			code := exitErr.Sys().(syscall.WaitStatus).ExitStatus()
			os.Exit(code)
		}
		errAndExit("%v", err)
	}
}

示例#20
文件: docker_cli_cp_test.go 项目: fwalker/dashboard

func (s *DockerSuite) TestCpToDot(c *check.C) {
	out, exitCode := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "echo lololol > /test")
	if exitCode != 0 {
		c.Fatal("failed to create a container", out)
	}

	cleanedContainerID := strings.TrimSpace(out)

	out, _ = dockerCmd(c, "wait", cleanedContainerID)
	if strings.TrimSpace(out) != "0" {
		c.Fatal("failed to set up container", out)
	}

	tmpdir, err := ioutil.TempDir("", "docker-integration")
	if err != nil {
		c.Fatal(err)
	}
	defer os.RemoveAll(tmpdir)
	cwd, err := os.Getwd()
	if err != nil {
		c.Fatal(err)
	}
	defer os.Chdir(cwd)
	if err := os.Chdir(tmpdir); err != nil {
		c.Fatal(err)
	}
	_, _ = dockerCmd(c, "cp", cleanedContainerID+":/test", ".")
	content, err := ioutil.ReadFile("./test")
	if string(content) != "lololol\n" {
		c.Fatalf("Wrong content in copied file %q, should be %q", content, "lololol\n")
	}
}

示例#21
文件: graph_test.go 项目: hooklift/terraform

func TestGraph_noArgs(t *testing.T) {
	cwd, err := os.Getwd()
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	if err := os.Chdir(testFixturePath("graph")); err != nil {
		t.Fatalf("err: %s", err)
	}
	defer os.Chdir(cwd)

	ui := new(cli.MockUi)
	c := &GraphCommand{
		Meta: Meta{
			ContextOpts: testCtxConfig(testProvider()),
			Ui:          ui,
		},
	}

	args := []string{}
	if code := c.Run(args); code != 0 {
		t.Fatalf("bad: \n%s", ui.ErrorWriter.String())
	}

	output := ui.OutputWriter.String()
	if !strings.Contains(output, "provider.test") {
		t.Fatalf("doesn't look like digraph: %s", output)
	}
}

示例#22
文件: helper_test.go 项目: samuelyao314/mygo

func goTests(output string) error {
	// Change directory to artifact directory root
	if err := os.Chdir(output); err != nil {
		return err
	}

	defer func() {
		// Back to src directory
		if err := os.Chdir(".."); err != nil {
			// Should not reach here
			panic(err)
		}
	}()

	funcs := []func(output string) error{
		goGet,
		goBuild,
		goTest,
		goVet,
	}

	for _, gf := range funcs {
		err := gf(output)
		if err != nil {
			return err
		}
	}

	return nil
}

示例#23
文件: path_test.go 项目: WXB506/golang

func TestAbs(t *testing.T) {
	oldwd, err := os.Getwd()
	if err != nil {
		t.Fatal("Getwd failed: " + err.String())
	}
	defer os.Chdir(oldwd)
	goroot := os.Getenv("GOROOT")
	cwd := filepath.Join(goroot, "src")
	os.Chdir(cwd)
	for _, path := range abstests {
		path = strings.Replace(path, "$GOROOT", goroot, -1)
		abspath, err := filepath.Abs(path)
		if err != nil {
			t.Errorf("Abs(%q) error: %v", path, err)
		}
		info, err := os.Stat(path)
		if err != nil {
			t.Errorf("%s: %s", path, err)
		}
		absinfo, err := os.Stat(abspath)
		if err != nil || absinfo.Ino != info.Ino {
			t.Errorf("Abs(%q)=%q, not the same file", path, abspath)
		}
		if !filepath.IsAbs(abspath) {
			t.Errorf("Abs(%q)=%q, not an absolute path", path, abspath)
		}
		if filepath.IsAbs(path) && abspath != filepath.Clean(path) {
			t.Errorf("Abs(%q)=%q, isn't clean", path, abspath)
		}
	}
}

示例#24
文件: at.go 项目: henrylee2cn/godocdown

func At(there string, fn func() error) (err []error) {
	origin, err_ := os.Getwd()
	if err_ != nil {
		origin = ""
		return []error{err_, nil}
	}
	err_ = os.Chdir(there)
	if err_ != nil {
		origin = ""
		return []error{err_, nil}
	}
	defer func() {
		if origin != "" {
			err_ = os.Chdir(origin)
			if err != nil {
				err[0] = err_
			} else {
				err = []error{err_, nil}
			}
		}
	}()
	err_ = fn()
	if err_ != nil {
		return []error{nil, err_}
	}
	return nil
}

示例#25
文件: output_test.go 项目: AssertSelenium/terraform

func TestOutput_stateDefault(t *testing.T) {
	originalState := &terraform.State{
		Modules: []*terraform.ModuleState{
			&terraform.ModuleState{
				Path: []string{"root"},
				Outputs: map[string]string{
					"foo": "bar",
				},
			},
		},
	}

	// Write the state file in a temporary directory with the
	// default filename.
	td, err := ioutil.TempDir("", "tf")
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	statePath := filepath.Join(td, DefaultStateFilename)

	f, err := os.Create(statePath)
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	err = terraform.WriteState(originalState, f)
	f.Close()
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	// Change to that directory
	cwd, err := os.Getwd()
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	if err := os.Chdir(filepath.Dir(statePath)); err != nil {
		t.Fatalf("err: %s", err)
	}
	defer os.Chdir(cwd)

	ui := new(cli.MockUi)
	c := &OutputCommand{
		Meta: Meta{
			ContextOpts: testCtxConfig(testProvider()),
			Ui:          ui,
		},
	}

	args := []string{
		"foo",
	}
	if code := c.Run(args); code != 0 {
		t.Fatalf("bad: \n%s", ui.ErrorWriter.String())
	}

	actual := strings.TrimSpace(ui.OutputWriter.String())
	if actual != "bar" {
		t.Fatalf("bad: %#v", actual)
	}
}

示例#26
文件: fileio.go 项目: freedomfita/src

// load the packets for a file
func (f *FileHeader) LoadPackets() {
	curDir, _ := os.Getwd()
	// calculate number of packets
	numPackets := int(f.Info.FileSize) / gPacketSize

	f.Packets = make(map[ID]Packet, numPackets+1)
	// open the directory containing the packet files
	dir, err := os.Open(gShareDirectory + "/" + f.PacketDir)
	if err != nil {
		log.Fatal("Open: ", err)
	}
	packet_files, err := dir.Readdir(0)
	if err != nil {
		log.Fatal("Readdir: ", err)
	}
	os.Chdir(f.PacketDir)
	// fill each packet with the appropriate data
	for i := 0; i < len(packet_files); i++ {
		fi := packet_files[i]

		var p Packet
		// read the file into a byte array
		fbytes, err := ioutil.ReadFile(fi.Name())
		if err != nil {
			log.Fatal("ReadFile: ", err)
		}

		copy(p.Data, fbytes)
		p.PacketID = p.sha1hash()
		p.PacketSize = len(fbytes)
		f.Packets[p.PacketID] = p
	}
	os.Chdir(curDir)
	return
}

示例#27
文件: path_test.go 项目: albrow/glide

func TestVendor(t *testing.T) {
	td, err := filepath.Abs(testdata)
	if err != nil {
		t.Fatal(err)
	}
	wd, _ := os.Getwd()

	os.Chdir(filepath.Join(td, "a/b/c"))
	res, err := Vendor()
	if err != nil {
		t.Errorf("Failed to resolve vendor directory: %s", err)
	}
	expect := filepath.Join(td, "a", "vendor")
	if res != expect {
		t.Errorf("Failed to find vendor: expected %s got %s", expect, res)
	}

	os.Chdir(filepath.Join(td, "x/y/z"))
	res, err = Vendor()
	if err != nil {
		t.Errorf("Failed to resolve vendor directory: %s", err)
	}
	expect = filepath.Join(td, "x", "symlinked_vendor")
	if res != expect {
		t.Errorf("Failed to find vendor: expected %s got %s", expect, res)
	}

	os.Chdir(wd)
}

示例#28
文件: e2e.go 项目: titilambert/kubernetes

func UpgradeTest(args string) bool {
	old, err := os.Getwd()
	if err != nil {
		log.Printf("Failed to os.Getwd(): %v", err)
		return false
	}
	defer os.Chdir(old)
	err = os.Chdir("../kubernetes_skew")
	if err != nil {
		log.Printf("Failed to cd ../kubernetes_skew: %v", err)
		return false
	}
	previous, present := os.LookupEnv("E2E_REPORT_PREFIX")
	if present {
		defer os.Setenv("E2E_REPORT_PREFIX", previous)
	} else {
		defer os.Unsetenv("E2E_REPORT_PREFIX")
	}
	os.Setenv("E2E_REPORT_PREFIX", "upgrade")
	return finishRunning("Upgrade Ginkgo tests",
		exec.Command(
			"go", "run", "./hack/e2e.go",
			"--test",
			"--test_args="+args,
			fmt.Sprintf("--v=%t", *verbose),
			fmt.Sprintf("--check_version_skew=%t", *checkVersionSkew)))
}

示例#29
文件: gitdeploy.go 项目: EconomistWhichMBA/go.gitdeploy

func doRelease(commit string) error {
	if err := os.Chdir("working"); err != nil {
		errors.New("Failed to chdir to working\n")
		return err
	}
	// Deploy.
	out, err := exec.Command("git", "pull", "origin", branch).Output()
	if err != nil {
		log("Failed to update working copy.")
		return err
	}
	log(string(out))

	if err := os.Chdir("../"); err != nil {
		log("Failed to chdir to working\n")
		return err
	}

	t := time.Now()
	releasedir := "releases/" + fmt.Sprintf("%d-%02d-%02d.%02d%02d%02d.%s", t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), commit)
	log("Release to: " + releasedir + "\n")

	err = CopyDir("working", releasedir)
	if err != nil {
		return err
	}

	os.Remove("current")
	err = os.Symlink(releasedir, "current")
	if err != nil {
		return err
	}

	return nil
}

示例#30
文件: tar_test.go 项目: liyangdal/kurma

func makeTestDir(t *testing.T) string {
	cwd, err := os.Getwd()
	TestExpectSuccess(t, err)
	AddTestFinalizer(func() {
		TestExpectSuccess(t, os.Chdir(cwd))
	})
	dir := TempDir(t)
	TestExpectSuccess(t, os.Chdir(dir))
	mode := os.FileMode(0755)
	os.Mkdir(cwd, mode) //Don't care about return value.  For some reason CWD is not created by go test on all systems.
	TestExpectSuccess(t, os.Mkdir("a", mode))
	TestExpectSuccess(t, os.Mkdir("a/b", mode))
	TestExpectSuccess(t, os.Mkdir("a/b/c", mode))
	TestExpectSuccess(t, os.Mkdir("a/b/c/d", mode))
	TestExpectSuccess(t, os.Mkdir("a/b/i", mode))
	TestExpectSuccess(t, os.Mkdir("a/b/i/j", mode))
	TestExpectSuccess(t, ioutil.WriteFile("a/b/c/d/e", []byte{}, mode))
	TestExpectSuccess(t, ioutil.WriteFile("a/b/c/f", []byte{}, mode))
	TestExpectSuccess(t, ioutil.WriteFile("a/b/g", []byte{}, mode))
	TestExpectSuccess(t, ioutil.WriteFile("a/b/i/j/k", []byte{}, mode))
	TestExpectSuccess(t, os.Symlink("/bin/bash", "a/b/bash"))
	TestExpectSuccess(t, os.Symlink("../i", "a/b/c/l"))
	TestExpectSuccess(t, os.Symlink("g", "a/b/h"))
	TestExpectSuccess(t, os.Symlink("k", "a/b/i/j/l"))
	TestExpectSuccess(t, os.Symlink("../../g", "a/b/i/j/m"))
	return dir
}

展开阅读全文