Skip to content

Commit c3a8d6b

Browse files
Merge pull request #29 from pranavbaburaj/master
Refactor and beatified the CLI #29
2 parents 5590ba6 + 3f1d304 commit c3a8d6b

5 files changed

Lines changed: 168 additions & 43 deletions

File tree

main.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,17 @@
11
#!/usr/bin/env python
2+
23
import argparse
34
from src.arguments.search import Search
4-
search_obj = Search()
5+
56
PARSER = argparse.ArgumentParser()
6-
PARSER.add_argument("-s", "--search", help="enable debug mode",
7+
PARSER.add_argument("-s",
8+
"--search",
9+
help="enable debug mode",
710
action="store_true")
811

912
ARGV = PARSER.parse_args()
1013

14+
search_flag = Search(ARGV)
15+
1116
if __name__ == "__main__":
12-
search_obj.search_args()
17+
search_flag.search_args()

requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,3 +4,4 @@ idna==2.10
44
requests==2.24.0
55
termcolor==1.1.0
66
urllib3==1.25.10
7+
rich==9.9.0

setup.py

Lines changed: 23 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,24 @@
1-
from setuptools import setup
2-
setup(
3-
name='dynamic',
4-
version='0.0.1',
5-
entry_points={
6-
'console_scripts': [
7-
'dynamic=main:search_obj.search_args'
8-
]
9-
}
1+
import setuptools
2+
3+
with open("README.md", "r", encoding="utf-8") as fh:
4+
long_description = fh.read()
5+
6+
DEPENDENCIES = []
7+
8+
setuptools.setup(
9+
name="dynamic",
10+
version="0.0.1",
11+
description="Search for your questions in stackoverflow",
12+
long_description=long_description,
13+
long_description_content_type="text/markdown",
14+
url="https://github.com/IndianOpenSourceFoundation/dynamic-cli",
15+
packages=setuptools.find_packages(),
16+
install_requires=DEPENDENCIES,
17+
entry_points={"console_scripts": ['dynamic=main:search_obj.search_args']},
18+
classifiers=[
19+
"Programming Language :: Python :: 3",
20+
"License :: OSI Approved :: MIT License",
21+
"Operating System :: OS Independent",
22+
],
23+
python_requires='>=3.6',
1024
)

src/arguments/search.py

Lines changed: 35 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,45 @@
11
#!/usr/bin/env python
22
import argparse
33
from termcolor import colored
4-
from .utility import Utility
4+
from .utility import Utility, SearchError
5+
import sys as sys
56

6-
PARSER = argparse.ArgumentParser()
7-
PARSER.add_argument(
8-
"-s", "--search", help="enable debug mode", action="store_true")
7+
class Prompt():
8+
def __init__(self, message):
9+
self.message = message
910

10-
ARGV = PARSER.parse_args()
11-
utility_obj = Utility()
11+
def prompt(self):
12+
print(colored(f"{self.message} [?] ", 'cyan'), end='')
13+
data = input()
1214

13-
14-
class Search:
15+
return str(data)
16+
class Search():
17+
def __init__(self, arguments):
18+
self.arguments = arguments
19+
self.utility_object = Utility()
1520

1621
def search_args(self):
17-
if ARGV.search:
18-
print("What do you want to search - ", end=" ")
19-
question = input()
20-
print("Tags : ", end=" ")
21-
tags = input()
22-
json_output = utility_obj.make_request(question, tags)
23-
questions = utility_obj.get_que(json_output)
22+
if self.arguments.search:
23+
queries = ["What do you want to search", "Tags"]
24+
query_solutions = []
25+
26+
# ask quesiton
27+
for each_query in queries:
28+
# Be careful if there are
29+
# KeyBpard Interupts or EOErrors
30+
try:
31+
prompt = Prompt(str(each_query)).prompt()
32+
except:
33+
sys.exit()
34+
35+
query_solutions.append(prompt)
36+
37+
question, tags = query_solutions[0], query_solutions[1]
38+
json_output = self.utility_object.make_request(question, tags)
39+
questions = self.utility_object.get_que(json_output)
2440
if questions == []:
25-
print(colored('No answer found,', 'red'),
26-
colored('Please try reddit', 'green'))
41+
# evoke an error
42+
search_error = SearchError("No answer found",
43+
"Please try reddit")
2744
else:
28-
utility_obj.get_ans(questions)
45+
self.utility_object.get_ans(questions)

src/arguments/utility.py

Lines changed: 101 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,67 @@
11
import requests
22
from termcolor import colored
3+
from rich.console import Console
4+
from rich.markdown import Markdown
5+
import sys as sys
36

7+
# the rich console
8+
console = Console()
49

5-
class Utility:
10+
# render markdown text in the terminal
11+
# def print_markdown(markdown):
12+
# md = Markdown(markdown)
13+
# console.print(md)
14+
15+
16+
class MarkdownRenderer(object):
17+
def __init__(self, markdown_text, console_print=True):
18+
assert isinstance(markdown_text, str), "Expected a string"
19+
20+
self.markdown_text = markdown_text
21+
self.do_console_print = bool(console_print)
22+
23+
self.console = Console() # rich console
24+
25+
self.render = self.print_mark_down_text()
26+
27+
def print_mark_down_text(self):
28+
rendered_markdown = Markdown(self.markdown_text)
29+
30+
if self.do_console_print:
31+
self.console.print(rendered_markdown)
32+
33+
return rendered_markdown
34+
35+
def __repr__(self):
36+
return str(self.render)
37+
38+
39+
class SearchError():
40+
def __init__(self, error_statement, suggestion="Try again"):
41+
# the error statement
42+
self.error_statement = error_statement
43+
44+
# the suggestion statement
45+
self.suggestion = suggestion
46+
47+
self.evoke_search_error(self.error_statement)
48+
49+
def evoke_search_error(self, error_statement):
50+
print_text = [
51+
colored(error_statement, 'red'),
52+
colored(self.suggestion, 'green')
53+
]
54+
for text_to_print in print_text:
55+
print(text_to_print)
56+
57+
58+
class Utility():
59+
def __init__(self):
60+
# the parent url
61+
self.search_content_url = "https://api.stackexchange.com/"
62+
63+
def __get_search_url(self, question, tags):
64+
return f"{self.search_content_url}/2.2/search/advanced?order=desc&sort=relevance&tagged={tags}&title={question}&site=stackoverflow"
665

766
def make_request(self, que, tag: str):
867
"""
@@ -16,8 +75,11 @@ def make_request(self, que, tag: str):
1675
:rtype: Json format data
1776
"""
1877
print("Searching for the answer")
19-
resp = requests.get("https://api.stackexchange.com/" +
20-
"/2.2/search/advanced?order=desc&sort=relevance&tagged={}&title={}&site=stackoverflow".format(tag, que))
78+
try:
79+
resp = requests.get(self.__get_search_url(que, tag))
80+
except:
81+
SearchError("Search Failed", "Try connecting to the internet")
82+
sys.exit()
2183
return resp.json()
2284

2385
def get_que(self, json_data):
@@ -30,14 +92,40 @@ def get_que(self, json_data):
3092
def get_ans(self, questions_list):
3193
# ans = []
3294
for questions in range(1):
33-
resp = requests.get("https://api.stackexchange.com/" +
34-
"/2.2/questions/{}/answers?order=desc&sort=activity&site=stackoverflow&filter=!--1nZwsgqvRX".format(questions_list[questions]))
95+
try:
96+
resp = requests.get(
97+
f"{self.search_content_url}/2.2/questions/{questions_list[questions]}/answers?order=desc&sort=activity&site=stackoverflow&filter=!--1nZwsgqvRX"
98+
)
99+
except:
100+
SearchError("Search Failed", "Try connecting to the internet")
101+
sys.exit()
35102
json_ans_data = resp.json()
36-
print(
37-
colored("--------------------------------------------------------", 'red'))
38-
for data in json_ans_data['items']:
39-
print(data["body_markdown"])
40-
print("Link to answer : ", end=" ")
41-
print(data["link"])
42-
print(
43-
colored("--------------------------------------------------------", 'red'))
103+
104+
for data in json_ans_data["items"]:
105+
output_content = [
106+
colored(
107+
"--------------------------------------------------------",
108+
'red'), data["body_markdown"],
109+
f"Link to the answer:{data['link']}"
110+
]
111+
112+
for output_index, output_text in enumerate(output_content):
113+
"""
114+
Loop through the output_text and print the element
115+
if it the last one, the text[0] is printed
116+
along with text[-1]
117+
118+
if text is markdown , render the markdown
119+
"""
120+
if output_index == len(output_content) - 1:
121+
console.print(output_text)
122+
123+
console.print(output_content[0])
124+
break
125+
126+
if output_index == len(output_content) - 2:
127+
renderer = MarkdownRenderer(output_text)
128+
129+
continue
130+
131+
console.print(output_text)

0 commit comments

Comments
 (0)