// ensureDir ensures the specified path is a directory, or
// if it does not exist, that a directory can be created there.
779709
func ensureDir(d dirFuncs, path string) error {
	// If path already exists, we check that it is empty.
	// It is up to the storage provisioner to ensure that any
	// shared storage constraints and attachments with the same
	// path are validated etc. So the check here is more a sanity check.
	fi, err := d.lstat(path)
	if err == nil {
		if !fi.IsDir() {
			return errors.Errorf("path %q must be a directory", path)
		}
		return nil
	}
	if !os.IsNotExist(err) {
		return errors.Trace(err)
	}
	if err := d.mkDirAll(path, 0755); err != nil {
		return errors.Annotate(err, "could not create directory")
	}
	return nil
}
820946
func ReplaceDir(fs utilfs.Filesystem, path string, files map[string]string) error {
	// write data to a temporary directory
	tmpPath, err := WriteTempDir(fs, path, files)
	if err != nil {
		return err
	}
	// rename over target directory
	return fs.Rename(tmpPath, path)
}
506817
func IsDir(filePath string) bool {
	fi, err := os.Stat(filePath)
	return err == nil && fi.IsDir()
}
637171
func ValidateDir(dir string) (validationErrors []string, err error) {
	mpath := yamlPath(dir)
	yml, err := ioutil.ReadFile(mpath)
	if err != nil {
		return nil, err
	}

	jbytes, err := yaml.YAMLToJSON(yml)
	if err != nil {
		return nil, errors.Wrap(err, "could not transform YAML to JSON")
	}

	schemaLoader := gojsonschema.NewReferenceLoader("https://choria.io/schemas/choria/machine/v1/manifest.json")
	documentLoader := gojsonschema.NewBytesLoader(jbytes)

	result, err := gojsonschema.Validate(schemaLoader, documentLoader)
	if err != nil {
		return nil, errors.Wrapf(err, "could not perform schema validation")
	}

	if result.Valid() {
		return []string{}, nil
	}

	validationErrors = []string{}
	for _, desc := range result.Errors() {
		validationErrors = append(validationErrors, desc.String())
	}

	return validationErrors, nil
}
352552
func fsRemoveDir(ctx context.Context, dirPath string) (err error) {
	if dirPath == "" {
		logger.LogIf(ctx, errInvalidArgument)
		return errInvalidArgument
	}

	if err = checkPathLength(dirPath); err != nil {
		logger.LogIf(ctx, err)
		return err
	}

	if err = os.Remove((dirPath)); err != nil {
		if os.IsNotExist(err) {
			return errVolumeNotFound
		} else if isSysErrNotEmpty(err) {
			return errVolumeNotEmpty
		}
		logger.LogIf(ctx, err)
		return err
	}

	return nil
}
1167915
func (p *Probe) checkDir(c context.Context, dir string, selfDir os.FileInfo, env environ.Env) string {
	// If we have a self directory defined, ensure that "dir" isn't the same
	// directory. If it is, we will ignore this option, since we are looking for
	// something outside of the wrapper directory.
	if selfDir != nil {
		switch checkDirStat, err := os.Stat(dir); {
		case err == nil:
			// "dir" exists; if it is the same as "selfDir", we can ignore it.
			if os.SameFile(selfDir, checkDirStat) {
				logging.Debugf(c, "Candidate shares wrapper directory [%s]; skipping...", dir)
				return ""
			}

		case os.IsNotExist(err):
			logging.Debugf(c, "Candidate directory does not exist [%s]; skipping...", dir)
			return ""

		default:
			logging.Debugf(c, "Failed to stat candidate directory [%s]: %s", dir, err)
			return ""
		}
	}

	t, err := findInDir(p.Target, dir, env)
	if err != nil {
		return ""
	}

	// Make sure this file isn't the same as "self", if available.
	if p.SelfStat != nil {
		switch st, err := os.Stat(t); {
		case err == nil:
			if os.SameFile(p.SelfStat, st) {
				logging.Debugf(c, "Candidate [%s] is same file as wrapper; skipping...", t)
				return ""
			}

		case os.IsNotExist(err):
			// "t" no longer exists, so we can't use it.
			return ""

		default:
			logging.Debugf(c, "Failed to stat candidate path [%s]: %s", t, err)
			return ""
		}
	}

	if err := filesystem.AbsPath(&t); err != nil {
		logging.Debugf(c, "Failed to normalize candidate path [%s]: %s", t, err)
		return ""
	}

	// Try running the candidate command and confirm that it is not a wrapper.
	if p.CheckWrapper != nil {
		switch isWrapper, err := p.CheckWrapper(c, t, env); {
		case err != nil:
			logging.Debugf(c, "Failed to check if [%s] is a wrapper: %s", t, err)
			return ""

		case isWrapper:
			logging.Debugf(c, "Candidate is a wrapper: %s", t)
			return ""
		}
	}

	return t
}
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()
		}
	}
}
234537
func RevokableChangeDir(dir string) (func() error, error) {
	origDir, err := CurrentWorkingDirectoryAbsolutePath()
	if err != nil {
		return nil, err
	}

	revokeFn := func() error {
		return os.Chdir(origDir)
	}

	return revokeFn, os.Chdir(dir)
}
759032
def _ensureDir(dir_name):
    
    try:
        os.makedirs(dir_name)
    except OSError, why:
        if why.errno != EEXIST or not os.path.isdir(dir_name):
            raise
