tl;dr: ==、!=、&&、||を使っている時に、warningを出すcoffeelintのcustom ruleを作ったよ
coffeescriptの有名なcoding styleとして、polarmobileがあります。このcoding styleに則って書いているのですが、coding styleを維持するために、何か良いツールがないか探した所、coffeelintなるものを見つけました。
coffeelintでもある程度カバーできるのですが、カバーできない部分で、自分で実装できそうな部分をcustom ruleとして作りました。
具体的には、==、!=、&&、||を使っている場合に、warningを出すルールです。polar mobileのcoding styleでは
i is i # Yes
i == i # No
の様に、英語風のoperatorを優先して使う様に、勧めています。coffeelint標準のオプションでは、なかったので、実装しました。coffeelintのcustom ruleを作る事自体は簡単で、
module.exports = class RuleProcessor
rule:
name: 'custome_rule_name'
description: 'description of custom rule.'
level: 'error' # or 'warn'
message: 'message shown when lint failed'
# add one from below
lintLine: (line, lineApi) ->
# return true if lint fails
lintToken(token, tokenApi) ->
lintNode(node, nodeApi) ->
で終わりです。あとはlintLine、lintToken、lintNodeの中身を実装するだけです。今回作ったcustom ruleは、正規表現を使った簡単なもので、
lintLine: (line, lineApi) ->
/[&|\||\=]{2}|\!\=/.test(line)
のみです。
使う時は、
npm installでcoffeelint-prefer-english-operatorをインストールcoffeelint --makeconfig > coffeelint.jsonでcoffeelint.jsonを作成coffeelint.jsonに以下を足します
"prefer_english_operator": {
"module": "coffeelint-prefer-english-operator",
"level": "error"
}
あとはcoffeelint *.coffeeでlintしたいcoffeeファイルを指定すれば、lintしてくれます。
感想
npmに不慣れで、色々とハマりましたが、custom ruleを作る事自体はとても簡単でした。