Test for the directory, open old and new ledger, migrate data, rename directories
502692
def _migrate_ledger(data_directory,
                    old_ledger_file, new_ledger_file,
                    serializer: MappingSerializer = None):
    

    # we should have ChunkedFileStorage implementation of the Ledger
    if not os.path.isdir(os.path.join(data_directory, old_ledger_file)):
        msg = 'Could not find directory {} for migration.'.format(
            old_ledger_file)
        logger.error(msg)
        raise Exception(msg)

    # open the old ledger using the specified serializer
    old_ledger_file_backup = old_ledger_file + "_new"
    old_txn_log_store = ChunkedFileStore(data_directory,
                                         old_ledger_file_backup,
                                         isLineNoKey=True,
                                         storeContentHash=False)
    old_ledger = Ledger(CompactMerkleTree(),
                        dataDir=data_directory,
                        txn_serializer=serializer,
                        hash_serializer=serializer,
                        fileName=old_ledger_file_backup,
                        transactionLogStore=old_txn_log_store)

    # open the new ledger with new serialization
    new_ledger = Ledger(CompactMerkleTree(),
                        dataDir=data_directory,
                        fileName=new_ledger_file)
    logger.info("new size for {}: {}".format(
        old_ledger_file_backup, str(new_ledger.size)))

    # add all txns into the old ledger
    for _, txn in new_ledger.getAllTxn():
        old_ledger.add(txn)
    logger.info("old size for {}: {}".format(
        new_ledger_file, str(old_ledger.size)))

    old_ledger.stop()
    new_ledger.stop()

    # now that everything succeeded, remove the new files and move the old
    # files into place
    shutil.rmtree(
        os.path.join(data_directory, new_ledger_file))
    os.rename(
        os.path.join(data_directory, old_ledger_file_backup),
        os.path.join(data_directory, old_ledger_file))
16495
def migrate_paths(opts):
    '''
    
    '''
    oldpki_dir = os.path.join(syspaths.CONFIG_DIR, 'pki')

    if not os.path.exists(oldpki_dir):
        # There's not even a pki directory, don't bother migrating
        return

    newpki_dir = opts['pki_dir']

    if opts['default_include'].startswith('master'):
        keepers = ['master.pem',
                   'master.pub',
                   'syndic_master.pub',
                   'minions',
                   'minions_pre',
                   'minions_rejected',
                   ]
        if not os.path.exists(newpki_dir):
            os.makedirs(newpki_dir)
        for item in keepers:
            oi_path = os.path.join(oldpki_dir, item)
            ni_path = os.path.join(newpki_dir, item)
            if os.path.exists(oi_path) and not os.path.exists(ni_path):
                shutil.move(oi_path, ni_path)

    if opts['default_include'].startswith('minion'):
        keepers = ['minion_master.pub',
                   'minion.pem',
                   'minion.pub',
                   ]
        if not os.path.exists(newpki_dir):
            os.makedirs(newpki_dir)
        for item in keepers:
            oi_path = os.path.join(oldpki_dir, item)
            ni_path = os.path.join(newpki_dir, item)
            if os.path.exists(oi_path) and not os.path.exists(ni_path):
                shutil.move(oi_path, ni_path)
249356
public static void rename(FileSystem fs, String oldName, String newName)
    throws IOException {
    Path oldDir = new Path(oldName);
    Path newDir = new Path(newName);
    if (!fs.rename(oldDir, newDir)) {
      throw new IOException("Could not rename " + oldDir + " to " + newDir);
    }
  }
471763
function createDirectory(options) {
  return new Promise(function(resolve, reject) {
    mkdirp( options.directory, function (err) {
      if(err && err.code !== 'EEXIST') {
        reject(err);
      } else {
        resolve(options);
      }
    });
  });
}
1282090
async def refresh_pool_ledger(handle: int) -> None:
    

    logger = logging.getLogger(__name__)
    logger.debug("refresh_pool_ledger: >>> config_name: %r",
                 handle)

    if not hasattr(refresh_pool_ledger, "cb"):
        logger.debug("refresh_pool_ledger: Creating callback")
        refresh_pool_ledger.cb = create_cb(CFUNCTYPE(None, c_int32, c_int32))

    c_handle = c_int32(handle)

    res = await do_call('indy_refresh_pool_ledger',
                        c_handle,
                        refresh_pool_ledger.cb)

    logger.debug("refresh_pool_ledger: <<< res: %r", res)
    return res
767961
function refresh (env) {
    return safeWipe(env.dest, {
      force: true,
      parent: is.string(env.src) || is.array(env.src) ? g2b(env.src) : null,
      silent: true,
    })
      .then(() => mkdir(env.dest))
      .then(() => {
        env.logger.log(`Folder \`${env.displayDest}\` successfully refreshed.`)
      })
      .catch(err => {
        // Friendly error for already existing directory.
        throw new errors.SassDocError(err.message)
      })
  }
