Finds best matching target migration file
184487
def find_target_migration_file(database=DEFAULT_DB_ALIAS, changelog_file=None):
    """"""

    if not database:
        database = DEFAULT_DB_ALIAS

    if not changelog_file:
        changelog_file = get_changelog_file_for_database(database)

    try:
        doc = minidom.parse(changelog_file)
    except ExpatError as ex:
        raise InvalidChangelogFile(
                'Could not parse XML file %s: %s' % (changelog_file, ex))

    try:
        dbchglog = doc.getElementsByTagName('databaseChangeLog')[0]
    except IndexError:
        raise InvalidChangelogFile(
            'Missing <databaseChangeLog> node in file %s' % (
                                                    changelog_file))
    else:
        nodes = list(filter(lambda x: x.nodeType is x.ELEMENT_NODE,
                            dbchglog.childNodes))
        if not nodes:
            return changelog_file

        last_node = nodes[-1]

        if last_node.tagName == 'include':
            last_file = last_node.attributes.get('file').firstChild.data
            return find_target_migration_file(
                    database=database, changelog_file=last_file)
        else:
            return changelog_file
881401
def matchingfiles(self, projectpath):
        """"""
        l = []
        for inputtemplate in self.input:
            l += inputtemplate.matchingfiles(projectpath)
        return l
1254820
def migrate(ctx, start_version, end_version):
    """"""
    if ctx.type == 'file':
        if ctx.data_file:
            file_path = ctx.data_file
        else:
            file_path = os.path.join(ctx.data_file, ctx.namespace + '.json')

        # todo make this more like alemebic and determine/load versions automatically
        with open(file_path, 'r') as f:
            data = json.loads(f.read())

        data = run_migration(data, start_version, end_version)
        with open(file_path, 'w') as f:
            f.write(json.dumps(data))
1155448
def howToMigrate(self, fromVersion, toVersion=None):
        
        # slice notation [start:end:step]
        # by adding a step of 1 we make a slice from 0:0 be empty
        # rather than containing the whole list.
        if toVersion is not None:
            return self.migrations[fromVersion:toVersion:1]
        else:
            return self.migrations[fromVersion::1]
1091251
protected function getNewMigrations()
    {
        $applied = [];
        foreach ($this->getMigrationHistory(null) as $class => $time) {
            $applied[trim($class, '\\')] = true;
        }

        $migrationPaths = [];
        if (is_array($this->migrationPath)) {
            foreach ($this->migrationPath as $path) {
                $migrationPaths[] = [$path, ''];
            }
        } elseif (!empty($this->migrationPath)) {
            $migrationPaths[] = [$this->migrationPath, ''];
        }
        foreach ($this->migrationNamespaces as $namespace) {
            $migrationPaths[] = [$this->getNamespacePath($namespace), $namespace];
        }

        $migrations = [];
        foreach ($migrationPaths as $item) {
            [$migrationPath, $namespace] = $item;
            if (!file_exists($migrationPath)) {
                continue;
            }
            $handle = opendir($migrationPath);
            while (($file = readdir($handle)) !== false) {
                if ($file === '.' || $file === '..') {
                    continue;
                }
                $path = $migrationPath . DIRECTORY_SEPARATOR . $file;
                if (preg_match('/^(m(\d{6}_?\d{6})\D.*?)\.php$/is', $file, $matches) && is_file($path)) {
                    $class = $matches[1];
                    if (!empty($namespace)) {
                        $class = $namespace . '\\' . $class;
                    }
                    $time = str_replace('_', '', $matches[2]);
                    if (!isset($applied[$class])) {
                        $migrations[$time . '\\' . $class] = $class;
                    }
                }
            }
            closedir($handle);
        }
        ksort($migrations);

        return array_values($migrations);
    }
