Skip to content

Instantly share code, notes, and snippets.

@smuuf
Last active January 11, 2017 11:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smuuf/37e63d24a3da3a3e35327a14aa458eab to your computer and use it in GitHub Desktop.
Save smuuf/37e63d24a3da3a3e35327a14aa458eab to your computer and use it in GitHub Desktop.
Rename Alembic migrations to contain date time (PHP)
<?php
// This script ONLY RETURNS BASH COMMANDS that would take care of the renaming.
// Usage:
// alembic_filename_date.php --glob=<glob_pattern:*.py> --format=<date_format:Y-m-d_H-i_>
$optGlob = '*.py';
$optFormat = 'Y-m-d_H-i_';
foreach ($argv as $a) {
switch (true) {
case preg_match('#--glob=([^\s]+)#', $a, $m):
$optGlob = $m[1];
break;
case preg_match('#--format=([^\s]+)#', $a, $m):
$optFormat = $m[1];
break;
}
}
$files = glob($optGlob);
$count = 0;
if (!$files) {
printf("! Zero files matching '%s'.\n", $optGlob);
exit(1);
}
foreach ($files as $f) {
// Skip already in the correct format.
$parsedDate = date_parse_from_format($optFormat . "+", $f);
if (!$parsedDate['errors']) {
// Date was able to be parsed - the filename is already in correct form.
continue;
}
foreach (file($f) as $line) {
if (preg_match('#^Create Date:\s*(.*)#', $line, $m)) {
$date = strtotime($m[1]);
break;
}
}
$formatted = date($optFormat, $date);
$new = $formatted . $f;
$count++;
printf ('mv "%s" "%s"%s', $f, $new, "\n");
}
if (!$count) {
echo "! Zero files need to be renamed.\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment