-
-
Save al3xandru/e10547141f9e3c47179c to your computer and use it in GitHub Desktop.
Alfred quick question workflow -- a script filter triggered with python $HOME/bin/qq.py "{query}"
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
#!/usr/local/env python | |
import argparse | |
import codecs | |
import os | |
import subprocess | |
import sys | |
DEBUG = False | |
FILE_PREFIX = 'qq-' | |
FILE_EXT = '.md' | |
SAVE_DIR = os.path.expanduser('~/Dropbox/ka/nvall') | |
SEARCH_DIRS = (SAVE_DIR, os.path.expanduser('~/Dropbox/ka/knarc/Files')) | |
def main(action, args): | |
if action == 'add': | |
add(args) | |
else: | |
search(args) | |
def add(args): | |
new_file = os.path.join(SAVE_DIR, "%s.md" % ' '.join(args)) | |
if os.path.exists(new_file): | |
if DEBUG: | |
print "WARN: A file for qq already exists '%s'" % new_file | |
else: | |
with open(new_file, 'a+') as fout: | |
fout.flush() | |
subprocess.call(['open', new_file]) | |
_ALFRED_ITEM_TEMPLATE = u""" | |
<item arg="%(arg)s" uid="%(uid)s"> | |
<title>%(title)s</title> | |
<subtitle>%(subtitle)s</subtitle> | |
</item>""" | |
_NO_RESULTS = u""" | |
<?xml version="1.0"?> | |
<items> | |
<item uid="noresults" arg="noresults" valid="yes"> | |
<title>No results</title> | |
<subtitle>Unfortunately your quick question remained unanswered</subtitle> | |
</item> | |
</items> | |
""" | |
def search(args): | |
cmd = ['mdfind'] | |
for dir in SEARCH_DIRS: | |
cmd.append('-onlyin') | |
cmd.append(dir) | |
cmd.append('-interpret') | |
cmd.append("filename:%s AND filename:%s AND %s" % (FILE_PREFIX, FILE_EXT, ' '.join(args))) | |
if DEBUG: | |
print "[DEBUG]: %s" % cmd | |
results = subprocess.check_output(cmd) | |
if results: | |
output_results(results) | |
else: | |
print _NO_RESULTS | |
def output_results(result_output): | |
xml_result = u"" | |
i = 0 | |
for line in result_output.splitlines(False): | |
bname = os.path.basename(line) | |
question = bname[len(FILE_PREFIX):-len(FILE_EXT)] | |
entry = {'uid': question.replace(' ', ''), 'arg': line, 'title': question + ':'} | |
with codecs.open(line, 'r', 'utf8') as fin: | |
for li in fin: | |
if li.strip(): | |
entry['subtitle'] = li.strip().replace('<', '<').replace('>', '>') | |
break | |
xml_result += _ALFRED_ITEM_TEMPLATE % entry | |
i += 1 | |
print (u"""<?xml version="1.0"?>\n<items>""" + xml_result + u"""\n</items>""").encode('utf8') | |
if __name__ == '__main__': | |
if len(sys.argv) < 2: | |
print "ERROR: Usage %s [-a|--add] question" % sys.argv[0] | |
sys.exit(1) | |
action = 'search' | |
idx = 1 | |
if sys.argv[1] in ('-a', '--add'): | |
action = 'add' | |
idx = 2 | |
main(action, sys.argv[idx:]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment