首页 > 其他分享 >code2markdown class

code2markdown class

时间:2024-01-18 20:36:35浏览次数:27  
标签:__ md code code2markdown self file path class

"""convert code to markdown

"""
import os
import re
from datetime import datetime

# 需要过滤的文件夹
exclude_dirs = [
    "__pycache__",
    "venv",
    "build",
    "dist",
    "node_modules",
    "public",
    "LICENSE",
    "assets",
    "vendor",
    "tmp",
    "static",
    "templates",
    "bin",
    "obj",
    "Migrations",
    "Properties",
    "packages",  # dotnet 的本地依赖包
]

# 需要过滤文件后缀
exclude_files = [
    "_NOTE.md",
    ".d.ts",
    ".lock",
    ".png",
    ".woff2",
    ".ttf",
    ".woff",
    ".css",
    "README.md",
    ".toml",
    "swagger-ui-bundle.js",
    "-lock.json",
    "zz_code2md.py",
    "temp.md",
]

# 需要保留的文件
include_exts = [
    ".py",
    ".vue",
    ".js",
    ".ts",
    ".html",
    ".go",
    ".mod",
    ".json",
    ".txt",
    ".sh",
    ".command",
    ".cs",
    "csproj",
    ".jsx",
    ".sln",
    ".sh",
    ".bat",
]

#
md_suffix_table = {"command": "sh", "csproj": "xml"}


class CodeToMarkDown:
    """_summary_"""

    __slots__ = ["path", "md_path", "code_file_path"]

    def __init__(self, path: str = None) -> None:
        if path:
            self.path = path
        else:
            self.path = os.getcwd()

    def generate_md(self):
        self.__generate_md_file_path()
        self.__collect_code_files()
        self.__generate_md_file()

    def __generate_md_file_path(self):
        cur_time_str = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
        md_name = f"Z_{cur_time_str}_NOTE.md"
        self.md_path = os.path.join(self.path, md_name)

    def __collect_code_files(self):
        """_summary_
        Returns:
            _type_: _description_
        """
        self.code_file_path = []
        for root, dirs, files in os.walk(self.path):
            # 过滤不符合的文件夹------------------------------------------------------------------------
            dirs[:] = [d for d in dirs if not d.startswith(".") and not any(ex in d for ex in exclude_dirs)]
            # 过滤不符合的文件-----------------------------------------------------------------------------
            files[:] = [f for f in files if not f.startswith(".") and not any(ex in f for ex in exclude_files)]
            # 筛选所有符合后缀的文件------------------------------------------------------------------------
            for file in files:
                # 正向过滤含有(\.py|vue|js|ts)$ 结尾的文件
                if any(file.endswith(ext) for ext in include_exts):
                    self.code_file_path.append(os.path.join(root, file))

    def __generate_md_file(self):
        for i, code_file_path in enumerate(self.code_file_path):
            print(i + 1, "->", self.__get_md_title_level_one(code_file_path))
            self.__readcode_writemd(code_file_path)

    def __get_md_title_level_one(self, code_file_path):
        """获取每个代码文件的md标题,去掉项目之前的文件路径
        Args:
            code_file_path (_type_): 代码路径
            project_path (_type_): 项目根路径
        Returns:
            _type_: 每个代码文件的md标题
        """
        # Get the common prefix of the two paths
        common_prefix = os.path.commonprefix([code_file_path, self.path])
        # Get the different parts of the two paths
        diff1 = code_file_path[len(common_prefix) + 1 :]
        md_title = os.path.join(os.path.basename(self.path), diff1)
        return md_title

    def __readcode_writemd(self, code_file_path):
        """_summary_
        Args:
            code_file_path (_type_): _description_
        """
        with open(code_file_path, "r", encoding="utf-8") as f:  # 打开文件
            try:
                content = f.read()
            except Exception as e:
                print(f"{code_file_path}{e}文件编码读取错误")
                content = ""
            self.__write2md(content, code_file_path)

    def __write2md(
        self,
        content,
        code_file_path,
    ):
        """_summary_
        Args:
            content (_type_): _description_
            suffix (_type_): _description_
            code_file_path (_type_): _description_
        """
        with open(self.md_path, "a", encoding="utf-8") as f:  # 打开文件
            md_title_level_one = self.__get_md_title_level_one(code_file_path)
            code_label = self.__get_code_md_lable_by_suffix(code_file_path)
            f.write("\n")
            f.write(f"# `{md_title_level_one}`\n\n")
            f.write(f"```{code_label}\n")
            f.write(content)
            f.write("\n")
            f.write("```\n\n\n")

    def __get_code_md_lable_by_suffix(self, code_file_path):
        suffix = re.findall(r'\.[^.\\/:*?"<>|\r\n]+$', code_file_path)
        if len(suffix):
            suffix = suffix[0][1:]
        if md_suffix_table.get(suffix) is not None:
            return md_suffix_table.get(suffix)
        return suffix


