Skip to content

Instantly share code, notes, and snippets.

@ttscoff
Last active May 18, 2021 01:51
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save ttscoff/beaad26bda3564544a3c97cedb21b73c to your computer and use it in GitHub Desktop.
Read MultiMarkdown metadata tags from files and apply them as macOS tags
#!/usr/bin/env ruby
# encoding: utf-8
#
# Read MultiMarkdown metadata tags from files and apply them as macOS tags
#
# Usage:
# mmdtagstomacos.rb *.md
require 'shellwords'
mmd = '/usr/local/bin/multimarkdown'
def apply_tags(file, tag_array)
raise "No tags" unless tag_array
raise "Invalid file specified" unless File.exists?(file)
plist = '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><array>'
plist += tag_array.map{|tag| "<string>#{tag}</string>"}.join('')
plist += '</array></plist>'
$stderr.puts("Tagging #{file} (#{tag_array.join(' ')})")
%x{xattr -w com.apple.metadata:_kMDItemUserTags '#{plist}' #{Shellwords.escape(file)}}
end
ARGV.each do |file|
file = File.expand_path(file)
if File.exists?(file)
mmd_tags = %x{#{mmd} -e tags #{Shellwords.escape(file)}}.strip
if mmd_tags.length > 0
# Handle any instances of tags in YAML/JSON array format, e.g. [tag1,tag2]
mmd_tags.sub!(/^\[(.*?)\]$/,'\1')
tag_array = mmd_tags.split(/,/).map{|t|
# trim spaces
t.strip!
# Avoid shell characters causing issues
Shellwords.escape(t)
}
apply_tags(file, tag_array)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment