当前位置: 首页>>代码示例>>Golang>>正文


Golang os.Chdir函数代码示例

本文整理汇总了Golang中os.Chdir函数的典型用法代码示例。如果您正苦于以下问题:Golang Chdir函数的具体用法?Golang Chdir怎么用?Golang Chdir使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了Chdir函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: pullRepo

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
}
开发者ID:jumanjiman,项目名称:eris-cli,代码行数:27,代码来源:writers.go

示例2: camputMany

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
}
开发者ID:stunti,项目名称:camlistore,代码行数:25,代码来源:bot.go

示例3: TestFmt_workingDirectory

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)
	}
}
开发者ID:RezaDKhan,项目名称:terraform,代码行数:35,代码来源:fmt_test.go

示例4: TestShow_noArgsNoState

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())
	}
}
开发者ID:devendraPSL,项目名称:terraform-api,代码行数:31,代码来源:show_test.go

示例5: TestNexPlusYacc

// 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))
	}
}
开发者ID:infogulch,项目名称:nex,代码行数:34,代码来源:nex_test.go

示例6: TestAbs

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)
		}
	}
}
开发者ID:TomHoenderdos,项目名称:go-sunos,代码行数:60,代码来源:path_test.go

示例7: SetUpTest

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)
	}
}
开发者ID:jkary,项目名称:core,代码行数:32,代码来源:build_test.go

示例8: downloadComicBook

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("..")
}
开发者ID:ZCLanner,项目名称:manhua8_fetcher,代码行数:33,代码来源:main.go

示例9: compress

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)
}
开发者ID:Mechador,项目名称:wpress-archiver,代码行数:33,代码来源:wpress.go

示例10: TestZGlobAbs

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)
		}
	}
}
开发者ID:moul,项目名称:advanced-ssh-config,代码行数:31,代码来源:zglob_test.go

示例11: Init

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))
	}
}
开发者ID:robbassi,项目名称:tulva,代码行数:34,代码来源:diskio.go

示例12: TestZGlob

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)
		}
	}
}
开发者ID:moul,项目名称:advanced-ssh-config,代码行数:28,代码来源:zglob_test.go

示例13: TestInit_cwd

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)
	}
}
开发者ID:AssertSelenium,项目名称:terraform,代码行数:35,代码来源:init_test.go

示例14: TestPlan_stateDefault

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)
	}
}
开发者ID:JasonGiedymin,项目名称:terraform,代码行数:60,代码来源:plan_test.go

示例15: extractTarball

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
}
开发者ID:nicolas-brousse,项目名称:rack,代码行数:31,代码来源:main.go


注:本文中的os.Chdir函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。