Skip to content

Instantly share code, notes, and snippets.

@minrk
Last active March 22, 2024 13:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save minrk/a6006e75d60c4d53e08dbb5cfc0b6271 to your computer and use it in GitHub Desktop.
Save minrk/a6006e75d60c4d53e08dbb5cfc0b6271 to your computer and use it in GitHub Desktop.
"""
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)
#!/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
@minrk
Copy link
Author

minrk commented Mar 22, 2024

To use this:

Step 1. create a new Automator workflow. Select Quick Action

Screenshot 2024-03-22 at 13 38 14

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:

  • Workflow receives current text in any application
  • Check Output replaces selected text
Screenshot 2024-03-22 at 14 00 21

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:

Screenshot 2024-03-22 at 13 32 55

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!

Screenshot 2024-03-22 at 14 10 42

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment