|
| 1 | +"""Upgrade one implementation to another in hydra configs.""" |
| 2 | + |
| 3 | +import os |
| 4 | +import re |
| 5 | + |
| 6 | +import numpy as np |
| 7 | +from rich import print |
| 8 | +from rich.columns import Columns |
| 9 | +from rich.panel import Panel |
| 10 | + |
| 11 | +from nrdk.framework import Result |
| 12 | + |
| 13 | + |
| 14 | +def _format_context( |
| 15 | + context: str, line_num: int | np.integer, |
| 16 | + start: int | np.integer, end: int | np.integer |
| 17 | +) -> str: |
| 18 | + return '\n'.join([ |
| 19 | + f"{'>>>' if n == line_num else ' '} {line}" |
| 20 | + for n, line in zip(range(start, end), context.split('\n')) |
| 21 | + ]) |
| 22 | + |
| 23 | + |
| 24 | +def _search( |
| 25 | + text: str, pattern: str | re.Pattern, context_size: int = 2 |
| 26 | +) -> list[tuple[int, str]]: |
| 27 | + if isinstance(pattern, str): |
| 28 | + pattern = re.compile(pattern) |
| 29 | + |
| 30 | + newlines = np.where(np.frombuffer( |
| 31 | + text.encode('utf-8'), dtype=np.uint8) == ord('\n'))[0] |
| 32 | + newlines = np.concatenate([[-1], newlines, [len(text)]]) |
| 33 | + |
| 34 | + matches = [] |
| 35 | + search_start = 0 |
| 36 | + while True: |
| 37 | + match = pattern.search(text, search_start) |
| 38 | + if not match: |
| 39 | + break |
| 40 | + |
| 41 | + line_num = np.searchsorted(newlines, match.start(), side='right') - 1 |
| 42 | + |
| 43 | + start = max(0, line_num - context_size) |
| 44 | + end = min(len(newlines) - 1, line_num + 1 + context_size) |
| 45 | + |
| 46 | + context = text[newlines[start] + 1:newlines[end]] |
| 47 | + matches.append( |
| 48 | + (line_num, _format_context(context, line_num, start, end))) |
| 49 | + |
| 50 | + search_start = match.end() |
| 51 | + |
| 52 | + return matches |
| 53 | + |
| 54 | + |
| 55 | +def cli_upgrade( |
| 56 | + target: str, /, to: str | None = None, |
| 57 | + dry_run: bool = False, path: str = ".", follow_symlinks: bool = False |
| 58 | +) -> None: |
| 59 | + """Upgrade implementation references in hydra configs. |
| 60 | +
|
| 61 | + !!! info "Usage" |
| 62 | +
|
| 63 | + First test with a dry run: |
| 64 | + ```sh |
| 65 | + nrdk upgrade-config <target> --path ./results --dry-run |
| 66 | + ``` |
| 67 | + If you're happy with what you see, you can then run the actual upgrade: |
| 68 | + ```sh |
| 69 | + nrdk upgrade-config <target> <to> --path ./results |
| 70 | + ``` |
| 71 | +
|
| 72 | + !!! danger |
| 73 | +
|
| 74 | + This is a potentially destructive operation! Always run with |
| 75 | + `--dry-run` first, and make sure that `to` does not overlap with |
| 76 | + any other existing implementations in your configs. |
| 77 | +
|
| 78 | + You can also use the `upgrade-config` tool to check for this overlap |
| 79 | + first: |
| 80 | + ```sh |
| 81 | + nrdk upgrade-config <to> --path ./results --dry-run |
| 82 | + # Shouldn't return any of the config files you are planning to upgrade |
| 83 | + ``` |
| 84 | +
|
| 85 | + For each valid [results directory][nrdk.framework.Result] in the specified |
| 86 | + `path`, search for all `_target_` fields in the hydra config, and replace |
| 87 | + any occurrences of `from` with `to`. |
| 88 | +
|
| 89 | + Args: |
| 90 | + target: full path name of the implementation to replace. |
| 91 | + to: full path name of the implementation to replace with. |
| 92 | + dry_run: if `True`, only log the changes that would be made, and do not |
| 93 | + actually modify any files. |
| 94 | + path: path to search for results directories. |
| 95 | + follow_symlinks: whether to follow symlinks when searching for results. |
| 96 | + """ |
| 97 | + pattern = re.compile(rf"_target_\s*:\s*{re.escape(target)}(?=\s|$)") |
| 98 | + results = Result.find(path, follow_symlinks=follow_symlinks) |
| 99 | + |
| 100 | + if dry_run: |
| 101 | + all_matches = {} |
| 102 | + for r in results: |
| 103 | + config_path = os.path.join(r, ".hydra", "config.yaml") |
| 104 | + if os.path.exists(config_path): |
| 105 | + with open(config_path, "r") as f: |
| 106 | + config = f.read() |
| 107 | + |
| 108 | + matches = _search(config, pattern, context_size=2) |
| 109 | + for line_num, context in matches: |
| 110 | + if context not in all_matches: |
| 111 | + all_matches[context] = [] |
| 112 | + all_matches[context].append((config_path, line_num)) |
| 113 | + |
| 114 | + for k, v in all_matches.items(): |
| 115 | + print( |
| 116 | + f"Found {len(v)} occurrence(s) of '{target}' " |
| 117 | + f"with this context:") |
| 118 | + print(Panel(k)) |
| 119 | + print(Columns( |
| 120 | + f"{os.path.relpath(config_path, path)}:{line_num}" |
| 121 | + for config_path, line_num in v)) |
| 122 | + print() |
| 123 | + |
| 124 | + else: |
| 125 | + if to is None: |
| 126 | + raise ValueError("Must specify `to` when not doing a dry run.") |
| 127 | + |
| 128 | + for r in results: |
| 129 | + config_path = os.path.join(r, ".hydra", "config.yaml") |
| 130 | + if os.path.exists(config_path): |
| 131 | + with open(config_path, "r") as f: |
| 132 | + config = f.read() |
| 133 | + |
| 134 | + n = re.findall(pattern, config) |
| 135 | + if n: |
| 136 | + print(f"Upgrading {len(n)} occurrence(s): {config_path}") |
| 137 | + new_config = re.sub(pattern, f"_target_: {to}", config) |
| 138 | + with open(config_path, "w") as f: |
| 139 | + f.write(new_config) |
0 commit comments