Fs adapter stores executed migration in file system.
NOTICE: because of entry file is read and write and it's async operations
parallel execution of write operations (`markExecuted` or `unmarkExecuted`)
could break executed migrations list.
192615
function Adapter(params) {
	this.params = params || {};

	if (!this.params.dir) {
		throw new Error('`dir` parameter required');
	}

	this.migrationsFilePath = (
		this.params.migrationsFile ||
		pathUtils.join(this.params.dir, '.migrations')
	);

	this.dir = __dirname;
}
225395
public void migrateLegacyStorage() {
		try {
			File unencryptedFile = Util.getUnencryptedFilename(file);
			if (unencryptedFile.exists()) {
				try {
					List<MessageEntry> entries = readFromLegacyFile(unencryptedFile);
					messageEntries.addAll(entries);
					writeToFile();
				} finally {
					boolean deleted = unencryptedFile.delete();
					ApptentiveLog.d(CONVERSATION, "Deleted legacy message storage: %b", deleted);
				}
			}
		} catch (Exception e) {
			ApptentiveLog.e(CONVERSATION, e, "Exception while migrating messages");
			logException(e);
		}
	}
1289577
function RedisMulti(instance) {
  
  // The Native Storage Multi for RedisStorage works by replacing the 
  // internal calls to `this.client` with calls to a multi object. This
  // queues the calls instead of executing them immediately.
  
  // Additionally, the exec() method of the multi object has no effect,
  // in case the storage method uses multi internally, it will just reflect
  // as an additional statement being queued in the transaction.
  
  var multi = instance.client.multi();
  
  this.multi = multi;
  this.instance = instance;
  
  // Fake instance, used in place of the original storage instance
  this.fakeInstance = {client: multi}
  
  // Add original exec method
  multi.__exec = multi.exec;
  
  // Replace original multi exec method with empty function
  multi.exec = this.fakeExec;
  
}
419099
protected function migrationsToRun()
    {
        // Get all migration files
        $path = APPDIR.'/src/'.str_replace('\\', '/', $this->migrationNamespace);

        if (! is_dir($path)) {
            return [];
        }

        $dir = new DirectoryIterator($path);

        $migrations = [];
        foreach ($dir as $file) {
            // Ignore directories and dotfiles (e.g. .DS_Store)
            if (! $file->isFile() or substr($file->getBasename(), 0, 1) === '.') {
                continue;
            }

            $class = $this->migrationNamespace.$file->getBasename('.php');

            $migrations[] = new $class;
        }

        $alreadyExecutedMigrations = $this->alreadyExecutedMigrations();

        $migrationsToRun = [];
        foreach ($migrations as $migration) {
            $compare = new ArrayObject([
                'description' => $migration->getDescription(),
                'timestamp'   => $migration->getTimestamp(),
            ]);

            if (in_array($compare, $alreadyExecutedMigrations)) {
                continue;
            }

            $migrationsToRun[] = $migration;
        }

        return $migrationsToRun;
    }
758964
void migrateProfile(Node oldUserNode) throws Exception
   {
      UserProfile userProfile = new UserProfileImpl(oldUserNode.getName());

      Node attrNode = null;
      try
      {
         attrNode = oldUserNode.getNode(JCROrganizationServiceImpl.JOS_PROFILE + "/" + MigrationTool.JOS_ATTRIBUTES);
      }
      catch (PathNotFoundException e)
      {
         return;
      }
      PropertyIterator props = attrNode.getProperties();

      while (props.hasNext())
      {
         Property prop = props.nextProperty();

         // ignore system properties
         if (!(prop.getName()).startsWith("jcr:") && !(prop.getName()).startsWith("exo:")
            && !(prop.getName()).startsWith("jos:"))
         {
            userProfile.setAttribute(prop.getName(), prop.getString());
         }
      }

      if (findUserProfileByName(userProfile.getUserName()) != null)
      {
         removeUserProfile(userProfile.getUserName(), false);
      }

      saveUserProfile(userProfile, false);
   }
581859
void fileWritten() throws ConfigurationPersistenceException {
        if (!doneBootup.get() || interactionPolicy.isReadOnly()) {
            return;
        }
        try {
            FilePersistenceUtils.copyFile(mainFile, lastFile);
        } catch (IOException e) {
            throw ControllerLogger.ROOT_LOGGER.failedToBackup(e, mainFile);
        }
    }
174346
function (data, fragmentKey, cachePath, callback) {
    debug('  write content in file system');
    var basePath =  path.dirname(fragmentKey);
    if (basePath){
      mkdirp.sync(cachePath + '/' + basePath);
    }
    fs.writeFile(cachePath + '/' + fragmentKey, data, function (err) {
      if (err) {
        callback(err);
      } else {
        callback(null, data);
      }
    });
  }
1209684
def write_file_list_cache(opts, data, list_cache, w_lock):
    '''
    
    '''
    serial = salt.payload.Serial(opts)
    with salt.utils.files.fopen(list_cache, 'w+b') as fp_:
        fp_.write(serial.dumps(data))
        _unlock_cache(w_lock)
        log.trace('Lockfile %s removed', w_lock)
1057210
function readEntries (directoryReader, oldEntries, callback) {
  directoryReader.readEntries(
    (entries) => {
      const newEntries = [...oldEntries, ...entries]
      // According to the FileSystem API spec, readEntries() must be called until it calls the callback with an empty array.
      if (entries.length) {
        setTimeout(() => {
          readEntries(directoryReader, newEntries, callback)
        }, 0)
      // Done iterating this particular directory
      } else {
        callback(newEntries)
      }
    },
    // Make sure we resolve on error anyway
    () =>
      callback(oldEntries)
  )
}
878833
void onPartitionMigrate(MigrationInfo migrationInfo) {
        Iterator<WaitSetEntry> it = queue.iterator();
        int partitionId = migrationInfo.getPartitionId();
        while (it.hasNext()) {
            if (Thread.currentThread().isInterrupted()) {
                return;
            }
            WaitSetEntry entry = it.next();
            if (!entry.isValid()) {
                continue;
            }

            Operation op = entry.getOperation();
            if (partitionId == op.getPartitionId()) {
                entry.setValid(false);
                PartitionMigratingException pme = new PartitionMigratingException(nodeEngine.getThisAddress(),
                        partitionId, op.getClass().getName(), op.getServiceName());
                op.sendResponse(pme);
                it.remove();
            }
        }
    }
31575
function migrateAttsAndSeqs(txn, callback) {
    var seqStore = txn.objectStore(BY_SEQ_STORE);
    var attStore = txn.objectStore(ATTACH_STORE);
    var attAndSeqStore = txn.objectStore(ATTACH_AND_SEQ_STORE);

    // need to actually populate the table. this is the expensive part,
    // so as an optimization, check first that this database even
    // contains attachments
    var req = attStore.count();
    req.onsuccess = function (e) {
      var count = e.target.result;
      if (!count) {
        return callback(); // done
      }

      seqStore.openCursor().onsuccess = function (e) {
        var cursor = e.target.result;
        if (!cursor) {
          return callback(); // done
        }
        var doc = cursor.value;
        var seq = cursor.primaryKey;
        var atts = Object.keys(doc._attachments || {});
        var digestMap = {};
        for (var j = 0; j < atts.length; j++) {
          var att = doc._attachments[atts[j]];
          digestMap[att.digest] = true; // uniq digests, just in case
        }
        var digests = Object.keys(digestMap);
        for (j = 0; j < digests.length; j++) {
          var digest = digests[j];
          attAndSeqStore.put({
            seq: seq,
            digestSeq: digest + '::' + seq
          });
        }
        cursor.continue();
      };
    };
  }
966892
function runnerFactory(direction, migrations) {
      // Override the `execute` method for the migration helpers with a version
      // that queues the intended query and immediately moves on. in a migration
      // we want to handle the queries in parallel.
      helpers.execute = function execute(sql, callback) {
        function cb(callback) {
          QueryRunner.expecting--;
          return callback;
        }
        QueryRunner.expecting++;
        return QueryRunner.enqueue([sql, cb(callback)]);
      };

      return function runMigration(version, callback) {
        var key = lookup(version, migrations);

        if (!key) {
          var error = new Error('Could not find migration with the following lookup parameter: ' + _.quote(version));
          error.name = 'MigrationNotFound';
          return callback(error);
        }
        
        migrations[key][direction].bind(helpers)(helpers);
        QueryRunner.flush();
        QueryRunner.once('done', function (err) {
          // #TODO: pass back an error saying
          // - the version of the migration
          // - what went wrong
          // - exactly which query failed?
          if (err) return callback(err);
          var ver = (direction === 'up')
            ? key
            : previous(version, migrations);
          this.updateSchemaVersion(ver, callback);
        }.bind(this));

      };
    }
