写在前面

本工具是通过Python脚本实现 GitBook 自动 生成 执行 编译 发布的功能

你可以在这里下载exe

使用

1. exe下载,并移动位置

将exe文件放在你的任意文件夹中

2. file.md

创建 名为file.md的文件,在你要写book的目录下

注意: 这里file.md文件名不可更改

3. 编辑文件内容

类似这样

1
2
3
4
01_JVM内存与垃概述.md
02_如何看术与JVM.md
03_为什学习JVM.md
04_面课程特点.md

4. 运行

gitbook-tools-21.4.18.exe

1618599141367

gitbook-tools-21.4.23.exe

1618654713205

5. 执行

1:生成md

运行这条选项会根据file.md每行的文本生成对应文件

1618599290568

并且在每个文件中自动加入 一级标题

1618599404144

现在就可以编写主要内容了

2: 转换SUMMARY

执行这条命令会根据file.md每行的文本生成

目录格式的 SUMMARY.md

生成后的文件如下

1618599578828

如果你可以自己写SUMMARY,这步可以忽略

3. 编译build

这步相当于

在终端直接敲

1
gitbook build

不同的是,如果你没有README文件,会自动创建

1618599701544

编译后,会在当前目录生成_book
文件夹,里面为编译后的HTML,可供发布或部署

4. git 指令

1
2
3
git add _book
git commit -m\"Commit by gitbook tool!!!\"
git push

这里 add 只是add了 _book 文件夹

commit的信息的固定的

push时,如果是已经clone下来自己的库,能够直接push

否则要先登录

5. gitee pages

gitee pages 部署,这个update

只有gitee pro 会员才能够 支持自动 更新

但是这里可以通过py提供了一些代码参考

先 tag一个 TODO

环境

Python: 3.7

GitBook CLI version: 2.3.2

GitBook version: 3.2.3

Node.js v15.8.0

npm@7.10.0

Pycharm 2021.3

Pyinstaller

Gitee Pages

Gitbook 介绍

GitBook 是一个基于 Node.js 的命令行工具,可使用 Github/Git 和 Markdown 来制作精美的电子书,GitBook 并非关于 Git 的教程。

Gitbook教程

安装遇到的问题

实现功能

  1. 生成md文件列表,通过读取文件,创建md文件

  2. 生成SUMMARY.md 替换文件名 为 Gitbook的SUMMARY格式

  3. build 编译gitbook ,html格式以便发布

  4. git 自动 push _book文件夹

  5. gitee pages 自动update(dev)

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
'''
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Created by victor
# Created Time: '2021/4/17 0:42'
'''

'''
version: 21.4.18
TODO : gitee pages auto sync!!!
'''
import os
# import sys
# import re


# dir 是全路径
# 比如: E:\Projects\PycharmProjects\untitled\test\database\redis\2019-09-25-deepin-install-redis.md
# :param dir:
# :return:
class GitbookTool:
def __init__(self):
self.sum_file_name = "file.md"
# 当前脚本目录
# self.pypath = sys.path[0]
# self.pypath = os.getcwd()
self.pypath = input("please input the root path(windows split symbol is \\)\n:")
# self.root_path = self.pypath
# sour_path source 源 路径
self.sour_path = self.pypath + "\\" + self.sum_file_name
# SUMMARY.md 路径
self.summary_path = self.pypath + "\\" + "SUMMARY.md"
print("| self.pypath >>> ",self.pypath)
def repSpilt(self, path):
"""
替换路径分隔符
:param path:
:return:
"""
return path.replace("\\", "\\\\")

def newFile(self, line, dirname):
'''
创建文件
:param line:
:param dirname:
:return:
'''
print("| gen file >>>")
# 新建文件的文件名,最后的\n去掉
newName = dirname + "\\" + line[:-1]
print("| \t", line[:-1])
with open(newName, "w", encoding="utf-8") as f2:
f2.write("# " + line[:-4])

def for_line(self, file):
'''
读取 sm文件,并遍历行
:param file:
:return:
'''
# 获取目录
dirname = os.path.dirname(file)
with open(file, "r", encoding="utf-8") as f1:
i = 0
for line in f1:

