如何進行lint-check

前幾天嘗試在一個 Latex 作為主要語言的專案當中自動進行 lint check,就在這裡筆記一下學到的事情吧。

要做的事情有兩個,將指令寫到 Makefile 當中,並將自動化流程定義在 .github/workflows 的 yaml 檔裡,走過得步驟是:

在自己的電腦上行可行性測試

確認自己的想法是否可行,直接的想法是直接在自己的電腦上進行一遍。首先是找到 linter 並安裝:

1
sudo apt install chktex

然後就可以使用 chktex.tex檔進行 lint check:

1
chktex cese.tex projection.tex ustmesh.tex

這個時候chktex會對這些檔案進行靜態分析,有可能會跳出很多 warning,可以暫時不管,後面在回頭把 warning 消除。

將指令加入makefile

接著就是將指令寫到 Makefile 當中

1
2
3
4
5
6
.PHONY: tex
tex:
chktex cese.tex projection.tex ustmesh.tex

.PHONY: lint
lint: tex

完成後就可以用 make lint來 lint check 囉。

在這裡藉由了兩個target來完成任務:linttex,藉由一個 target 同樣可以達到需求。用兩個是考量到後續可能需要會加入其他語言的 linter ,當有多個 linter 在一個專案中做使用時,這可以增加可讀性與結構性,如 modmesh 的 lint check

1
2
3
4
5
6
7
8
9
10
11
12
13
14
.PHONY: cformat
cformat: $(CFFILES)
...

.PHONY: cinclude
cinclude: $(CFFILES)
if ...

.PHONY: flake8
flake8:
cmake --build ...

.PHONY: lint
lint: cformat cinclude flake8

將自動化流程定義在 .github/workflows 的 yaml檔裡

回到一開始在電腦上的測試,讓chktex能在電腦上能使用,我們也需將個 dependency 寫入自動化文件中的 jobs 裡:

1
2
3
4
5
6
7
jobs:
...
- name: dependency by apt
run: |
...
# for lint
sudo apt-get -qy install chktex

再將 lint check 的指令也寫入:

1
2
3
4
5
jobs:
...
- name: lint check
run: |
make lint

接著就差一步就完成囉~

消除 warning

前面所產生的 warning 會返回非0的數值,進而導致 github action 的 ci test 不通過。這個問題就要回歸 chktex 的 document 一一將警告消除拉。根據文件方法有三:

  • 依照 linter 的規定走,修改我們所攥寫的.tex文件。
  • 如果覺得 linter 的規定跟需求不符,可以在創一個.chktexrc的文件,在裡頭客製化修改 linter 的規定:
    1
    2
    3
    4
    5
    6
    # Appends
    NumDash { 1 } #Warning 8

    # Overwrite
    Linker = { \vref \pageref \eqref } # Warning 2
    PostLink = { \index } # Warning 24
  • 但並非每一個 warning 都能夠客製設定,這時候就可以藉由 per-line suppression 或是 per-file suppression:
    • Per-line suppression: 針對單行的程式碼抑制 warning ,在想要抑制的那行程式尾端加入% chktex ##
      1
      \hat{j} % chktex 7
    • Per-file suppression: 針對單一文件抑制 warning ,在想要抑制的那分文件於開頭加入% chktex-file ##
      1
      2
      3
      4
      5
      % chktex-file 7

      \RequirePackage[2020-02-02]{latexrelease}
      \documentclass[11pt,dvips]{article}
      ...

接著就可以 Push 回 github,大功告成囉~