470961
function migrations(direction, lastMigrationNum, migrateTo) {
		var isDirectionUp = direction === 'up',
			hasMigrateTo = !!migrateTo,
			migrateToNum = hasMigrateTo ? parseInt(migrateTo, 10) : undefined,
			migrateToFound = !hasMigrateTo;

		var migrationsToRun = fs.readdirSync('migrations')
			.filter(function (file) {
				var formatCorrect = file.match(/^\d+.*\.js$/),
					migrationNum = formatCorrect && parseInt(file.match(/^\d+/)[0], 10),
					isRunnable = formatCorrect && isDirectionUp ? migrationNum > lastMigrationNum : migrationNum <= lastMigrationNum,
					isFile = fs.statSync(path.join('migrations', file)).isFile();

				if (isFile && !formatCorrect) {
					console.log('"' + file + '" ignored. Does not match migration naming schema');
				}

				return formatCorrect && isRunnable && isFile;
			}).sort(function (a, b) {
				var aMigrationNum = parseInt(a.match(/^\d+/)[0], 10),
						bMigrationNum = parseInt(b.match(/^\d+/)[0], 10);

				if (aMigrationNum > bMigrationNum) {
					return isDirectionUp ? 1 : -1;
				}
				if (aMigrationNum < bMigrationNum) {
					return isDirectionUp ? -1 : 1;
				}

				return 0;
			}).filter(function(file){
				var formatCorrect = file.match(/^\d+.*\.js$/),
					migrationNum = formatCorrect && parseInt(file.match(/^\d+/)[0], 10),
					isRunnable = formatCorrect && isDirectionUp ? migrationNum > lastMigrationNum : migrationNum <= lastMigrationNum;

				if (hasMigrateTo) {
					if (migrateToNum === migrationNum) {
						migrateToFound = true;
					}

					if (isDirectionUp) {
						isRunnable = isRunnable && migrateToNum >= migrationNum;
					} else {
						isRunnable = isRunnable && migrateToNum < migrationNum;
					}
				}

				return formatCorrect && isRunnable;
			}).map(function(file){
				return 'migrations/' + file;
			});

		if (!migrateToFound) {
			return abort('migration `'+ migrateTo + '` not found!');
		}

		return migrationsToRun;
	}
1337974
function lookup(version, migrations) {
  var regex = RegExp('^' + version + '.*$');
  for (var m in migrations)
    if (migrations.hasOwnProperty(m) && m.match(regex)) return m;
  return null;
}
1215551
def ListMigrationsToProcess(migrations_root,
                            current_migration_number
                           ):
  """"""
  migrations = []
  for m in os.listdir(migrations_root):
    if (current_migration_number is None or
        _MigrationFilenameToInt(m) > current_migration_number):
      migrations.append(m)

  return sorted(migrations, key=_MigrationFilenameToInt)
1205589
public function find($extension = null, $file = null)
	{
		// Exclude certain thiings from our search
		$exclude = array(".", "..");
		$files   = [];
		$ext     = '';

		foreach ($this->searchPaths as $path)
		{
			if (!is_dir($path . DS . 'migrations'))
			{
				continue;
			}
			$found = array_diff(scandir($path . DS . 'migrations'), $exclude);

			foreach ($found as $f)
			{
				$files[$path . DS . 'migrations' . DS . $f] = $f;
			}
		}

		asort($files);

		if (!is_null($file))
		{
			if (in_array($file, $files))
			{
				$this->files[] = array_search($file, $files);
				return true;
			}
			else
			{
				$this->log("Provided file ({$file}) could not be found.", 'error');
				return false;
			}
		}

		if (!is_null($extension))
		{
			$parts = explode('_', $extension);
			foreach ($parts as $part)
			{
				$ext .= ucfirst($part);
			}
		}

		foreach ($files as $path => $file)
		{
			// Make sure they have a php extension and proper filename format
			if (preg_match('/^Migration[0-9]{14}[[:alnum:]]+\.php$/', $file))
			{
				// If an extension was provided...match against it...
				if (empty($ext) || (!empty($ext) && preg_match('/Migration[0-9]{14}'.$ext.'\.php/', $file)))
				{
					$this->files[] = $path;
				}
			}
		}

		return true;
	}
