tree.py 14.4 KB
Newer Older
CSDN-Ada助手's avatar
CSDN-Ada助手 已提交
1
import json
M
Mars Liu 已提交
2
import logging
CSDN-Ada助手's avatar
CSDN-Ada助手 已提交
3 4
import os
import re
M
Mars Liu 已提交
5
import subprocess
M
Mars Liu 已提交
6 7
import sys
import uuid
M
Mars Liu 已提交
8
import re
M
Mars Liu 已提交
9

CSDN-Ada助手's avatar
CSDN-Ada助手 已提交
10

M
Mars Liu 已提交
11
id_set = set()
M
Mars Liu 已提交
12
logger = logging.getLogger(__name__)
M
Mars Liu 已提交
13 14 15 16 17
logger.setLevel(logging.INFO)
handler = logging.StreamHandler(sys.stdout)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
M
Mars Liu 已提交
18

M
Mars Liu 已提交
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
def search_author(author_dict, username):
    for key in author_dict:
        names = author_dict[key]
        if username in names:
            return key
    return username

def user_name(md_file, author_dict):
    ret = subprocess.Popen([
        "git", "log", md_file
    ], stdout=subprocess.PIPE)
    lines = list(map(lambda l: l.decode(), ret.stdout.readlines()))
    author_lines = []
    for line in lines:
        if line.startswith('Author'):
            author_lines.append(line.split(' ')[1])
    author_nick_name = author_lines[-1]
    return search_author(author_dict, author_nick_name)
M
Mars Liu 已提交
37

CSDN-Ada助手's avatar
CSDN-Ada助手 已提交
38 39 40 41 42 43 44 45 46 47 48
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:
M
Mars Liu 已提交
49
            logger.error(f"{p} already exist")
CSDN-Ada助手's avatar
CSDN-Ada助手 已提交
50 51
            sys.exit(0)

M
Mars Liu 已提交
52
    with open(p, 'w+', encoding="utf8") as f:
CSDN-Ada助手's avatar
CSDN-Ada助手 已提交
53 54 55
        f.write(json.dumps(j, indent=2, ensure_ascii=False))


M
Mars Liu 已提交
56 57 58 59 60 61 62 63 64 65
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)


CSDN-Ada助手's avatar
CSDN-Ada助手 已提交
66 67 68 69 70 71 72 73 74 75 76 77
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

M
Mars Liu 已提交
78

M
Mars Liu 已提交
79 80 81 82 83 84 85 86 87 88 89 90 91
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

CSDN-Ada助手's avatar
CSDN-Ada助手 已提交
92

M
Mars Liu 已提交
93
class TreeWalker:
M
Mars Liu 已提交
94 95 96 97 98 99 100 101 102 103 104 105
    def __init__(
        self, root,
        tree_name,
        title=None,
        log=None,
        authors=None,
        enable_notebook=None,
        ignore_keywords=False
    ):
        self.ignore_keywords = ignore_keywords
        self.authors = authors if authors else {}
        self.enable_notebook = enable_notebook
M
Mars Liu 已提交
106 107 108 109
        self.name = tree_name
        self.root = root
        self.title = tree_name if title is None else title
        self.tree = {}
M
Mars Liu 已提交
110
        self.logger = logger if log is None else log
M
Mars Liu 已提交
111

M
Mars Liu 已提交
112 113 114 115 116
    def walk(self):
        root = self.load_root()
        root_node = {
            "node_id": root["node_id"],
            "keywords": root["keywords"],
M
Mars Liu 已提交
117 118 119
            "children": [],
            "keywords_must": root["keywords_must"],
            "keywords_forbid": root["keywords_forbid"]
M
Mars Liu 已提交
120 121 122 123 124 125 126
        }
        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]
M
Mars Liu 已提交
127
            level_path = os.path.join(self.root, f"{index + 1}.{level_title}")
M
Mars Liu 已提交
128 129 130 131
            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]
M
Mars Liu 已提交
132 133
                chapter_path = os.path.join(
                    level_path, f"{index + 1}.{chapter_title}")
M
Mars Liu 已提交
134 135 136
                self.load_sections(chapter_path, chapter_node)
                for index, section_node in enumerate(chapter_node["children"]):
                    section_title = list(section_node.keys())[0]
M
Mars Liu 已提交
137 138
                    full_path = os.path.join(
                        chapter_path, f"{index + 1}.{section_title}")
M
Mars Liu 已提交
139
                    if os.path.isdir(full_path):
M
Mars Liu 已提交
140
                        self.check_section_keywords(full_path)
M
Mars Liu 已提交
141 142 143 144 145 146
                        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