if line == "\n":
# line 是空行
pass
else:
# 判断line是不是最后一行
if line[-1] != "\n":
# 加上换行
line += "\n"

i += 1
self.newFile(line, dirname)

print("| gen ", i, "file success!!!")
print("| path:", dirname)

def gen_md(self):
"""
生成md文件
:return:
"""
# 获取输入
print("| -----------------------------------------------------")
print("| md文件生成器")
print("| 通过读取file.md文件中的行数来创建文件")
print("| 生成的文件会和源文件同目录")
print("| 注意:原有文件会被替换")
# print("| 请输入源目录文件路径,window用 \ 来分隔文件夹")
# sourceFile = input(":")

# E:\Projects\PycharmProjects\untitled\newFile
# sourceFile = self.pypath + "\\" + "SUMMARY.md"
self.for_line(self.repSpilt(self.sour_path))
os.system('pause')

def gitbook_build(self):
'''
编译gitbook

:return:
'''
# fname = self.pypath + +"\\"+"SUMMARY.md"
# os.path.isfile(fname)
rname = self.pypath + "\\" + "README.md"
# print("rname >>> ",rname)
if os.path.isfile(rname):
# 文件存在
pass
else:
with open(rname, "w", encoding="utf-8") as f2:
f2.write("This file is generated by py script!!!\n")
f2.write("Please write the contents of the README.md")
print("| building...")
os.chdir(self.pypath)
os.system("gitbook build")
os.system('pause')

def replace_sum(self):
with open(self.sour_path, "r", encoding="utf-8") as f1, open(self.summary_path, "w", encoding="utf-8") as f2:
i = 0
for line in f1:
if line == "\n":
# line 是空行
pass
else:
# 判断line是不是最后一行
i += 1
if line[-1] != "\n":
# 加上换行
line += "\n"
f2.write("- [")
f2.write(line[:-4])
f2.write("](")
f2.write(line[:-1])
f2.write(")")
f2.write("\n")
print("| gen summary success!!!")
print("| total effect line:",i)
os.system('pause')
def qucik_git(self):
os.chdir(self.pypath)
os.system("git add _book")
os.system("git commit -m\"Commit by gitbook tool!!!\"")
os.system("git push")
os.system('pause')

def menu(self):
# 获取输入
# print("| =========================================")
# print("| ================ gitbook tools ================")
print("| --------------------------- gitbook tools ---------------------------")
print("| 1:生成md")
print("| 2: 转换SUMMARY")
print("| 3: 编译>HTML")
print("| 4: 发布Git")
print("| 0: exit()")
print("| --------------------------- gitbook tools ---------------------------")

return input("| choose operation you need:")



if __name__ == '__main__':
yt = '''
┌─┐ ┌─┐ + +
┌──┘ ┴───────┘ ┴──┐++
│ │
│ ─── │++ + + +
███████───███████ │+
│ │+
│ ─┴─ │
│ │
└───┐ ┌───┘
│ │
│ │ + +
│ │
│ └──────────────┐
│ │
│ ├─┐
│ ┌─┘
│ │
└─┐ ┐ ┌───────┬──┐ ┌──┘ + + + +
│ ─┤ ─┤ │ ─┤ ─┤
└──┴──┘ └──┴──┘ + + + +
神兽保佑
代码无BUG!

'''
print(yt)
print("| --------------------------- gitbook tools ---------------------------")
print("| @version: 21.4.18")
print("| @description: gitbook tools auto gen file & build & sync to git")
print("| @author: victor")
print("| @site: https://victorfengming.gitee.io/")
print("| @introduce: https://victorfengming.gitee.io/comic/python-gitbook-tools/")
print("| @readme: https://victorfengming.gitee.io/file/exe/gitbook-tools/readme.md")
print("| @download: https://victorfengming.gitee.io/file/exe/gitbook-tools/gitbook-tools-21.4.18.exe")
print("| --------------------------- gitbook tools ---------------------------")
print("| 注意:使用前请将exe文件放到file.md同级目录下")
# print("| ========================================")
# print(os.path.isfile("E:\\Projects\\PycharmProjects\\untitled\\newFiletest\\12.md"))
gt = GitbookTool()
while True:
cho = gt.menu()
if cho == "1":
print(1)
gt.gen_md()
elif cho == "2":
print(2)
gt.replace_sum()
elif cho == "3":
print(3)
gt.gitbook_build()
elif cho == "4":
print(4)
gt.qucik_git()
elif cho == "0":
# print("| bye~")
exit(0)