506373
def find_migrations_directory():
    
    here = os.path.abspath(os.path.dirname(__file__))
    return os.path.join(here, 'sql/migrations')
1049018
def execute_migration(self, migration_file_relative):
        
        migration_file = os.path.join(self.db_config['migrations_dir'], migration_file_relative)
        m_type = self.repository.migration_type(migration_file)
        if m_type == 'native':
            return self.execute_native_migration(migration_file)
        if m_type == 'py':
            module = imp.load_source('migration_module', migration_file)
            return self.execute_python_migration(migration_file, module)
        assert False, 'Unknown migration type %s' % migration_file
413037
function match(self, dirname, basename, callback) {
  var pathname, stats, pattern, matches;

  pattern = patternFor(self, basename);
  matches = self.entries(dirname).filter(function(m) { return pattern.test(m); });
  matches = sortMatches(self, matches, basename);

  while (matches.length) {
    pathname  = path.join(dirname, matches.shift());
    stats     = self.stat(pathname);

    if (stats && stats.isFile() && callback(pathname)) {
      return pathname;
    }
  }
}
237516
function pathMatchesGlobs(filePath, patterns, excludedPatterns) {
  const patternList = [].concat(patterns);
  const excludedPatternList = [].concat(excludedPatterns || []);
  const opts = { matchBase: true };

  return (
    patternList.some(pattern => minimatch(filePath, pattern, opts)) &&
    !excludedPatternList.some(excludedPattern =>
      minimatch(filePath, excludedPattern, opts)
    )
  );
}
629989
protected function applySearchAndReplaceOperations()
    {
        foreach (Files::getRecursiveDirectoryGenerator($this->targetPackageData['path'], null, true) as $pathAndFilename) {
            $pathInfo = pathinfo($pathAndFilename);
            if (!isset($pathInfo['filename'])) {
                continue;
            }
            if (strpos($pathAndFilename, 'Migrations/Code') !== false) {
                continue;
            }

            foreach ($this->operations['searchAndReplace'] as $operation) {
                list($search, $replacement, $filter, $regularExpression) = $operation;
                if (is_array($filter)) {
                    if ($filter !== array() && (!isset($pathInfo['extension']) || !in_array($pathInfo['extension'], $filter, true))) {
                        continue;
                    }
                } elseif (substr($pathAndFilename, -strlen($filter)) !== $filter) {
                    continue;
                }
                Tools::searchAndReplace($search, $replacement, $pathAndFilename, $regularExpression);
            }
        }
    }
376992
protected function getMigrationFiles()
    {
        $config = $this->getConfig();
        $paths = $config->getMigrationPaths();
        $files = [];

        foreach ($paths as $path) {
            $files[] = Util::glob($path . DIRECTORY_SEPARATOR . '*.php');
        }

        $files = array_merge(...$files);

        // glob() can return the same file multiple times
        // This will cause the migration to fail with a
        // false assumption of duplicate migrations
        // http://php.net/manual/en/function.glob.php#110340
        return array_unique($files);
    }
311742
def _MigrationFilenameToInt(fname):
  """"""
  base, _ = os.path.splitext(fname)
  return int(base)
134877
private function findFilesInDiffToTarget(string $targetBranch) : GitChangeSet
    {
        $mergeBase = $this->processRunner->runAsProcess('git', 'merge-base', 'HEAD', $targetBranch);

        $rawDiffUnfilteredString = $this->processRunner->runAsProcess(
            'git',
            'diff',
            '--name-only',
            '--diff-filter=d',
            $mergeBase
        );

        $rawDiffUnfiltered = explode("\n", trim($rawDiffUnfilteredString));

        $result = $this->gitChangeSetFactory->build($rawDiffUnfiltered, $mergeBase);

        return $result;
    }