Skip to content

armgit / zulip

Public Imported from GitHub
0

Zulip server and web application. Open-source team chat that helps teams stay productive and focused.

renumber-migrations: Tidy up structure and naming.

Alex Vandiver87e800813a2b
diff --git a/tools/renumber-migrations b/tools/renumber-migrations
index f216ab76a01..a52f777b89e 100755
--- a/tools/renumber-migrations
+++ b/tools/renumber-migrations
@@ -6,17 +6,18 @@ import os
import re
import sys
+# When we need to backport migrations to a previous release, we
+# sometimes end up with multiple having the same ID number (which
+# isn't a problem; the migrations graph structure, not the IDs, is
+# what matters).
+MIGRATIONS_TO_SKIP = {"0209", "0261", "0501", "0001"}
+
def validate_order(order: list[int], length: int) -> None:
- if len(order) != length:
- print("Please enter the sequence of all the conflicting files at once")
+ if sorted(order) != list(range(1, length + 1)):
+ print(f"Expected a permutation of 1..{length}; got: {order}")
sys.exit(1)
- for i in order:
- if i > length or i < 1 or order.count(i) > 1:
- print("Incorrect input")
- sys.exit(1)
-
def renumber_migration(
conflicts: list[str],
@@ -25,58 +26,51 @@ def renumber_migration(
migrations_dir: str,
app_label: str,
) -> None:
- # Match only ("<app_label>", "NNNN_xxx") tuples, not things like
# `1_000` or cross-app deps. ruff-format always puts `, ` between
# the two tuple elements, so the replacement hardcodes that.
dep_pattern = re.compile(rf'"{re.escape(app_label)}"\s*,\s*"\d+(?:_[a-z0-9]+)+"')
- stack: list[str] = []
+ seen_prefixes: set[str] = set()
for i in order:
- if conflicts[i - 1][0:4] not in stack:
- stack.append(conflicts[i - 1][0:4])
- else:
- path = os.path.join(migrations_dir, conflicts[i - 1])
- # Don't touch migration-merge files: with two in-app deps in
- # the same file, the substitution would collapse both to the
- # same predecessor and produce a self-referential migration.
- with open(path) as f:
- if len(dep_pattern.findall(f.read())) > 1:
- print(
- f"Refusing to renumber {conflicts[i - 1]}: it has multiple "
- f"in-app dependencies (a migration merge). Renumber it by hand."
- )
- sys.exit(1)
- replacement = f'"{app_label}", "{last_correct_migration}"'
- with fileinput.FileInput(path, inplace=True) as f:
- for line in f:
- print(dep_pattern.sub(replacement, line), end="")
-
- # Rename the migration indexing at the end
- new_name = conflicts[i - 1].replace(
- conflicts[i - 1][0:4], f"{int(last_correct_migration[0:4]) + 1:04}"
- )
- os.rename(path, os.path.join(migrations_dir, new_name))
-
- last_correct_migration = new_name.replace(".py", "")
-
-
-def resolve_conflicts(
- conflicts: list[str], files_list: list[str], migrations_dir: str, app_label: str
-) -> None:
+ prefix = conflicts[i - 1][0:4]
+ if prefix not in seen_prefixes:
+ seen_prefixes.add(prefix)
+ continue
+ path = os.path.join(migrations_dir, conflicts[i - 1])
+ # Don't touch migration-merge files: with two in-app deps in
+ # the same file, the substitution would collapse both to the
+ # same predecessor and produce a self-referential migration.
+ with open(path) as f:
+ if len(dep_pattern.findall(f.read())) > 1:
+ print(
+ f"Refusing to renumber {conflicts[i - 1]}: it has multiple "
+ f"in-app dependencies (a migration merge). Renumber it by hand."
+ )
+ sys.exit(1)
+ replacement = f'"{app_label}", "{last_correct_migration}"'
+ with fileinput.FileInput(path, inplace=True) as f:
+ for line in f:
+ print(dep_pattern.sub(replacement, line), end="")
+
+ new_name = conflicts[i - 1].replace(prefix, f"{int(last_correct_migration[0:4]) + 1:04}")
+ os.rename(path, os.path.join(migrations_dir, new_name))
+
+ last_correct_migration = new_name.removesuffix(".py")
+
+
+def resolve_conflicts(conflicts: list[str], migrations_dir: str, app_label: str) -> None:
print("Conflicting migrations:")
- for i in range(len(conflicts)):
- print(str(i + 1) + ". " + conflicts[i])
+ for i, name in enumerate(conflicts, 1):
+ print(f"{i}. {name}")
order_input = input("Enter the order in which these migrations should be arranged: ")
order = list(map(int, order_input.split()))
validate_order(order, len(conflicts))
- last_correct_migration = conflicts[order[0] - 1]
-
- last_correct_migration = last_correct_migration.replace(".py", "")
+ last_correct_migration = conflicts[order[0] - 1].removesuffix(".py")
renumber_migration(conflicts, order, last_correct_migration, migrations_dir, app_label)
-if __name__ == "__main__":
+def main() -> None:
parser = argparse.ArgumentParser(description="Renumber migration files.")
parser.add_argument(
"app_label",
@@ -91,37 +85,29 @@ if __name__ == "__main__":
print(f"Error: Directory '{migrations_dir}' does not exist.")
sys.exit(1)
- MIGRATIONS_TO_SKIP = {"0209", "0261", "0501", "0001"}
while True:
- conflicts: list[str] = []
- stack: list[str] = []
files_list = [
os.path.basename(path) for path in glob.glob(os.path.join(migrations_dir, "????_*.py"))
]
- file_index = [file[0:4] for file in files_list]
-
- for file in file_index:
- migration_number = file[0:4]
- counter = file_index.count(migration_number)
+ prefixes = [file[0:4] for file in files_list]
+ conflicts: list[str] = []
+ seen_prefixes: set[str] = set()
+ for prefix in prefixes:
if (
- counter > 1
- and file[0:4] not in stack
- # When we need to backport migrations to a previous
- # release, we sometimes end up with multiple having
- # the same ID number (which isn't a problem; the
- # migrations graph structure, not the IDs, is what
- # matters).
- and migration_number not in MIGRATIONS_TO_SKIP
+ prefixes.count(prefix) > 1
+ and prefix not in seen_prefixes
+ and prefix not in MIGRATIONS_TO_SKIP
):
- conflicts += [
- file_name for file_name in files_list if file_name.startswith(migration_number)
- ]
- stack.append(migration_number)
-
- if len(conflicts) > 0:
- resolve_conflicts(conflicts, files_list, migrations_dir, args.app_label)
- else:
+ conflicts += [f for f in files_list if f.startswith(prefix)]
+ seen_prefixes.add(prefix)
+
+ if not conflicts:
break
+ resolve_conflicts(conflicts, migrations_dir, args.app_label)
print("All conflicts resolved")
+
+
+if __name__ == "__main__":
+ main()