Last active
March 22, 2024 13:55
-
-
Save minrk/a6006e75d60c4d53e08dbb5cfc0b6271 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Format stdin with ruff to stdout | |
When formatting fails, append error message | |
For use in an Automator Quick Action (Run Shell Script), | |
accessible everywhere via right click -> Services > ruff format, | |
or global keyboard shortcut registered in System Settings > Keyboard > Keyboard Shortcuts | |
Find the action under Services | |
""" | |
# SPDX-License-Identifier: CC0-1.0 | |
# public domain, no rights reserved | |
import sys | |
from subprocess import run | |
ruff_exe = "/opt/homebrew/bin/ruff" | |
source = sys.stdin.read() | |
p = run( | |
[ruff_exe, "format", "-"], input=source, capture_output=True, text=True, check=False | |
) | |
if p.returncode: | |
# format failed (probably SyntaxError), keep original code and append error | |
print(source) | |
print(p.stderr) | |
else: | |
print(p.stdout) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
# lighter version using just sh | |
src=$(cat -) | |
# pipe error to stdout, so error messages are captured | |
echo "$src" | /opt/homebrew/bin/ruff format - 2>&1 | |
exit_code=$? | |
if [ $exit_code -ne 0 ]; then | |
# if error, echo original source | |
# since we are replacing text | |
# error message will be at the top | |
echo "$src" | |
fi | |
echo # trailing newline |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To use this:
Step 1. create a new Automator workflow. Select Quick Action
Step 2: just one step, Run Shell Script with the above Python code (Shell: /usr/local/bin/python3), or shell script (Shell: /bin/sh)
Settings:
text
inany application
Output replaces selected text
Step 3 (optional): Register global keyboard shortcut. Pick one that's available in every application you might use this (hard!), and set it for your Quick Action in System Settings > Keyboard > Keyboard Shortcuts > Services:
While you're there, probably uncheck lots of things registered by applications that you've never used.
Now you can format code in any text box anywhere, by keyboard shortcut or right-click, including in GitHub or forum comments!