gitee page 代码(dev)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52


from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait as Wait

print("start refresh gitee pages...")

repo_user_name = "victorfengming"
repo_name = "shell"
login_user = "victorfengming"
login_pwd = "xxxx"

url = "https://gitee.com/"+repo_user_name+"/"+repo_name+"/pages"

driver = "E:\\chrome\\chromedriver.exe"
chrome_options = Options()
chrome_options.add_argument("--window-size=1920,1080")
chrome_options.add_argument("--start-maximized")
chrome_options.add_argument("--headless")
browser=webdriver.Chrome(executable_path=driver, options=chrome_options)

browser.get(url)

Wait(browser, 10).until(EC.presence_of_element_located((By.CLASS_NAME, "item.git-nav-user__login-item")))
print("load finish. url=" + url)
login_btn = browser.find_element_by_class_name("item.git-nav-user__login-item")
login_btn.click()

Wait(browser, 10).until(EC.presence_of_element_located((By.ID, "user_login")))
Wait(browser, 10).until(EC.presence_of_element_located((By.ID, "user_password")))
print("login page load finish.")
user_input = browser.find_element_by_id("user_login")
pwd_input = browser.find_element_by_id("user_password")
login_btn = browser.find_element_by_name("commit")
user_input.send_keys(login_user)
pwd_input.send_keys(login_pwd)
login_btn.click()

Wait(browser, 10).until(EC.presence_of_element_located((By.CLASS_NAME, "button.orange.redeploy-button.ui.update_deploy")))
print("login finish.")
deploy_btn = browser.find_element_by_class_name('button.orange.redeploy-button.ui.update_deploy')

browser.execute_script("window.scrollTo(100, document.body.scrollHeight);")
deploy_btn.click()
dialog = browser.switch_to.alert
dialog.accept()
print("refresh gitee pages finish.")
browser.close()

参考: https://www.jianshu.com/p/6460df84a099

https://blog.csdn.net/weixin_29981095/article/details/113987875

Pyinstaller

1618600264685

设置 运行参数

1
-F $FileNameWithoutExtension$.py

TODO

gitee pages 自动update(dev)

tkinter界面

附录源码

cmd 版本 (fix bug)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
'''
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Created by victor
# Created Time: '2021/4/17 0:42'
'''

'''
version: 21.4.18
TODO : gitee pages auto sync!!!
'''
import os
# import sys
# import re


# dir 是全路径
# 比如: E:\Projects\PycharmProjects\untitled\test\database\redis\2019-09-25-deepin-install-redis.md
# :param dir:
# :return:
class GitbookTool:
def __init__(self):
self.sum_file_name = "file.md"
# 当前脚本目录
# self.pypath = sys.path[0]
# self.pypath = os.getcwd()
self.pypath = input("please input the root path(windows split symbol is \\)\n:")
# self.root_path = self.pypath
# sour_path source 源 路径
self.sour_path = self.pypath + "\\" + self.sum_file_name
# SUMMARY.md 路径
self.summary_path = self.pypath + "\\" + "SUMMARY.md"
print("| self.pypath >>> ",self.pypath)
def repSpilt(self, path):
"""
替换路径分隔符
:param path:
:return:
"""
return path.replace("\\", "\\\\")

def newFile(self, line, dirname):
'''
创建文件
:param line:
:param dirname:
:return:
'''
print("| gen file >>>")
# 新建文件的文件名,最后的\n去掉
newName = dirname + "\\" + line[:-1]
print("| \t", line[:-1])
with open(newName, "w", encoding="utf-8") as f2:
f2.write("# " + line[:-4])

def for_line(self, file):
'''
读取 sm文件,并遍历行
:param file:
:return:
'''
# 获取目录
dirname = os.path.dirname(file)
with open(file, "r", encoding="utf-8") as f1:
i = 0
for line in f1:

if line == "\n":
# line 是空行
pass
else:
# 判断line是不是最后一行
if line[-1] != "\n":
# 加上换行
line += "\n"

i += 1
self.newFile(line, dirname)

print("| gen ", i, "file success!!!")
print("| path:", dirname)

def gen_md(self):
"""
生成md文件
:return:
"""
# 获取输入
print("| -----------------------------------------------------")
print("| md文件生成器")
print("| 通过读取file.md文件中的行数来创建文件")
print("| 生成的文件会和源文件同目录")
print("| 注意:原有文件会被替换")
# print("| 请输入源目录文件路径,window用 \ 来分隔文件夹")
# sourceFile = input(":")

# E:\Projects\PycharmProjects\untitled\newFile
# sourceFile = self.pypath + "\\" + "SUMMARY.md"
self.for_line(self.repSpilt(self.sour_path))
os.system('pause')

def gitbook_build(self):
'''
编译gitbook

:return:
'''
# fname = self.pypath + +"\\"+"SUMMARY.md"
# os.path.isfile(fname)
rname = self.pypath + "\\" + "README.md"
print("rname >>> ",rname)
if os.path.isfile(rname):
# 文件存在
pass
else:
with open(rname, "w", encoding="utf-8") as f2:
f2.write("This file is generated by py script!!!\n")
f2.write("Please write the contents of the README.md")

# bookignore = self.pypath + +"\\"+"SUMMARY.md"
# os.path.isfile(fname)
bookignore = self.pypath + "\\" + ".bookignore"
if os.path.isfile(bookignore):
# 文件存在 啥也不干
pass
else:
with open(bookignore, "w", encoding="utf-8") as f2:
f2.write("file.md")


print("| building...")
os.chdir(self.pypath)
os.system("gitbook build")
os.system('pause')

def replace_sum(self):
with open(self.sour_path, "r", encoding="utf-8") as f1, open(self.summary_path, "w", encoding="utf-8") as f2:
i = 0
for line in f1:
if line == "\n":
# line 是空行
pass
else:
# 判断line是不是最后一行
i += 1
if line[-1] != "\n":
# 加上换行
line += "\n"
f2.write("- [")
f2.write(line[:-4])
f2.write("](")
f2.write(line[:-1])
f2.write(")")
f2.write("\n")
print("| gen summary success!!!")
print("| total effect line:",i)
os.system('pause')
def qucik_git(self):

os.chdir(self.pypath)
os.system("git add _book")
os.system("git commit -m\"Commit by gitbook tool!!!\"")
os.system("git push")
os.system('pause')

def menu(self):
# 获取输入
# print("| =========================================")
# print("| ================ gitbook tools ================")
print("| --------------------------- gitbook tools ---------------------------")
print("| 1:生成md")
print("| 2: 转换SUMMARY")
print("| 3: 编译>HTML")
print("| 4: 发布Git")
print("| 0: exit()")
print("| --------------------------- gitbook tools ---------------------------")

return input("| choose operation you need:")



if __name__ == '__main__':
yt = '''
┌─┐ ┌─┐ + +
┌──┘ ┴───────┘ ┴──┐++
│ │
│ ─── │++ + + +
███████───███████ │+
│ │+
│ ─┴─ │
│ │
└───┐ ┌───┘
│ │
│ │ + +
│ │
│ └──────────────┐
│ │
│ ├─┐
│ ┌─┘
│ │
└─┐ ┐ ┌───────┬──┐ ┌──┘ + + + +
│ ─┤ ─┤ │ ─┤ ─┤
└──┴──┘ └──┴──┘ + + + +
神兽保佑
代码无BUG!

'''
print(yt)
print("| --------------------------- gitbook tools ---------------------------")
print("| @version: 21.4.22")
print("| @description: gitbook tools auto gen file & build & sync to git")
print("| @author: victor")
print("| @site: https://victorfengming.gitee.io/")
print("| @introduce: https://victorfengming.gitee.io/comic/python-gitbook-tools/")
print("| @readme: https://victorfengming.gitee.io/file/exe/gitbook-tools/readme.md")
print("| @download: https://victorfengming.gitee.io/file/exe/gitbook-tools/gitbook-tools-21.4.22.exe")
print("| --------------------------- gitbook tools ---------------------------")
print("| 注意:使用前请将exe文件放到file.md同级目录下")
# print("| ========================================")
# print(os.path.isfile("E:\\Projects\\PycharmProjects\\untitled\\newFiletest\\12.md"))
gt = GitbookTool()
while True:
cho = gt.menu()
if cho == "1":
print(1)
gt.gen_md()
elif cho == "2":
print(2)
gt.replace_sum()
elif cho == "3":
print(3)
gt.gitbook_build()
elif cho == "4":
print(4)
gt.qucik_git()
elif cho == "0":
# print("| bye~")
exit(0)


图形Tk版本

main.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
# 导包
from tkinter import *
from tkinter import filedialog, messagebox
from gitbook_tools import GitbookTool

'''

| --------------------------- gitbook tools ---------------------------
| @version: 21.4.23
| @description: gitbook tools auto gen file & build & sync to git
| @author: victor
| @site: https://victorfengming.gitee.io/
| @introduce: https://victorfengming.gitee.io/comic/python-gitbook-tools/
| @readme: https://victorfengming.gitee.io/file/exe/gitbook-tools/readme.md
| @download: https://victorfengming.gitee.io/file/exe/gitbook-tools/gitbook-tools-21.4.23.exe
| --------------------------- gitbook tools ---------------------------
| TODO :
| 1. 递归扫描md文件,根据相对路径 生成`SUMMARY.md`
| 2. cmd 日志 放入 tk页面
| 5. gitee pages auto update by chrome tools
| --------------------------- gitbook tools ---------------------------

'''
class Tk_gui():

def __init__(self, gt):
'''
初始化魔术方法
用于设置界面的初始状态
'''
# 创建tkinter窗口
self.root = Tk()
# 设置窗口的标题
self.root.title('Gitbook Tools')
# 设置窗口的长和宽,最大值和最小值设置相同,用户不可调整窗口大小
self.root.minsize(90, 180)
self.root.maxsize(780, 180)
self.gt = gt
self.root_path = ""

# 初始化
# 初始化主要url

# 调用主要逻辑执行函数
self.main_logic()

def main_logic(self):
'''
主业务逻辑
:return:
'''
# 顶部信息栏
topp = Frame()
topp.grid(row=0, column=0)
# 内容栏
self.cont = Frame()
self.cont.grid(row=1, column=0)
# 输入选项操作
self.indo = Frame()
self.indo.grid(row=0, column=1, rowspan=2)

# 状态栏
self.stat = Frame()
self.stat.grid(row=2, column=0)

# self.get_path()
self.put_button()

# 加入主消息循环
self.root.mainloop()
# #
# self.myStdout() # 实例化重定向类
# self.restoreStd() # 恢复标准输出

def put_button(self):
'''
用于绘制顶部菜单
:param topp:
:return:
'''
# 菜单栏
# print("| 1:生成md")
# print("| 2: 转换SUMMARY")
# print("| 3: 编译>HTML")
# print("| 4: 发布Git")
# print("| 0: exit()")
self.gen_button("设置工作路径", self.get_path).grid(row=0, column=0)
self.gen_button("生成md", lambda: self.button_run_before(gt.gen_md)()).grid(row=1, column=0)
self.gen_button("转换SUMMARY", lambda: self.button_run_before(gt.replace_sum)()).grid(row=2, column=0)
self.gen_button("编译>HTML", lambda: self.button_run_before(gt.gitbook_build)()).grid(row=3, column=0)
self.gen_button("发布Git", lambda: self.button_run_before(gt.qucik_git)()).grid(row=4, column=0)

def gen_button(self, text, method):
'''
生成 button
:param text:
:param method:
:return:
'''
return Button(self.cont, text=text, command=method, width=22)

def get_path(self):
self.root_path = filedialog.askdirectory()
print("getpath>>>",self.root_path)
# 将路径 从 图形类 传入 工具类
self.gt.pypath = self.root_path

