Skip to content

Instantly share code, notes, and snippets.

@GersiD
Forked from jnnnnn/rustlings-generate-modules.py
Last active October 27, 2023 11:23
Show Gist options
  • Save GersiD/9f1598cbcf436de56c2c16d88181efa6 to your computer and use it in GitHub Desktop.
Save GersiD/9f1598cbcf436de56c2c16d88181efa6 to your computer and use it in GitHub Desktop.
# this script will generate mod.rs files that let rust-analyzer work
# without `rust-project.json` on the rustlings examples.
import os
import glob
for folder in glob.glob("exercises/*"):
if not os.path.isdir(folder):
continue
with open(os.path.join(folder, "mod.rs"), "w") as f:
for file in glob.glob(os.path.join(folder, "*.rs")):
if not os.path.isfile(file) or os.path.basename(file) == "mod.rs":
continue
filename = os.path.splitext(os.path.basename(file))[0]
f.write(f"mod r#{filename};\n")
# write the base module
with open("exercises/mod.rs", "w") as f:
f.write("#![allow(dead_code)]\n")
for folder in glob.glob("exercises/*"):
if os.path.isdir(folder):
foldername = os.path.basename(folder)
f.write(f"mod r#{foldername};\n")
# for the root files (like quiz1.rs)
for rust_file in glob.glob("exercises/*.rs"):
if os.path.isfile(rust_file) and os.path.basename(rust_file) != "mod.rs":
filename = os.path.splitext(os.path.basename(rust_file))[0]
f.write(f"mod r#{filename};\n")
# make sure cargo.toml has the lib defined:
lib = """
[lib]
name = "exercises"
path = "exercises/mod.rs"
"""
with open("Cargo.toml", "r") as f:
if 'name = "exercises"' not in f.read():
with open("Cargo.toml", "a") as f:
f.write(lib)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment