// EnsureDir ensures that a directory exists at `path`, and if it must create the directory any
// necessary parent directories will also be created and the new directory will be empty.
968399
func EnsureDir(fs utilfs.Filesystem, path string) error {
	// if dir exists, don't change it, but do report any unexpected errors
	if ok, err := DirExists(fs, path); ok || err != nil {
		return err
	} // Assert: dir does not exist

	// create the dir
	return fs.MkdirAll(path, defaultPerm)
}
942071
func (u *Untar) recursivelyCreateDir(dir string) error {
	// process the uid/gid ownership
	uid := u.MappedUserID
	gid := u.MappedGroupID
	if u.PreserveOwners {
		var err error
		if uid, err = u.OwnerMappingFunc(uid); err != nil {
			return fmt.Errorf("failed to map UID for file: %v", err)
		}
		if gid, err = u.GroupMappingFunc(gid); err != nil {
			return fmt.Errorf("failed to map GID for file: %v", err)
		}
	}

	abs := filepath.IsAbs(dir)
	parts := strings.Split(dir, string(os.PathSeparator))
	if abs {
		parts = parts[1:]
	}

	for i := range parts {
		p := filepath.Join(parts[:i+1]...)
		if abs {
			p = string(os.PathSeparator) + p
		}

		if err := os.Mkdir(p, os.FileMode(0755)); err != nil {
			if os.IsExist(err) {
				continue
			}
			return err
		}
		// We don't error check on chown incase the process is
		// unprivledged. Additionally, only chown when we actually created it.
		os.Chown(p, uid, gid)
	}
	return nil
}
781455
func InDir(path string) func(*icmd.Cmd) func() {
	return func(cmd *icmd.Cmd) func() {
		cmd.Dir = path
		return nil
	}
}
1250213
func (c *Client) EnsureVMFolder(ctx context.Context, folderPath string) (*object.Folder, error) {
	finder, datacenter, err := c.finder(ctx)
	if err != nil {
		return nil, errors.Trace(err)
	}
	folders, err := datacenter.Folders(ctx)
	if err != nil {
		return nil, errors.Trace(err)
	}

	createFolder := func(parent *object.Folder, name string) (*object.Folder, error) {
		folder, err := parent.CreateFolder(ctx, name)
		if err != nil && soap.IsSoapFault(err) {
			switch soap.ToSoapFault(err).VimFault().(type) {
			case types.DuplicateName:
				return finder.Folder(ctx, parent.InventoryPath+"/"+name)
			}
		}
		return folder, err
	}

	parentFolder := folders.VmFolder
	for _, name := range strings.Split(folderPath, "/") {
		folder, err := createFolder(parentFolder, name)
		if err != nil {
			return nil, errors.Annotatef(
				err, "creating folder %q in %q",
				name, parentFolder.InventoryPath,
			)
		}
		parentFolder = folder
	}
	return parentFolder, nil
}
641078
func (c *V1) EnsureInit() error {
	c.initOnce.Do(c.init)
	return c.aclCheckerInitErr
}
554
func EnsureDir(dir string, mode os.FileMode) error {
	if fileOptions, err := os.Stat(dir); os.IsNotExist(err) {
		if errMake := os.MkdirAll(dir, mode); errMake != nil {
			return fmt.Errorf("Could not create directory %s. %v", dir, err)
		}
	} else if err != nil {
		return fmt.Errorf("Error asserting directory %s: %v", dir, err)
	} else if !fileOptions.IsDir() {
		return fmt.Errorf("Path already exists as a file: %s", dir)
	}
	return nil
}
733859
func IsDir(path string) bool {
	f, err := os.Open(path)
	if err != nil {
		return false
	}
	defer func() {
		errutil.Trace(f.Close())
	}()

	fi, err := f.Stat()
	if err != nil {
		return false
	}

	return fi.Mode().IsDir()
}
693374
func EnsurePath(path string, dir bool) error {
	if !dir {
		path = filepath.Dir(path)
	}
	return os.MkdirAll(path, 0755)
}
973504
func IsEmptyDir(path string) (bool, error) {
	empty := true
	if err := filepath.Walk(path, func(fp string, fi os.FileInfo, ferr error) error {
		if ferr != nil {
			return ferr
		}
		if fi.IsDir() && (fi.Name() == "." || fi.Name() == "..") {
			return filepath.SkipDir
		}
		if fi.Mode().IsRegular() {
			empty = false
		}
		return nil
	}); err != nil {
		return false, err
	}
	return empty, nil
}
437608
func ensureShared(path string, mountInfos []*dockermounts.Info) error {
	sourceMount, optionalOpts, err := getSourceMount(path, mountInfos)
	if err != nil {
		return err
	}

	// Make sure source mount point is shared.
	optsSplit := strings.Split(optionalOpts, " ")
	for _, opt := range optsSplit {
		if strings.HasPrefix(opt, "shared:") {
			return nil
		}
	}

	return fmt.Errorf("path %q is mounted on %q but it is not a shared mount", path, sourceMount)
}
253927
func preCreateDirs(rootfs string) error {
	dirs := []string{
		"proc",
		"sys",
		"dev",
		"lib/modules",
	}
	for _, dir := range dirs {
		err := createIfNotExists(filepath.Join(rootfs, dir), true)
		if err != nil {
			return err
		}
	}
	return nil
}
289940
func Ensure(path, key, home string) (*Config, error) {
	c := New()

	if err := c.EnsurePaths(path); err != nil {
		return c, err
	}

	_, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL, 0600)
	if err != nil {
		return c, err
	}

	home, err = filepath.Abs(home)

	c.PID = string(os.Getpid())
	c.File = path
	c.Home = home
	c.HostKey = random.Hex(20)

	if key != "" {
		c.HostKey = key
	}

	if err := c.Write(); err != nil {
		return c, err
	}

	return c, nil
}
95600
func (s *CpusetGroup) ensureParent(current, root string) error {
	parent := filepath.Dir(current)
	if libcontainerUtils.CleanPath(parent) == root {
		return nil
	}
	// Avoid infinite recursion.
	if parent == current {
		return fmt.Errorf("cpuset: cgroup parent path outside cgroup root")
	}
	if err := s.ensureParent(parent, root); err != nil {
		return err
	}
	if err := os.MkdirAll(current, 0755); err != nil {
		return err
	}
	return s.copyIfNeeded(current, parent)
}
844933
func (d *S3Driver) ChangeDir(path string) bool {
	// resp, err := d.s3DirContents(path, 1, "")

	if strings.HasPrefix(path, "/") {
		d.WorkingDirectory = strings.TrimPrefix(path, "/")
	} else {
		if strings.HasSuffix(d.WorkingDirectory, "/") {
			d.WorkingDirectory = d.WorkingDirectory + path
		} else {
			d.WorkingDirectory = d.WorkingDirectory + "/" + path
		}
	}

	fmt.Println("PWD:", d.WorkingDirectory)
	return true

	//
	// if err == nil && len(resp.Contents) > 0 {
	// 	d.WorkingDirectory = strings.TrimPrefix(path, "/")
	// 	return true
	// } else {
	// 	return false
	// }
}
1115861
func IsDir(path string) bool {
	finfo, err := os.Stat(path)
	switch {
	case err != nil:
		return false
	case finfo.IsDir():
		return true
	default:
		return false
	}
}
831536
func IsSourceDir(dir string) bool {
	if _, err := os.Stat(dir); err == nil {
		return true
	}
	return false
}
209224
func (e *Env) ensure(c context.Context, blocking bool) (err error) {
	// Fastest path: If this environment is already complete, then there is no
	// additional setup necessary.
	if err := e.AssertCompleteAndLoad(); err == nil {
		logging.Debugf(c, "Environment is already initialized: %s", e.Environment)
		return nil
	}

	// Repeatedly try and create our Env. We do this so that if we
	// encounter a lock, we will let the other process finish and try and leverage
	// its success.
	for {
		// We will be creating the Env. Acquire an exclusive lock so that any other
		// processes will wait for our setup to complete.
		switch lock, err := e.acquireExclusiveLock(); err {
		case nil:
			// We MUST successfully release our exclusive lock on completion.
			return mustReleaseLock(c, lock, func() error {
				// Fast path: if our complete flag is present, assume that the
				// environment is setup and complete. No additional work is necessary.
				err := e.AssertCompleteAndLoad()
				if err == nil {
					// This will generally happen if another process created the environment
					// in between when we checked for the completion stamp initially and
					// when we actually obtained the lock.
					logging.Debugf(c, "Completion flag found! Environment is set-up: %s", e.completeFlagPath)
					return nil
				}
				logging.WithError(err).Debugf(c, "VirtualEnv is not complete.")

				// No complete flag. Create a new VirtualEnv here.
				if err := e.createLocked(c); err != nil {
					return errors.Annotate(err, "failed to create new VirtualEnv").Err()
				}

				// Mark that this environment is complete. This MUST succeed so other
				// instances know that this environment is complete.
				if err := e.touchCompleteFlagLocked(); err != nil {
					return errors.Annotate(err, "failed to create complete flag").Err()
				}

				logging.Debugf(c, "Successfully created new virtual environment [%s]!", e.Name)
				return nil
			})

		case fslock.ErrLockHeld:
			// We couldn't get an exclusive lock. Try again to load the environment
			// stamp, asserting the existence of the completion flag in the process.
			// If another process has created the environment, we may be able to use
			// it without ever having to obtain its lock!
			if err := e.AssertCompleteAndLoad(); err == nil {
				logging.Infof(c, "Environment was completed while waiting for lock: %s", e.EnvironmentStampPath)
				return nil
			}

			logging.Fields{
				logging.ErrorKey: err,
				"path":           e.EnvironmentStampPath,
			}.Debugf(c, "Lock is held, and environment is not complete.")
			if !blocking {
				return errors.Annotate(err, "VirtualEnv lock is currently held (non-blocking)").Err()
			}

			// Some other process holds the lock. Sleep a little and retry.
			if err := blocker(c)(); err != nil {
				return err
			}

		default:
			return errors.Annotate(err, "failed to ensure VirtualEnv").Err()
		}
	}
}