Check Python Syntax in BBEdit with flake8

There are existing scripts out there that will run flake8 against a python file in BBEdit, but none of them worked quite the way I wanted. So here is mine:

(*
run flake8 against the frontmost BBEdit document
You need to install flake8 with
sudo easy_install flake8
more info here http://flake8.readthedocs.org/en/latest/
*)
property maxLength : 256
property maxComplexity : 12
property flakePath : "/usr/local/bin/flake8"
tell application "Finder"
-- reality check 0: is the flake8 binary installed?
if not (exists (POSIX file flakePath as alias)) then
display dialog "Could not find flake8 binary at '" & flakePath & "'"
return
end if
end tell
tell application "BBEdit"
-- reality check 1: is there a front most document
if not (exists text document 1) then
return
end if
if source language of text document 1 is not "Python" then
set thename to name of text document 1
display dialog "Document '" & n & "' does not seem to be Python!"
return
end if
save text document 1
set sourceFile to file of text document 1
end tell
set thepath to quoted form of POSIX path of (sourceFile as alias)
set r to do shell script flakePath & " --max-line-length=" & maxLength & " --max-complexity=" & maxComplexity & space & thepath & " --exit-zero"
set errorList to {}
repeat with x in every paragraph of r
set oldDelimiters to AppleScript's text item delimiters
set AppleScript's text item delimiters to {":"}
set {filepath, linenumber, charoffset, themessage} to every text item in x as list
set AppleScript's text item delimiters to oldDelimiters
tell application "BBEdit"
set errorCode to character 2 of themessage
if errorCode is "W" then
set thekind to warning_kind
else if errorCode is in {"E", "F"} then
set thekind to error_kind
else
set thekind to note_kind
end if
copy {result_document:text document 1, result_kind:thekind, result_file:filepath, result_line:linenumber, message:themessage} to end of errorList
end tell
end repeat
tell application "BBEdit"
make new results browser with data errorList with properties ¬
{name:"flake8 for " & thepath}
end tell

Before you can run this, you need to install flake with sudo easy_install flake8. Then you need to drop this script in ~/Library/Application Support/BBEdit/Scripts. You can launch it from the menu with the script icon.

Published by

ab

Mac Admin, Consultant, and Author