#coding: utf-8
import workflow
import fnmatch
import os
import editor
def get_words(filename, ignore_case=True):
with open(filename) as fp:
for line in fp:
for word in line.split():
if ignore_case:
word = word.lower()
yield word
def get_parameters(action_in):
inputs = action_in.split('\n') +['']*5
wordlist, path, include_pattern, exclude_pattern, ignore_case = [i.strip() for i in inputs[:5]]
if ignore_case == '':
ignore_case = True
else:
if ignore_case == 'ON':
ignore_case = True
else:
ignore_case = False
if path:
if path == '.':
path = os.path.split(editor.get_path())[0]
elif not path.startswith('/'):
path = os.path.join(os.path.expanduser('~/Documents'), path)
else:
path = os.path.expanduser('~/Documents')
return (wordlist, path, include_pattern, exclude_pattern, ignore_case)
def search_files(wordlist, directory, ignore_case=True,
include_pattern=None, exclude_pattern=None):
if ignore_case:
wordset = set([w.lower() for w in wordlist.split()])
else:
wordset = set(wordlist.split())
fnlist = []
for dirpath, dirs, files in os.walk(directory):
for filename in files:
fname = os.path.join(dirpath, filename)
to_include = True
if exclude_pattern:
if fnmatch.fnmatch(filename, exclude_pattern):
to_include = False
if include_pattern and to_include:
if not fnmatch.fnmatch(filename, include_pattern):
to_include = False
if to_include:
if wordset.issubset(get_words(fname, ignore_case)):
fnlist.append(fname.split('Documents/')[1])
return fnlist
action_in = workflow.get_input()
wordlist, path, include_pattern, exclude_pattern, ignore_case = get_parameters(action_in)
#print(wordlist, path, include_pattern, exclude_pattern, ignore_case)
action_out = '\n'.join(search_files(wordlist, path,
ignore_case=ignore_case,
include_pattern=include_pattern,
exclude_pattern=exclude_pattern))
print(action_out)
workflow.set_output(action_out)
There are no comments yet.