Skip to content

Commit fbb0a71

Browse files
tgamblinCeleritasCelery
authored andcommitted
Add option to only blacken if the project uses black
* only blacken on save if the project uses black To make it easier to use blacken across multiple projects, some of which are *not* using black, add the following changes to blacken.el: 1. `blacken.el` now searches for a `pyproject.toml` file in parent directories of the current buffer. 2. If it finds such a file, it checks whether there is a `[tool.black]` section in it, and it only blackens on save if there is. This allows me to auto-blacken my Python code for projects that use black, but to avoid code churn in projects that do not. * make blacken-only-if-project-is-blackened an option
1 parent e076442 commit fbb0a71

File tree

1 file changed

+21
-2
lines changed

1 file changed

+21
-2
lines changed

blacken.el

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,11 @@ If `fill', the `fill-column' variable value is used."
7474
:type 'boolean
7575
:safe 'booleanp)
7676

77+
(defcustom blacken-only-if-project-is-blackened nil
78+
"Only blacken if project has a pyproject.toml with a [tool.black] section."
79+
:type 'boolean
80+
:safe 'booleanp)
81+
7782
(defun blacken-call-bin (input-buffer output-buffer error-buffer)
7883
"Call process black.
7984
@@ -113,9 +118,21 @@ Return black process the exit code."
113118
(when blacken-skip-string-normalization
114119
(list "--skip-string-normalization"))
115120
(when (string-match "\.pyi$" (buffer-file-name (current-buffer)))
116-
(list "--pyi"))
121+
(list "--pyi"))
117122
'("-")))
118123

124+
(defun blacken-regex-in-file (regex file)
125+
"Reads a file and returns a list of lines in that file"
126+
(with-temp-buffer
127+
(insert-file-contents file)
128+
(re-search-forward regex nil t 1)))
129+
130+
(defun blacken-project-is-blackened (&optional display)
131+
"Whether the project has a pyproject.toml with [tool.black] in it."
132+
(let ((parent (locate-dominating-file default-directory "pyproject.toml")))
133+
(and parent
134+
(blacken-regex-in-file "^\\[tool.black\\]$" (concat parent "pyproject.toml")))))
135+
119136
;;;###autoload
120137
(defun blacken-buffer (&optional display)
121138
"Try to blacken the current buffer.
@@ -150,7 +167,9 @@ Show black output, if black exit abnormally and DISPLAY is t."
150167
"Automatically run black before saving."
151168
:lighter " Black"
152169
(if blacken-mode
153-
(add-hook 'before-save-hook 'blacken-buffer nil t)
170+
(when (or (not blacken-only-if-project-is-blackened)
171+
(blacken-project-is-blackened))
172+
(add-hook 'before-save-hook 'blacken-buffer nil t))
154173
(remove-hook 'before-save-hook 'blacken-buffer t)))
155174

156175
(provide 'blacken)

0 commit comments

Comments
 (0)