M
Mars Liu 已提交
147 148 149 150 151
    def sort_dir_list(self, dirs):
        result = [self.extract_node_env(dir) for dir in dirs]
        result.sort(key=lambda item: item[0])
        return result

M
Mars Liu 已提交
152 153 154 155 156 157 158 159
    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))
M
Mars Liu 已提交
160 161

        levels = self.resort_children(self.root, levels)
M
Mars Liu 已提交
162 163 164 165 166 167 168 169 170 171 172 173
        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": [],
M
Mars Liu 已提交
174 175
                "keywords_must": config["keywords_must"],
                "keywords_forbid": config["keywords_forbid"]
M
Mars Liu 已提交
176 177
            }
        }
M
Mars Liu 已提交
178

M
Mars Liu 已提交
179 180 181 182 183 184 185 186 187 188
        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))

M
Mars Liu 已提交
189
        chapters = self.resort_children(base, chapters)
M
Mars Liu 已提交
190 191 192 193 194 195 196 197 198 199 200
        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))

M
Mars Liu 已提交
201
        sections = self.resort_children(base, sections)
M
Mars Liu 已提交
202 203 204
        chapter_node["children"] = [item[1] for item in sections]
        return chapter_node

M
Mars Liu 已提交
205 206 207 208 209
    def resort_children(self, base, children):
        children.sort(key=lambda item: item[0])
        for index, [number, element] in enumerate(children):
            title = list(element.keys())[0]
            origin = os.path.join(base, f"{number}.{title}")
M
Mars Liu 已提交
210
            posted = os.path.join(base, f"{index + 1}.{title}")
M
Mars Liu 已提交
211 212 213 214 215
            if origin != posted:
                self.logger.info(f"rename [{origin}] to [{posted}]")
            os.rename(origin, posted)
        return children

M
Mars Liu 已提交
216 217 218 219 220 221 222 223 224 225 226
    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(),
M
Mars Liu 已提交
227 228
                "keywords_must": [],
                "keywords_forbid": []
M
Mars Liu 已提交
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
            }
            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()
            }
M
Mars Liu 已提交
245
            dump_json(config_path, config, exist_ok=True, override=True)
M
Mars Liu 已提交
246 247 248 249
        else:
            config = load_json(config_path)
            flag, result = self.ensure_node_id(config)
            if flag:
M
Mars Liu 已提交
250
                dump_json(config_path, config, exist_ok=True, override=True)
M
Mars Liu 已提交
251 252 253 254 255 256 257
        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(),
M
Mars Liu 已提交
258 259 260
                "keywords": [],
                "keywords_must": [],
                "keywords_forbid": []
M
Mars Liu 已提交
261
            }
M
Mars Liu 已提交
262
            dump_json(config_path, config, exist_ok=True, override=True)
M
Mars Liu 已提交
263 264 265 266
        else:
            config = load_json(config_path)
            flag, result = self.ensure_node_id(config)
            if flag:
M
Mars Liu 已提交
267
                dump_json(config_path, config, exist_ok=True, override=True)
M
Mars Liu 已提交
268 269 270 271 272 273 274 275
        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": [],
M
Mars Liu 已提交
276 277
                "children": [],
                "export": []
M
Mars Liu 已提交
278 279 280 281 282 283
            }
            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:
M
Mars Liu 已提交
284
                dump_json(config_path, result, exist_ok=True, override=True)
M
Mars Liu 已提交
285 286 287
        return config

    def ensure_node_id(self, config):
M
Mars Liu 已提交
288
        flag = False
M
Mars Liu 已提交
289
        if "node_id" not in config or \
M
Mars Liu 已提交
290
                not config["node_id"].startswith(f"{self.name}-") or \
M
Mars Liu 已提交
291 292 293 294
                config["node_id"] in id_set:
            new_id = self.gen_node_id()
            id_set.add(new_id)
            config["node_id"] = new_id
M
Mars Liu 已提交
295 296 297 298 299 300 301 302
            flag = True

        for child in config.get("children", []):
            child_node = list(child.values())[0]
            f, _ = self.ensure_node_id(child_node)
            flag = flag or f

        return flag, config
M
Mars Liu 已提交
303 304 305 306 307

    def gen_node_id(self):
        return f"{self.name}-{uuid.uuid4().hex}"

    def extract_node_env(self, path):
M
Mars Liu 已提交
308 309 310 311 312 313 314
        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}] 解析失败,结构不合法,可能是缺少序号")
M
Mars Liu 已提交
315 316
            # sys.exit(1)
            raise error
