To extend the previous Python script so it can scan Rust files from a public GitHub repository and potentially handle subfolders, we'll integrate the ability to clone the repository, scan through its contents, and then extract the Rust types converting them to TypeScript. This requires using Git and handling file paths programmatically. The script will accept command line arguments for flexibility.
To use this script, run it from the command line by providing the repository URL and optionally an output file path:
python script_name.py <repo_url> --output path/to/output.ts
If no output path is provided, it will default to output.ts
in the current working directory.
rust_to_ts
) needs to be fully implemented based on specific requirements or earlier snippets.gitpython
to clone and manage repositories.argparse
to handle command-line arguments.gitpython
via pip: pip install gitpython
import os
import re
import argparse
import tempfile
import shutil
from git import Repo
def rust_to_ts(rust_code):
# Convert Rust structs to TypeScript interfaces
structs = re.findall(r"pub struct (\\w+)\\s*{([^}]*)}", rust_code, re.S)
ts_structs = []
for name, fields in structs:
ts_fields = []
for field in fields.strip().split('\\n'):
if field.strip():
fname, ftype = field.strip().split(':')
fname = fname.strip()
ftype = ftype.replace(';', '').strip()
ts_type = ftype # Here you would map Rust types to TS types
ts_fields.append(f"{fname}: {ts_type};")
ts_struct = f"interface {name} {{\\n " + "\\n ".join(ts_fields) + "\\n}"
ts_structs.append(ts_struct)
def scan_rust_files(directory, output_path):
ts_results = []
for root, _, files in os.walk(directory):
for filename in files:
if filename.endswith('.rs'):
file_path = os.path.join(root, filename)
with open(file_path, 'r', encoding='utf-8') as file:
rust_code = file.read()
ts_definitions = rust_to_ts(rust_code)
ts_results.extend(ts_definitions)
with open(output_path, 'w', encoding='utf-8') as output_file:
output_file.write('\\\\n\\\\n'.join(ts_results))
def main(repo_url, output_path=None):
if output_path is None:
output_path = os.path.join(os.getcwd(), 'output.ts')
# Create a temporary directory
with tempfile.TemporaryDirectory() as tmpdirname:
print(f"Cloning repository {repo_url} to temporary directory...")
Repo.clone_from(repo_url, tmpdirname)
print(f"Scanning Rust files in repository...")
scan_rust_files(tmpdirname, output_path)
print(f"TypeScript definitions written to {output_path}")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Convert Rust types in a GitHub repo to TypeScript.")
parser.add_argument("repo_url", type=str, help="URL of the GitHub repository")
parser.add_argument("--output", type=str, help="Output file path (optional)")
args = parser.parse_args()
main(args.repo_url, args.output)
This setup provides a robust foundation for programmatically handling Rust files from GitHub repositories and could be further extended or integrated into larger systems as needed.