Skip to content

Instantly share code, notes, and snippets.

@jordanlambrecht
Last active July 6, 2024 22:29
Show Gist options
  • Save jordanlambrecht/66efceb22f6eae87d49e75405b7c3cd5 to your computer and use it in GitHub Desktop.
Save jordanlambrecht/66efceb22f6eae87d49e75405b7c3cd5 to your computer and use it in GitHub Desktop.
Add the _kMDItemUserTags color tag xattr onto MacOS files via Python
#!/usr/bin/env python3
# Created by Jordan Lambrecht, https://github.com/jordanlambrecht, https://jordanlambrecht.com
# 1) Create an env via `python3 -m venv myenv` and `source myenv/bin/activate`
# 2) Install xattr via `pip3 install xattr`
# 3) Change the variables file_path and color as desired
# 4) Set the script to be executable via `chmod +x ./color-tagger.py`
# 5) Run the script via `python3 ./color-tagger.py`
# 6) Get a broom to push off all the ladies swarming you because of how well-organized and sexy your filesystem is
import xattr
file_path = './test2.txt'
color = 'green'
def set_color_tag(file_path, color):
# Color mapping as per the documentation
color_map = {
"none": 0,
"grey": 1,
"green": 2,
"purple": 3,
"blue": 4,
"yellow": 5,
"red": 6,
"orange": 7
}
if color not in color_map:
print(f"Invalid color: {color}")
return
color_value = color_map[color]
# tag_value = f"Purple\n{color_value}"
tag_value = f'''
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
<string>{color}
{color_value}</string>
</array>
</plist>'''
try:
# Remove the existing attribute if it exists
try:
xattr.removexattr(file_path, 'com.apple.metadata:_kMDItemUserTags')
except OSError:
pass # Ignore if the attribute does not exist
# Set the extended attribute using pyxattr
xattr.setxattr(file_path, 'com.apple.metadata:_kMDItemUserTags', tag_value.encode('utf-8'))
print(f"Color tag set to {color} for file {file_path}")
except OSError as e:
print(f"Error setting color tag: {e}")
if __name__ == "__main__":
set_color_tag(file_path, color)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment