// deleteDirOnDisk attempts to delete a directory. It checks for files/dirs inside
// the directory and removes them if possible or returns an error if it fails
779919
func (f *sendReceiveFolder) deleteDirOnDisk(dir string, scanChan chan<- string) error {
	files, _ := f.fs.DirNames(dir)

	toBeDeleted := make([]string, 0, len(files))

	hasIgnored := false
	hasKnown := false
	hasToBeScanned := false

	for _, dirFile := range files {
		fullDirFile := filepath.Join(dir, dirFile)
		if fs.IsTemporary(dirFile) || f.ignores.Match(fullDirFile).IsDeletable() {
			toBeDeleted = append(toBeDeleted, fullDirFile)
		} else if f.ignores != nil && f.ignores.Match(fullDirFile).IsIgnored() {
			hasIgnored = true
		} else if cf, ok := f.fset.Get(protocol.LocalDeviceID, fullDirFile); !ok || cf.IsDeleted() || cf.IsInvalid() {
			// Something appeared in the dir that we either are not aware of
			// at all, that we think should be deleted or that is invalid,
			// but not currently ignored -> schedule scan. The scanChan
			// might be nil, in which case we trust the scanning to be
			// handled later as a result of our error return.
			if scanChan != nil {
				scanChan <- fullDirFile
			}
			hasToBeScanned = true
		} else {
			// Dir contains file that is valid according to db and
			// not ignored -> something weird is going on
			hasKnown = true
		}
	}

	if hasToBeScanned {
		return errDirHasToBeScanned
	}
	if hasIgnored {
		return errDirHasIgnored
	}
	if hasKnown {
		return errDirNotEmpty
	}

	for _, del := range toBeDeleted {
		f.fs.RemoveAll(del)
	}

	err := osutil.InWritableDir(f.fs.Remove, f.fs, dir)
	if err == nil || fs.IsNotExist(err) {
		// It was removed or it doesn't exist to start with
		return nil
	}
	if _, serr := f.fs.Lstat(dir); serr != nil && !fs.IsPermission(serr) {
		// We get an error just looking at the directory, and it's not a
		// permission problem. Lets assume the error is in fact some variant
		// of "file does not exist" (possibly expressed as some parent being a
		// file and not a directory etc) and that the delete is handled.
		return nil
	}

	return err
}
1182512
func (oc *openContext) returnDirNoCleanup(f dokan.File) (
	dokan.File, dokan.CreateStatus, error) {
	if err := oc.ReturningDirAllowed(); err != nil {
		return nil, 0, err
	}
	return f, dokan.ExistingDir, nil
}
658569
func (etcdClient *SimpleEtcdClient) DelDir(key string) error {
	api := client.NewKeysAPI(etcdClient.etcd)
	_, err := api.Delete(context.Background(), key, &client.DeleteOptions{Dir: true, Recursive: true})
	if err != nil {
		if client.IsKeyNotFound(err) {
			return nil
		}
	}
	return err
}
509921
func (fs *fakeFs) MkdirAll(path string, perm os.FileMode) error {
	return fs.a.Fs.MkdirAll(path, perm)
}
256501
func (c oauthClient) DeleteFolder(folder wl.Folder) error {
	url := fmt.Sprintf(
		"%s/folders/%d?revision=%d",
		c.apiURL,
		folder.ID,
		folder.Revision,
	)

	req, err := c.newDeleteRequest(url)
	if err != nil {
		return err
	}

	resp, err := c.do(req)
	if err != nil {
		return err
	}

	if resp.StatusCode != http.StatusNoContent {
		return fmt.Errorf("Unexpected response code %d - expected %d", resp.StatusCode, http.StatusNoContent)
	}

	return nil
}
1085196
func (fbo *folderBlockOps) getDirtyDirUnrefsLocked(
	lState *kbfssync.LockState, ptr data.BlockPointer) []data.BlockInfo {
	fbo.blockLock.AssertRLocked(lState)
	return fbo.dirtyDirs[ptr]
}
212442
func (s *DiskOfferingService) NewDeleteDiskOfferingParams(id string) *DeleteDiskOfferingParams {
	p := &DeleteDiskOfferingParams{}
	p.p = make(map[string]interface{})
	p.p["id"] = id
	return p
}
317108
func (client *Client) DeleteLoadBalancer(loadBalancerId string) (err error) {
	args := &DeleteLoadBalancerArgs{
		LoadBalancerId: loadBalancerId,
	}
	response := &DeleteLoadBalancerResponse{}
	err = client.Invoke("DeleteLoadBalancer", args, response)
	return err
}
613651
func (f *sendReceiveFolder) deleteDir(file protocol.FileInfo, dbUpdateChan chan<- dbUpdateJob, scanChan chan<- string) {
	// Used in the defer closure below, updated by the function body. Take
	// care not declare another err.
	var err error

	events.Default.Log(events.ItemStarted, map[string]string{
		"folder": f.folderID,
		"item":   file.Name,
		"type":   "dir",
		"action": "delete",
	})

	defer func() {
		events.Default.Log(events.ItemFinished, map[string]interface{}{
			"folder": f.folderID,
			"item":   file.Name,
			"error":  events.Error(err),
			"type":   "dir",
			"action": "delete",
		})
	}()

	if err = f.deleteDirOnDisk(file.Name, scanChan); err != nil {
		f.newPullError(file.Name, errors.Wrap(err, "delete dir"))
		return
	}

	dbUpdateChan <- dbUpdateJob{file, dbUpdateDeleteDir}
}
1317784
func (nm DatastoreNamespaceManager) DeleteDirectory(ctx context.Context, dc *Datacenter, datastorePath string) error {

	req := &types.DeleteDirectory{
		This:          nm.Reference(),
		DatastorePath: datastorePath,
	}

	if dc != nil {
		ref := dc.Reference()
		req.Datacenter = &ref
	}

	if _, err := methods.DeleteDirectory(ctx, nm.c, req); err != nil {
		return err
	}

	return nil
}
1171569
func MkdirForFile(path string) error {
	return os.MkdirAll(filepath.Dir(path), DefaultDirectoryPermissions)
}
743248
func decodeDir(data []byte, isRoot bool) (*dir, error) {
	data = bytes.TrimSpace(data)
	if len(data) == 0 {
		return nil, io.EOF
	}

	// get the name of the dir and remove it from the data.  In case the
	// there is no name and isRoot is true, just use "" as the name.
	var name string
	switch end := bytes.IndexRune(data, dirStartMark); end {
	case -1:
		return nil, fmt.Errorf("%c not found", dirStartMark)
	case 0:
		if isRoot {
			name = ""
		} else {
			return nil, fmt.Errorf("inner unnamed dirs not allowed: %s", data)
		}
	default:
		name = string(data[0:end])
		data = data[end:]
	}

	// check data ends with the dirEndMark
	if data[len(data)-1] != dirEndMark {
		return nil, fmt.Errorf("malformed data: last %q not found",
			dirEndMark)
	}
	data = data[1 : len(data)-1] // remove initial '(' and last ')'

	children, err := decodeChildren(data)
	if err != nil {
		return nil, err
	}

	return newDir(name, children)
}
902721
func (util *RBDUtil) DetachBlockDisk(disk rbdDiskUnmapper, mapPath string) error {

	if pathExists, pathErr := mount.PathExists(mapPath); pathErr != nil {
		return fmt.Errorf("Error checking if path exists: %v", pathErr)
	} else if !pathExists {
		klog.Warningf("Warning: Unmap skipped because path does not exist: %v", mapPath)
		return nil
	}
	// If we arrive here, device is no longer used, see if we need to logout of the target
	device, err := getBlockVolumeDevice(mapPath)
	if err != nil {
		return err
	}

	if len(device) == 0 {
		return fmt.Errorf("DetachDisk failed , device is empty")
	}

	exec := disk.plugin.host.GetExec(disk.plugin.GetPluginName())

	var rbdCmd string

	// Unlike map, we cannot fallthrough here.
	// Any nbd device must be unmapped by rbd-nbd
	if strings.HasPrefix(device, "/dev/nbd") {
		rbdCmd = "rbd-nbd"
		klog.V(4).Infof("rbd: using rbd-nbd for unmap function")
	} else {
		rbdCmd = "rbd"
		klog.V(4).Infof("rbd: using rbd for unmap function")
	}

	// rbd unmap
	output, err := exec.Run(rbdCmd, "unmap", device)
	if err != nil {
		return rbdErrors(err, fmt.Errorf("rbd: failed to unmap device %s, error %v, rbd output: %s", device, err, string(output)))
	}
	klog.V(3).Infof("rbd: successfully unmap device %s", device)

	return nil
}
53269
func (util *RBDUtil) cleanOldRBDFile(plugin *rbdPlugin, rbdFile string) error {
	mounter := &rbdMounter{
		// util.rbdUnlock needs it to run command.
		rbd: newRBD("", "", "", "", false, plugin, util),
	}
	fp, err := os.Open(rbdFile)
	if err != nil {
		return fmt.Errorf("rbd: open err %s/%s", rbdFile, err)
	}
	defer fp.Close()

	decoder := json.NewDecoder(fp)
	if err = decoder.Decode(mounter); err != nil {
		return fmt.Errorf("rbd: decode err: %v.", err)
	}

	if err != nil {
		klog.Errorf("failed to load rbd info from %s: %v", rbdFile, err)
		return err
	}
	// Remove rbd lock if found.
	// The disk is not attached to this node anymore, so the lock on image
	// for this node can be removed safely.
	err = util.rbdUnlock(*mounter)
	if err == nil {
		os.Remove(rbdFile)
	}
	return err
}
1010808
func WriteIntelRdtTasks(dir string, pid int) error {
	if dir == "" {
		return fmt.Errorf("no such directory for %s", IntelRdtTasks)
	}

	// Don't attach any pid if -1 is specified as a pid
	if pid != -1 {
		if err := ioutil.WriteFile(filepath.Join(dir, IntelRdtTasks), []byte(strconv.Itoa(pid)), 0700); err != nil {
			return fmt.Errorf("failed to write %v to %v: %v", pid, IntelRdtTasks, err)
		}
	}
	return nil
}
1019890
func (fs *FS) MkdirAll(filename string, perm os.FileMode) (err error) {
	fs.log.CDebugf(fs.ctx, "MkdirAll %s", filename)
	defer func() {
		fs.deferLog.CDebugf(fs.ctx, "MkdirAll done: %+v", err)
	}()

	if err := fs.requireNonEmpty(); err != nil {
		return err
	}

	return fs.mkdirAll(filename, perm)
}
1303924
func (d Dir) RemoveAll(name string) error {
	if name = d.resolve(name); name == "" {
		return os.ErrNotExist
	}

	if name == filepath.Clean(string(d)) {
		// Prohibit removing the virtual root directory.
		return os.ErrInvalid
	}
	return os.RemoveAll(name)
}