示例#1
0
文件: touch.go 项目: manveru/goblin
func main() {
	flag.Parse()

	mtime := time.Unix(*flagTime, 0)

	for _, arg := range flag.Args() {
		err := os.Chtimes(arg, mtime, mtime)

		if err == nil {
			continue
		}

		if *flagNoCreate {
			reportPathError(err)
			continue
		}

		f, err := os.Create(arg)
		if err != nil {
			reportPathError(err)
			continue
		}

		err = os.Chtimes(arg, mtime, mtime)
		f.Close()
		if err != nil {
			reportPathError(err)
			continue
		}
	}
}
示例#2
0
func writeTime(path string, t time.Time) {
	err := os.Chtimes(path, t, t)
	if os.IsNotExist(err) {
		ioutil.WriteFile(path, nil, 0666)
		os.Chtimes(path, t, t)
	}
}
func TestStaticStale(t *testing.T) {
	srv, wd := stubServer(t)
	defer os.RemoveAll(wd)
	f, err := ioutil.TempFile(wd, "paste")
	check(t, err)
	name := f.Name()
	defer os.Remove(name)
	f.Write([]byte("foo"))
	f.Close()

	asset, err := newStatic(srv, "bar", name)
	if err != nil {
		t.Errorf("ran into error: %s", err.Error())
	}
	if asset.Stale() {
		t.Errorf("shouldn't be stale when just created")
	}
	future := time.Now().Add(5 * time.Second)
	check(t, os.Chtimes(name, future, future))
	if asset.Stale() {
		t.Errorf("shouldn't be stale with old contents")
	}

	check(t, ioutil.WriteFile(name, []byte("bar"), 0644))
	check(t, os.Chtimes(name, future, future))
	if !asset.Stale() {
		t.Errorf("should be stale now with new contents")
	}
}
func TestProcessedSingleFile(t *testing.T) {
	srv, wd := stubServer(t)
	defer os.RemoveAll(wd)
	stubFile(t, wd, "foo.js", "bar")
	file := filepath.Join(wd, "foo.js")

	asset, err := newProcessed(srv, "foo.js", file)
	if err != nil {
		t.Fatalf("ran into error: %s", err.Error())
	}

	bits, err := ioutil.ReadFile(asset.Pathname())
	check(t, err)
	if string(bits) != "bar" {
		t.Errorf("should contain 'bar'")
	}
	if asset.Stale() {
		t.Errorf("shouldn't be stale when just created")
	}
	future := time.Now().Add(5 * time.Second)
	check(t, os.Chtimes(file, future, future))
	if asset.Stale() {
		t.Errorf("shouldn't be stale with old contents")
	}

	check(t, ioutil.WriteFile(file, []byte("foo"), 0644))
	check(t, os.Chtimes(file, future, future))
	if !asset.Stale() {
		t.Errorf("should be stale now with new contents")
	}
}
func TestProcessedConcatenates(t *testing.T) {
	srv, wd := stubServer(t)
	defer os.RemoveAll(wd)
	stubFile(t, wd, "foo.js", "//= require bar\nfoo")
	stubFile(t, wd, "bar.js", "//= require baz.js\nbar")
	stubFile(t, wd, "baz.js", "baz")
	file := filepath.Join(wd, "foo.js")

	asset, err := newProcessed(srv, "foo.js", file)
	if err != nil {
		t.Fatalf("ran into error: %s", err.Error())
	}
	bits, err := ioutil.ReadFile(asset.Pathname())
	check(t, err)
	if string(bits) != "baz\n//= require baz.js\nbar\n//= require bar\nfoo" {
		t.Errorf("wrong contents:\n%s", string(bits))
	}
	if asset.Stale() {
		t.Errorf("shouldn't be stale")
	}
	future := time.Now().Add(5 * time.Second)
	check(t, os.Chtimes(filepath.Join(wd, "bar.js"), future, future))
	if asset.Stale() {
		t.Errorf("shouldn't be stale with same contents")
	}

	check(t, ioutil.WriteFile(filepath.Join(wd, "baz.js"), []byte("baz2"), 0644))
	check(t, os.Chtimes(filepath.Join(wd, "baz.js"), future, future))
	if !asset.Stale() {
		t.Errorf("should be stale now with new contents")
	}
}
示例#6
0
// Run compiles and links the Go source file on args[0] and
// runs it with arguments args[1:].
func Run(args []string) error {
	sourcefile := args[0]
	rundir, runfile, err := RunFile(sourcefile)
	if err != nil {
		return err
	}

	compile := false

	// Now must be called before Stat of sourcefile below,
	// so that changing the file between Stat and Chtimes still
	// causes the file to be updated on the next run.
	now := time.Now()

	sstat, err := os.Stat(sourcefile)
	if err != nil {
		return err
	}

	rstat, err := os.Stat(runfile)
	switch {
	case err != nil:
		compile = true
	case rstat.Mode()&(os.ModeDir|os.ModeSymlink|os.ModeDevice|os.ModeNamedPipe|os.ModeSocket) != 0:
		return errors.New("not a file: " + runfile)
	case rstat.ModTime().Before(sstat.ModTime()) || rstat.Mode().Perm()&0700 != 0700:
		compile = true
	default:
		// We have spare cycles. Maybe remove old files.
		if err := os.Chtimes(runfile, now, now); err == nil {
			CleanDir(rundir, now)
		}
	}

	for retry := 3; retry > 0; retry-- {
		if compile {
			err := Compile(sourcefile, runfile)
			if err != nil {
				return err
			}
			// If sourcefile was changed, will be updated on next run.
			os.Chtimes(runfile, sstat.ModTime(), sstat.ModTime())
		}

		err = syscall.Exec(runfile, args, os.Environ())
		if os.IsNotExist(err) {
			// Got cleaned up under our feet.
			compile = true
			continue
		}
		break
	}
	if err != nil {
		panic("exec returned but succeeded")
	}
	return err
}
示例#7
0
func TestServeFUSE_Chtimes(t *testing.T) {
	maybeSkipTest(t)
	fs := fusetestFileSystem()

	stableT := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)

	fusetestCommon(t, fs, func(mountpoint string) {
		dirpath := path.Join(mountpoint, "hokkaido")
		if err := os.Mkdir(dirpath, 0755); err != nil {
			t.Errorf("Failed to mkdir: %v", err)
			return
		}

		filepath := path.Join(dirpath, "otaru.txt")
		if err := ioutil.WriteFile(filepath, HelloWorld, 0644); err != nil {
			t.Errorf("failed to write file: %v", err)
			return
		}

		if err := os.Chtimes(dirpath, stableT, stableT); err != nil {
			t.Errorf("Failed to chtimes dir: %v", err)
			return
		}
		if err := os.Chtimes(filepath, stableT, stableT); err != nil {
			t.Errorf("Failed to chtimes file: %v", err)
			return
		}

		fi, err := os.Stat(dirpath)
		if err != nil {
			t.Errorf("Failed to stat dir: %v", err)
			return
		}
		if !fi.IsDir() {
			t.Errorf("dir isn't dir!")
		}
		if fi.ModTime().Sub(stableT) > time.Second {
			t.Errorf("invalid modifiedT! %v", fi.ModTime())
		}

		fi, err = os.Stat(filepath)
		if err != nil {
			t.Errorf("Failed to stat file: %v", err)
			return
		}
		if fi.IsDir() {
			t.Errorf("file is dir!")
		}
		if fi.ModTime().Sub(stableT) > time.Second {
			t.Errorf("invalid modifiedT! %v", fi.ModTime())
		}
	})
}
示例#8
0
func TestMain(m *testing.M) {
	timeStart := time.Unix(0, 0)
	time1 := timeStart.Add(time.Duration(1))
	os.Chtimes("test/proc/1/status", time1, time1)
	time20 := timeStart.Add(time.Duration(20))
	os.Chtimes("test/proc/20/status", time20, time20)
	time21 := timeStart.Add(time.Duration(21))
	os.Chtimes("test/proc/21/status", time21, time21)
	time30 := timeStart.Add(time.Duration(30))
	os.Chtimes("test/proc/30/status", time30, time30)
	os.Exit(m.Run())
}
示例#9
0
func buildFS(dir string, files []*buildFileInfo) error {
	if err := os.MkdirAll(dir, 0755); err != nil {
		return err
	}

	dirs := []*buildFileInfo{}
	for _, f := range files {
		p := filepath.Join(dir, f.path)
		switch f.typeflag {
		case tar.TypeDir:
			dirs = append(dirs, f)
			if err := os.MkdirAll(p, f.mode); err != nil {
				return err
			}
			dir, err := os.Open(p)
			if err != nil {
				return err
			}
			if err := dir.Chmod(f.mode); err != nil {
				dir.Close()
				return err
			}
			dir.Close()
		case tar.TypeReg:
			err := ioutil.WriteFile(p, []byte(f.contents), f.mode)
			if err != nil {
				return err
			}

		}

		if err := os.Chtimes(p, f.atime, f.mtime); err != nil {
			return err
		}
	}

	// Restore dirs atime and mtime. This has to be done after extracting
	// as a file extraction will change its parent directory's times.
	for _, d := range dirs {
		p := filepath.Join(dir, d.path)
		if err := os.Chtimes(p, d.atime, d.mtime); err != nil {
			return err
		}
	}

	defaultTime := time.Unix(0, 0)
	// Restore the base dir time as it will be changed by the previous extractions
	if err := os.Chtimes(dir, defaultTime, defaultTime); err != nil {
		return err
	}
	return nil
}
func SaveTarReaderToPath(logger SimpleLogger, bodyReader io.Reader, savePath string) {
	tarReader := tar.NewReader(bodyReader)

	foundEndOfTar := false
	for {
		hdr, err := tarReader.Next()
		if err == io.EOF {
			// end of tar archive
			break
		}
		CheckError(err) //Check after checking for EOF

		if hdr.Name == END_OF_TAR_FILENAME {
			foundEndOfTar = true
			continue
		}

		relativePath := hdr.Name

		if hdr.FileInfo().IsDir() {
			fullDestinationDirPath := filepath.Join(savePath, relativePath)
			logger.Debug("(TAR) Creating directory %s", fullDestinationDirPath)
			os.MkdirAll(fullDestinationDirPath, os.FileMode(hdr.Mode))
			defer os.Chtimes(fullDestinationDirPath, hdr.AccessTime, hdr.ModTime)
		} else {
			fullDestinationFilePath := filepath.Join(savePath, relativePath)
			if val, ok := hdr.Xattrs["SINGLE_FILE_ONLY"]; ok && val == "1" {
				fullDestinationFilePath = savePath
			}

			err = os.MkdirAll(filepath.Dir(fullDestinationFilePath), os.FileMode(hdr.Mode))
			CheckError(err)

			logger.Debug("(TAR) Saving file %s", fullDestinationFilePath)
			file, err := os.OpenFile(fullDestinationFilePath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.FileMode(hdr.Mode))
			CheckError(err)

			defer func() {
				file.Close()
				os.Chtimes(fullDestinationFilePath, hdr.AccessTime, hdr.ModTime)
			}()

			_, err = io.Copy(file, tarReader)
			CheckError(err)
		}
	}

	if !foundEndOfTar {
		panic("TAR stream validation failed, something has gone wrong during the transfer.")
	}
}
示例#11
0
func (e *Export) Extract(r io.Reader) error {

	err := os.MkdirAll(e.Path, 0755)
	if err != nil {
		return err
	}

	t := tar.NewReader(r)
	for {
		header, err := t.Next()
		if err != nil {
			if err == io.EOF {
				return nil
			}
			return err
		}

		if header.Name == "." || header.Name == ".." || header.Name == "./" {
			continue
		}
		fn := path.Join(e.Path, header.Name)

		if header.FileInfo().IsDir() {
			err = os.Mkdir(fn, header.FileInfo().Mode())
			if err != nil {
				return err
			}
			err := os.Chtimes(fn, time.Now().UTC(), header.FileInfo().ModTime())
			if err != nil {
				return err
			}

			continue
		}

		item, err := os.OpenFile(fn, os.O_CREATE|os.O_WRONLY, header.FileInfo().Mode())
		if err != nil {
			return err
		}
		if _, err := io.Copy(item, t); err != nil {
			log.Fatalln(err)
		}
		item.Close()
		err = os.Chtimes(fn, time.Now().UTC(), header.FileInfo().ModTime())
		if err != nil {
			return err
		}
	}
}
示例#12
0
func (f *File) serializeAsDesktopEntry(destPath string, urlMExt *urlMimeTypeExt) (int, error) {
	deskEnt := f.toDesktopEntry(urlMExt)
	handle, err := os.Create(destPath)
	if err != nil {
		return 0, err
	}

	defer func() {
		handle.Close()
		chmodErr := os.Chmod(destPath, 0755)

		if chmodErr != nil {
			fmt.Fprintf(os.Stderr, "%s: [desktopEntry]::chmod %v\n", destPath, chmodErr)
		}

		chTimeErr := os.Chtimes(destPath, f.ModTime, f.ModTime)
		if chTimeErr != nil {
			fmt.Fprintf(os.Stderr, "%s: [desktopEntry]::chtime %v\n", destPath, chTimeErr)
		}
	}()

	icon := strings.Replace(deskEnt.icon, UnescapedPathSep, MimeTypeJoiner, -1)

	return fmt.Fprintf(handle, "[Desktop Entry]\nIcon=%s\nName=%s\nType=%s\nURL=%s\n",
		icon, deskEnt.name, LinkKey, deskEnt.url)
}
示例#13
0
文件: json.go 项目: vovkasm/facette
// JSONDump dumps the data structure using JSON format on the filesystem.
func JSONDump(filePath string, data interface{}, modTime time.Time) error {
	output, err := json.MarshalIndent(data, "", "    ")
	if err != nil {
		return err
	}

	dirPath, _ := path.Split(filePath)

	err = os.MkdirAll(dirPath, 0755)
	if err != nil {
		return err
	}

	fd, err := os.OpenFile(filePath, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644)
	if err != nil {
		return err
	}
	defer fd.Close()

	fd.Write(output)
	fd.Write([]byte("\n"))

	os.Chtimes(filePath, modTime, modTime)

	return nil
}
示例#14
0
文件: util.go 项目: wmwwmv/syncthing
func generateOneFile(fd io.ReadSeeker, p1 string, s int64) error {
	src := io.LimitReader(&inifiteReader{fd}, int64(s))
	dst, err := os.Create(p1)
	if err != nil {
		return err
	}

	_, err = io.Copy(dst, src)
	if err != nil {
		return err
	}

	err = dst.Close()
	if err != nil {
		return err
	}

	_ = os.Chmod(p1, os.FileMode(rand.Intn(0777)|0400))

	t := time.Now().Add(-time.Duration(rand.Intn(30*86400)) * time.Second)
	err = os.Chtimes(p1, t, t)
	if err != nil {
		return err
	}

	return nil
}
示例#15
0
文件: rkt.go 项目: knobunc/kubernetes
// KillPod invokes 'systemctl kill' to kill the unit that runs the pod.
// TODO(yifan): Handle network plugin.
func (r *Runtime) KillPod(pod *api.Pod, runningPod kubecontainer.Pod) error {
	glog.V(4).Infof("Rkt is killing pod: name %q.", runningPod.Name)

	serviceName := makePodServiceFileName(runningPod.ID)
	r.generateEvents(&runningPod, "Killing", nil)
	for _, c := range runningPod.Containers {
		r.containerRefManager.ClearRef(c.ID)
	}

	// Touch the systemd service file to update the mod time so it will
	// not be garbage collected too soon.
	if err := os.Chtimes(serviceFilePath(serviceName), time.Now(), time.Now()); err != nil {
		glog.Errorf("rkt: Failed to change the modification time of the service file %q: %v", serviceName, err)
		return err
	}

	// Since all service file have 'KillMode=mixed', the processes in
	// the unit's cgroup will receive a SIGKILL if the normal stop timeouts.
	reschan := make(chan string)
	_, err := r.systemd.StopUnit(serviceName, "replace", reschan)
	if err != nil {
		glog.Errorf("rkt: Failed to stop unit %q: %v", serviceName, err)
		return err
	}

	res := <-reschan
	if res != "done" {
		glog.Errorf("rkt: Failed to stop unit %q: %s", serviceName, res)
		return err
	}

	return nil
}
示例#16
0
func (fp *FileProvider) SessionRead(sid string) (SessionStore, error) {
	err := os.MkdirAll(path.Join(fp.savePath, string(sid[0]), string(sid[1])), 0777)
	if err != nil {
		println(err.Error())
	}
	_, err = os.Stat(path.Join(fp.savePath, string(sid[0]), string(sid[1]), sid))
	var f *os.File
	if err == nil {
		f, err = os.OpenFile(path.Join(fp.savePath, string(sid[0]), string(sid[1]), sid), os.O_RDWR, 0777)
	} else if os.IsNotExist(err) {
		f, err = os.Create(path.Join(fp.savePath, string(sid[0]), string(sid[1]), sid))
	} else {
		return nil, err
	}
	os.Chtimes(path.Join(fp.savePath, string(sid[0]), string(sid[1]), sid), time.Now(), time.Now())
	var kv map[interface{}]interface{}
	b, err := ioutil.ReadAll(f)
	if err != nil {
		return nil, err
	}
	if len(b) == 0 {
		kv = make(map[interface{}]interface{})
	} else {
		kv, err = decodeGob(b)
		if err != nil {
			return nil, err
		}
	}
	f.Close()
	f, err = os.Create(path.Join(fp.savePath, string(sid[0]), string(sid[1]), sid))
	ss := &FileSessionStore{f: f, sid: sid, values: kv}
	return ss, nil
}
示例#17
0
func main() {
	var files int
	var maxexp int
	var srcname string

	flag.IntVar(&files, "files", 1000, "Number of files")
	flag.IntVar(&maxexp, "maxexp", 20, "Maximum file size (max = 2^n + 128*1024 B)")
	flag.StringVar(&srcname, "src", "/usr/share/dict/words", "Source material")
	flag.Parse()

	fd, err := os.Open(srcname)
	if err != nil {
		log.Fatal(err)
	}

	for i := 0; i < files; i++ {
		n := name()
		p0 := filepath.Join(string(n[0]), n[0:2])
		err = os.MkdirAll(p0, 0755)
		if err != nil {
			log.Fatal(err)
		}

		s := 1 << uint(mr.Intn(maxexp))
		a := 128 * 1024
		if a > s {
			a = s
		}
		s += mr.Intn(a)

		src := io.LimitReader(&inifiteReader{fd}, int64(s))

		p1 := filepath.Join(p0, n)
		dst, err := os.Create(p1)
		if err != nil {
			log.Fatal(err)
		}

		_, err = io.Copy(dst, src)
		if err != nil {
			log.Fatal(err)
		}

		err = dst.Close()
		if err != nil {
			log.Fatal(err)
		}

		err = os.Chmod(p1, os.FileMode(mr.Intn(0777)|0400))
		if err != nil {
			log.Fatal(err)
		}

		t := time.Now().Add(-time.Duration(mr.Intn(30*86400)) * time.Second)
		err = os.Chtimes(p1, t, t)
		if err != nil {
			log.Fatal(err)
		}
	}
}
示例#18
0
文件: chtimes.go 项目: CNDonny/scope
// Chtimes changes the access time and modified time of a file at the given path
func Chtimes(name string, atime time.Time, mtime time.Time) error {
	unixMinTime := time.Unix(0, 0)
	unixMaxTime := maxTime

	// If the modified time is prior to the Unix Epoch, or after the
	// end of Unix Time, os.Chtimes has undefined behavior
	// default to Unix Epoch in this case, just in case

	if atime.Before(unixMinTime) || atime.After(unixMaxTime) {
		atime = unixMinTime
	}

	if mtime.Before(unixMinTime) || mtime.After(unixMaxTime) {
		mtime = unixMinTime
	}

	if err := os.Chtimes(name, atime, mtime); err != nil {
		return err
	}

	// Take platform specific action for setting create time.
	if err := setCTime(name, mtime); err != nil {
		return err
	}

	return nil
}
示例#19
0
func (p *puller) handleEmptyBlock(b bqBlock) {
	f := b.file
	of := p.openFiles[f.Name]

	if b.last {
		if of.err == nil {
			of.file.Close()
		}
	}

	if f.Flags&protocol.FlagDeleted != 0 {
		if debug {
			l.Debugf("pull: delete %q", f.Name)
		}
		os.Remove(of.temp)
		os.Remove(of.filepath)
	} else {
		if debug {
			l.Debugf("pull: no blocks to fetch and nothing to copy for %q / %q", p.repo, f.Name)
		}
		t := time.Unix(f.Modified, 0)
		os.Chtimes(of.temp, t, t)
		os.Chmod(of.temp, os.FileMode(f.Flags&0777))
		defTempNamer.Show(of.temp)
		Rename(of.temp, of.filepath)
	}
	delete(p.openFiles, f.Name)
	p.model.updateLocal(p.repo, f)
}
示例#20
0
func (s *S) TestReloading(c *C) {
	rlName := "reloading.neste"
	rlPath := path.Join(baseDir, rlName)
	data := "foo"
	st := []byte("starting template: {@}\n")
	mt := []byte("modified template: {@}\n")
	sExpected := "starting template: foo\n"
	mExpected := "modified template: foo\n"

	ioutil.WriteFile(rlPath, st, 0644)
	tm := New(baseDir, nil)
	c.Assert(tm.reloading, Equals, false)
	t := tm.MustAddFile(rlName)

	output, err := t.Render(data)
	c.Assert(err, IsNil)
	c.Assert(output, Equals, sExpected)

	// Write changes
	ioutil.WriteFile(rlPath, mt, 0644)
	tm.SetReloading(true)

	// Attempt to force mtime to change.
	err = os.Chtimes(rlPath, time.Nanoseconds(), time.Nanoseconds())
	c.Assert(err, IsNil)

	output, err = t.Render(data)
	c.Assert(err, IsNil)
	c.Assert(output, Equals, mExpected)
}
示例#21
0
func copyFile(src, dest string) error {
	in, err := os.Open(src)
	if err != nil {
		return err
	}
	defer in.Close()
	fi, err := in.Stat()
	if err != nil {
		return err
	}
	// Remove the destination file in case it is read-only (packfiles of git
	// submodules are read-only).
	if err := os.Remove(dest); err != nil && !os.IsNotExist(err) {
		return err
	}
	out, err := os.OpenFile(dest, os.O_CREATE|os.O_RDWR, fi.Mode())
	if err != nil {
		return err
	}
	if _, err := io.Copy(out, in); err != nil {
		return err
	}
	if err := out.Close(); err != nil {
		return nil
	}
	return os.Chtimes(dest, time.Now(), fi.ModTime())
}
示例#22
0
func Test_Runner_Kill(t *testing.T) {
	bin := filepath.Join("test_fixtures", "writing_output")
	if runtime.GOOS == "windows" {
		bin += ".bat"
	}

	runner := gin.NewRunner(bin)

	cmd1, err := runner.Run()
	expect(t, err, nil)

	cmd2, err := runner.Run()
	expect(t, err, nil)
	expect(t, cmd1, cmd2)

	time.Sleep(time.Second * 1)
	os.Chtimes(bin, time.Now(), time.Now())
	if err != nil {
		t.Fatal("Error with Chtimes")
	}

	cmd3, err := runner.Run()
	expect(t, err, nil)

	if runtime.GOOS != "windows" {
		// does not seem to work as expected on windows
		refute(t, cmd1, cmd3)
	}
}
示例#23
0
func TestGetEmail(t *testing.T) {
	storageBasePath = string(testStorage) // to contain calls that create a new Storage...

	// let's not clutter up the output
	origStdout := os.Stdout
	os.Stdout = nil
	defer func() { os.Stdout = origStdout }()

	defer testStorage.clean()
	DefaultEmail = "*****@*****.**"

	// Test1: Use default email from flag (or user previously typing it)
	actual := getEmail(testStorage, true)
	if actual != DefaultEmail {
		t.Errorf("Did not get correct email from memory; expected '%s' but got '%s'", DefaultEmail, actual)
	}

	// Test2: Get input from user
	DefaultEmail = ""
	stdin = new(bytes.Buffer)
	_, err := io.Copy(stdin, strings.NewReader("[email protected]\n"))
	if err != nil {
		t.Fatalf("Could not simulate user input, error: %v", err)
	}
	actual = getEmail(testStorage, true)
	if actual != "*****@*****.**" {
		t.Errorf("Did not get correct email from user input prompt; expected '%s' but got '%s'", "*****@*****.**", actual)
	}

	// Test3: Get most recent email from before
	DefaultEmail = ""
	for i, eml := range []string{
		"*****@*****.**", // test case insensitivity
		"*****@*****.**",
		"*****@*****.**",
	} {
		u, err := newUser(eml)
		if err != nil {
			t.Fatalf("Error creating user %d: %v", i, err)
		}
		err = saveUser(testStorage, u)
		if err != nil {
			t.Fatalf("Error saving user %d: %v", i, err)
		}

		// Change modified time so they're all different, so the test becomes deterministic
		f, err := os.Stat(testStorage.user(eml))
		if err != nil {
			t.Fatalf("Could not access user folder for '%s': %v", eml, err)
		}
		chTime := f.ModTime().Add(-(time.Duration(i) * time.Second))
		if err := os.Chtimes(testStorage.user(eml), chTime, chTime); err != nil {
			t.Fatalf("Could not change user folder mod time for '%s': %v", eml, err)
		}
	}
	actual = getEmail(testStorage, true)
	if actual != "*****@*****.**" {
		t.Errorf("Did not get correct email from storage; expected '%s' but got '%s'", "*****@*****.**", actual)
	}
}
示例#24
0
// extractFile extracts zip.File to file system.
func extractFile(f *zip.File, destPath string) error {
	filePath := path.Join(destPath, f.Name)
	os.MkdirAll(path.Dir(filePath), os.ModePerm)

	rc, err := f.Open()
	if err != nil {
		return err
	}
	defer rc.Close()

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

	if _, err = io.Copy(fw, rc); err != nil {
		return err
	}

	// Skip symbolic links.
	if f.FileInfo().Mode()&os.ModeSymlink != 0 {
		return nil
	}
	// Set back file information.
	if err = os.Chtimes(filePath, f.ModTime(), f.ModTime()); err != nil {
		return err
	}
	return os.Chmod(filePath, f.FileInfo().Mode())
}
示例#25
0
文件: tar.go 项目: kcbabo/origin
func extractFile(dir string, header *tar.Header, tarReader io.Reader) error {
	path := filepath.Join(dir, header.Name)
	glog.V(3).Infof("Creating %s", path)

	file, err := os.Create(path)
	// The file times need to be modified after it's been closed thus this function
	// is deferred after the file close (LIFO order for defer)
	defer os.Chtimes(path, time.Now(), header.FileInfo().ModTime())
	defer file.Close()
	if err != nil {
		return err
	}
	glog.V(3).Infof("Extracting/writing %s", path)
	written, err := io.Copy(file, tarReader)
	if err != nil {
		return err
	}
	if written != header.Size {
		return fmt.Errorf("Wrote %d bytes, expected to write %d", written, header.Size)
	}
	if runtime.GOOS != "windows" { // Skip chmod if on windows OS
		return file.Chmod(header.FileInfo().Mode())
	}
	return nil
}
示例#26
0
func copyFile(src string, dst string) (err error) {
	srcFile, err := os.Open(src)
	if err != nil {
		return err
	}
	defer srcFile.Close()

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

	if OS == "linux" {
		err = dstFile.Chmod(os.ModePerm)
		if err != nil {
			return
		}
	}

	_, err = io.Copy(dstFile, srcFile)
	if err != nil {
		return
	}

	err = os.Chtimes(dst, time.Now(), time.Now())
	return err
}
示例#27
0
// shortcutFile sets file mode and modification time, when that's the only
// thing that has changed.
func (p *rwFolder) shortcutFile(file protocol.FileInfo) error {
	realName := filepath.Join(p.dir, file.Name)
	if !p.ignorePermissions(file) {
		if err := os.Chmod(realName, os.FileMode(file.Flags&0777)); err != nil {
			l.Infof("Puller (folder %q, file %q): shortcut: chmod: %v", p.folder, file.Name, err)
			p.newError(file.Name, err)
			return err
		}
	}

	t := time.Unix(file.Modified, 0)
	if err := os.Chtimes(realName, t, t); err != nil {
		// Try using virtual mtimes
		info, err := os.Stat(realName)
		if err != nil {
			l.Infof("Puller (folder %q, file %q): shortcut: unable to stat file: %v", p.folder, file.Name, err)
			p.newError(file.Name, err)
			return err
		}

		p.virtualMtimeRepo.UpdateMtime(file.Name, info.ModTime(), t)
	}

	// This may have been a conflict. We should merge the version vectors so
	// that our clock doesn't move backwards.
	if cur, ok := p.model.CurrentFolderFile(p.folder, file.Name); ok {
		file.Version = file.Version.Merge(cur.Version)
	}

	return nil
}
func TestCacheArchiverIsUpToDate(t *testing.T) {
	ioutil.WriteFile(cacheArchiverTestArchivedFile, nil, 0600)
	defer os.Remove(cacheArchiverTestArchivedFile)

	defer os.Remove(cacheArchiverArchive)
	cmd := CacheArchiverCommand{
		File: cacheArchiverArchive,
		fileArchiver: fileArchiver{
			Paths: []string{
				cacheArchiverTestArchivedFile,
			},
		},
	}
	cmd.Execute(nil)
	fi, _ := os.Stat(cacheArchiverArchive)
	cmd.Execute(nil)
	fi2, _ := os.Stat(cacheArchiverArchive)
	assert.Equal(t, fi.ModTime(), fi2.ModTime(), "archive is up to date")

	// We need to wait one second, since the FS doesn't save milliseconds
	time.Sleep(time.Second)

	os.Chtimes(cacheArchiverTestArchivedFile, time.Now(), time.Now())
	cmd.Execute(nil)
	fi3, _ := os.Stat(cacheArchiverArchive)
	assert.NotEqual(t, fi.ModTime(), fi3.ModTime(), "archive should get updated")
}
示例#29
0
func TestUnionFsChtimes(t *testing.T) {
	wd, clean := setupUfs(t)
	defer clean()

	writeToFile(wd+"/ro/file", "a")
	err := os.Chtimes(wd+"/ro/file", 42e9, 43e9)
	CheckSuccess(err)

	err = os.Chtimes(wd+"/mnt/file", 82e9, 83e9)
	CheckSuccess(err)

	fi, err := os.Lstat(wd + "/mnt/file")
	if fi.Atime_ns != 82e9 || fi.Mtime_ns != 83e9 {
		t.Error("Incorrect timestamp", fi)
	}
}
func TestTouch(t *testing.T) {
	ts := NewTestCase(t)
	defer ts.Cleanup()

	contents := []byte{1, 2, 3}
	err := ioutil.WriteFile(ts.origFile, []byte(contents), 0700)
	if err != nil {
		t.Fatalf("WriteFile failed: %v", err)
	}
	err = os.Chtimes(ts.mountFile, time.Unix(42, 0), time.Unix(43, 0))
	if err != nil {
		t.Fatalf("Chtimes failed: %v", err)
	}

	var stat syscall.Stat_t
	err = syscall.Lstat(ts.mountFile, &stat)
	if err != nil {
		t.Fatalf("Lstat failed: %v", err)
	}
	if stat.Atim.Sec != 42 {
		t.Errorf("Got atime.sec %d, want 42. Stat_t was %#v", stat.Atim.Sec, stat)
	}
	if stat.Mtim.Sec != 43 {
		t.Errorf("Got mtime.sec %d, want 43. Stat_t was %#v", stat.Mtim.Sec, stat)
	}
}