# cmd 消息 放入 tk页面 (dev)
# def myStdout(self): # 重定向类
# # 将其备份
# self.stdoutbak = sys.stdout
# self.stderrbak = sys.stderr
# # 重定向
# sys.stdout = self
# sys.stderr = self
#
# def write(self, info):
# t = Text(self.cont) # 创建多行文本控件
# t.pack() # 布局在窗体上
# # info信息即标准输出sys.stdout和sys.stderr接收到的输出信息
# t.insert('end', info) # 在多行文本控件最后一行插入print信息
# t.update() # 更新显示的文本,不加这句插入的信息无法显示
# t.see(END) # 始终显示最后一行,不加这句,当文本溢出控件最后一行时,不会自动显示最后一行
#
# def restoreStd(self):
# # 恢复标准输出
# sys.stdout = self.stdoutbak
# sys.stderr = self.stderrbak


def button_run_before(self,func):
# 判断
# if func != self.get_path and self.root_path == "":
if self.root_path == "":
messagebox.showinfo('错误','请先设置工作路径')
self.get_path()
else:
return func

# print("| ========================================")
# print(os.path.isfile("E:\\Projects\\PycharmProjects\\untitled\\newFiletest\\12.md"))


# gt = GitbookTool(input("please input the root path(windows split symbol is \\)\n:"))

gt = GitbookTool()

t = Tk_gui(gt)

gitbook_tools.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249

'''
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Created by victor
# Created Time: '2021/4/17 0:42'
'''

'''
version: 21.4.18
TODO : gitee pages auto sync!!!
'''
import os
# import sys
# import re


# dir 是全路径
# 比如: E:\Projects\PycharmProjects\untitled\test\database\redis\2019-09-25-deepin-install-redis.md
# :param dir:
# :return:
class GitbookTool:
def __init__(self):
self.sum_file_name = "file.md"
self.summary_file_name = "SUMMARY.md"
self.readme_name = "README.md"
# 当前脚本目录
# self.pypath = sys.path[0]
# self.pypath = os.getcwd()
# self.pypath = input("please input the root path(windows split symbol is \\)\n:")
self.pypath = ""
# self.root_path = self.pypath
# sour_path source 源 路径
self.sour_path = self.pypath + "\\" + self.sum_file_name
# SUMMARY.md 路径
self.summary_path = self.pypath + "\\" + self.summary_file_name
print("| self.pypath >>> ",self.pypath)
def repSpilt(self, path):
"""
替换路径分隔符
:param path:
:return:
"""
return path.replace("\\", "\\\\")

def newFile(self, line, dirname):
'''
创建文件
:param line:
:param dirname:
:return:
'''
print("| gen file >>>")
# 新建文件的文件名,最后的\n去掉
newName = dirname + "\\" + line[:-1]
print("| \t", line[:-1])
with open(newName, "w", encoding="utf-8") as f2:
f2.write("# " + line[:-4])

def for_line(self, file):
'''
读取 sm文件,并遍历行
:param file:
:return:
'''
# 获取目录
dirname = os.path.dirname(file)
with open(file, "r", encoding="utf-8") as f1:
i = 0
for line in f1:
if line == "\n":
# line 是空行
pass
else:
# 判断line是不是最后一行
if line[-1] != "\n":
# 加上换行
line += "\n"

i += 1
self.newFile(line, dirname)

print("| gen ", i, "file success!!!")
print("| path:", dirname)

def gen_md(self):
"""
生成md文件
:return:
"""
# 获取输入
print("| -----------------------------------------------------")
print("| md文件生成器")
print("| 通过读取file.md文件中的行数来创建文件")
print("| 生成的文件会和源文件同目录")
print("| 注意:原有文件会被替换")
# print("| 请输入源目录文件路径,window用 \ 来分隔文件夹")
# sourceFile = input(":")

# E:\Projects\PycharmProjects\untitled\newFile
# sourceFile = self.pypath + "\\" + "SUMMARY.md"
sour_path = self.pypath + "\\" + self.sum_file_name
self.for_line(self.repSpilt(sour_path))
# os.system('pause')

def gitbook_build(self):
'''
编译gitbook

:return:
'''
# fname = self.pypath + +"\\"+"SUMMARY.md"
# os.path.isfile(fname)
rname = self.pypath + "\\" + self.readme_name
print("rname >>> ",rname)
if os.path.isfile(rname):
# 文件存在
pass
else:
with open(rname, "w", encoding="utf-8") as f2:
f2.write("This file is generated by py script!!!\n")
f2.write("Please write the contents of the README.md")

# bookignore = self.pypath + +"\\"+"SUMMARY.md"
# os.path.isfile(fname)
bookignore = self.pypath + "\\" + ".bookignore"
if os.path.isfile(bookignore):
# 文件存在 啥也不干
pass
else:
with open(bookignore, "w", encoding="utf-8") as f2:
f2.write("file.md\n")


print("| building...")
os.chdir(self.pypath)
os.system("gitbook build")
# os.system('pause')

def replace_sum(self):
# SUMMARY.md 路径
# 更新路径
summary_path = self.pypath + "\\" + self.summary_file_name
sour_path = self.pypath + "\\" + self.sum_file_name

# summary_path = self.pypath + "\\" + "SUMMARY.md"
with open(sour_path, "r", encoding="utf-8") as f1, open(summary_path, "w", encoding="utf-8") as f2:
i = 0
for line in f1:
if line == "\n":
# line 是空行
pass
else:
# 判断line是不是最后一行
i += 1
if line[-1] != "\n":
# 加上换行
line += "\n"
f2.write("- [")
f2.write(line[:-4])
f2.write("](")
f2.write(line[:-1])
f2.write(")")
f2.write("\n")
print("| gen summary success!!!")
print("| total effect line:",i)
# os.system('pause')
def qucik_git(self):

os.chdir(self.pypath)
os.system("git add _book")
os.system("git commit -m\"Commit by gitbook tool!!!\"")
os.system("git push")
# os.system('pause')

def menu(self):
# 获取输入
# print("| =========================================")
# print("| ================ gitbook tools ================")
print("| --------------------------- gitbook tools ---------------------------")
print("| 1:生成md")
print("| 2: 转换SUMMARY")
print("| 3: 编译>HTML")
print("| 4: 发布Git")
print("| 0: exit()")
print("| --------------------------- gitbook tools ---------------------------")

return input("| choose operation you need:")



if __name__ == '__main__':
yt = '''
┌─┐ ┌─┐ + +
┌──┘ ┴───────┘ ┴──┐++
│ │
│ ─── │++ + + +
███████───███████ │+
│ │+
│ ─┴─ │
│ │
└───┐ ┌───┘
│ │
│ │ + +
│ │
│ └──────────────┐
│ │
│ ├─┐
│ ┌─┘
│ │
└─┐ ┐ ┌───────┬──┐ ┌──┘ + + + +
│ ─┤ ─┤ │ ─┤ ─┤
└──┴──┘ └──┴──┘ + + + +
神兽保佑
代码无BUG!

'''
print(yt)
print("| --------------------------- gitbook tools ---------------------------")
print("| @version: 21.4.23")
print("| @description: gitbook tools auto gen file & build & sync to git")
print("| @author: victor")
print("| @site: https://victorfengming.gitee.io/")
print("| @introduce: https://victorfengming.gitee.io/comic/python-gitbook-tools/")
print("| @readme: https://victorfengming.gitee.io/file/exe/gitbook-tools/readme.md")
print("| @download: https://victorfengming.gitee.io/file/exe/gitbook-tools/gitbook-tools-21.4.23.exe")
print("| --------------------------- gitbook tools ---------------------------")
# print("| 注意:使用前请将exe文件放到file.md同级目录下")
# print("| ========================================")
# print(os.path.isfile("E:\\Projects\\PycharmProjects\\untitled\\newFiletest\\12.md"))
gt = GitbookTool(input("please input the root path(windows split symbol is \\)\n:"))
while True:
cho = gt.menu()
if cho == "1":
print(1)
gt.gen_md()
elif cho == "2":
print(2)
gt.replace_sum()
elif cho == "3":
print(3)
gt.gitbook_build()
elif cho == "4":
print(4)
gt.qucik_git()
elif cho == "0":
# print("| bye~")
exit(0)