510316
function renameFiles(files)
{
  files.forEach(function (file)
  {
    var originalName = path.basename(file);
    var newFileName = originalName.toLowerCase();
    var directory = path.dirname(file);
    if (originalName != newFileName)
    {
      fs.renameSync(file, directory + "/" + newFileName); //, function(err)

      if (debug)
        console.log('Renamed: %s --> %s', originalName, newFileName);

      originalFiles.push(originalName);
      renamedFiles.push(newFileName);
    }
  });
}
806146
function(sourceDir, newDirLocation, opts) {

        if (!opts || !opts.preserve) {
            try {
                if(fs.statSync(newDirLocation).isDirectory()) {
                    exports.rmdirSyncRecursive(newDirLocation);
                }
            }
            catch(e) { }
        }

        /*  Create the directory where all our junk is moving to; read the mode of the source directory and mirror it */
        var checkDir = fs.statSync(sourceDir);
        try {
            fs.mkdirSync(newDirLocation, checkDir.mode);
        }
        catch (e) {
            //if the directory already exists, that's okay
            if (e.code !== 'EEXIST') {
                throw e;
            }
        }

        var files = fs.readdirSync(sourceDir);

        for(var i = 0; i < files.length; i++) {
            var currFile = fs.lstatSync(sourceDir + "/" + files[i]);

            if(currFile.isDirectory()) {
                /*  recursion this thing right on back. */
                copyDirectoryRecursiveSync(sourceDir + "/" + files[i], newDirLocation + "/" + files[i], opts);
            }
            else if(currFile.isSymbolicLink()) {
                var symlinkFull = fs.readlinkSync(sourceDir + "/" + files[i]);
                fs.symlinkSync(symlinkFull, newDirLocation + "/" + files[i]);
            }
            else {
                /*  At this point, we've hit a file actually worth copying... so copy it on over. */
                var contents = fs.readFileSync(sourceDir + "/" + files[i]);
                fs.writeFileSync(newDirLocation + "/" + files[i], contents);
            }
        }
    }
1035857
def refresh(self, new_path=None, force_current=False):
        """"""
        if new_path is None:
            new_path = getcwd_or_home()
        if force_current:
            index = self.set_current_folder(new_path)
            self.expand(index)
            self.setCurrentIndex(index)
        self.set_previous_enabled.emit(
                             self.histindex is not None and self.histindex > 0)
        self.set_next_enabled.emit(self.histindex is not None and \
                                   self.histindex < len(self.history)-1)
        # Disable the view of .spyproject. 
        self.filter_directories()
681385
def change_directory(self, path, *args, **kwargs):
		
		client = self.dav_client()
		previous_path = self.session_path()
		try:
			if client.is_dir(self.session_path(path)) is False:
				raise ValueError('Unable to change current working directory to non-directory entry')
		except Exception:
			self.session_path(previous_path)
			raise
79627
function createConfigurationDirectory()
    {
        $this->files->ensureDirExists(preg_replace('~/valet$~', '', VALET_HOME_PATH), user());

        $oldPath = posix_getpwuid(fileowner(__FILE__))['dir'].'/.valet';

        if ($this->files->isDir($oldPath)) {
            rename($oldPath, VALET_HOME_PATH);
            $this->prependPath(VALET_HOME_PATH.'/Sites');
        }

        $this->files->ensureDirExists(VALET_HOME_PATH, user());
    }
1043958
def rename_gallery_folder(self, old_folder_name, new_folder_name, scope='content/write'):
        
        return _put(
            token=self.oauth.get_user_token(scope),
            uri='/user/media/' + urllib.quote(old_folder_name),
            data=new_folder_name
        )
831501
def refresh_db(root=None):
    '''
    
    '''
    # Remove rtag file to keep multiple refreshes from happening in pkg states
    salt.utils.pkg.clear_rtag(__opts__)
    ret = {}
    out = __zypper__(root=root).refreshable.call('refresh', '--force')

    for line in out.splitlines():
        if not line:
            continue
        if line.strip().startswith('Repository') and '\'' in line:
            try:
                key = line.split('\'')[1].strip()
                if 'is up to date' in line:
                    ret[key] = False
            except IndexError:
                continue
        elif line.strip().startswith('Building') and '\'' in line:
            key = line.split('\'')[1].strip()
            if 'done' in line:
                ret[key] = True
    return ret
855115
async function archiveWorkingDir(dirPath, archive) {
  // recursively collect all entries (files and directories)
  const allEntries = await collectFSEntries(dirPath, []);

  const process = (entry, cb) => {
    const p = relativePaths(dirPath, entry.path);
    if (p.length) {
      if (entry.stats.isDirectory()) {
        archive.append(null, { name: `${p}/` });
      } else {
        archive.append(fse.createReadStream(entry.path), { name: p });
      }
    }
    cb();
  };

  return new Promise((resolve, reject) => {
    async.eachSeries(
      allEntries,
      process,
      (err) => {
        if (err) {
          reject(err);
        } else {
          resolve(archive);
        }
      },
    );
  });
}
1350847
def rename_file(self, old_save_name, new_save_name, new_path):
        
        if old_save_name in self._files:
            del self._files[old_save_name]
        self.update_file(new_save_name, new_path)
1215581
def rename(src, dst):
    '''
    
    '''
    src = os.path.expanduser(src)
    dst = os.path.expanduser(dst)

    if not os.path.isabs(src):
        raise SaltInvocationError('File path must be absolute.')

    try:
        os.rename(src, dst)
        return True
    except OSError:
        raise CommandExecutionError(
            'Could not rename \'{0}\' to \'{1}\''.format(src, dst)
        )
    return False
650017
def cleanup(test_data, udfs, tmp_data, tmp_db):
    """"""
    con = make_ibis_client(ENV)

    if udfs:
        # this comes before test_data bc the latter clobbers this too
        con.hdfs.rmdir(os.path.join(ENV.test_data_dir, 'udf'))

    if test_data:
        con.drop_database(ENV.test_data_db, force=True)
        con.hdfs.rmdir(ENV.test_data_dir)

    if tmp_data:
        con.hdfs.rmdir(ENV.tmp_dir)

    if tmp_db:
        con.drop_database(ENV.tmp_db, force=True)