1238025
function (files, latestMigrationFile) {
        if (direction === 'do') {
            return files
                .sort()
                .filter(function () {
                var _mustBeApplied = (latestMigrationFile === null);
                return function (name) {
                    if (latestMigrationFile === name) {
                        _mustBeApplied = !_mustBeApplied;
                        return false;
                    }
                    return _mustBeApplied;
                };
            }()
            );
        } else {
            return files.sort().reverse().filter(function (name) {
                return latestMigrationFile === name;
            });
        }
    }
653901
function ( noPrune ) {
        removeNotFoundFiles();

        noPrune = typeof noPrune === 'undefined' ? true : noPrune;

        var entries = normalizedEntries;
        var keys = Object.keys( entries );

        if ( keys.length === 0 ) {
          return;
        }

        var me = this;

        keys.forEach( function ( entryName ) {
          var cacheEntry = entries[ entryName ];

          try {
            var meta = useChecksum ? me._getMetaForFileUsingCheckSum( cacheEntry ) : me._getMetaForFileUsingMtimeAndSize( cacheEntry );
            cache.setKey( entryName, meta );
          } catch (err) {
            // if the file does not exists we don't save it
            // other errors are just thrown
            if ( err.code !== 'ENOENT' ) {
              throw err;
            }
          }
        } );

        cache.save( noPrune );
      }
132130
private void writeEntry(HashtableEntry entry)

    throws IOException, EOFException, FileManagerException, ClassNotFoundException {

        long index = getHtindex(entry.index, entry.tableid);
        if (index == 0) { // first one in this bucket
            updateEntry(entry); // write to disk
            writeHashIndex(entry.index, entry.location, entry.tableid); // update index
        } else if (index == entry.location) { // replacing first entry
            updateEntry(entry);
            writeHashIndex(entry.index, entry.location, entry.tableid); // update index
        } else { // 
            //
            // If the entry has a "previous" pointer, then it was read earlier
            // from disk.  Otherwise, it is a brand new entry.  If it is a brand
            // entry, we write it to disk and chain at the front of the bucket.
            // If "previous" is not zero, we check to see if reallocation is
            // needed (location == 0).  If not, we simply update on disk and we're
            // done.  If reallocation is needed we update on disk to do the allocation
            // and call updatePointer to chain into the bucket.
            //
            if (entry.previous == 0) {
                entry.next = index;
                updateEntry(entry);
                writeHashIndex(entry.index, entry.location, entry.tableid); // update index
            } else {
                if (entry.location == 0) { // allocation needed?
                    updateEntry(entry); // do allocation
                    updatePointer(entry.previous, entry.location); // chain in
                } else {
                    updateEntry(entry); // no allocation, just update fields
                }
            }
        }

    }
341137
def rollback_migration(engine, connection, path, migration_to_rollback):
    

    # Get migrations applied
    migrations_applied = get_migrations_applied(engine, connection)

    # Ensure that the migration was previously applied
    if not is_applied(migrations_applied, migration_to_rollback):
        raise RuntimeError(
            '`%s` is not in the list of previously applied migrations.' % (migration_to_rollback))

    # Rollback file
    file = path + migration_to_rollback + '/down.sql'

    # Ensure that the file exists
    check_exists(file)

    # Set vars
    basename = os.path.basename(os.path.dirname(file))

    # Get migration source
    source = get_migration_source(file)
    # print (source);

    # Run migration rollback
    run_migration(connection, source, engine)

    # Delete migration
    delete_migration(connection, basename)

    # Log
    print('   -> Migration `%s` has been rolled back' % (basename))

    return True
1173759
function writeEmittedFiles(emitOutput, jsFilePath, sourceMapFilePath, writeByteOrderMark, sourceFiles) {
                if (compilerOptions.sourceMap && !compilerOptions.inlineSourceMap) {
                    ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap.getText(), /*writeByteOrderMark*/ false, sourceFiles);
                }
                if (sourceMapDataList) {
                    sourceMapDataList.push(sourceMap.getSourceMapData());
                }
                ts.writeFile(host, emitterDiagnostics, jsFilePath, emitOutput, writeByteOrderMark, sourceFiles);
            }