M
Mars Liu 已提交
317 318 319 320 321 322 323 324 325

    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": [],
M
Mars Liu 已提交
326 327
                "keywords_must": config["keywords_must"],
                "keywords_forbid": config["keywords_forbid"]
M
Mars Liu 已提交
328
            }
CSDN-Ada助手's avatar
CSDN-Ada助手 已提交
329
        }
M
Mars Liu 已提交
330 331 332 333 334 335 336 337 338
        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"],
M
Mars Liu 已提交
339 340 341
                "children": config.get("children", []),
                "keywords_must": config["keywords_must"],
                "keywords_forbid": config["keywords_forbid"]
M
Mars Liu 已提交
342 343 344 345 346 347 348 349
            }
        }
        # if "children" in config:
        #     result["children"] = config["children"]
        return num, result

    def ensure_exercises(self, section_path):
        config = self.ensure_section_config(section_path)
M
Mars Liu 已提交
350
        flag = False
M
Mars Liu 已提交
351 352 353 354 355
        for e in os.listdir(section_path):
            base, ext = os.path.splitext(e)
            _, source = os.path.split(e)
            if ext != ".md":
                continue
M
Mars Liu 已提交
356 357
            mfile = base + ".json"
            meta_path = os.path.join(section_path, mfile)
M
Mars Liu 已提交
358 359
            md_file = os.path.join(section_path, e)
            self.ensure_exercises_meta(meta_path, source, md_file)
M
Mars Liu 已提交
360
            export = config.get("export", [])
M
Mars Liu 已提交
361
            if mfile not in export and self.name != "algorithm":
M
Mars Liu 已提交
362 363 364 365 366
                export.append(mfile)
                flag = True
                config["export"] = export

        if flag:
M
Mars Liu 已提交
367 368
            dump_json(os.path.join(section_path, "config.json"),
                      config, True, True)
M
Mars Liu 已提交
369

M
Mars Liu 已提交
370 371 372
        for e in config.get("export", []):
            full_name = os.path.join(section_path, e)
            exercise = load_json(full_name)
M
Mars Liu 已提交
373 374 375
            if "exercise_id" not in exercise or exercise.get("exercise_id") in id_set:
                eid = uuid.uuid4().hex
                exercise["exercise_id"] = eid
M
Mars Liu 已提交
376
                dump_json(full_name, exercise, True, True)
M
Mars Liu 已提交
377 378
            else:
                id_set.add(exercise["exercise_id"])
M
Mars Liu 已提交
379

M
Mars Liu 已提交
380
    def ensure_exercises_meta(self, meta_path, source, md_file):
M
Mars Liu 已提交
381
        _, mfile = os.path.split(meta_path)
M
Mars Liu 已提交
382
        meta = None
M
Mars Liu 已提交
383
        if os.path.exists(meta_path):
M
Mars Liu 已提交
384 385 386 387 388 389 390 391 392 393 394
            with open(meta_path) as f:
                content = f.read()
            if content:
                meta = json.loads(content)
                if "exercise_id" not in meta:
                    meta["exercise_id"] = uuid.uuid4().hex
                if "notebook_enable" not in meta:
                    meta["notebook_enable"] = self.default_notebook()
                if "source" not in meta:
                    meta["source"] = source
                if "author" not in meta:
M
Mars Liu 已提交
395
                    meta["author"] = user_name(md_file, self.authors)
M
Mars Liu 已提交
396 397
                if "type" not in meta:
                    meta["type"] = "code_options"
M
Mars Liu 已提交
398 399 400 401 402 403 404 405 406

        if meta is None:
            meta = {
                "type": "code_options",
                "author": user_name(md_file, self.authors),
                "source": source,
                "notebook_enable": self.default_notebook(),
                "exercise_id": uuid.uuid4().hex
            }
M
Mars Liu 已提交
407 408 409
        dump_json(meta_path, meta, True, True)

    def default_notebook(self):
M
Mars Liu 已提交
410 411
        if self.enable_notebook is not None:
            return self.enable_notebook
M
Mars Liu 已提交
412
        if self.name in ["python", "java", "c"]:
M
Mars Liu 已提交
413 414 415 416
            return True
        else:
            return False

M
Mars Liu 已提交
417
    def check_section_keywords(self, full_path):
M
Mars Liu 已提交
418 419
        if self.ignore_keywords:
            return
M
Mars Liu 已提交
420 421 422 423
        config = self.ensure_section_config(full_path)
        if not config.get("keywords", []):
            self.logger.error(f"节点 [{full_path}] 的关键字为空,请修改配置文件写入关键字")
            sys.exit(1)