@kyanny's blog

My thoughts, my life. Views/opinions are my own.

Python: Git ブランチ名に .py が含まれると flake8 が誤作動する場合がある

  1. Git ブランチ名に .py が含まれる(例: fix/foo.py
  2. flake8--exclude オプションを指定して実行する(例: flake8 --exclude venv .

という条件を満たすと、以下のようなエラーが発生することがある。

./.git/logs/refs/heads/foo.py:1:42: E999 SyntaxError: invalid syntax
./.git/logs/refs/heads/foo.py:1:80: E501 line too long (157 > 79 characters)
./.git/logs/refs/heads/foo.py:1:98: E225 missing whitespace around operator
./.git/logs/refs/heads/foo.py:1:114: E225 missing whitespace around operator
./.git/logs/refs/heads/foo.py:1:128: E225 missing whitespace around operator
./.git/logs/refs/heads/foo.py:2:80: E501 line too long (150 > 79 characters)
./.git/logs/refs/heads/foo.py:2:98: E225 missing whitespace around operator
./.git/logs/refs/heads/foo.py:2:114: E225 missing whitespace around operator
./.git/logs/refs/heads/foo.py:2:128: E225 missing whitespace around operator
./.git/logs/refs/remotes/origin/foo.py:1:42: E999 SyntaxError: invalid syntax
./.git/logs/refs/remotes/origin/foo.py:1:80: E501 line too long (146 > 79 characters)
./.git/logs/refs/remotes/origin/foo.py:1:98: E225 missing whitespace around operator
./.git/logs/refs/remotes/origin/foo.py:1:114: E225 missing whitespace around operator
./.git/logs/refs/remotes/origin/foo.py:1:128: E225 missing whitespace around operator
./.git/refs/heads/foo.py:1:2: E999 SyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers
./.git/refs/remotes/origin/foo.py:1:1: F821 undefined name 'da7d6585eeac60722e04b10f612acb327e9cd72c'

これは、

  • --exclude オプションを明示したことによって flake8--exclude オプションの初期値がクリアされる(初期値には .git が含まれる)
  • flake8.git 以下をチェック対象にする
  • .git 以下に Git が内部的に利用するファイルがあるが、ブランチ名に .py が含まれるとそれらのファイルが Python スクリプトのように見える
  • flake8 が見かけ上 Python スクリプトっぽいファイルに syntax check を実施してエラーを出す

という仕組みで発生しているようだ。

対策としては、 --extend-exclude オプションを利用する。

$ flake8 --extend-exclude venv .