Skip to content

Instantly share code, notes, and snippets.

@trstringer
Created October 30, 2017 21:17
Show Gist options
  • Save trstringer/929b3dacdaab43bc2fb186d4e82d1f22 to your computer and use it in GitHub Desktop.
Save trstringer/929b3dacdaab43bc2fb186d4e82d1f22 to your computer and use it in GitHub Desktop.
Miki terminal workflow
#!/bin/bash
CWD=$(python -c "import os; print(os.getcwd())")
python3 -m venv venv
. venv/bin/activate
pip install -r requirements.txt
cat > ~/bin/miki << EOF
cd $CWD
. venv/bin/activate
python miki.py "\$@"
EOF
chmod 755 ~/bin/miki
"""miki search utility"""
import glob
import re
import os
import sys
def topics(search_term):
"""Retrieve all topics"""
repo_dir = os.path.dirname(os.path.realpath(__file__))
counter = 1
for found_filename in [_ for _ in glob.iglob('**/readme.md', recursive=True) if _ != 'readme.md']:
with open(os.path.join(repo_dir, found_filename), 'r') as found_file:
file_lines = [
_.replace('\n', '').replace('### ', '')
for _ in found_file.readlines()
if re.search(r'###\s.*{}'.format(search_term), _, re.IGNORECASE)
and 'mikird' not in _
]
for line in file_lines:
yield dict(index=counter, location=found_filename, topic=line)
counter += 1
def cache_data_filename():
"""Single source for cache filename"""
return os.path.join(os.path.dirname(os.path.abspath(__file__)), '.mikicache')
def cache_data():
"""Get the cached data"""
cached_filename = cache_data_filename()
try:
with open(cached_filename, 'r') as cached_file:
cached_lines = cached_file.readlines()
except FileNotFoundError:
return None
return cached_lines
def write_cache(data):
"""Write cache data to tmp file"""
cache_filename = cache_data_filename()
with open(cache_filename, 'w') as cache_file:
cache_file.writelines(data)
def parse_cache_data(data):
"""Parse the cache data"""
for line in data:
index = line[:line.index('-')]
line = line[line.index('-') + 1:]
location = line[:line.index('-')]
line = line[line.index('-') + 1:]
topic = line
yield dict(index=index, location=location, topic=topic)
def display_topic(topic):
"""Display entire topic by topic title"""
repo_dir = os.path.dirname(os.path.realpath(__file__))
readme_filename = os.path.join(repo_dir, topic['location'])
with open(readme_filename) as readme_file:
lines = readme_file.readlines()
in_current_found_section = False
for line in [i.replace('\n', '') for i in lines]:
if in_current_found_section:
# if there is a line that matches '###\s.*' then this would be
# the start of a new section and we want to stop displaying
if re.search(r'^###\s.*', line):
break
else:
print(line)
else:
if line == '### {}'.format(topic['topic'].replace('\n', '')):
in_current_found_section = True
print(line)
def main():
"""Main program execution"""
if len(sys.argv) < 2:
inputarg = '.'
else:
inputarg = sys.argv[1]
# if the search term is an integer than reference a cached entry
# otherwise search for the term and cache the results
if re.search(r'^\d+$', inputarg):
previous_search = cache_data()
if not previous_search:
print('No cached search found')
sys.exit(1)
for stuff in parse_cache_data(previous_search):
if stuff['index'] == inputarg:
display_topic(stuff)
break
else:
cache_lines = []
for i in topics(inputarg):
print('[{}] ({}) {}'.format(
i['index'],
re.search(r'^(.+)/', i['location']).group(1),
i['topic']
))
cache_lines.append('{}-{}-{}'.format(i['index'], i['location'], i['topic']))
write_cache('\n'.join(cache_lines))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment