文章目錄
前言
本文最終實現的是:利用Github Actions自動導出Gitbook並將其部署到Github Pages。
效果展示:https://wangzhebufangqi.github.io/Leetcode/
項目github地址:https://github.com/wangzhebufangqi/auto-export-gitbook
(如果覺得有趣,不妨點個star!😄后續更新第一時間會放在這個倉庫)
最開始的靈感來源為使用 travis + gitbook + github pages 優雅地發布自己的書1,后來在學習的過程中發現Github Actions和Github結合的更加密切,因此將Travis CI替換成了Github Actions,並在原文的基礎上進行了一系列優化。
本文涉及到的主要工具、技術有:
- markdown
- gitbook
- git/github
- github pages
- travis ci
- github actions
默認你會以下的技能:
- 使用過github,掌握了一定的命令
- fq
Getting Started
如果你想快速使用👉使用方法
(最終使用時本地無需安裝gitbook,本地只需要配置好git環境)
Gitbook
安裝
環境需求
- NodeJS(4.0及以上版本)
- Windows, Linux, Unix, 或 Mac OS X
其中,NodeJS可在其官網(https://nodejs.org/zh-cn/)下載安裝。安裝好后可查看版本號:
利用npm安裝gitbook
安裝好NodeJS后,可利用它的包管理器(npm)安裝gitbook:
npm install gitbook-cli -g
npm的包安裝分為本地安裝(local)、全局安裝(global)兩種
本地安裝:
npm install xxx 安裝到命令行所在目錄的node_module目錄。
全局安裝:
npm install xxx -g 安裝到 \AppData\Roaming\npm\node_modules目錄
gitbook-cli是一個實用程序,可在同一系統上安裝和使用多個版本的gitbook。 它將自動安裝所需版本的gitbook。安裝好后可查看版本號:
創建
gitbook能創建模板書:
gitbook init [./directory]
最后一個參數為創建的目錄,可省略,默認為當前目錄下。
命令執行完后會生成兩個文件:README.md
和SUMMARY.md
README.md文件用來介紹該書籍,SUMMARY.md文件為該書籍的目錄。
對SUMMARY.md文件進行如下編輯:
# Summary
* [Introduction](README.md)
* [Easy](easy/README.md)
* [1.Two Sum](easy/1.Two Sum.md)
* [7.Reverse Integer](easy/7.Reverse Integer.md)
* [Medium](medium/README.md)
* [2.Add Two Numbers](medium/2.Add Two Numbers.md)
* [3.Longest Substring Without Repeating Characters](medium/3.Longest Substring Without Repeating Characters.md)
再次執行命令gitbook init
,如果目錄里的文件不存在,將會自動創建:
然后我們對其中的md文件編寫相應的內容即可。
輸出
website
執行命令可進行預覽:
gitbook serve ./{book_name}
最后一個參數指定輸出靜態網站內容的目錄,可省略,默認會在當前目錄下新建一個子目錄_book
:
若只執行gitbook build
,會生成_book目錄,但不能預覽。
_book目錄中包含以下文件:
│ index.html
│ search_index.json
│
├─easy
│ 1.Two Sum.html
│ 1.Two Sum.md
│ 7.Reverse Integer.html
│ 7.Reverse Integer.md
│ index.html
│ README.md
│
├─gitbook
│ │ gitbook.js
│ │ style.css
│ │ theme.js
│ │
│ ├─fonts
│ │ └─fontawesome
| | ..(略)
│ ├─gitbook-plugin-fontsettings
| | ..
│ ├─gitbook-plugin-highlight
│ │ ..
│ ├─gitbook-plugin-livereload
│ │ ..
│ ├─gitbook-plugin-lunr
│ │ ..
│ ├─gitbook-plugin-search
│ │ ..
│ ├─gitbook-plugin-sharing
│ │ ..
│ └─images
│ apple-touch-icon-precomposed-152.png
│ favicon.ico
└─medium
2.Add Two Numbers.html
2.Add Two Numbers.md
3.Longest Substring Without Repeating Characters.html
3.Longest Substring Without Repeating Characters.md
index.html
README.md
可以看到原md文件都對應生成了一個html文件(README.md生成了index.html),新生成的gitbook文件夾包含了一些主題、樣式、字體、插件、圖像等。
同時也可以看到,默認加載了7個插件。關於插件的內容,后文會詳細介紹。
在網址localhost:4000
即可預覽書籍,即本機的4000端口。按CTRL+C鍵
可退出,退出后,瀏覽器頁面點擊目錄不再跳轉。
這時候如果想將書籍提供給他人閱讀,豈不是只需要將這個靜態網站打包,再上傳到服務器上即可?沒錯!就是這樣。
ebook
gitbook創建的書籍還可以導出為電子書,比如pdf、epub和mobi格式。
gitbook pdf ./ ./mybook.pdf
gitbook epub ./ ./mybook.epub
gitbook mobi ./ ./mybook.mobi
其中,最后一個參數表示輸出文件的文件名,可省略,默認輸出為當前目錄下的book文件。
再前面一個參數表示gitbook所在的目錄。
直接運行上述命令可能會報錯,導出電子書之前,需先安裝一款本地電子書管理工具:Calibre
安裝后記得將其安裝根目錄添加到環境變量PATH中
然后就可以成功的導出為電子書了。
轉成的pdf格式如下:
可惜的是有個小問題,導出的pdf無論是左側書簽還是TOC目錄,在跳轉上存在着一些問題。但是導出的epub和mobi都非常棒。
配置
所有的配置都以JSON格式存儲在名為 book.json
的文件中。主要有以下字段:
字段 | 示例 | 說明 |
---|---|---|
gitbook | { “gitbook”: “>=2.0.0” } | 探測用來生成書本的GitBook的版本。格式是一個 SEMVER 條件。 |
title | {“title”: “Summary”} | 書名,默認從README中提取 |
authon | {“author”: “tom”} | 作者名 |
description | { “description”: “This is my first book!” } | 定義了書本的描述,默認是從 README(第一段)中提取的。 |
isbn | { “isbn”: “978-7-115-32010-0” } | 定義了書本的ISBN |
language | { “language”: “fr” } | 定義了書本的語言,默認值是 en |
direction | { “direction”: “rtl” } | 用來重新設置語言的文字方向的。rtl:從右至左。ltr:從左至右 |
styles | {“styles”: { “website”: “styles/website.css”, “pdf”: “styles/pdf.css” } } | 自定義書本的css |
plugins | { “plugins”: [“myplugins”] } | 插件列表 |
pluginsConfig | { “pluginsConfig”: { “myplugins”: { “message”: “Hello World” } } } | 插件配置 |
structure | { “structure”: {“readme”: “INTRO.md” } } | 指定README,SUMMARY等文件的路徑 |
variables | { “variables”: { “myTest”: “Hello World” } } | 定義在 模板 中使用的變量值 |
links | “links” : { “sidebar” : { “Home” : “https://wangzhebufangqi.github.io” } } | 在左側導航欄添加鏈接信息 |
插件
插件是擴展 GitBook 功能(電子書和網站)最好的方式。
查找插件
在nmp官網(https://www.npmjs.com/ )上搜索關鍵詞gitbook-plugin
或gitbook
即可
添加插件
添加至book.json
文件后,再執行命令gitbook install
將插件下載至本地即可
{
"plugins": ["myPlugin", "anotherPlugin"]
}
刪除插件
如果不想使用自帶的插件,在插件名稱前面加-
:
{
"plugins":[ "-search"]
}
如果不是自帶的,將其從插件列表中去掉即可。
插件推薦:
折疊目錄👉Expandable-chapters-small
{
"plugins": ["expandable-chapters-small"]
}
提供非官方的github按鈕(star, fork, sponsor, and follow )👉github-buttons
{
"plugins": [
"github-buttons"
],
"pluginsConfig": {
"github-buttons": {
"buttons": [{
"user": "azu",
"repo": "JavaScript-Plugin-Architecture",
"type": "star",
"size": "large"
}, {
"user": "azu",
"type": "follow",
"width": "230",
"count": false
}]
}
}
}
Option | Description | 備注 |
---|---|---|
user |
GitHub username that owns the repo/Username to sponsor | 必須,用戶名 |
repo |
GitHub repository to pull the forks and watchers counts | 必須,倉庫名 |
type |
Type of button to show: watch , fork , sponsor , or follow |
必須,4種類型之一 |
count |
Show the optional watchers or forks count: none by default or true |
可選,是否顯示計數 |
size |
Optional flag for using a larger button: none by default or large |
可選,按鈕大小 |
Google Analysis👉ga
{
"plugins": ["ga"],
"pluginsConfig": {
"ga": {
"token": "UA-XXXX-Y"
}
}
}
在Google Analysis官網(https://analytics.google.com/)(需fq)開通服務獲取Token
百度多渠道統計👉baidu-tongji-with-multiple-channel
單渠道:
{
"plugins": [
"baidu-tongji-with-multiple-channel"
],
"pluginsConfig": {
"baidu-tongji-with-multiple-channel": {
"token": "73be72a36cee8ef8daa9843c7861cecc"
}
}
}
推薦!百度統計官網:https://tongji.baidu.com/
Disqus評論插件👉disqus
{
"plugins": ["disqus"],
"pluginsConfig": {
"disqus": {
"shortName": "XXXXXXX"
}
}
}
登錄disqus官網(https://disqus.com/)(需fq),申請一個shortName。
頁面頂部編輯本頁👉editlink
{
"plugins": ["editlink"],
"pluginsConfig": {
"editlink": {
"base": "https://github.com/zhaoda/webpack-handbook/edit/master/content",
"label": "Edit This Page",
"multilingual": false
}
}
}
復制代碼按鈕👉copy-code-button
{
"plugins": ["copy-code-button"]
}
錨點導航-ex👉anchor-navigation-ex
{
"plugins": [
"anchor-navigation-ex"
]
}
- 給頁面H1-H6標題增加錨點效果
- 浮動導航模式
- 頁面內頂部導航模式
- 導航標題前的層級圖標是否顯示,自定義H1-H3的層級圖標
- plugins[“theme-default”],頁面標題層級與官方默認主題的
showLevel
層級關聯 - plugins[“theme-default”],插件樣式支持官網默認主題的三種樣式:White、Sepia、Night
- 在頁面中增加
<extoc></extoc>
標簽,會在此處生成TOC目錄 - 在頁面中增加
<!-- ex_nonav -->
標簽,不會在該頁面生成懸浮導航 - config.printLog=true,打印當前的處理進度,排錯很有用
- config.multipleH1=false,去掉丑陋的多余的1. 序號(如過您的書籍遵循一個MD文件只有一個H1標簽的話)
- config.showGoTop=true,顯示返回頂部按鈕 V1.0.11+
- config.float.floatIcon 可以配置浮動導航的懸浮圖標樣式 V1.0.12+
- 在頁面中增加
<!-- ex_nolevel -->
不會在該頁面生成層級序號 V1.0.12+
定制頁腳👉page-footer-ex
{
"plugins": [
"page-footer-ex"
],
"pluginsConfig": {
"page-footer-ex": {
"copyright": "[mrcode](https://github.com/zq99299)",
"markdown": true,
"update_label": "<i>updated</i>",
"update_format": "YYYY-MM-DD HH:mm:ss"
}
}
}
基於Prism的代碼高亮👉prism
使用prism時,要移除默認的代碼高亮插件highlight
{
"plugins": ["prism", "-highlight"]
}
選擇CSS樣式:(https://github.com/PrismJS/prism)
"pluginsConfig": {
"prism": {
"css": [
"prismjs/themes/prism-solarizedlight.css"
]
}
}
通過別名化現有前綴來支持非標准語法前綴:
"pluginsConfig": {
"prism": {
"lang": {
"flow": "typescript"
}
}
}
忽視某些語言:
"pluginsConfig": {
"prism": {
"ignore": [
"mermaid",
"eval-js"
]
}
}
中文搜索👉search-pro
{
"plugins": [
"-lunr", "-search", "search-pro"
]
}
捐贈打賞👉donate
{
"plugins": ["donate"],
"pluginsConfig": {
"donate": {
"wechat": "例:/images/qr.png",
"alipay": "http://blog.willin.wang/static/images/qr.png",
"title": "默認空",
"button": "默認值:Donate",
"alipayText": "默認值:支付寶捐贈",
"wechatText": "默認值:微信捐贈"
}
}
}
左側拖拽欄👉splitter
{
"plugins": ["splitter"]
}
…
更多插件推薦可參考gitbook常用的插件2
其他
自動生成SUMMARY.md文件
前面提到,修改SUMMARY.md文件后,再執行gitbook init
命令可以創建不存在的文件。那么是否存在一種方法,使得新創建md文件后,無需去手動修改SUMMARY.md呢?
(若是不去修改SUMMARY.md文件呢?創建的md文件就不會被導出為html文件,加入不了靜態網站或電子書)
實際上,存在兩種方法可以自動生成SUMMARY.md文件,一種是gitbook-plugin-summary,另一種是Gitbook Summary。
第一種是一個插件,筆者嘗試了幾次沒有取得好的效果,這里就不采用它了。
第二種是先將其作為一個npm包,進行全局安裝,然后運行腳本,效果挺好。
下面對第二種方法進行簡單的介紹:
安裝
npm install -g gitbook-summary
下載到路徑:C:\Users\LENOVO\AppData\Roaming\npm\node_modules\gitbook-summary
使用
進入到項目根目錄,執行book sm
命令,即可生成SUMMARY.md文件。后面可帶參數:
PS F:\gitbookTest> book sm --help
Usage: summary|sm [options]
Generate a `SUMMARY.md` from a folder
Options:
-r, --root [string] root folder, default is `.`
-t, --title [string] book title, default is `Your Book Title`.
-c, --catalog [list] catalog folders included book files, default is `all`.
-i, --ignores [list] ignore folders that be excluded, default is `[]`.
-u, --unchanged [list] unchanged catalog like `request.js`, default is `[]`.
-o, --outputfile [string] output file, defaut is `./SUMMARY.md`
-s, --sortedBy [string] sorted by sortedBy, for example: `num-`, defaut is sorted by characters
-d, --disableTitleFormatting don't convert filename/folder name to start case (for example: `JavaScript` to `Java Script`), default is `false`
-h, --help output usage information
為了簡便,可以將參數寫入到book.json
文件中,比如:
{
"title": "json-config-name",
"outputfile": "test.md",
"catalog": "all", // or [chapter1,chapter2, ...]
"ignores": [], //Default: '.*', '_book'...
"unchanged": [], // for example: ['myApp'] -> `myApp` not `My App`
"sortedBy": "-",
"disableTitleFormatting": true // default: false
}
然后只需在命令行執行book sm
即可。
采用這種方式自動生成的SUMMARY.md文件:
# Summary
- [Easy](easy/README.md)
* [1.Two Sum](easy/1.Two Sum.md)
* [7.Reverse Integer](easy/7.Reverse Integer.md)
- [Medium](medium/README.md)
* [2.Add Two Numbers](medium/2.Add Two Numbers.md)
* [3.Longest Substring Without Repeating Characters](medium/3.Longest Substring Without Repeating Characters.md)
可參考的book.json文件
基礎版:
{
"title": "Summary",
"plugins" : [
"expandable-chapters",
"github-buttons",
"editlink",
"copy-code-button",
"page-footer-ex",
"anchor-navigation-ex",
"expandable-chapters-small",
"prism",
"-highlight",
"-lunr",
"-search",
"search-pro",
"donate",
"splitter"
],
"pluginsConfig": {
"editlink": {
"base": "https://github.com/wangzhebufangqi/ActionTest/tree/main",
"label": "Edit This Page"
},
"github-buttons": {
"buttons": [{
"user": "wangzhebufangqi",
"repo": "ActionTest",
"type": "star",
"size": "small"
}]
},
"page-footer-ex": {
"copyright": "By [wangzhebufangqi](https://github.com/wangzhebufangqi),使用[知識共享 署名-相同方式共享 4.0協議](https://creativecommons.org/licenses/by-sa/4.0/)發布",
"markdown": true,
"update_label": "<i>updated</i>",
"update_format": "YYYY-MM-DD HH:mm:ss"
},
"prism": {
"css": ["prismjs/themes/prism-solarizedlight.css"],
"lang": {"flow": "typescript"}
},
"donate": {
"wechat": "https://gitee.com/wangzhebufangqi/PictureBed/raw/master/20201122131942.png",
"alipay": "https://gitee.com/wangzhebufangqi/PictureBed/raw/master/20201122131820.png",
"title": "",
"button": "Donate",
"alipayText": "支付寶捐贈",
"wechatText": "微信捐贈"
}
},
"ignores" : ["_book", "node_modules"]
}
使用的插件無需在第三方網站上進行注冊。只需要修改對應的github用戶名與圖片鏈接即可。
小結
gitbook是一個基於Node.js的命令行工具,可使用Github/Git來制作精美的電子書。這部分介紹了gitbook的本地預覽,后文會介紹將其部署到Github Pages上。
Github Pages
概述
Github Pages 是面向用戶、組織和項目開放的公共靜態頁面搭建托管服務,站點可以被免費托管在 Github 上,你可以選擇使用 Github Pages 默認提供的域名 github.io 或者自定義域名來發布站點。
每個github賬號有且只有一個主頁站點(<username>.github.io),無限多的項目站點(<username>.github.io/repo)。
開通
新建github倉庫
如未開通主頁站點,先新建名為<username>.github.io
(如:wangzhebufangqi.github.io)的倉庫,再在其中添加文件index.html
即可訪問主頁站點,可能需要等10分鍾左右。
❗其實不開通主頁站點也能開通項目站點。
利用主頁站點配合jekyll、hexo等靜態博客生成系統可以搭建博客。可以參考筆者的博客搭建4。閑話休提,下面的主角是項目站點。
新建空倉庫gitbookTest
,不必勾選添加README.md文件
按前文所提到的,只需要將_book
中的文件上傳到該倉庫,再開通Github Pages就能訪問站點了。試一試:
cd _book
git init
git add . #添加_book目錄下的所有文件
git commit -m "first commit"
git branch -M main
git remote add origin https://github.com/wangzhebufangqi/gitbookTest.git #注意修改用戶名
git push -u origin main
push完成后倉庫目錄為:
設置Github Pages
進入倉庫,Settings -> Options -> Github Pages
選擇好分支與目錄,點擊Save。
訪問項目站點(wangzhebufangqi.github.io/gitbookTest):(下圖效果未新增插件,有時更新站點需要較長時間)
到這一步,已經成功的將gitbook生成的書籍部署到了Github Pages上。但是又有問題來了,每次新增或刪除文件時,都要執行gitbook build,進入到_book目錄,再手動push,能不能更簡單、智能一些呢?
新建gh-pages分支
Github支持一個名為Travis CI的服務,后面會提到,可以簡單看成能執行線上腳本的工具。這就需要將根目錄也push進倉庫。同時也可以發現,Github Pages可以選擇分支,這就提供了一種思路:
- 將項目根目錄下所有源文件push進倉庫的main分支
- 利用Travis CI服務生成_book
- 將_book中的所有文件push進同一個倉庫的gh-pages分支
- Github Pages依賴的分支設置為gh-pages(默認完成)
如此這般。下面在不利用Travis CI的情況下測試一遍:
刪除並新建github倉庫
進遠程倉庫,Settings -> Options ->Danger Zone -> Delete this repository
刪除遠程倉庫比較麻煩,為了方便這里將其直接刪除再重新新建(本地git記錄也要刪掉)。
將根目錄下所有文件push進main分支(gitbook編譯前)
git init
git add . #添加根目錄下的所有文件
git commit -m "first commit"
git branch -M main
git remote add origin https://github.com/wangzhebufangqi/gitbookTest.git #注意修改用戶名
git push -u origin main
gitbook編譯
gitbook build
在項目根目錄下重新生成_book文件夾
將_book目錄下所有文件push至gh-pages分支
cd _book
git init
git remote add origin https://github.com/wangzhebufangqi/gitbookTest.git
git add .
git commit -m "second commit"
git branch -M main
git push --force --quiet "https://github.com/wangzhebufangqi/gitbookTest.git" main:gh-pages #將_book中的main分支強制提交到遠程倉庫的gh-pages分支,不提示多余消息
可以看到創建分支成功
設置Github Pages依賴分支
會默認設置好為gh-pages的根目錄
小結
至此,整個流程的大概思路就清楚了:在main分支進行寫作,gitbook靜態網站資源保存至gh-pages分支。
其實生成的gitbook導出至gitbook.com可能會更方便。但是現在登錄該網站需要fq,而且對免費用戶的書籍也有數量限制。因此就選擇導出至Github Pages,數量無限制,而且又能DIY,最后實現也很方便,何樂而不為呢?
下一步是利用Travis CI服務,利用main分支的源文件,自動進行gitbook build,並把生成的靜態網站push到gh-pages分支,使得Github Pages生效。
Travis CI
概述
Travis CI是在軟件開發領域中的一個在線的,分布式的持續集成服務,用來構建及測試在GitHub托管的代碼。
Travis CI 提供的是持續集成服務(Continuous Integration,簡稱 CI)。它綁定 Github 上面的項目,只要有新的代碼,就會自動抓取。然后,提供一個運行環境,執行測試,完成構建,還能部署到服務器。
持續集成指的是只要代碼有變更,就自動運行構建和測試,反饋運行結果。確保符合預期以后,再將新代碼"集成"到主干。
開始使用
Travis CI的官方網站有兩個,https://travis-ci.org/為免費版,https://travis-ci.com/為收費版(有免費次數)。但是.org在2020/12/31后會更改為一個只讀的網站,目前正在進行.org向.com的遷移,所以這里選擇.com。
Q. When will the migration from travis-ci.org to travis-ci.com be completed? #
A. In an effort to ensure that all of our users - whether you build open-source, public or private repositories - receive regular feature updates, security patches and UX/UI enhancements, we are announcing that travis-ci.org will be officially closed down completely no later than December 31st, 2020, allowing us to focus all our efforts on bringing new features and fixes to travis-ci.com and all of our awesome users like yourself on the travis-ci.com domain.
Q. What will happen to travis-ci.org after December 31st, 2020? #
A. Travis-ci.org will be switched to a read-only platform, allowing you to see your jobs build history from all repositories previously connected to travis-ci.org.
登錄Travis CI
SIGN IN WITH GITHUB,登入之后點擊ACTIVATE ALL REPOSITORIES USING GITHUB APPS
批准安裝Travis CI
激活Travis Ci服務
點擊https://travis-ci.com/網站上方的Dashboard
會顯示Active respositories。
編寫.travis.yml
Travis 要求項目的根目錄下面,必須有一個
.travis.yml
文件。這是配置文件,指定了 Travis 的行為。該文件必須保存在 Github 倉庫里面,一旦代碼倉庫有新的 Commit,Travis 就會去找這個文件,執行里面的命令。
該文件采用的格式為YAML。示例:
language: python
sudo: required
before_install: sudo pip install foo
script: py.test
上面代碼中,設置了四個字段:運行環境是 python,需要sudo權限,在安裝依賴之前需要安裝foo模塊,然后執行腳本py.test。
下面根據此次任務編寫所需的.travis.yml文件:
language: node_js #運行環境為nodejs
node_js: #設置版本號
- "10"
cache: npm
notifications: #通知
email:
recipients:
- 1823636309@qq.com #設置通知郵件
on_success: change
on_failure: always
install: #install階段 安裝依賴
- npm install -g gitbook-cli #安裝gitbook
- gitbook install #安裝插件
- npm install -g gitbook-summary #使自動生成SUMMARY.md的一個工具
script: #script階段 運行腳本
- book sm #利用安裝的工具gitbook-summary自動生成SUMMARY.md文件
- gitbook build #gitbook編譯,生成靜態網站站點_book
after_script: #script階段之后執行
- cd _book #進入_book目錄
- git init
- git remote add origin https://${REF} #設置要托管到的倉庫名
- git add . #添加_book目錄下的所有文件
- git commit -m "Updated By Travis-CI With Build $TRAVIS_BUILD_NUMBER For Github Pages"
- git branch -M main
- git push --force --quiet "https://${TOKEN}@${REF}" main:gh-pages #強制推送到gh-pages分支
branches:
only:
- main
env:
global:
- REF=github.com/wangzhebufangqi/gitbookTest.git # 設置 github 地址
測試
創建github個人訪問令牌
為了使Travis CI有權限往github倉庫提交代碼,還需要在github上創建個人訪問令牌(Personal access tokens)
Settings -> Developer Settings -> Personal access tokens
點擊Generate new token
,勾選repo
,再點擊Generate Token
生成個人訪問令牌。
生成的個人訪問令牌詳細信息只會出現一次,妥善保存。
令牌填入Travis CI
回到Travis CI,選擇倉庫gitbookTest,More options -> Settings -> Environment Variables
將復制好的個人訪問令牌填入環境變量,將其命名為TOKEN
,前面的腳本用的就是這個值。
將項目托管至github
這里為了更直觀的看到效果,可以刪除遠程倉庫重新新建,並將本地.git文件、gitbook編譯生成的_book文件夾刪除,然后將上文提到的.travis.yml文件添加至項目根目錄,最后進行push:
git init
git add . #添加根目錄下的所有文件
git commit -m "first commit"
git branch -M main
git remote add origin https://github.com/wangzhebufangqi/gitbookTest.git #注意修改用戶名
git push -u origin main
push成功后,Travis CI檢測到有.travis.yml文件,收到任務(Job Received
),然后進行排隊(Queued
),再是開啟虛擬機(Booting virtual machine
),開始執行腳本,在Job log
欄可以查看進度/日志,View config
可以查看配置信息(.travis.yml)。
最后不出意外的話如下圖,如失敗請檢查上述步驟是否有錯漏之處(成功或失敗會發郵件通知):
檢查github可發現,gh-pages分支被創建並且更新了相關文件,項目站點也可以被訪問。
小結
到這部分,已經成功結合了gitbook+Github Pages+Travis CI,完成了最初的設想。但Travis CI到2021年可能會需要付費,因此下一部分考慮用Github Action替換Travis CI。
更多信息,如加密Token,.travis.yml完整的生命周期等,可參考持續集成服務Travis CI教程5
小插曲:
筆者一開始不知道竟然有兩個官網,在.org網站上遭遇了很長的排隊時長,一個多小時才開始執行腳本。
后來發現正值.org網站向.com網站遷移完成之際,難怪如此。
關於Travis CI以后是否還面向免費用戶,官網上有個相關的Q&A:
Q. Will Travis CI be getting rid of free users? #
A. Travis CI will continue to offer a free tier for public or open-source repositories on travis-ci.com and will not be affected by the migration.
現在免費用戶有10000初始積分(Credit),build會消耗積分,關於后續積分補充可能需要申請或氪金。
Github Actions
概述
GitHub Actions 是 GitHub 的持續集成服務,於2018年10月推出。
持續集成由很多操作組成,比如抓取代碼、運行測試、登錄遠程服務器,發布到第三方服務等等。GitHub 把這些操作就稱為 actions。
很多操作在不同項目里面是類似的,完全可以共享。GitHub 注意到了這一點,想出了一個很妙的點子,允許開發者把每個操作寫成獨立的腳本文件,存放到代碼倉庫,使得其他開發者可以引用。
如果你需要某個 action,不必自己寫復雜的腳本,直接引用他人寫好的 action 即可,整個持續集成過程,就變成了一個 actions 的組合。這就是 GitHub Actions 最特別的地方。
github官方的actions放在https://github.com/actions,可以進行引用,比如:
name: learn-github-actions #文件名
on: [push] #push觸發
jobs:
check-bats-version:
runs-on: ubuntu-latest #運行環境設置為支持的最新版ubuntu
steps:
- uses: actions/checkout@v2 #https://github.com/actions/checkout/tree/v2
- uses: actions/setup-node@v1 #https://github.com/actions/setup-node/tree/v1
- run: npm install -g bats
- run: bats -v
更多細節可參考Github Actions官方文檔6
快速開始
GitHub Actions 的配置文件叫做 workflow 文件,存放在代碼倉庫的
.github/workflows
目錄。
github新建遠程空倉庫ActionTest
,本地新建文件夾ActionTest
,新建文件README.md,新建目錄.github/workflows
,在該目錄下新建文件test.yml
,文件內容參見上一節。
git init
git add .
git commit -m "first commit"
git branch -M main
git remote add origin https://github.com/wangzhebufangqi/ActionTest.git
git push -u origin main
進行push后,Github Actions檢測到文件.github/workflows/test.yml
,開始執行腳本
點擊進去查看工作日志
一些版本信息如下:
比如設置的ubuntu為18.04.5的LTS版本、用到了兩個github官方的actions:checkout和setup-node
Current runner version: '2.274.2'
Operating System
Ubuntu
18.04.5
LTS
Virtual Environment
Environment: ubuntu-18.04
Version: 20201115.1
Included Software: https://github.com/actions/virtual-environments/blob/ubuntu18/20201115.1/images/linux/Ubuntu1804-README.md
Prepare workflow directory
Prepare all required actions
Getting action download info
Download action repository 'actions/checkout@v2'
Download action repository 'actions/setup-node@v1'
可以嘗試更多命令,此處不贅述。熟悉之后開始編寫這次所需要的.yml文件。
編寫.github/workflow/*.yml
.yml文件縮進很重要,YAML、YML在線編輯(校驗)器可以檢驗yml格式是否正確。
主要命令已經在.travis.yml寫過了,這里將其轉換為Github Actions所需的格式:
name: auto-generate-gitbook
on: #在main分支上進行push時觸發
push:
branches:
- main
jobs:
main-to-gh-pages:
runs-on: ubuntu-latest
steps:
- name: checkout main
uses: actions/checkout@v2
with:
ref: main
- name: install nodejs
uses: actions/setup-node@v1
- name: configue gitbook
run: | npm install -g gitbook-cli gitbook install npm install -g gitbook-summary
- name: generate _book folder
run: | book sm gitbook build cp SUMMARY.md _book
- name: push _book to branch gh-pages
env:
TOKEN: ${{ secrets.TOKEN }}
REF: github.com/${{github.repository}}
MYEMAIL: 1823636309@qq.com # !!記得修改為自己github設置的郵箱
MYNAME: ${{github.repository_owner}}
run: | cd _book git config --global user.email "${MYEMAIL}" git config --global user.name "${MYNAME}" git init git remote add origin https://${REF} git add . git commit -m "Updated By Github Actions With Build ${{github.run_number}} of ${{github.workflow}} For Github Pages" git branch -M main git push --force --quiet "https://${TOKEN}@${REF}" main:gh-pages
測試
新建Person Access Token
在個人設置里生成一個新的個人令牌,權限僅選擇repo
即可。進入倉庫,點擊Settiings -> Secrets -> New repository
,將其命名為TOKEN
。
將項目托管至github
添加一些測試的md文件,在前文push的基礎上再進行push:
git add .
git commit -m "update"
git push
項目站點:https://wangzhebufangqi.github.io/ActionTest/
測試成功。
小結
至此,成功的用Github Actions替代了Travis CI。Github Actions比起Travis CI,Github Actions毫無疑問和Github結合的更好,用戶可以使用他人分享在GitHub Marketplace的workflows,非常方便。而且對開源倉庫是免費的。
一些錯誤:
一個step
中不能同時含有鍵uses
和run
設置email和name
后記
筆者最開始是因為實在太喜歡gitbook樣式的書籍了,就想着自己DIY一下,於是在學習的過程中學到了很多。后面會慢慢改進的。