import json
from argparse import ArgumentParser
from os import path

import requests


def make_request(endpoint, url, data=None):
    try:
        return requests.get(path.join(url, endpoint), json=None).json()
    except Exception as e:
        print(path.join(url, endpoint))
        raise e


def get_docs(url):
    return make_request('docs/docs.json', url)


def get_index(doc_set, url):
    return make_request(path.join('docs', doc_set, 'index.json'), url)

def priority(query, string):
    if string.startswith(query):
        return 2
    elif query in string:
        return 1
    else:
        return 0


def search_dicts(docs, query, key):
    matched_docs = []
    for doc in docs:
        doc['priority'] = priority(query, doc[key])
        if doc['priority'] > 0:
            matched_docs.append(doc)

    matched_docs.sort(key=lambda doc: (doc['priority'] * -1, doc[key]))
    return matched_docs

def docsets_handler(args):
    docsets = get_docs(args.url)
    for doc in search_dicts(docsets, ' '.join(args.filter), 'slug'):
        print(doc['slug'])


def search_handler(args):
    docset_index = get_index(args.doc_set, args.url)
    matched_docs = search_dicts(docset_index['entries'], ' '.join(args.query), 'name')
    for doc in matched_docs:
        print(doc['name'])


def create_parser():
    parser = ArgumentParser(description='Query devdocs.io')
    parser.add_argument('-u', '--url', help='base url of devdocs', default='https://devdocs.io')
    subparsers = parser.add_subparsers()

    search = subparsers.add_parser('search', help='search through one doc set')
    search.add_argument('doc_set', help='Document set to search')
    search.add_argument('query', nargs='*', help='Query to search')
    search.set_defaults(func=search_handler)

    docsets = subparsers.add_parser('docsets', help='search through one doc set')
    docsets.add_argument('filter', nargs='*', help='filter docsets')
    docsets.set_defaults(func=docsets_handler)

    return parser


def main():
    args = create_parser().parse_args()
    args.func(args)


if __name__ == '__main__':
    main()

@@ -5,16 +5,26 @@
 rt json%0A
+import re%0A
 from arg
@@ -75,70 +75,522 @@
 ath%0A
-%0Aimport requests%0A%0A%0Adef make_request(endpoint, url, data=None):
+from subprocess import run%0Afrom tempfile import NamedTemporaryFile%0A%0Afrom bs4 import BeautifulSoup%0Aimport requests%0A%0A%0ADEFAULT_URL='https://devdocs.io'%0ADOCS_URL='https://docs.devdocs.io'%0A%0A%0Adef make_request(endpoint, url, transform=False):%0A    # Should handle this in a better way%0A    # local devdocs allows docs/%3Cslug%3E/db.json, but devdocs.io%0A    # requires docs.devdocs.io/%3Cslug%3E/db.json%0A    if transform and url == DEFAULT_URL and endpoint.startswith('docs/'):%0A        url = DOCS_URL%0A        endpoint = endpoint%5B5:%5D
 %0A   
@@ -921,16 +921,351 @@
 , url)%0A%0A
+%0Adef get_db(doc_set, url):%0A    return make_request(path.join('docs', doc_set, 'db.json'), url, transform=True)%0A%0Adef view_in_elinks(string, tag=''):%0A    if tag:%0A        tag = '#' + tag%0A    with NamedTemporaryFile(suffix='.html') as tempfile:%0A        tempfile.write(string.encode('utf-8'))%0A        run(('elinks', tempfile.name + tag))%0A%0A%0A
 def prio
@@ -2082,24 +2082,433 @@
 c%5B'name'%5D)%0A%0A
+def view_handler(args):%0A    docset_index = get_index(args.doc_set, args.url)%0A    matched_docs = search_dicts(docset_index%5B'entries'%5D, ' '.join(args.query), 'name')%0A    if len(matched_docs) %3E 0:%0A        path = matched_docs%5B0%5D%5B'path'%5D%0A        db = get_db(args.doc_set, args.url)%0A        tag = ''%0A        if '#' in path:%0A            path, tag = path.split('#', maxsplit=1)%0A        view_in_elinks(db%5Bpath%5D, tag)%0A%0A
 %0Adef create_
@@ -2652,36 +2652,27 @@
 default=
-'https://devdocs.io'
+DEFAULT_URL
 )%0A    su
@@ -2963,24 +2963,266 @@
 h_handler)%0A%0A
+    view = subparsers.add_parser('view', help='view through one doc set')%0A    view.add_argument('doc_set', help='Document set to view')%0A    view.add_argument('query', nargs='*', help='Query to view')%0A    view.set_defaults(func=view_handler)%0A%0A
     docsets 

Add ability to view docs from terminal