使用Sphinx + GitHub + Read the Docs搭建wiki

2017.10.14

Sphinx 是一个基于 ReStructuredText 的文档生成工具,有很多开源工程都采用sphinx作为文档生成系统,最有名的就是 python 官方文档。

Read the Docs是一个在线文档托管服务,可以从各种版本控制系统中导入文档。支持 webhooks,当你提交代码时,文档将被自动构建。

Sphinx + GitHub + ReadtheDocs 作为一个文档写作工具, 用 Sphinx 生成文档,GitHub 托管文档,再导入到 ReadtheDocs。我们可以使用这个工具写文档、记笔记等。

搭建过程

安装 Sphinx

$ sudo pip install sphinx

创建wiki目录

使用 sphinx 自带的配置工具 sphinx-quickstart 快速创建工程。

$ mkdir mywiki
$ sphinx-quickstart  //大部分使用默认选项,直接按回车即可
Welcome to the Sphinx 1.6.3 quickstart utility.
...
# 分离source和build目录,方便管理
> Separate source and build directories (y/n) [n]: y

# 指定工程名、作者名、版本号、语言
The project name will occur in several places in the built documentation.
> Project name: mywiki
> Author name(s): abnerzhao
> Project version []: 0.1
> Project release [0.1]:
> Project language [en]: zh_CN
...
Creating file ./source/conf.py.
Creating file ./source/index.rst.
Creating file ./Makefile.
Creating file ./make.bat.

Finished: An initial directory structure has been created.
...
$ ls
Makefile build    make.bat source

创建完成后,mywiki目录有以下文件:

  • build目录:运行make命令后,生成的文件都在这个目录里面
  • source目录:放置文档的源文件
  • make.bat:批处理命令
  • Makefile

修改配置文件

conf.py 文件包含了 sphinx 工程的所有配置选项,包括一些无法在 sphinx-quickstart 中进行设置的。

$ vi source/conf.py
...
html_theme = 'sphinx_rtd_theme' # 输出html的主题
...

使用 github 进行版本控制

首先在 github 创建新的仓库 mywiki,然后将本地的 mywiki/source 目录 push 到 mywiki 远程仓库。

$ cd source
$ echo "# mywiki" >> README.md
$ git init
$ git add .
$ git commit -m "first commit"
$ git remote add origin git@github.com:[yourusename]/mywiki.git
$ git push -u origin master

导入到 ReadtheDocs

首先到 github 中选择 mywiki 仓库,Settings / Services / Add ReadTheDocs

然后到 ReadtheDocs 网站 import mywiki 仓库,导入成功后可看到如下页面:

构建文档

现在 mywiki 目录只有默认内容,需要我们自己添加内容,然后构建。构建方式有两种:

  • 命令行执行 make html
  • ReadtheDocs 网站手动构建

我们先看一下默认构建出来是什么样子,执行make html 成功后,即可到 ReadtheDocs 网站阅读文档。

$ cd /Users/Mr-zhao/mywiki
$ ls
Makefile build    make.bat source
$ make html

简单的 wiki 就基本搭建完成了,后续我们需要添加内容。不过这玩意使用的 reStructureText 语法而不是我们熟悉的 Markdown,我们可以通过 pandoc 进行格式转换。reStructureText 的语法也比较简单。

开始写 wiki

简单添加些内容,看看效果

$ cat /Users/Mr-zhao/mywiki/index.rst
.. mywiki documentation master file, created by
   sphinx-quickstart on Sat Oct 14 14:26:23 2017.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

Abnerzhao's Wiki
=============================================

.. toctree::
   :maxdepth: 2
   :glob:

   programming/index

$ cd /Users/Mr-zhao/mywiki/source/programming 
$ cat index.rst
一、编程
==================

.. toctree::
    :maxdepth: 2
    :glob:

    python.rst
$ cat python.rst

1. Python
----------

1.1 基础知识
~~~~~~~~~~~~~~

1.2 爬虫
~~~~~~~~~~

1.3 Web
~~~~~~~~~
$ cd /Users/Mr-zhao/mywiki
$ make html  

再次查看文档:

小结

Sphinx + GitHub + ReadtheDocs 总体的使用感受比 GitBook 要好,GitBook 使用起来总感觉很慢。平时写博客记点东西都比较琐碎,使用 Sphinx 更规范系统些。

工具倒是搭建好,能否坚持系统地总结梳理知识,Emm….这是个问题!

参考

Sphinx使用手册 使用sphinx记笔记 如何用 ReadtheDocs、Sphinx 快速搭建写书环境