|
| 1 | +#!/usr/bin/env python3 |
| 2 | +import argparse |
| 3 | +import os |
| 4 | +import re |
| 5 | +import sys |
| 6 | +from typing import Optional |
| 7 | +import subprocess |
| 8 | + |
| 9 | + |
| 10 | +DESC = """ |
| 11 | +dash_core_version_switcher.py: switch all Cargo.toml dashcore deps between local path and git (rev/branch). |
| 12 | +
|
| 13 | +Usage: |
| 14 | + dash_core_version_switcher.py local |
| 15 | + dash_core_version_switcher.py rev <rev> |
| 16 | + dash_core_version_switcher.py branch <branch> |
| 17 | +
|
| 18 | +This edits inline-table or simple dependencies like: |
| 19 | + dashcore = { path = "../../../rust-dashcore/dash", features = [ ... ], default-features = false } |
| 20 | + dashcore = { git = "https://github.com/dashpay/rust-dashcore", rev = "<rev>", features = [ ... ], default-features = false } |
| 21 | + dashcore = "0.40" |
| 22 | +
|
| 23 | +It preserves existing features/default-features and only switches path/git+rev/branch or version key. |
| 24 | +Commented lines are not modified. |
| 25 | +""" |
| 26 | + |
| 27 | + |
| 28 | +GIT_URL = "https://github.com/dashpay/rust-dashcore" |
| 29 | + |
| 30 | +# Dependency names we switch and their local paths |
| 31 | +DEP_LOCAL_PATHS = { |
| 32 | + "dashcore": "../../../rust-dashcore/dash", |
| 33 | + "key-wallet": "../../../rust-dashcore/key-wallet", |
| 34 | + "key-wallet-manager": "../../../rust-dashcore/key-wallet-manager", |
| 35 | + "dash-spv": "../../../rust-dashcore/dash-spv", |
| 36 | + "dashcore-rpc": "../../../rust-dashcore/rpc-client", |
| 37 | + "key-wallet-ffi": "../../../rust-dashcore/key-wallet-ffi", |
| 38 | + "dash-spv-ffi": "../../../rust-dashcore/dash-spv-ffi", |
| 39 | +} |
| 40 | + |
| 41 | + |
| 42 | +def find_cargo_tomls(root: str): |
| 43 | + for dirpath, dirnames, filenames in os.walk(root): |
| 44 | + # skip typical build dirs |
| 45 | + skip = any(part in dirpath for part in ("/target/", "/.git/", "/node_modules/", "/.build/")) |
| 46 | + if skip: |
| 47 | + continue |
| 48 | + if "Cargo.toml" in filenames: |
| 49 | + yield os.path.join(dirpath, "Cargo.toml") |
| 50 | + |
| 51 | + |
| 52 | +def iter_dep_blocks(text: str): |
| 53 | + dep_names = "|".join(map(re.escape, DEP_LOCAL_PATHS.keys())) |
| 54 | + # Inline tables |
| 55 | + pattern_inline = re.compile(rf"(^|\n)(?P<indent>\s*)(?P<name>{dep_names})\s*=\s*\{{[^}}]*\}}", re.S) |
| 56 | + for m in pattern_inline.finditer(text): |
| 57 | + block_start = m.start() + (0 if text[m.start()] != '\n' else 1) |
| 58 | + block_end = m.end() |
| 59 | + # Skip commented lines |
| 60 | + line_start = text.rfind('\n', 0, block_start) + 1 |
| 61 | + line_end = text.find('\n', line_start) |
| 62 | + if line_end == -1: |
| 63 | + line_end = len(text) |
| 64 | + if text[line_start:line_end].lstrip().startswith('#'): |
| 65 | + continue |
| 66 | + dep_name = m.group('name') |
| 67 | + yield (block_start, block_end, dep_name, 'inline') |
| 68 | + |
| 69 | + # Simple string dependencies: name = "x.y.z" |
| 70 | + pattern_simple = re.compile(rf"(^|\n)(?P<indent>\s*)(?P<name>{dep_names})\s*=\s*\"[^\"]*\"", re.S) |
| 71 | + for m in pattern_simple.finditer(text): |
| 72 | + block_start = m.start() + (0 if text[m.start()] != '\n' else 1) |
| 73 | + block_end = m.end() |
| 74 | + line_start = text.rfind('\n', 0, block_start) + 1 |
| 75 | + line_end = text.find('\n', line_start) |
| 76 | + if line_end == -1: |
| 77 | + line_end = len(text) |
| 78 | + if text[line_start:line_end].lstrip().startswith('#'): |
| 79 | + continue |
| 80 | + dep_name = m.group('name') |
| 81 | + yield (block_start, block_end, dep_name, 'simple') |
| 82 | + |
| 83 | + |
| 84 | +def parse_inline_table(s: str): |
| 85 | + brace_open = s.find('{') |
| 86 | + brace_close = s.rfind('}') |
| 87 | + inner = s[brace_open + 1:brace_close] |
| 88 | + parts = [] |
| 89 | + buf = [] |
| 90 | + depth = 0 |
| 91 | + for ch in inner: |
| 92 | + if ch == '[': |
| 93 | + depth += 1 |
| 94 | + elif ch == ']': |
| 95 | + depth -= 1 |
| 96 | + if ch == ',' and depth == 0: |
| 97 | + parts.append(''.join(buf).strip()) |
| 98 | + buf = [] |
| 99 | + else: |
| 100 | + buf.append(ch) |
| 101 | + if buf: |
| 102 | + parts.append(''.join(buf).strip()) |
| 103 | + kv = [] |
| 104 | + for p in parts: |
| 105 | + if not p or '=' not in p: |
| 106 | + continue |
| 107 | + k, v = p.split('=', 1) |
| 108 | + kv.append((k.strip(), v.strip())) |
| 109 | + return kv |
| 110 | + |
| 111 | + |
| 112 | +def serialize_inline_table(prefix: str, pairs): |
| 113 | + body = ', '.join(f"{k} = {v}" for k, v in pairs) |
| 114 | + return f"{prefix}{{ {body} }}" |
| 115 | + |
| 116 | + |
| 117 | +def get_default_branch(remote_url: str) -> str: |
| 118 | + try: |
| 119 | + out = subprocess.check_output(["git", "ls-remote", "--symref", remote_url, "HEAD"], text=True) |
| 120 | + for line in out.splitlines(): |
| 121 | + line = line.strip() |
| 122 | + if line.startswith("ref:") and "refs/heads/" in line: |
| 123 | + ref = line.split()[1] |
| 124 | + return ref.split("/")[-1] |
| 125 | + raise RuntimeError(f"Could not determine default branch from: {out}") |
| 126 | + except subprocess.CalledProcessError as e: |
| 127 | + raise RuntimeError(f"git ls-remote failed: {e}") |
| 128 | + |
| 129 | + |
| 130 | +def get_branch_head_sha(remote_url: str, branch: str) -> str: |
| 131 | + try: |
| 132 | + ref = f"refs/heads/{branch}" |
| 133 | + out = subprocess.check_output(["git", "ls-remote", remote_url, ref], text=True) |
| 134 | + sha = out.strip().split()[0] |
| 135 | + if not sha: |
| 136 | + raise RuntimeError(f"Unexpected ls-remote output: {out}") |
| 137 | + return sha |
| 138 | + except subprocess.CalledProcessError as e: |
| 139 | + raise RuntimeError(f"git ls-remote failed: {e}") |
| 140 | + |
| 141 | + |
| 142 | +def switch_dep(block_text: str, dep_name: str, mode: str, value: Optional[str]): |
| 143 | + if '{' in block_text: |
| 144 | + prefix = block_text[:block_text.find('{')] |
| 145 | + pairs = parse_inline_table(block_text) |
| 146 | + keys = [k for k, _ in pairs] |
| 147 | + d = {k: v for k, v in pairs} |
| 148 | + |
| 149 | + for k in ("git", "rev", "branch", "path", "version"): |
| 150 | + if k in d: |
| 151 | + del d[k] |
| 152 | + if k in keys: |
| 153 | + keys.remove(k) |
| 154 | + |
| 155 | + if mode == 'local': |
| 156 | + keys.insert(0, 'path') |
| 157 | + d['path'] = f'"{DEP_LOCAL_PATHS[dep_name]}"' |
| 158 | + elif mode == 'rev': |
| 159 | + keys.insert(0, 'git') |
| 160 | + d['git'] = f'"{GIT_URL}"' |
| 161 | + keys.insert(1, 'rev') |
| 162 | + d['rev'] = f'"{value}"' |
| 163 | + elif mode == 'branch': |
| 164 | + keys.insert(0, 'git') |
| 165 | + d['git'] = f'"{GIT_URL}"' |
| 166 | + keys.insert(1, 'branch') |
| 167 | + d['branch'] = f'"{value}"' |
| 168 | + else: |
| 169 | + raise RuntimeError(f"Unknown mode {mode}") |
| 170 | + |
| 171 | + ordered_pairs = [] |
| 172 | + for k in keys: |
| 173 | + if k in d: |
| 174 | + ordered_pairs.append((k, d[k])) |
| 175 | + for k, v in d.items(): |
| 176 | + if k not in keys: |
| 177 | + ordered_pairs.append((k, v)) |
| 178 | + |
| 179 | + return serialize_inline_table(prefix, ordered_pairs) |
| 180 | + else: |
| 181 | + # simple: name = "x.y.z" -> upgrade to inline form on switches |
| 182 | + name, _, _ = block_text.partition('=') |
| 183 | + name_prefix = name + '= ' |
| 184 | + if mode == 'local': |
| 185 | + body = f'{{ path = "{DEP_LOCAL_PATHS[dep_name]}" }}' |
| 186 | + elif mode == 'rev': |
| 187 | + body = f'{{ git = "{GIT_URL}", rev = "{value}" }}' |
| 188 | + elif mode == 'branch': |
| 189 | + body = f'{{ git = "{GIT_URL}", branch = "{value}" }}' |
| 190 | + else: |
| 191 | + raise RuntimeError(f"Unknown mode {mode}") |
| 192 | + return name_prefix + body |
| 193 | + |
| 194 | + |
| 195 | +def process_file(path: str, mode: str, value: Optional[str]) -> bool: |
| 196 | + with open(path, 'r', encoding='utf-8') as f: |
| 197 | + text = f.read() |
| 198 | + |
| 199 | + blocks = list(iter_dep_blocks(text)) |
| 200 | + if not blocks: |
| 201 | + return False |
| 202 | + |
| 203 | + changed = False |
| 204 | + for start, end, dep_name, _kind in reversed(blocks): |
| 205 | + block_text = text[start:end] |
| 206 | + new_block = switch_dep(block_text, dep_name, mode, value) |
| 207 | + if new_block != block_text: |
| 208 | + text = text[:start] + new_block + text[end:] |
| 209 | + changed = True |
| 210 | + |
| 211 | + if changed: |
| 212 | + with open(path, 'w', encoding='utf-8', newline='\n') as f: |
| 213 | + f.write(text) |
| 214 | + return changed |
| 215 | + |
| 216 | + |
| 217 | +def main(): |
| 218 | + parser = argparse.ArgumentParser(description=DESC) |
| 219 | + sub = parser.add_subparsers(dest='cmd', required=True) |
| 220 | + sub.add_parser('local') |
| 221 | + p_rev = sub.add_parser('rev') |
| 222 | + p_rev.add_argument('rev') |
| 223 | + p_branch = sub.add_parser('branch') |
| 224 | + p_branch.add_argument('branch') |
| 225 | + sub.add_parser('main_branch_latest') |
| 226 | + args = parser.parse_args() |
| 227 | + |
| 228 | + mode = args.cmd |
| 229 | + val = None |
| 230 | + resolved = None |
| 231 | + if mode == 'rev': |
| 232 | + val = args.rev |
| 233 | + elif mode == 'branch': |
| 234 | + val = args.branch |
| 235 | + elif mode == 'main_branch_latest': |
| 236 | + branch = get_default_branch(GIT_URL) |
| 237 | + sha = get_branch_head_sha(GIT_URL, branch) |
| 238 | + mode = 'rev' |
| 239 | + val = sha |
| 240 | + resolved = (branch, sha) |
| 241 | + |
| 242 | + repo_root = os.getcwd() |
| 243 | + edited = [] |
| 244 | + for cargo in find_cargo_tomls(repo_root): |
| 245 | + if process_file(cargo, mode, val): |
| 246 | + edited.append(cargo) |
| 247 | + |
| 248 | + if edited: |
| 249 | + print(f"Updated rust-dashcore dependencies in {len(edited)} file(s):") |
| 250 | + for p in edited: |
| 251 | + print(f" - {os.path.relpath(p, repo_root)}") |
| 252 | + if resolved: |
| 253 | + print(f"Resolved default branch '{resolved[0]}' at {resolved[1]}") |
| 254 | + else: |
| 255 | + print("No Cargo.toml files with dashcore dependency found to update.") |
| 256 | + |
| 257 | + |
| 258 | +if __name__ == '__main__': |
| 259 | + try: |
| 260 | + main() |
| 261 | + except KeyboardInterrupt: |
| 262 | + sys.exit(130) |
| 263 | + except Exception as e: |
| 264 | + print(f"Error: {e}", file=sys.stderr) |
| 265 | + sys.exit(1) |
0 commit comments