Exemplo n.º 1
3
func UnixAudienceListener(sockaddr string) {
	fi, err := os.Stat(sockaddr)
	if err == nil {
		fmode := fi.Mode()
		if fmode&os.ModeType == os.ModeSocket {
			o.Warn("Removing stale socket at %s", sockaddr)
			os.Remove(sockaddr)
		} else {
			o.Fail("%s exists and is not a socket", sockaddr)
		}
	}
	laddr, err := net.ResolveUnixAddr("unix", sockaddr)
	o.MightFail(err, "Couldn't resolve audience socket address")
	l, err := net.ListenUnix("unix", laddr)
	o.MightFail(err, "Couldn't start audience unixsock listener")
	// Fudge the permissions on the unixsock!
	fi, err = os.Stat(sockaddr)
	if err == nil {
		os.Chmod(sockaddr, fi.Mode()|0777)
	} else {
		o.Warn("Couldn't fudge permission on audience socket: %s", err)
	}

	// make sure we clean up the unix socket when we die.
	defer l.Close()
	defer os.Remove(sockaddr)
	AudienceListener(l)
}
Exemplo n.º 2
1
func TestSetUpAndTearDown(t *testing.T) {
	tempDir, err := ioutil.TempDir("", "CreateVolumes")
	if err != nil {
		t.Errorf("Unexpected error: %v", err)
	}
	defer os.RemoveAll(tempDir)
	fakeID := "my-id"
	type VolumeTester interface {
		Builder
		Cleaner
	}
	volumes := []VolumeTester{
		&EmptyDir{"empty", fakeID, tempDir},
		&GCEPersistentDisk{"pd", fakeID, tempDir, "pd-disk", "ext4", "", false, &MockDiskUtil{}, &MockMounter{}},
	}

	for _, vol := range volumes {
		err = vol.SetUp()
		path := vol.GetPath()
		if err != nil {
			t.Errorf("Unexpected error: %v", err)
		}
		if _, err := os.Stat(path); os.IsNotExist(err) {
			t.Errorf("SetUp() failed, volume path not created: %v", path)
		}
		err = vol.TearDown()
		if err != nil {
			t.Errorf("Unexpected error: %v", err)
		}
		if _, err := os.Stat(path); !os.IsNotExist(err) {
			t.Errorf("TearDown() failed, original volume path not properly removed: %v", path)
		}
	}
}
Exemplo n.º 3
1
func backupFiles(versionID string, wg *sync.WaitGroup) {
	defer wg.Done()

	if _, err := os.Stat(backupDir); err != nil {
		if os.IsNotExist(err) {
			makeBackupDir()
		}
	}

	if debug {
		fmt.Printf("backupFiles - %s\n", versionID)
	}
	log.Printf("backupFiles - %s\n", versionID)

	fileName := fmt.Sprintf("%s%s%s_backup", backupDir, string(os.PathSeparator), versionID)
	worldDir := fmt.Sprintf("%s", worldDir)

	if _, err := os.Stat(backupDir); err != nil {
		if os.IsNotExist(err) {
			if debug {
				fmt.Println("Nothing to backup right now.")
			}
			log.Println("Nothing to backup right now.")
		} else {
			zip := new(archivex.ZipFile)
			zip.Create(fileName)
			fmt.Printf("worldDir - %s\n", worldDir)
			fmt.Printf("fileName - %s\n", fileName)
			zip.AddAll(worldDir, true)
			fmt.Printf("after addall\n")
			zip.Close()
		}
	}
}
Exemplo n.º 4
1
func TestTempDirCreate(t *testing.T) {
	if err := InitDir(); err != nil {
		t.Fatalf("Error during creating the temp directory: %s\n", err.Error())
	}
	if _, err := os.Stat(aufsTempDir); err != nil {
		if os.IsNotExist(err) {
			t.Fatalf("Temp dir create failed")
		} else {
			t.Fatalf("Temp dir create failed, %s", err.Error())
		}
	}

	if err := InitFile(); err != nil {
		t.Fatalf("Error during creating the test file: %s\n", err.Error())
	}
	if _, err := os.Stat(testFile3); err != nil {
		if os.IsNotExist(err) {
			t.Fatalf("Temp dir create failed")
		} else {
			t.Fatalf("Temp dir create failed, %s", err.Error())
		}
	}

	if err := Cleanup(); err != nil {
		t.Fatalf("Error during removing files and dirs: %s\n", err.Error())
	}

}
Exemplo n.º 5
1
func certKeyXor(certFile, keyFile string) (bool, []error) {
	certInfo, err := os.Stat(certFile)
	certExists := !os.IsNotExist(err)
	certIsFile := certExists && certInfo.Mode().IsRegular()

	keyInfo, err := os.Stat(keyFile)
	keyExists := !os.IsNotExist(err)
	keyIsFile := keyExists && keyInfo.Mode().IsRegular()

	errors := make([]error, 0)
	if certExists && certIsFile && keyExists && keyIsFile {
		return true, errors
	}
	if !certExists && !keyExists {
		return false, errors
	}
	if !certExists {
		errors = append(errors, fmt.Errorf("Cert %s does not exist", certFile))
	} else if !certIsFile {
		errors = append(errors, fmt.Errorf("Cert %s is not a file", certFile))
	}
	if !keyExists {
		errors = append(errors, fmt.Errorf("Key %s does not exist", keyFile))
	} else if !keyIsFile {
		errors = append(errors, fmt.Errorf("Key %s is not a file", keyFile))
	}
	return false, errors
}
Exemplo n.º 6
0
Arquivo: main.go Projeto: eswdd/bosun
func exePath() (string, error) {
	prog := os.Args[0]
	p, err := filepath.Abs(prog)
	if err != nil {
		return "", err
	}
	fi, err := os.Stat(p)
	if err == nil {
		if !fi.Mode().IsDir() {
			return p, nil
		}
		err = fmt.Errorf("%s is directory", p)
	}
	if filepath.Ext(p) == "" {
		p += ".exe"
		fi, err := os.Stat(p)
		if err == nil {
			if !fi.Mode().IsDir() {
				return p, nil
			}
			err = fmt.Errorf("%s is directory", p)
		}
	}
	return "", err
}
Exemplo n.º 7
0
func copyFile(src, folder, name string) error {
	if _, err := os.Stat(src); os.IsNotExist(err) {
		return nil
	}

	dst := path.Join(folder, name)
	if _, err := os.Stat(dst); err == nil {
		return nil
	}

	if err := createDirs(folder); err != nil {
		return err
	}

	srcFile, err := os.Open(src)
	if err != nil {
		return err
	}
	defer srcFile.Close()

	dstFile, err := os.Create(dst)
	if err != nil {
		return err
	}
	defer dstFile.Close()

	_, err = io.Copy(dstFile, srcFile)
	return err
}
Exemplo n.º 8
0
func updateGitFolder(path string) {
	fmt.Println()
	fmt.Println("Path: " + path)
	if _, err := os.Stat(path); os.IsNotExist(err) {
		fmt.Println("Not exists! Ignored")
		return
	}
	if err := os.Chdir(path); err != nil {
		fmt.Println("Access denied")
		return
	}
	if _, err := os.Stat(".git"); os.IsNotExist(err) {
		fmt.Println("Not a GIT folder! Ignored")
		return
	}
	fmt.Println("Revert all changes...")
	runCommand(exec.Command("git", "reset", "--hard", "HEAD"))
	fmt.Println("Pulling...")
	runCommand(exec.Command("git", "pull"))

	if _, err := os.Stat("deploy.sh"); err == nil {
		fmt.Println("Running external deploy.sh script...")
		runCommand(exec.Command("./deploy.sh"))
	}

	if _, err := os.Stat("build.sh"); err == nil {
		fmt.Println("Running external build.sh script...")
		runCommand(exec.Command("./build.sh"))
	}

	fmt.Println("Done")
}
Exemplo n.º 9
0
func (d *Fusion5Driver) Verify() error {
	if _, err := os.Stat(d.AppPath); err != nil {
		if os.IsNotExist(err) {
			return fmt.Errorf("Fusion application not found at path: %s", d.AppPath)
		}

		return err
	}

	if _, err := os.Stat(d.vmrunPath()); err != nil {
		if os.IsNotExist(err) {
			return fmt.Errorf(
				"Critical application 'vmrun' not found at path: %s", d.vmrunPath())
		}

		return err
	}

	if _, err := os.Stat(d.vdiskManagerPath()); err != nil {
		if os.IsNotExist(err) {
			return fmt.Errorf(
				"Critical application vdisk manager not found at path: %s",
				d.vdiskManagerPath())
		}

		return err
	}

	return nil
}
Exemplo n.º 10
0
// Test that given a set of tasks, each task gets a directory and that directory
// has the shared alloc dir inside of it.
func TestAllocDir_BuildAlloc(t *testing.T) {
	tmp, err := ioutil.TempDir("", "AllocDir")
	if err != nil {
		t.Fatalf("Couldn't create temp dir: %v", err)
	}
	defer os.RemoveAll(tmp)

	d := NewAllocDir(tmp)
	defer d.Destroy()
	tasks := []*structs.Task{t1, t2}
	if err := d.Build(tasks); err != nil {
		t.Fatalf("Build(%v) failed: %v", tasks, err)
	}

	// Check that the AllocDir and each of the task directories exist.
	if _, err := os.Stat(d.AllocDir); os.IsNotExist(err) {
		t.Fatalf("Build(%v) didn't create AllocDir %v", tasks, d.AllocDir)
	}

	for _, task := range tasks {
		tDir, ok := d.TaskDirs[task.Name]
		if !ok {
			t.Fatalf("Task directory not found for %v", task.Name)
		}

		if _, err := os.Stat(tDir); os.IsNotExist(err) {
			t.Fatalf("Build(%v) didn't create TaskDir %v", tasks, tDir)
		}
	}
}
Exemplo n.º 11
0
func TestIndexOpen(t *testing.T) {
	repo := createTestRepo(t)
	defer cleanupTestRepo(t, repo)

	path := repo.Workdir() + "/heyindex"

	_, err := os.Stat(path)
	if !os.IsNotExist(err) {
		t.Fatal("new index file already exists")
	}

	idx, err := OpenIndex(path)
	checkFatal(t, err)

	if path != idx.Path() {
		t.Fatalf("mismatched index paths, expected %v, got %v", path, idx.Path())
	}

	err = idx.Write()
	checkFatal(t, err)

	_, err = os.Stat(path)
	if os.IsNotExist(err) {
		t.Fatal("new index file did not get written")
	}
}
Exemplo n.º 12
0
func TestCommandLine(t *testing.T) {
	testDir, err := ioutil.TempDir("", "kbbin")
	defer os.RemoveAll(testDir)
	if err != nil {
		t.Fatalf("%s", err)
	}

	binPath, err := filepath.Abs(os.Args[0])
	if err != nil {
		t.Fatalf("%s", err)
	}
	linkPath := filepath.Join(testDir, "kbtest")

	// Install
	err = installCommandLineForBinPath(binPath, linkPath, true)
	if err != nil {
		t.Fatalf("%s", err)
	}
	_, err = os.Stat(linkPath)
	if err != nil {
		t.Fatalf("%s", err)
	}

	// Install again
	err = installCommandLineForBinPath(binPath, linkPath, true)
	if err != nil {
		t.Fatalf("%s", err)
	}
	_, err = os.Stat(linkPath)
	if err != nil {
		t.Fatalf("%s", err)
	}
}
Exemplo n.º 13
0
func tryConfigFilePath(configFilePath string) (string, error) {
	if configFilePath != "" {
		configFilePath, _ = filepath.Abs(configFilePath)
		if _, err := os.Stat(configFilePath); err == nil {
			log.Println("found log file at " + configFilePath)
			return configFilePath, nil
		} else {
			return "", err
		}
	} else {
		posibleConfigFiles := []string{}
		if p, e := os.Getwd(); e == nil {
			// loop for lighthouse.json from current working directory
			posibleConfigFiles = append(posibleConfigFiles, p+"/lighthouse.json")
		}
		if u, e := user.Current(); e == nil {
			// loop for lighthouse.json from current user's home directory
			posibleConfigFiles = append(posibleConfigFiles, u.HomeDir+"/lighthouse.json")
		}
		for _, path := range posibleConfigFiles {
			if _, err := os.Stat(path); err == nil {
				log.Println("found configuration file at " + path)
				return path, nil
			}
		}
		log.Println("no configuration file found. use defalut config.")
		// not valid config file found
		return "", nil
	}
}
Exemplo n.º 14
0
func TestAgent_PurgeCheck(t *testing.T) {
	config := nextConfig()
	dir, agent := makeAgent(t, config)
	defer os.RemoveAll(dir)
	defer agent.Shutdown()

	check := &structs.HealthCheck{
		Node:    config.NodeName,
		CheckID: "mem",
		Name:    "memory check",
		Status:  structs.HealthPassing,
	}

	file := filepath.Join(agent.config.DataDir, checksDir, stringHash(check.CheckID))
	if err := agent.AddCheck(check, nil, true, ""); err != nil {
		t.Fatalf("err: %v", err)
	}

	// Not removed
	if err := agent.RemoveCheck(check.CheckID, false); err != nil {
		t.Fatalf("err: %s", err)
	}
	if _, err := os.Stat(file); err != nil {
		t.Fatalf("err: %s", err)
	}

	// Removed
	if err := agent.RemoveCheck(check.CheckID, true); err != nil {
		t.Fatalf("err: %s", err)
	}
	if _, err := os.Stat(file); !os.IsNotExist(err) {
		t.Fatalf("bad: %#v", err)
	}
}
Exemplo n.º 15
0
func TestAgent_PurgeService(t *testing.T) {
	config := nextConfig()
	dir, agent := makeAgent(t, config)
	defer os.RemoveAll(dir)
	defer agent.Shutdown()

	svc := &structs.NodeService{
		ID:      "redis",
		Service: "redis",
		Tags:    []string{"foo"},
		Port:    8000,
	}

	file := filepath.Join(agent.config.DataDir, servicesDir, stringHash(svc.ID))
	if err := agent.AddService(svc, nil, true, ""); err != nil {
		t.Fatalf("err: %v", err)
	}

	// Not removed
	if err := agent.RemoveService(svc.ID, false); err != nil {
		t.Fatalf("err: %s", err)
	}
	if _, err := os.Stat(file); err != nil {
		t.Fatalf("err: %s", err)
	}

	// Removed
	if err := agent.RemoveService(svc.ID, true); err != nil {
		t.Fatalf("err: %s", err)
	}
	if _, err := os.Stat(file); !os.IsNotExist(err) {
		t.Fatalf("bad: %#v", err)
	}
}
Exemplo n.º 16
0
func TestAgent_loadChecks_checkFails(t *testing.T) {
	config := nextConfig()
	dir, agent := makeAgent(t, config)
	defer os.RemoveAll(dir)
	defer agent.Shutdown()

	// Persist a health check with an invalid service ID
	check := &structs.HealthCheck{
		Node:      config.NodeName,
		CheckID:   "service:redis",
		Name:      "redischeck",
		Status:    structs.HealthPassing,
		ServiceID: "nope",
	}
	if err := agent.persistCheck(check, nil); err != nil {
		t.Fatalf("err: %s", err)
	}

	// Check to make sure the check was persisted
	checkHash := stringHash(check.CheckID)
	checkPath := filepath.Join(config.DataDir, checksDir, checkHash)
	if _, err := os.Stat(checkPath); err != nil {
		t.Fatalf("err: %s", err)
	}

	// Try loading the checks from the persisted files
	if err := agent.loadChecks(config); err != nil {
		t.Fatalf("err: %s", err)
	}

	// Ensure the erroneous check was purged
	if _, err := os.Stat(checkPath); err == nil {
		t.Fatalf("should have purged check")
	}
}
Exemplo n.º 17
0
func (s *preallocSuite) TestPreallocFilesWriteErrors(c *gc.C) {
	dir := c.MkDir()
	prefix := filepath.Join(dir, "test.")
	err := ioutil.WriteFile(prefix+"0", nil, 0644)
	c.Assert(err, gc.IsNil)
	err = ioutil.WriteFile(prefix+"1", nil, 0644)
	c.Assert(err, gc.IsNil)

	var called int
	s.PatchValue(mongo.PreallocFile, func(filename string, size int) (bool, error) {
		var created bool
		var err error
		called++
		if called == 2 {
			created = true
			err = fmt.Errorf("failed to zero test.1")
		}
		return created, err
	})

	err = mongo.PreallocFiles(prefix, 4096, 8192)
	c.Assert(err, gc.ErrorMatches, "failed to zero test.1")

	// test.0 still exists because we said we didn't
	// create it (i.e. it already existed)
	_, err = os.Stat(prefix + "0")
	c.Assert(err, gc.IsNil)

	// test.1 no longer exists because we said we created
	// it, but then failed to write to it.
	_, err = os.Stat(prefix + "1")
	c.Assert(err, jc.Satisfies, os.IsNotExist)
}
Exemplo n.º 18
0
func TestIsSameFile(t *testing.T) {
	absPath, err := filepath.Abs("../tests/files/")

	assert.NotNil(t, absPath)
	assert.Nil(t, err)

	fileInfo1, err := os.Stat(absPath + "/logs/test.log")
	fileInfo2, err := os.Stat(absPath + "/logs/system.log")

	assert.Nil(t, err)
	assert.NotNil(t, fileInfo1)
	assert.NotNil(t, fileInfo2)

	file1 := &File{
		FileInfo: fileInfo1,
	}

	file2 := &File{
		FileInfo: fileInfo2,
	}

	file3 := &File{
		FileInfo: fileInfo2,
	}

	assert.False(t, file1.IsSameFile(file2))
	assert.False(t, file2.IsSameFile(file1))

	assert.True(t, file1.IsSameFile(file1))
	assert.True(t, file2.IsSameFile(file2))

	assert.True(t, file3.IsSameFile(file2))
	assert.True(t, file2.IsSameFile(file3))
}
Exemplo n.º 19
0
// Test -init -plaintextnames
func TestInitPlaintextNames(t *testing.T) {
	dir := tmpDir + "TestInitPlaintextNames/"
	err := os.Mkdir(dir, 0777)
	if err != nil {
		t.Fatal(err)
	}
	cmd := exec.Command(gocryptfsBinary, "-init", "-extpass", "echo test",
		"-scryptn=10", "-plaintextnames", dir)
	if testing.Verbose() {
		cmd.Stdout = os.Stdout
		cmd.Stderr = os.Stderr
	}
	err = cmd.Run()
	if err != nil {
		t.Fatal(err)
	}
	_, err = os.Stat(dir + cryptfs.ConfDefaultName)
	if err != nil {
		t.Fatal(err)
	}
	_, err = os.Stat(dir + cryptfs.DIRIV_FILENAME)
	if err == nil {
		t.Errorf("gocryptfs.diriv should not have been created with -plaintextnames")
	}
	_, cf, err := cryptfs.LoadConfFile(dir+cryptfs.ConfDefaultName, "test")
	if err != nil {
		t.Fatal(err)
	}
	if !cf.IsFeatureFlagSet(cryptfs.FlagPlaintextNames) {
		t.Error("PlaintextNames flag should be set but isnt")
	}
	if cf.IsFeatureFlagSet(cryptfs.FlagEMENames) || cf.IsFeatureFlagSet(cryptfs.FlagDirIV) {
		t.Error("FlagEMENames and FlagDirIV should be not set")
	}
}
Exemplo n.º 20
0
func TestStepTempDir(t *testing.T) {
	state := testState(t)
	step := new(StepTempDir)
	defer step.Cleanup(state)

	// sanity test
	if _, ok := state.GetOk("temp_dir"); ok {
		t.Fatalf("temp_dir should not be in state yet")
	}

	// run the step
	if action := step.Run(state); action != multistep.ActionContinue {
		t.Fatalf("bad action: %#v", action)
	}

	// Verify that we got the temp dir
	dirRaw, ok := state.GetOk("temp_dir")
	if !ok {
		t.Fatalf("should've made temp_dir")
	}
	dir := dirRaw.(string)

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

	// Cleanup
	step.Cleanup(state)
	if _, err := os.Stat(dir); err == nil {
		t.Fatalf("dir should be gone")
	}
}
Exemplo n.º 21
0
// OnUserChange event. Checks UserChange type, and adjusts items such as skiplists to reflect
// the current status of the users on the server.
func (dj *mumbledj) OnUserChange(e *gumble.UserChangeEvent) {
	if e.Type.Has(gumble.UserChangeDisconnected) {
		if dj.audioStream.IsPlaying() {
			if !isNil(dj.queue.CurrentSong().Playlist()) {
				dj.queue.CurrentSong().Playlist().RemoveSkip(e.User.Name)
			}
			dj.queue.CurrentSong().RemoveSkip(e.User.Name)
		}
	} else if (e.Type.Has(gumble.UserChangeConnected) || e.Type.Has(gumble.UserChangeChannel)) && e.User.Channel == dj.client.Self.Channel { // Play welcome message
		if !dj.audioStream.IsPlaying() {
			var filename = ""
			if _, err := os.Stat(dj.homeDir + "/.mumbledj/greetings/" + e.User.Name + ".mp3"); os.IsNotExist(err) { // Check for custom welcome message
				filename = "default.mp3" // If file does not exist
			} else {
				filename = e.User.Name + ".mp3" // If file exists
			}
			if _, err := os.Stat(fmt.Sprintf("%s/.mumbledj/greetings/%s", dj.homeDir, filename)); os.IsNotExist(err) {
			} else {
				dj.audioStream.Source = gumble_ffmpeg.SourceFile(fmt.Sprintf("%s/.mumbledj/greetings/%s", dj.homeDir, filename))
				if err := dj.audioStream.Play(); err != nil {
					panic(err)
				} else {
					go func() {
						dj.audioStream.Wait()
						if dj.queue.Len() >= 1 {
							dj.queue.PrepareAndPlayNextSong()
						}
					}()
				}
			}
		}
	}
}
Exemplo n.º 22
0
// MakeBucket - PUT Bucket
func (fs Filesystem) MakeBucket(bucket, acl string) *probe.Error {
	fs.lock.Lock()
	defer fs.lock.Unlock()

	stfs, err := disk.Stat(fs.path)
	if err != nil {
		return probe.NewError(err)
	}

	// Remove 5% from total space for cumulative disk space used for journalling, inodes etc.
	availableDiskSpace := (float64(stfs.Free) / (float64(stfs.Total) - (0.05 * float64(stfs.Total)))) * 100
	if int64(availableDiskSpace) <= fs.minFreeDisk {
		return probe.NewError(RootPathFull{Path: fs.path})
	}

	// verify bucket path legal
	if !IsValidBucketName(bucket) {
		return probe.NewError(BucketNameInvalid{Bucket: bucket})
	}

	if !IsValidBucketACL(acl) {
		return probe.NewError(InvalidACL{ACL: acl})
	}

	// get bucket path
	bucketDir := filepath.Join(fs.path, bucket)
	// check if bucket exists
	if _, err = os.Stat(bucketDir); err == nil {
		return probe.NewError(BucketExists{
			Bucket: bucket,
		})
	}

	// make bucket
	err = os.Mkdir(bucketDir, 0700)
	if err != nil {
		return probe.NewError(err)
	}

	bucketMetadata := &BucketMetadata{}
	fi, err := os.Stat(bucketDir)
	// check if bucket exists
	if err != nil {
		if os.IsNotExist(err) {
			return probe.NewError(BucketNotFound{Bucket: bucket})
		}
		return probe.NewError(err)
	}
	if strings.TrimSpace(acl) == "" {
		acl = "private"
	}
	bucketMetadata.Name = fi.Name()
	bucketMetadata.Created = fi.ModTime()
	bucketMetadata.ACL = BucketACL(acl)
	fs.buckets.Metadata[bucket] = bucketMetadata
	if err := saveBucketsMetadata(fs.buckets); err != nil {
		return err.Trace(bucket)
	}
	return nil
}
Exemplo n.º 23
0
func (context *Context) loadThemeJavaScripts() template.HTML {
	var results []string
	var themes = []string{"default"}
	if context.Resource != nil {
		themes = append(themes, context.Resource.Config.Themes...)
	}

	for _, theme := range themes {
		for _, view := range context.getViewPaths() {
			file := path.Join("assets", "javascripts", theme+".js")
			if _, err := os.Stat(path.Join(view, file)); err == nil {
				results = append(results, fmt.Sprintf(`<script src="%s?theme=%s"></script>`, path.Join(context.Admin.GetRouter().Prefix, file), theme))
				break
			}
		}

		for _, view := range context.getViewPaths() {
			file := path.Join("../..", "themes", theme, "assets", "javascripts", "application.js")
			if _, err := os.Stat(path.Join(view, file)); err == nil {
				results = append(results, fmt.Sprintf(`<script src="%s?theme=%s"></script>`, path.Join(context.Admin.GetRouter().Prefix, file), theme))
				break
			}
		}
	}

	return template.HTML(strings.Join(results, " "))
}
Exemplo n.º 24
0
func TestWALName(t *testing.T) {
	db, err := CreateTemp("", "kv-wal-name", ".test", &Options{noClone: true})
	if err != nil {
		t.Fatal(err)
	}

	defer func(n, wn string) {
		if _, err := os.Stat(n); err != nil {
			t.Error(err)
		} else {
			if err := os.Remove(n); err != nil {
				t.Error(err)
			}
		}
		if _, err := os.Stat(wn); err != nil {
			t.Error(err)
		} else {
			if err := os.Remove(wn); err != nil {
				t.Error(err)
			}
		}
		t.Logf("%q\n%q", n, wn)

	}(db.Name(), db.WALName())

	if err := db.Close(); err != nil {
		t.Error(err)
		return
	}

	if n := db.WALName(); n != "" {
		t.Error(n)
	}
}
Exemplo n.º 25
0
// chooseGOPATH selects the gopath component that has the longest prefix in common with dest.
// It breaks ties by preferring earlier components.
func chooseGOPATH(gopaths []string, dest string) string {
	for {
		dest = strings.TrimSuffix(dest, "/")
		chosen := ""
		for i := len(gopaths) - 1; i >= 0; i-- {
			dir := filepath.Join(gopaths[i], "src", dest)
			if _, err := os.Stat(dir); err == nil {
				chosen = gopaths[i]
			}
		}
		if chosen != "" {
			return chosen
		}

		dest, _ = filepath.Split(dest)
		if dest == "" {
			break
		}
	}

	// None of the gopaths contain any prefix of dest.
	// Pick the first gopath that exists.
	for _, dir := range gopaths {
		if _, err := os.Stat(dir); err == nil {
			return dir
		}
	}
	return gopaths[0]
}
Exemplo n.º 26
0
// Remove cleans the directory for the specified key
func (ts *TreeStore) Remove(key string) error {
	treepath := filepath.Join(ts.path, key)
	// If tree path doesn't exist we're done
	_, err := os.Stat(treepath)
	if err != nil && os.IsNotExist(err) {
		return nil
	}
	if err != nil {
		return fmt.Errorf("treestore: failed to open tree store directory: %v", err)
	}

	renderedFilePath := filepath.Join(treepath, renderedfilename)
	// The "rendered" flag file should be the firstly removed file. So if
	// the removal ends with some error leaving some stale files IsRendered()
	// will return false.
	_, err = os.Stat(renderedFilePath)
	if err != nil && !os.IsNotExist(err) {
		return err
	}
	if !os.IsNotExist(err) {
		err := os.Remove(renderedFilePath)
		// Ensure that the treepath directory is fsynced after removing the
		// "rendered" flag file
		f, err := os.Open(treepath)
		if err != nil {
			return fmt.Errorf("treestore: failed to open tree store directory: %v", err)
		}
		defer f.Close()
		err = f.Sync()
		if err != nil {
			return fmt.Errorf("treestore: failed to sync tree store directory: %v", err)
		}
	}
	return os.RemoveAll(treepath)
}
Exemplo n.º 27
0
Arquivo: ahoy.go Projeto: dkinzer/ahoy
func getConfigPath(sourcefile string) (string, error) {
	var err error

	// If a specific source file was set, then try to load it directly.
	if sourcefile != "" {
		if _, err := os.Stat(sourcefile); err == nil {
			return sourcefile, err
		} else {
			logger("fatal", "An ahoy config file was specified using -f to be at "+sourcefile+" but couldn't be found. Check your path.")
		}
	}

	dir, err := os.Getwd()
	if err != nil {
		log.Fatal(err)
	}
	for dir != "/" && err == nil {
		ymlpath := filepath.Join(dir, ".ahoy.yml")
		//log.Println(ymlpath)
		if _, err := os.Stat(ymlpath); err == nil {
			//log.Println("found: ", ymlpath )
			return ymlpath, err
		}
		// Chop off the last part of the path.
		dir = path.Dir(dir)
	}
	return "", err
}
Exemplo n.º 28
0
func (*SymlinkSuite) TestReplace(c *gc.C) {
	target, err := symlink.GetLongPathAsString(c.MkDir())
	c.Assert(err, gc.IsNil)
	target_second, err := symlink.GetLongPathAsString(c.MkDir())
	c.Assert(err, gc.IsNil)
	link := filepath.Join(target, "link")

	_, err = os.Stat(target)
	c.Assert(err, gc.IsNil)
	_, err = os.Stat(target_second)
	c.Assert(err, gc.IsNil)

	err = symlink.New(target, link)
	c.Assert(err, gc.IsNil)

	link_target, err := symlink.Read(link)
	c.Assert(err, gc.IsNil)
	c.Assert(link_target, gc.Equals, filepath.FromSlash(target))

	err = symlink.Replace(link, target_second)
	c.Assert(err, gc.IsNil)

	link_target, err = symlink.Read(link)
	c.Assert(err, gc.IsNil)
	c.Assert(link_target, gc.Equals, filepath.FromSlash(target_second))
}
Exemplo n.º 29
0
func init() {
	fleetdBinPath = os.Getenv("FLEETD_BIN")
	fleetctlBinPath = os.Getenv("FLEETCTL_BIN")
	if fleetdBinPath == "" {
		fmt.Println("FLEETD_BIN environment variable must be set")
		os.Exit(1)
	} else if _, err := os.Stat(fleetdBinPath); err != nil {
		fmt.Printf("%v\n", err)
		os.Exit(1)
	}
	if fleetctlBinPath == "" {
		fmt.Println("FLEETCTL_BIN environment variable must be set")
		os.Exit(1)
	} else if _, err := os.Stat(fleetctlBinPath); err != nil {
		fmt.Printf("%v\n", err)
		os.Exit(1)
	}
	// sanity check etcd availability
	cmd := exec.Command("etcdctl", "ls")
	out, err := cmd.CombinedOutput()
	if err != nil {
		fmt.Printf("Unable to access etcd: %v\n", err)
		fmt.Println(string(out))
		os.Exit(1)
	}
}
Exemplo n.º 30
0
// findConfig returns the filename of the
// config. It searches parent directories
// if it can't find any of the config
// filenames in the current directory.
func findConfig(location string) string {
	configFiles := configFilenames(location)
	// Absolute path to config given
	if len(location) > 0 && path.IsAbs(location) {
		if _, err := os.Stat(location); err == nil {
			return location
		}
	} else { // Relative config
		configPath, _ := os.Getwd()
		for {
			for _, f := range configFiles {
				// the root path is a `/` but others don't have a trailing `/`
				filename := strings.TrimSuffix(configPath, "/") + "/" + f
				if _, err := os.Stat(filename); err == nil {
					return filename
				}
			}
			// loop only if we haven't yet reached the root
			if parentPath := path.Dir(configPath); len(parentPath) != len(configPath) {
				configPath = parentPath
			} else {
				break
			}
		}
	}
	panic(StatusError{fmt.Errorf("No configuration found %v", configFiles), 78})
}