提交 ed7e8991 编写于 作者: F feilong

init rust skill_tree repo

上级 727e1beb
target/
.vscode
.idea
.DS_Store
__pycache__
*.pyc
*.zip
*.out
Cargo.lock
\ No newline at end of file
# skill_tree_rust # skill_tree_rust
Rust 技能树 Rust 技能树
\ No newline at end of file
## 初始化技能树
技能树合成和id生成脚本目前用Python脚本统一处理
```bash
pip install -r requirement.txt
```
## 目录结构说明
* 技能树`骨架文件`
* 位置:`data/tree.json`
* 说明:该文件是执行 `python main.py` 生成的,请勿人工编辑
* 技能树`根节点`配置文件:
* 位置:`data/config.json`
* 说明:可编辑配置关键词等字段,其中 `node_id` 字段是生成的,请勿编辑
* 技能树`难度节点`
* 位置:`data/xxx`,例如: `data/1.rust初阶`
* 说明:
* 每个技能树有 3 个等级,目录前的序号是**必要**的,用来保持文件夹目录的顺序
* 每个目录下有一个 `config.json` 可配置关键词信息,其中 `node_id` 字段是生成的,请勿编辑
* 技能树`章节点`
* 位置:`data/xxx/xxx`,例如:`data/1.rust初阶/1.预备知识`
* 说明:
* 每个技能树的每个难度等级有 n 个章节,目录前的序号是**必要**的,用来保持文件夹目录的顺序
* 每个目录下有一个 `config.json` 可配置关键词信息,其中 `node_id` 字段是生成的,请勿编辑
* 技能树`知识节点`
* 位置:`data/xxx/xxx`,例如:`data/1.rust初阶/1.预备知识/1.rust简介`
* 说明:
* 每个技能树的每章有 n 个知识节点,目录前的序号是必要的,用来保持文件夹目录的顺序
* 每个目录下有一个 `config.json`
* 其中 `node_id` 字段是生成的,请勿编辑
* 其中 `keywords` 可配置关键字字段
* 其中 `children` 可配置该`知识节点`下的子树结构信息,参考后面描述
* 其中 `export` 可配置该`知识节点`下的导出习题信息,参考后面描述
## `知识节点` 子树信息结构
例如 `data/1.rust初阶/1.预备知识/1.rust简介/config.json` 里配置对该知识节点子树信息结构,用来增加技能树服务在该知识节点上的深度数据匹配:
```json
{
// ...
"children": [
{
"Rust的起源": {
"keywords": [
"Rust的起源",
"起源",
"Rust"
],
"children": []
}
}
],
}
```
## `知识节点` 的导出习题编辑
例如 `data/1.rust初阶/1.预备知识/1.rust简介/config.json` 里配置对该知识节点导出的习题
```json
{
// ...
"export": [
"helloworld.json",
// ...
]
}
```
`export` 字段中,我们列出习题定义的`json`文件列表 ,下面我们了解如何编写习题。
## `知识节点` 的导出习题选项配置编辑
目前我们支持使用 markdown 语法直接编辑习题和各选项。
如前文内容,我们在知识节点下增加习题 `helloworld`的定义文件,即在`data/1.rust初阶/1.预备知识/1.rust简介` 目录增加一个`helloworld.json`文件:
```json
{
"type": "code_options",
"author": "幻灰龙",
"source": "helloworld.md",
"notebook_enable": true
}
```
其中
* `type` 字段目前都固定是 `code_options`
* `notebook_enable` 字段决定这个习题是否生成对应的 `notebook`
* `source` 字段代表习题编辑的 `markdwon` 文件。
现在我们新建一个 `helloworld.md` 并编辑为:
````markdown
# Hello World
编写一个输出 "Hello,World!" 的 Rust 程序,以下错误的是?
## 答案
```rust
fn main() {
let str1 = "Hello,";
let str2 = "World!";
println!("{}", str1+str2);
}
```
## 选项
### 直接打印
```rust
fn main() {
let str = "Hello,World!";
println!("{}", str);
}
```
### 使用格式划宏拼接
```rust
fn main() {
let str = "Hello";
let str = format!("{},World", str);
println!("{}", str);
}
```
### 使用 String::from
```rust
fn main() {
let str1 = String::from("Hello");
let str2 = String::from("World");
let str = format!("{},{}!", str1, str2);
println!("{}", str);
}
```
### 使用mut+push_str
```rust
fn main() {
let mut str1 = String::from("Hello,");
let str2 = String::from("World!");
str1.push_str(str2.as_str());
println!("{}", str1);
}
```
````
这是一个最基本的习题结构,它包含标题、答案、选项,注意这几个一级和二级标题必须填写正确,解释器会读取这几个标题。而选项的标题会被直接忽略掉,在
最终生成的习题中不包含选项的三级标题,所以这个标题可以用来标注一些编辑信息,例如“使用mut+push_str”,“使用格式划宏拼接”等等。
## 可选的习题源代码项目
编辑习题中,为了测试方便,可以直接在知识点目录下创建对应的 `rust源代码项目目录`
例如 `data/1.rust初阶/1.预备知识/1.rust简介/helloworld/`,就是通过`cargo new helloworld` 创建的测试 `helloworld.md` 里描述的习题用的 rust 源代码项目。执行命令 `cargo build``cargo run` 可以便利地测试程序。
## 技能树合成
在根目录下执行 `python main.py` 会合成技能树文件,合成的技能树文件: `data/tree.json`
* 合成过程中,会自动检查每个目录下 `config.json` 里的 `node_id` 是否存在,不存在则生成
* 合成过程中,会自动检查每个知识点目录下 `config.json` 里的 `export` 里导出的习题配置,检查是否存在`exercise_id` 字段,如果不存在则生成
{
"node_id": "rust-7c394f164d8f44519521f03db08a1321",
"keywords": [],
"children": [],
"export": []
}
\ No newline at end of file
[package]
name = "helloworld"
version = "0.1.0"
authors = ["feilong <fanfeilong@outlook.com>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
fn main() {
let mut str1 = String::from("Hello,");
let str2 = String::from("World!");
str1.push_str(str2.as_str());
println!("{}", str1);
}
{
"node_id": "rust-502b3cef4dbc41fdad069522470f3662",
"keywords": [],
"children": [],
"export": []
}
\ No newline at end of file
{
"node_id": "rust-0d9e5f9449b94aa692a363f21a66c8af",
"keywords": [],
"children": [],
"export": []
}
\ No newline at end of file
{
"node_id": "rust-c3878925dc9d4ad6b45e244beceb5c87",
"keywords": []
}
\ No newline at end of file
{
"node_id": "rust-2cea732119294abab6f2887a364b242a",
"keywords": []
}
\ No newline at end of file
{
"node_id": "rust-e2292238ccbf403d85fb20dd7b4c85ad",
"keywords": []
}
\ No newline at end of file
{
"node_id": "rust-7377966439734497b91f3d775f9b0e0d",
"keywords": []
}
\ No newline at end of file
{
"node_id": "rust-981f4f37a8e547abb135f54592ac52a5",
"keywords": []
}
\ No newline at end of file
{
"tree_name": "rust",
"keywords": [],
"node_id": "rust-bab5ea3c37134f5a8fc69630792d9adb"
}
\ No newline at end of file
{
"rust": {
"node_id": "rust-bab5ea3c37134f5a8fc69630792d9adb",
"keywords": [],
"children": [
{
"rust初阶": {
"node_id": "rust-e2292238ccbf403d85fb20dd7b4c85ad",
"keywords": [],
"children": [
{
"预备知识": {
"node_id": "rust-c3878925dc9d4ad6b45e244beceb5c87",
"keywords": [],
"children": [
{
"rust简介": {
"node_id": "rust-7c394f164d8f44519521f03db08a1321",
"keywords": [],
"children": []
}
},
{
"rust安装": {
"node_id": "rust-502b3cef4dbc41fdad069522470f3662",
"keywords": [],
"children": []
}
},
{
"认识rust工具链": {
"node_id": "rust-0d9e5f9449b94aa692a363f21a66c8af",
"keywords": [],
"children": []
}
}
]
}
},
{
"rust基本概念": {
"node_id": "rust-2cea732119294abab6f2887a364b242a",
"keywords": [],
"children": []
}
}
]
}
},
{
"rust中阶": {
"node_id": "rust-7377966439734497b91f3d775f9b0e0d",
"keywords": [],
"children": []
}
},
{
"rust高阶": {
"node_id": "rust-981f4f37a8e547abb135f54592ac52a5",
"keywords": [],
"children": []
}
}
]
}
}
\ No newline at end of file
from json import load
from src.tree import TreeWalker, load_json, dump_json
import os
import re
if __name__ == '__main__':
walker = TreeWalker("data", "rust", "rust")
walker.walk()
import logging
from genericpath import exists
import json
import os
import uuid
import sys
import re
id_set = set()
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
handler = logging.StreamHandler(sys.stdout)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
def load_json(p):
with open(p, 'r') as f:
return json.loads(f.read())
def dump_json(p, j, exist_ok=False, override=False):
if os.path.exists(p):
if exist_ok:
if not override:
return
else:
logger.error(f"{p} already exist")
sys.exit(0)
with open(p, 'w+') as f:
f.write(json.dumps(j, indent=2, ensure_ascii=False))
def ensure_config(path):
config_path = os.path.join(path, "config.json")
if not os.path.exists(config_path):
node = {"keywords": []}
dump_json(config_path, node, exist_ok=True, override=False)
return node
else:
return load_json(config_path)
def parse_no_name(d):
p = r'(\d+)\.(.*)'
m = re.search(p, d)
try:
no = int(m.group(1))
dir_name = m.group(2)
except:
sys.exit(0)
return no, dir_name
def check_export(base, cfg):
flag = False
exports = []
for export in cfg.get('export', []):
ecfg_path = os.path.join(base, export)
if os.path.exists(ecfg_path):
exports.append(export)
else:
flag = True
if flag:
cfg["export"] = exports
return flag
def gen_node_id():
return "oceanbase-" + uuid.uuid4().hex
class TreeWalker:
def __init__(self, root, tree_name, title=None, log=None):
self.name = tree_name
self.root = root
self.title = tree_name if title is None else title
self.tree = {}
self.logger = logger if log is None else log
def walk(self):
root = self.load_root()
root_node = {
"node_id": root["node_id"],
"keywords": root["keywords"],
"children": []
}
self.tree[root["tree_name"]] = root_node
self.load_levels(root_node)
self.load_chapters(self.root, root_node)
for index, level in enumerate(root_node["children"]):
level_title = list(level.keys())[0]
level_node = list(level.values())[0]
level_path = os.path.join(self.root, f"{index+1}.{level_title}")
self.load_chapters(level_path, level_node)
for index, chapter in enumerate(level_node["children"]):
chapter_title = list(chapter.keys())[0]
chapter_node = list(chapter.values())[0]
chapter_path = os.path.join(
level_path, f"{index+1}.{chapter_title}")
self.load_sections(chapter_path, chapter_node)
for index, section_node in enumerate(chapter_node["children"]):
section_title = list(section_node.keys())[0]
full_path = os.path.join(
chapter_path, f"{index}.{section_title}")
if os.path.isdir(full_path):
self.ensure_exercises(full_path)
tree_path = os.path.join(self.root, "tree.json")
dump_json(tree_path, self.tree, exist_ok=True, override=True)
return self.tree
def load_levels(self, root_node):
levels = []
for level in os.listdir(self.root):
if not os.path.isdir(level):
continue
level_path = os.path.join(self.root, level)
num, config = self.load_level_node(level_path)
levels.append((num, config))
levels.sort(key=lambda item: item[0])
root_node["children"] = [item[1] for item in levels]
return root_node
def load_level_node(self, level_path):
config = self.ensure_level_config(level_path)
num, name = self.extract_node_env(level_path)
result = {
name: {
"node_id": config["node_id"],
"keywords": config["keywords"],
"children": [],
}
}
return num, result
def load_chapters(self, base, level_node):
chapters = []
for name in os.listdir(base):
full_name = os.path.join(base, name)
if os.path.isdir(full_name):
num, chapter = self.load_chapter_node(full_name)
chapters.append((num, chapter))
chapters.sort(key=lambda item: item[0])
level_node["children"] = [item[1] for item in chapters]
return level_node
def load_sections(self, base, chapter_node):
sections = []
for name in os.listdir(base):
full_name = os.path.join(base, name)
if os.path.isdir(full_name):
num, section = self.load_section_node(full_name)
sections.append((num, section))
sections.sort(key=lambda item: item[0])
chapter_node["children"] = [item[1] for item in sections]
return chapter_node
def ensure_chapters(self):
for subdir in os.listdir(self.root):
self.ensure_level_config(subdir)
def load_root(self):
config_path = os.path.join(self.root, "config.json")
if not os.path.exists(config_path):
config = {
"tree_name": self.name,
"keywords": [],
"node_id": self.gen_node_id(),
}
dump_json(config_path, config, exist_ok=True, override=True)
else:
config = load_json(config_path)
flag, result = self.ensure_node_id(config)
if flag:
dump_json(config_path, result, exist_ok=True, override=True)
return config
def ensure_level_config(self, path):
config_path = os.path.join(path, "config.json")
if not os.path.exists(config_path):
config = {
"node_id": self.gen_node_id()
}
dump_json(config_path, config, exist_ok=True, override=True)
else:
config = load_json(config_path)
flag, result = self.ensure_node_id(config)
if flag:
dump_json(config_path, config, exist_ok=True, override=True)
return config
def ensure_chapter_config(self, path):
config_path = os.path.join(path, "config.json")
if not os.path.exists(config_path):
config = {
"node_id": self.gen_node_id(),
"keywords": []
}
dump_json(config_path, config, exist_ok=True, override=True)
else:
config = load_json(config_path)
flag, result = self.ensure_node_id(config)
if flag:
dump_json(config_path, config, exist_ok=True, override=True)
return config
def ensure_section_config(self, path):
config_path = os.path.join(path, "config.json")
if not os.path.exists(config_path):
config = {
"node_id": self.gen_node_id(),
"keywords": [],
"children": [],
"export": []
}
dump_json(config_path, config, exist_ok=True, override=True)
else:
config = load_json(config_path)
flag, result = self.ensure_node_id(config)
if flag:
dump_json(config_path, config, exist_ok=True, override=True)
return config
def ensure_node_id(self, config):
if "node_id" not in config:
config["node_id"] = self.gen_node_id()
return True, config
else:
return False, config
def gen_node_id(self):
return f"{self.name}-{uuid.uuid4().hex}"
def extract_node_env(self, path):
try:
_, dir = os.path.split(path)
self.logger.info(path)
number, title = dir.split(".", 1)
return int(number), title
except Exception as error:
self.logger.error(f"目录 [{path}] 解析失败,结构不合法,可能是缺少序号")
sys.exit(1)
def load_chapter_node(self, full_name):
config = self.ensure_chapter_config(full_name)
num, name = self.extract_node_env(full_name)
result = {
name: {
"node_id": config["node_id"],
"keywords": config["keywords"],
"children": [],
}
}
return num, result
def load_section_node(self, full_name):
config = self.ensure_section_config(full_name)
num, name = self.extract_node_env(full_name)
result = {
name: {
"node_id": config["node_id"],
"keywords": config["keywords"],
"children": config.get("children", [])
}
}
# if "children" in config:
# result["children"] = config["children"]
return num, result
def ensure_exercises(self, section_path):
config = self.ensure_section_config(section_path)
for e in config.get("export", []):
full_name = os.path.join(section_path, e)
exercise = load_json(full_name)
if "exercise_id" not in exercise:
exercise["exercise_id"] = uuid.uuid4().hex
dump_json(full_name, exercise)
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册