// GetTempDir returns the default temp directory with trailing slash
// if subPath is not empty then it will be created recursively with mode 777 rwx rwx rwx
351905
func GetTempDir(fs Fs, subPath string) string {
	addSlash := func(p string) string {
		if FilePathSeparator != p[len(p)-1:] {
			p = p + FilePathSeparator
		}
		return p
	}
	dir := addSlash(os.TempDir())

	if subPath != "" {
		// preserve windows backslash :-(
		if FilePathSeparator == "\\" {
			subPath = strings.Replace(subPath, "\\", "____", -1)
		}
		dir = dir + UnicodeSanitize((subPath))
		if FilePathSeparator == "\\" {
			dir = strings.Replace(dir, "____", "\\", -1)
		}

		if exists, _ := Exists(fs, dir); exists {
			return addSlash(dir)
		}

		err := fs.MkdirAll(dir, 0777)
		if err != nil {
			panic(err)
		}
		dir = addSlash(dir)
	}
	return dir
}
555242
func getCertsDir() (string, *probe.Error) {
	p, err := getMcConfigDir()
	if err != nil {
		return "", err.Trace()
	}
	return filepath.Join(p, globalMCCertsDir), nil
}
184834
def gettempdir():
    """"""
    global tempdir
    if tempdir is None:
        _once_lock.acquire()
        try:
            if tempdir is None:
                tempdir = _get_default_tempdir()
        finally:
            _once_lock.release()
    return tempdir
63903
func TempDir(prefix string) (path string, err error) {
	// Create temp file
	var f *os.File
	if f, err = ioutil.TempFile(os.TempDir(), prefix); err != nil {
		err = errors.Wrap(err, "creating temporary file failed")
		return
	}
	path = f.Name()

	// Close temp file
	if err = f.Close(); err != nil {
		err = errors.Wrapf(err, "closing file %s failed", path)
		return
	}

	// Delete temp file
	if err = os.Remove(path); err != nil {
		err = errors.Wrapf(err, "removing %s failed", path)
		return
	}

	// Create temp dir
	if err = os.MkdirAll(path, 0755); err != nil {
		err = errors.Wrapf(err, "mkdirall of %s failed", path)
		return
	}
	return
}
824407
func getHomeDir() string {
	switch runtime.GOOS {
	case teleport.LinuxOS:
		return os.Getenv(teleport.EnvHome)
	case teleport.DarwinOS:
		return os.Getenv(teleport.EnvHome)
	case teleport.WindowsOS:
		return os.Getenv(teleport.EnvUserProfile)
	}
	return ""
}
155824
func TempDir(p string) string {
	var tmp string

	if user, err := user.Current(); err == nil {
		tmp = path.Join(os.TempDir(), fmt.Sprintf("serviced-%s", user.Username), p)
	} else {
		tmp = path.Join(os.TempDir(), fmt.Sprintf("serviced"), p)
		glog.Warningf("Defaulting home to %s", tmp)
	}

	return tmp
}
625685
func (streamFile *TargetFile) GetDir() (string, error) {
	// Assure path is existing
	if err := os.MkdirAll(streamFile.dir, streamFile.folderPermissions); err != nil {
		return "", fmt.Errorf("failed to create %s because of %s", streamFile.dir, err.Error())
	}

	return streamFile.dir, nil
}
510285
func (tz *TzArchive) AddEmptyDir(dirPath string) bool {
	if !strings.HasSuffix(dirPath, "/") {
		dirPath += "/"
	}

	for _, f := range tz.files {
		if dirPath == f.Name {
			return false
		}
	}

	dirPath = strings.TrimSuffix(dirPath, "/")
	if strings.Contains(dirPath, "/") {
		// Auto add all upper level directories.
		tz.AddEmptyDir(path.Dir(dirPath))
	}
	tz.files = append(tz.files, &File{
		Header: &tar.Header{
			Name: dirPath + "/",
		},
	})
	tz.updateStat()
	return true
}
793630
func (td *TempDir) Mkdir(name ...string) string {
	innerName := filepath.Join(name...)
	fullName := filepath.Join(td.dir, innerName)
	if err := os.MkdirAll(fullName, 0700); err != nil {
		msg := fmt.Sprintf("cannot create nested temporary directory %q: %v", fullName, err)
		td.assert.Fail(msg)
	}
	return fullName
}
1135246
func slashdir(p string) string {
	d := path.Dir(p)
	if d == "." || d == "/" {
		return "/"
	}
	if strings.HasPrefix(p, "/") {
		return d
	}
	return "/" + d
}
668119
func TempDir(dir, prefix string) (string, error) {
	tempDir, err := ioutil.TempDir(dir, prefix)
	if err != nil {
		return "", err
	}
	return longpath.AddPrefix(tempDir), nil
}
87998
func (td *TempDir) Restore() {
	err := os.RemoveAll(td.dir)
	if err != nil {
		msg := fmt.Sprintf("cannot remove temporary directory %q: %v", td.dir, err)
		td.assert.Fail(msg)
	}
}
345721
func (fs *FS) TempFile(dir, prefix string) (billy.File, error) {
	if err := fs.requireNonEmpty(); err != nil {
		return nil, err
	}

	// We'd have to turn off journaling to support TempFile perfectly,
	// but the given uniq ID and a random number should be good
	// enough.  Especially since most users will end up renaming the
	// temp file before journal flushing even happens.
	b := make([]byte, 8)
	_, err := rand.Read(b)
	if err != nil {
		return nil, err
	}
	suffix := fs.uniqID + "-" + base64.URLEncoding.EncodeToString(b)
	return fs.OpenFile(path.Join(dir, prefix+suffix),
		os.O_CREATE|os.O_EXCL, 0600)
}
783030
func (h *QuarantineXattrHandler) Getxattr(ctx context.Context,
	req *fuse.GetxattrRequest, resp *fuse.GetxattrResponse) (err error) {
	ctx = h.folder.fs.config.MaybeStartTrace(ctx, "QuarantineXattrHandler.Getxattr",
		fmt.Sprintf("%s %s", h.node.GetBasename(), req.Name))
	defer func() { h.folder.fs.config.MaybeFinishTrace(ctx, err) }()

	h.folder.fs.log.CDebugf(ctx,
		"QuarantineXattrHandler Getxattr %s %s", h.node.GetBasename(), req.Name)
	defer func() { err = h.folder.processError(ctx, libkbfs.ReadMode, err) }()

	if req.Name != quarantineXattrName {
		// The request is not about quarantine. Let the OS fallback to ._ file
		// based method.
		return fuse.ENOTSUP
	}

	xattr, err := h.folder.fs.config.XattrStore().GetXattr(
		ctx, h.node.GetBlockID(), libkbfs.XattrAppleQuarantine)
	switch errors.Cause(err) {
	case nil:
		if len(xattr) == 0 {
			return fuse.ENOATTR
		}
		resp.Xattr = xattr
		return nil
	case ldberrors.ErrNotFound:
		// We don't have an Xattr value stored locally, so just use a
		// quarantine value.

		// Stat on the node to get the Mtime.

		// This fits in situation 1 as described in
		// libkbfs/delayed_cancellation.go
		if err = libcontext.EnableDelayedCancellationWithGracePeriod(ctx,
			h.folder.fs.config.DelayedCancellationGracePeriod()); err != nil {
			return err
		}
		de, err := h.folder.fs.config.KBFSOps().Stat(ctx, h.node)
		if err != nil {
			if _, ok := err.(idutil.NoSuchNameError); ok {
				// The node is not found, so just return ENOTSUP
				return fuse.ENOTSUP
			}
			return err
		}

		resp.Xattr = makeQuarantine(time.Unix(0, de.Mtime))
		return nil
	default:
		return err
	}
}
306499
func (a *API) GetDirectoryTar(ctx context.Context, decrypt DecryptFunc, uri *URI) (io.ReadCloser, error) {
	apiGetTarCount.Inc(1)
	addr, err := a.Resolve(ctx, uri.Addr)
	if err != nil {
		return nil, err
	}
	walker, err := a.NewManifestWalker(ctx, addr, decrypt, nil)
	if err != nil {
		apiGetTarFail.Inc(1)
		return nil, err
	}

	piper, pipew := io.Pipe()

	tw := tar.NewWriter(pipew)

	go func() {
		err := walker.Walk(func(entry *ManifestEntry) error {
			// ignore manifests (walk will recurse into them)
			if entry.ContentType == ManifestType {
				return nil
			}

			// retrieve the entry's key and size
			reader, _ := a.Retrieve(ctx, storage.Address(common.Hex2Bytes(entry.Hash)))
			size, err := reader.Size(ctx, nil)
			if err != nil {
				return err
			}

			// write a tar header for the entry
			hdr := &tar.Header{
				Name:    entry.Path,
				Mode:    entry.Mode,
				Size:    size,
				ModTime: entry.ModTime,
				Xattrs: map[string]string{
					"user.swarm.content-type": entry.ContentType,
				},
			}

			if err := tw.WriteHeader(hdr); err != nil {
				return err
			}

			// copy the file into the tar stream
			n, err := io.Copy(tw, io.LimitReader(reader, hdr.Size))
			if err != nil {
				return err
			} else if n != size {
				return fmt.Errorf("error writing %s: expected %d bytes but sent %d", entry.Path, size, n)
			}

			return nil
		})
		// close tar writer before closing pipew
		// to flush remaining data to pipew
		// regardless of error value
		tw.Close()
		if err != nil {
			apiGetTarFail.Inc(1)
			pipew.CloseWithError(err)
		} else {
			pipew.Close()
		}
	}()

	return piper, nil
}
1322077
func getTmpROC(s *imagestore.Store, path string) (*removeOnClose, error) {
	h := sha512.New()
	h.Write([]byte(path))
	pathHash := s.HashToKey(h)

	tmp, err := s.TmpNamedFile(pathHash)
	if err != nil {
		return nil, errwrap.Wrap(errors.New("error setting up temporary file"), err)
	}

	// let's lock the file to avoid concurrent writes to the temporary file, it
	// will go away when removing the temp file
	_, err = lock.TryExclusiveLock(tmp.Name(), lock.RegFile)
	if err != nil {
		if err != lock.ErrLocked {
			return nil, errwrap.Wrap(errors.New("failed to lock temporary file"), err)
		}
		log.Printf("another rkt instance is downloading this file, waiting...")
		_, err = lock.ExclusiveLock(tmp.Name(), lock.RegFile)
		if err != nil {
			return nil, errwrap.Wrap(errors.New("failed to lock temporary file"), err)
		}
	}

	return &removeOnClose{File: tmp}, nil
}
410460
def getTempDirectory(rootDir=None):
    
    if rootDir is None:
        return tempfile.mkdtemp()
    else:
        if not os.path.exists(rootDir):
            try:
                os.makedirs(rootDir)
            except OSError:
                # Maybe it got created between the test and the makedirs call?
                pass
            
        while True:
            # Keep trying names until we find one that doesn't exist. If one
            # does exist, don't nest inside it, because someone else may be
            # using it for something.
            tmpDir = os.path.join(rootDir, "tmp_" + getRandomAlphaNumericString())
            if not os.path.exists(tmpDir):
                break
                
        os.mkdir(tmpDir)
        os.chmod(tmpDir, 0777) #Ensure everyone has access to the file.
        return tmpDir