Skip to content

Instantly share code, notes, and snippets.

@bbelderbos
Last active September 20, 2025 07:22
Show Gist options
  • Save bbelderbos/5046ff557de98f4600d1dbc45e57d91a to your computer and use it in GitHub Desktop.
Save bbelderbos/5046ff557de98f4600d1dbc45e57d91a to your computer and use it in GitHub Desktop.
import json
from pathlib import Path
import sys
from urllib.request import urlretrieve
API = "https://rustplatform.com/api/"
DOWNLOAD_FILE = "exercises.json"
if not Path(DOWNLOAD_FILE).exists():
urlretrieve(API, DOWNLOAD_FILE)
print(f"Saved to {DOWNLOAD_FILE}")
data = json.load(open(DOWNLOAD_FILE))
root = Path(sys.argv[1]) if len(sys.argv) > 1 else Path("rust_bites")
def crate_toml(name: str, libraries: str) -> str:
libs = libraries.strip()
deps_block = f"\n[dependencies]\n{libs}\n" if libs else ""
return f"""[package]
name = "{name}"
version = "0.1.0"
edition = "2021"{deps_block}"""
def root_toml(members) -> str:
return (
'[workspace]\nresolver = "2"\nmembers = [\n'
+ "".join(f' "{m}",\n' for m in members)
+ "]\n"
)
def lf(s: str) -> str:
return s.replace("\r\n", "\n").replace("\r", "\n")
new_count = 0
members = []
for ex in data:
lvl = ex["level"].strip().lower().replace(" ", "-")
slug = ex["slug"]
base = root / "exercises" / lvl / slug
is_new = not base.exists()
(base / "src").mkdir(parents=True, exist_ok=True)
if is_new:
new_count += 1
(base / "Cargo.toml").write_text(
crate_toml(slug, ex.get("libraries", "")), encoding="utf-8"
)
template = lf(ex["template"]).rstrip() + "\n"
desc = lf(ex["description"]).rstrip() + "\n"
(base / "src" / "lib.rs").write_text(template, encoding="utf-8")
(base / "bite.md").write_text(f"# {ex['name']}\n\n{desc}", encoding="utf-8")
members.append((Path("exercises") / lvl / slug).as_posix())
(root / "Cargo.toml").write_text(root_toml(members), encoding="utf-8")
print(f"Added {new_count} new exercises. Total now: {len(members)} under {root}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment