// CopyFile copies a file safely.
// It will create parent directories for destinationPath if they don't exist.
// It will overwrite an existing destinationPath.
434334
func CopyFile(sourcePath string, destinationPath string, log Log) error {
	log.Infof("Copying %s to %s", sourcePath, destinationPath)
	in, err := os.Open(sourcePath)
	if err != nil {
		return err
	}
	defer Close(in)

	if _, statErr := os.Stat(destinationPath); statErr == nil {
		log.Infof("Removing existing destination path: %s", destinationPath)
		if removeErr := os.RemoveAll(destinationPath); removeErr != nil {
			return removeErr
		}
	}

	if makeDirErr := MakeParentDirs(destinationPath, 0700, log); makeDirErr != nil {
		return makeDirErr
	}

	out, err := os.Create(destinationPath)
	if err != nil {
		return err
	}
	defer Close(out)
	_, err = io.Copy(out, in)
	closeErr := out.Close()
	if err != nil {
		return err
	}
	return closeErr
}
837323
func (f *File) Copy() (*File, error) {
	var datacopy = make([]byte, len(f.data))
	copy(datacopy[:], f.data)
	return &File{
		name:     f.name,
		filemode: f.filemode,
		time:     f.time,
		data:     datacopy,
	}, nil
}
796018
func (fs *Filespace) CopyFile(src, dest string) error {
	srcNode, err := fs.root.GetByPath(src)
	if err != nil {
		return err
	}
	if srcNode.IsDir() {
		return fmt.Errorf("Source node must be a file")
	}
	file := srcNode.(*File)
	copiedFile, err := file.Copy()
	if err != nil {
		return err
	}
	destDirName := path.Dir(dest)
	err = fs.MkdirAll(destDirName, 0777)
	if err != nil {
		return err
	}
	destNode, err := fs.root.GetByPath(destDirName)
	if err != nil {
		return err
	}
	if !destNode.IsDir() {
		return fmt.Errorf("Destination path exist and there is a file " + dest)
	}
	copiedFile.name = path.Base(dest)
	var destDir = destNode.(*Dir)
	destDir.AddNode(copiedFile)
	return nil
}
1179231
func CopyFile(dst, src string) error {
	if ok, err := IsTheSame(dst, src); err != nil {
		return err
	} else if ok {
		return nil
	}
	in, err := os.Open(src)
	if err != nil {
		return err
	}
	defer in.Close()
	fi, err := in.Stat()
	if err != nil {
		return err
	}
	var tmp *os.File
	if tmp, err = copy2temp(in, dst); err != nil {
		return err
	}
	if dst, err = dstfix(dst, src); err != nil {
		os.Remove(tmp.Name())
		return err
	}
	if err = os.Rename(tmp.Name(), dst); err != nil {
		os.Remove(tmp.Name())
		return err
	}
	if err = os.Chmod(dst, fi.Mode()); err != nil {
		os.Remove(dst)
		return err
	}
	return nil
}
478865
func (p *PNSExecutor) CopyFile(containerID string, sourcePath string, destPath string) (err error) {
	destFile, err := os.Create(destPath)
	if err != nil {
		return err
	}
	defer func() {
		// exit chroot and close the file. preserve the original error
		deferErr := p.exitChroot()
		if err == nil && deferErr != nil {
			err = errors.InternalWrapError(deferErr)
		}
		deferErr = destFile.Close()
		if err == nil && deferErr != nil {
			err = errors.InternalWrapError(deferErr)
		}
	}()
	w := bufio.NewWriter(destFile)
	err = p.enterChroot()
	if err != nil {
		return err
	}

	err = archive.TarGzToWriter(sourcePath, w)
	if err != nil {
		return err
	}

	return nil
}
791955
func copyFile(w io.Writer, file string) error {
	f, err := os.Open(file)
	if err != nil {
		return err
	}
	defer f.Close()
	_, err = io.Copy(w, f)
	return err
}
410926
func (fs *Filespace) CopyDirectory(src, dest string) error {
	srcNode, err := fs.root.GetByPath(src)
	if err != nil {
		return err
	}
	if !srcNode.IsDir() {
		return fmt.Errorf("Source node must be a directory")
	}
	dir := srcNode.(*Dir)
	copiedDir, err := dir.Copy()
	if err != nil {
		return err
	}
	destDirName := path.Dir(dest)
	err = fs.MkdirAll(destDirName, 0777)
	if err != nil {
		return err
	}
	destNode, err := fs.root.GetByPath(destDirName)
	if err != nil {
		return err
	}
	if !destNode.IsDir() {
		return fmt.Errorf("Destination path exist and there is a file " + dest)
	}
	copiedDir.name = path.Base(dest)
	var destDir = destNode.(*Dir)
	destDir.AddNode(copiedDir)
	return nil
}
1105364
func (f *FS) MoveFile(ctx context.Context, src dokan.File, sourceFI *dokan.FileInfo, targetPath string, replaceExisting bool) (err error) {
	// User checking was handled by original file open, this is no longer true.
	// However we only allow fake files with names that are not potential rename
	// paths. Filter those out here.

	f.vlog.CLogf(
		ctx, libkb.VLog1, "MoveFile %T %q -> %q", src,
		sourceFI.Path(), targetPath)
	// isPotentialRenamePath filters out some special paths
	// for rename. Especially those provided by fakeroot.go.
	if !isPotentialRenamePath(sourceFI.Path()) {
		f.log.CErrorf(ctx, "Refusing MoveFile access: not potential rename path")
		return dokan.ErrAccessDenied
	}
	switch src.(type) {
	case *FolderList, *File, *Dir, *TLF, *EmptyFolder:
	default:
		f.log.CErrorf(ctx, "Refusing MoveFile access: wrong type source argument")
		return dokan.ErrAccessDenied
	}

	f.logEnter(ctx, "FS MoveFile")
	// No racing deletions or renames.
	// Note that this calls Cleanup multiple times, however with nil
	// FileInfo which means that Cleanup will not try to lock renameAndDeletionLock.
	// renameAndDeletionLock should be the first lock to be grabbed in libdokan.
	f.renameAndDeletionLock.Lock()
	defer func() {
		f.renameAndDeletionLock.Unlock()
		f.reportErr(ctx, libkbfs.WriteMode, err)
	}()

	oc := newSyntheticOpenContext()

	// Source directory
	srcDirPath, err := windowsPathSplit(sourceFI.Path())
	if err != nil {
		return err
	}
	if len(srcDirPath) < 1 {
		return errors.New("Invalid source for move")
	}
	srcName := srcDirPath[len(srcDirPath)-1]
	srcDirPath = srcDirPath[0 : len(srcDirPath)-1]
	srcDir, _, err := f.open(ctx, oc, srcDirPath)
	if err != nil {
		return err
	}
	defer srcDir.Cleanup(ctx, nil)

	// Destination directory, not the destination file
	dstPath, err := windowsPathSplit(targetPath)
	if err != nil {
		return err
	}
	if len(dstPath) < 1 {
		return errors.New("Invalid destination for move")
	}
	dstDirPath := dstPath[0 : len(dstPath)-1]

	dstDir, dstCst, err := f.open(ctx, oc, dstDirPath)
	f.vlog.CLogf(
		ctx, libkb.VLog1, "FS MoveFile dstDir open %v -> %v,%v,%v dstType %T",
		dstDirPath, dstDir, dstCst, err, dstDir)
	if err != nil {
		return err
	}
	defer dstDir.Cleanup(ctx, nil)
	if !dstCst.IsDir() {
		return errors.New("Tried to move to a non-directory path")
	}

	fl1, ok := srcDir.(*FolderList)
	fl2, ok2 := dstDir.(*FolderList)
	if ok && ok2 && fl1 == fl2 {
		return f.folderListRename(ctx, fl1, oc, src, srcName, dstPath, replaceExisting)
	}

	srcDirD := asDir(ctx, srcDir)
	if srcDirD == nil {
		return errors.New("Parent of src not a Dir")
	}
	srcFolder := srcDirD.folder
	srcParent := srcDirD.node

	ddst := asDir(ctx, dstDir)
	if ddst == nil {
		return errors.New("Destination directory is not of type Dir")
	}

	switch src.(type) {
	case *Dir:
	case *File:
	case *TLF:
	default:
		return dokan.ErrAccessDenied
	}

	// here we race...
	if !replaceExisting {
		x, _, err := f.open(ctx, oc, dstPath)
		if err == nil {
			defer x.Cleanup(ctx, nil)
		}
		if !isNoSuchNameError(err) {
			f.vlog.CLogf(
				ctx, libkb.VLog1,
				"FS MoveFile required non-existent destination, got: %T %v",
				err, err)
			return dokan.ErrObjectNameCollision
		}

	}

	if srcFolder != ddst.folder {
		return dokan.ErrNotSameDevice
	}

	// overwritten node, if any, will be removed from Folder.nodes, if
	// it is there in the first place, by its Forget

	dstName := dstPath[len(dstPath)-1]
	f.vlog.CLogf(
		ctx, libkb.VLog1, "FS MoveFile KBFSOps().Rename(ctx,%v,%v,%v,%v)",
		srcParent, srcName, ddst.node, dstName)
	if err := srcFolder.fs.config.KBFSOps().Rename(
		ctx, srcParent, srcName, ddst.node, dstName); err != nil {
		f.log.CDebugf(ctx, "FS MoveFile KBFSOps().Rename FAILED %v", err)
		return err
	}

	switch x := src.(type) {
	case *Dir:
		x.parent = ddst.node
		x.name = dstName
	case *File:
		x.parent = ddst.node
		x.name = dstName
	}

	f.vlog.CLogf(ctx, libkb.VLog1, "FS MoveFile SUCCESS")
	return nil
}
1067615
func CopyFile(srcFile, destFile string) error {
	file, err := os.Open(srcFile)
	if err != nil {
		return err
	}
	defer file.Close()
	dest, err := os.Create(destFile)
	if err != nil {
		return err
	}
	defer dest.Close()
	_, err = io.Copy(dest, file)
	return err
}
476279
func createFile(path string, write func(*os.File) error) (err error) {
	file, err := os.Create(path)
	if err != nil {
		return err
	}
	defer func() {
		closeErr := file.Close()
		if err == nil {
			err = closeErr
		}
	}()
	return write(file)
}
513491
func Copy(source, destination string) error {
	src := cleanPath(source)
	dst := cleanPath(destination)
	s, err := os.Open(src)
	if err != nil {
		return err
	}
	// no need to check errors on read only file, we already got everything
	// we need from the filesystem, so nothing can go wrong now.
	defer s.Close()

	if IsDir(src) {
		return fmt.Errorf("source path is a directory")
	}
	if IsDir(dst) {
		basename := filepath.Base(src)
		dst = path.Join(dst, basename)
	}

	d, err := os.Create(dst)
	if err != nil {
		return err
	}
	if _, err := io.Copy(d, s); err != nil {
		d.Close()
		return err
	}
	return d.Close()
}
214985
func copyFile(src, dst string, relPath string, edit editFunc) error {
	data, err := ioutil.ReadFile(src)
	if err != nil {
		return fmt.Errorf("failed to read source: %s", err)
	}

	if edit != nil {
		data, err = edit(relPath, data)
		if err != nil {
			return fmt.Errorf("edit error: %s", err)
		}

	}
	if data == nil {
		return nil
	}
	return ioutil.WriteFile(dst, data, 0644)
}
852005
func CopyDir(dst, src string) error {
	err := os.MkdirAll(dst, 0755)
	if err != nil {
		return err
	}

	files, err := ioutil.ReadDir(src)

	for i := 0; i < len(files) && err == nil; i++ {
		file := files[i].Name()
		df := filepath.Join(dst, file)
		sf := filepath.Join(src, file)
		if IsFile(sf) {
			err = Copy(df, sf)
		} else {
			err = CopyDir(df, sf)
		}
	}

	return err
}
1120530
func Copy(src, dest string) error {
	// Gather file information to set back later.
	si, err := os.Lstat(src)
	if err != nil {
		return err
	}

	// Handle symbolic link.
	if si.Mode()&os.ModeSymlink != 0 {
		target, err := os.Readlink(src)
		if err != nil {
			return err
		}
		// NOTE: os.Chmod and os.Chtimes don't recoganize symbolic link,
		// which will lead "no such file or directory" error.
		return os.Symlink(target, dest)
	}

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

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

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

	// Set back file information.
	if err = os.Chtimes(dest, si.ModTime(), si.ModTime()); err != nil {
		return err
	}
	return os.Chmod(dest, si.Mode())
}
925725
func CopyDir(source string, dest string) (err error) {

	// get properties of source dir
	fi, err := os.Stat(source)
	if err != nil {
		return err
	}

	if !fi.IsDir() {
		return &CustomError{"Source is not a directory"}
	}

	// ensure dest dir does not already exist

	_, err = os.Open(dest)
	if !os.IsNotExist(err) {
		err = os.MkdirAll(dest, fi.Mode())
		if err != nil {
			return err
		}
	}

	// create dest dir

	entries, err := ioutil.ReadDir(source)

	for _, entry := range entries {

		sfp := source + "/" + entry.Name()
		dfp := dest + "/" + entry.Name()
		if entry.IsDir() {
			err = os.MkdirAll(dfp, fi.Mode())
			if err != nil {
				log.Println(err)
			}
			err = CopyDir(sfp, dfp)
			if err != nil {
				log.Println(err)
			}
		} else {
			// perform copy
			err = CopyFile(sfp, dfp)
			if err != nil {
				log.Println(err)
			}
		}

	}
	return
}
570080
func (tx *Tx) CopyFile(path string, mode os.FileMode) error {
	f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, mode)
	if err != nil {
		return err
	}

	err = tx.Copy(f)
	if err != nil {
		_ = f.Close()
		return err
	}
	return f.Close()
}
137320
func CopyFile(dst, src string) error {
	fsrc, err := os.Open(src)
	if err != nil {
		return err
	}
	defer fsrc.Close()
	fdst, err := os.Create(dst)
	if err != nil {
		return err
	}
	defer fdst.Close()
	if _, err = io.Copy(fdst, fsrc); err != nil {
		return err
	}
	return nil
}