Last active
January 5, 2024 00:37
-
-
Save posoo/146f97697d885bf4d6f060ccb96c5539 to your computer and use it in GitHub Desktop.
macOS Finder.app: Save and restore tags.
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
import os | |
import click | |
import mac_tag | |
import json | |
def scan(root): | |
os.chdir(root) | |
print('Working on ', os.getcwd()) | |
paths = [] | |
for path, subdirs, files in os.walk('.'): | |
paths += [os.path.join(path, item) for item in files] | |
paths += [os.path.join(path, item) for item in subdirs] | |
print('Found {} paths in total'.format(len(paths))) | |
return paths | |
def load_tags(json_file): | |
return json.load(open(json_file)) | |
def read_tags_save_to_json_file(root, json_file): | |
paths = scan(root) | |
tags = mac_tag.get(paths) | |
tags = {k.strip(): v for k, v in tags.items()} | |
with open(json_file, 'w') as f: | |
json.dump(tags, f, indent=4) | |
print('Scanned {} paths and saved to {}'.format(len(tags), json_file)) | |
return tags | |
def update_tags(tags): | |
for path, tag_list in tags.items(): | |
mac_tag.update(tag_list, [path]) | |
print('Updated: {}-{}'.format(path, tag_list)) | |
def clear_tags(paths): | |
mac_tag.remove(['*'], paths) | |
print('Tags of {} files are ALL CLEARED!'.format(len(paths))) | |
@click.command() | |
@click.option('--root', type=click.Path(exists=False), required=True) | |
@click.option('--json', type=click.Path(exists=False), required=True) | |
def load(root, json): | |
json_abs_path = os.path.abspath(json) | |
read_tags_save_to_json_file(root, json_abs_path) | |
@click.command() | |
@click.option('--root', type=click.Path(exists=False), required=True) | |
def clear(root): | |
paths = scan(root) | |
clear_tags(paths) | |
@click.command() | |
@click.option('--root', type=click.Path(exists=False), required=True) | |
@click.option('--json', type=click.Path(exists=False), required=True) | |
def update(root, json): | |
tags = load_tags(json) | |
print('Loaded {} tag records.'.format(len(tags))) | |
os.chdir(root) | |
print('Working on ', os.getcwd()) | |
update_tags(tags) | |
@click.group() | |
def cli(): | |
pass | |
cli.add_command(load) | |
cli.add_command(clear) | |
cli.add_command(update) | |
if __name__ == "__main__": | |
cli() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment