文档地址

Document

使用docsify

官方中文使用教程:docsify

个人index.html设置

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
  <meta name="description" content="Description">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/docsify@4/lib/themes/vue.css">
</head>

<body>
  <div id="app"></div>
  <script>
    window.$docsify = {
      name: 'lightsmile的docs',
      repo: '',
      loadSidebar: true,
      subMaxLevel: 10,
      coverpage: true,
      // basePath: "https://lightsmile.cn/docs/",
      // relativePath: true,
      search: {
        maxAge: 86400000, // 过期时间,单位毫秒,默认一天
        paths: 'auto', // or 'auto'
        placeholder: '搜索',
      },
      count: {
        countable: true,
        fontsize: '0.9em',
        color: 'rgb(90,90,90)',
        language: 'chinese'
      },
      copyCode: {
        buttonText: '点击复制',
        errorText: '错误',
        successText: '已复制'
      }

    }
  </script>
  <!-- Docsify v4 -->
  <script src="//cdn.jsdelivr.net/npm/docsify@4"></script>

  <!--全文搜索-->
  <script src="//cdn.jsdelivr.net/npm/docsify/lib/plugins/search.min.js"></script>

  <!--点击红心-->
  <script src="./js/clicklove.js"></script>

  <!--图片缩放-->
  <script src="//cdn.jsdelivr.net/npm/docsify/lib/plugins/zoom-image.min.js"></script>

  <!--复制到剪贴板-->
  <script src="https://unpkg.com/docsify-copy-code@2"></script>

  <!--分页导航插件-->
  <script src="//cdn.jsdelivr.net/npm/docsify-pagination/dist/docsify-pagination.min.js"></script>

  <!--字数统计-->
  <script src="//unpkg.com/docsify-count/dist/countable.js"></script>

  <!--代码高亮-->
  <script src="//cdn.jsdelivr.net/npm/prismjs@1/components/prism-bash.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/prismjs@1/components/prism-python.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/prismjs@1/components/prism-yaml.min.js"></script>
</body>

</html>

使用Python实现自动文件监视和_sidebar.md文件生成

编写两个脚本,一个是重新根据文件目录生成_sidebar.md文件脚本update.py,一个是监控文件夹脚本watch.py

两个python脚本都放到项目根目录下。

update.py

# -*- coding: utf-8 -*-
import os

from typing import List


WHITE_LIST = ['asserts', 'js', 'README.md', 'img']

SIDEBAR_PATH = '_sidebar.md'

BASE_DIR = '.'


def is_white_pace(path: str):
    if path in WHITE_LIST:
        return True
    if path.startswith('_'):
        return True
    if path.startswith('.') and len(path) > 1:
        return True
    if not path.endswith('.md') and os.path.isfile(path):
        return True
    return False


def gen_sidebar(path: str, res: List[str]):
    print(res)
    for item in res:
        print(item)
    with open(os.path.join(path, SIDEBAR_PATH), 'w', encoding='utf8') as f:
        f.write('\n'.join(res))


def recurve(path: str, indent: str = ""):
    res = []
    for file_item in os.listdir(path):
        if not is_white_pace(file_item):
            file_path = os.path.join(path, file_item)
            if os.path.isfile(file_path):
                print("file", file_path)
                file_name = file_item[:-3]
                file_url = os.path.join(path, file_name)
                res.append(indent + "* [{}]({})".format(file_name, file_url))
            elif os.path.isdir(file_path):
                print("dir", file_path)
                file_name = file_item
                res.append(indent + "* {}".format(file_name))
                res.append('')
                res.extend(recurve(file_path, indent + "    "))
    return res


if __name__ == '__main__':
    gen_sidebar(BASE_DIR, recurve(BASE_DIR))

watch.py

# -*- coding: utf-8 -*-
import sys
import time


from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

from lightutils import logger, execute_cmd


class DocsifyUpdateHandler(FileSystemEventHandler):
    def __init__(self, cmd: str):
        self._cmd = cmd

    def on_created(self, event):
        super(DocsifyUpdateHandler, self).on_created(event)
        logger.debug("成功创建{}".format(event.src_path))
        # state, result = execute_cmd(self._cmd)
        # if state:
        #     logger.info("更新_sidebar.md完成~")

    def on_modified(self, event):
        super(DocsifyUpdateHandler, self).on_modified(event)
        if not event.is_directory and not event.src_path.endswith('.py') and not event.src_path.endswith('_sidebar.md'):
            logger.info("成功修改{}".format(event.src_path))
            state, result = execute_cmd(self._cmd)
            if state:
                logger.info("更新_sidebar.md完成~")

    def on_deleted(self, event):
        super(DocsifyUpdateHandler, self).on_deleted(event)
        logger.error("成功删除{}".format(event.src_path))
        state, result = execute_cmd(self._cmd)
        if state:
            logger.info("更新_sidebar.md完成~")

    def on_moved(self, event):
        super(DocsifyUpdateHandler, self).on_moved(event)
        logger.critical("成功将{}移动至{}".format(event.src_path, event.dest_path))
        state, result = execute_cmd(self._cmd)
        if state:
            logger.info("更新_sidebar.md完成~")


if __name__ == '__main__':
    path = sys.argv[1] if len(sys.argv) > 1 else '.'
    cmd = sys.argv[2] if len(sys.argv) > 2 else 'python update.py'
    handler = DocsifyUpdateHandler(cmd)
    observer = Observer()
    observer.schedule(handler, path, recursive=True)
    observer.start()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

启动监视

  1. 新建tmux的session

     tmux new -s docsify
    
  2. 在新session中执行
     python watch.py . "python update.py"
    

使用效果

如图:

评论




博客内容遵循 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 协议

本站使用 Volantis 作为主题,总访问量为
载入天数...载入时分秒...
冀ICP备20001334号