if __name__ == "__main__":
    print("====================start====================")
    root_path = """F:\\song\\dotnet_efcore_two_database_learn\\SqliteToOracle"""
    code2md = CodeToMarkDown(root_path)
    code2md.generate_md()
    print("====================done====================")

标签:__,md,code,code2markdown,self,file,path,class
From: https://www.cnblogs.com/zhuoss/p/17973345

相关文章

  • jmeter安装成功后打不开,提示:Cause: CannotResolveClassException: com.blazemeter.jme
    下载安装Jmeter,环境变量也配置完成了,打开Jmeter脚本报错,提示:Cause:CannotResolveClassException:com.blazemeter.jmeter.threads.concurrency.ConcurrencyThreadGroup解决办法:1.可以试着下载安装Jmeter插件管理器,https://jmeter-plugins.org/install/Install/ 2.把步骤1中......
  • [Typescript] Static block for Class
    InrecentTypescript,itispossibletodefinestaticblockclassCar{staticnextSerialNumber=100static{//thisisthestaticfieldfetch('https://get-next-serial-number.com').then(res=>res.json()......
  • web DevOps / css id / css class / javascript / Browser Object Model / bom / Docu
    sNSD_DEVOPS_02CSS概述概念与理解层叠样式表—也就是CSS—是在HTML之后应该学习的第二门技术。HTML用于定义内容的结构和语义,CSS用于设计风格和布局。比如,我们可以使用CSS来更改内容的字体、颜色、大小、间距,将内容分为多列,或者添加动画及其他的装饰效果。修改页......
  • 无涯教程-LISP - 类(defclass)
    常见的LISP早于几十年的面向对象编程的发展,但是,它在稍后的阶段将面向对象并入其中。定义类defclass宏允许创建用户定义的类。它创建一个类作为数据类型。它具有以下语法-(defclassclass-name(superclass-name*)(slot-description*)class-option*))slot是存储数据......
  • Python Flask Class类默认方法(函数)
    前言全局说明Class类默认方法(函数)一、安装flask模块二、引用模块三、启动服务模块安装、引用模块、启动Web服务方法,参考下面链接文章:https://www.cnblogs.com/wutou/p/17963563四、Class类默认方法(函数)默认方法(函数)说明备注init类被调用后,自动执行......
  • arthas热更新class
    安装和启动下载https://arthas.aliyun.com/doc/download.html解压arthas的zip热更新代码找到项目进程号ps-ef|grepProject返回2222启动并选择jvm进程java-jararthus-boot.jarjad反编译代码,另存为.java文件jad--source-onlycom.tiandy.testdemo.Te......
  • Cannot load driver class: oracle.jdbc.OracleDriver
    错误信息Causedby:java.lang.IllegalStateException:Cannotloaddriverclass:oracle.jdbc.OracleDriver atorg.springframework.util.Assert.state(Assert.java:97)~[spring-core-5.2.9.RELEASE.jar:5.2.9.RELEASE] atorg.springframework.boot.autoconfigure.jdbc.Da......
  • 在Python中,classmethod是一个修饰符,它用于指定类中的某个方法为类方法1。这种方法不需
    classA(object):bar=1deffunc1(self):print('foo')@classmethoddeffunc2(cls):print('func2')print(cls.bar)cls().func1()A.func2()#不需要实例化Ins=A()Ins.func1()#需要实例化在Pyth......
  • Class对象
    1、需要特别注意的是,手动编写的每个class类,无论创建多少个实例对象,在JVM中都只有一个Class对象,即在内存中每个类有且只有一个相对应的Class对象。2、Java中每个类都有一个Class对象,当编译一个新创建的类就会产生一个对应Class对象并且这个Class对象会被保存在同名.class文件里(......
  • class ABC python
    如何实现Python中的类(classABC)作为一名经验丰富的开发者,我很高兴能教给你如何在Python中实现一个类(classABC)。下面是一个简单的步骤表格,将指导你完成这个过程。步骤描述步骤1定义一个类步骤2添加属性和方法步骤3创建类的实例步骤4使用类的属性和方法......