553267
func ensureEmptyDir(d dirFuncs, path string) error {
	fileCount, err := d.fileCount(path)
	if err != nil {
		return errors.Annotate(err, "could not read directory")
	}
	if fileCount > 0 {
		return errors.Errorf("%q is not empty", path)
	}
	return nil
}
392913
func Ensure(fname string) (err error) {
  if ! checkfile(fname) {
    // does not exist generate file now
    err = Save(fname)
  }
  if err == nil {
    err = Load(fname)
  }
  return
}
534189
func (sam *SAM) EnsureKeyfile(fname string) (keys I2PKeys, err error) {
	if fname == "" {
		// transient
		keys, err = sam.NewKeys()
		if err == nil {
			sam.keys = &keys
		}
	} else {
		// persistant
		_, err = os.Stat(fname)
		if os.IsNotExist(err) {
			// make the keys
			keys, err = sam.NewKeys()
			if err == nil {
				sam.keys = &keys
				// save keys
				var f io.WriteCloser
				f, err = os.OpenFile(fname, os.O_WRONLY|os.O_CREATE, 0600)
				if err == nil {
					err = StoreKeysIncompat(keys, f)
					f.Close()
				}
			}
		} else if err == nil {
			// we haz key file
			var f *os.File
			f, err = os.Open(fname)
			if err == nil {
				keys, err = LoadKeysIncompat(f)
				if err == nil {
					sam.keys = &keys
				}
			}
		}
	}
	return
}
1199109
func (c *ZooKeeperBackend) ensurePath(path string, value []byte) error {
	nodes := strings.Split(path, "/")
	fullPath := ""
	for index, node := range nodes {
		if strings.TrimSpace(node) != "" {
			fullPath += "/" + node
			isLastNode := index+1 == len(nodes)

			// set parent nodes to nil, leaf to value
			// this block reduces round trips by being smart on the leaf create/set
			if exists, _, _ := c.client.Exists(fullPath); !isLastNode && !exists {
				if _, err := c.client.Create(fullPath, nil, int32(0), c.acl); err != nil {
					return err
				}
			} else if isLastNode && !exists {
				if _, err := c.client.Create(fullPath, value, int32(0), c.acl); err != nil {
					return err
				}
			} else if isLastNode && exists {
				if _, err := c.client.Set(fullPath, value, int32(-1)); err != nil {
					return err
				}
			}
		}
	}
	return nil
}
1364787
func EnsureFile(ctx context.Context, fs FileSystem, path string, content io.Reader) error {
	return fs.EnsureFile(ctx, path, func(f *os.File) error {
		_, err := io.Copy(f, content)
		return err
	})
}
1297060
func (c *controller) ensureLease() (*coordv1beta1.Lease, bool, error) {
	lease, err := c.leaseClient.Get(c.holderIdentity, metav1.GetOptions{})
	if apierrors.IsNotFound(err) {
		// lease does not exist, create it
		lease, err := c.leaseClient.Create(c.newLease(nil))
		if err != nil {
			return nil, false, err
		}
		return lease, true, nil
	} else if err != nil {
		// unexpected error getting lease
		return nil, false, err
	}
	// lease already existed
	return lease, false, nil
}
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
}
1108150
func (n *Mounter) MakeDir(pathname string) error {
	args := []string{"-p", pathname}
	if _, err := n.ne.Exec("mkdir", args).CombinedOutput(); err != nil {
		return err
	}
	return nil
}