Skip to content

Commit b05e8f7

Browse files
Merge pull request #56 from pranavbaburaj/master
Added a feature #56
2 parents 2f43cef + 879b010 commit b05e8f7

File tree

6 files changed

+152
-88
lines changed

6 files changed

+152
-88
lines changed

main.py

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5,25 +5,31 @@
55

66
version = "0.1"
77

8-
PARSER = argparse.ArgumentParser()
9-
PARSER.add_argument("-s",
8+
parser = argparse.ArgumentParser()
9+
parser.add_argument("-s",
1010
"--search",
1111
help="enable debug mode",
1212
action="store_true")
1313

14-
PARSER.add_argument("-V",
14+
parser.add_argument("-V",
1515
"--version",
1616
version=f"Dynamic-CLI version {version}",
1717
action='version')
1818

19-
PARSER.add_argument("-n",
20-
"--new",
21-
help="Opens browser to create new Stack Overflow question.",
22-
const=True,
23-
metavar="title (optional)",
24-
nargs="?")
19+
parser.add_argument(
20+
"-n",
21+
"--new",
22+
help="Opens browser to create new Stack Overflow question.",
23+
const=True,
24+
metavar="title (optional)",
25+
nargs="?")
26+
27+
parser.add_argument("-file",
28+
"--file",
29+
help="Save answer to a file",
30+
action="store_true")
2531

26-
ARGV = PARSER.parse_args()
32+
ARGV = parser.parse_args()
2733

2834
search_flag = Search(ARGV)
2935

src/arguments/error.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
from termcolor import colored
2+
3+
4+
class SearchError():
5+
def __init__(self, error_statement, suggestion="Try again"):
6+
# the error statement
7+
self.error_statement = error_statement
8+
9+
# the suggestion statement
10+
self.suggestion = suggestion
11+
12+
self.evoke_search_error(self.error_statement)
13+
14+
def evoke_search_error(self, error_statement):
15+
print_text = [
16+
colored(error_statement, 'red'),
17+
colored(self.suggestion, 'green')
18+
]
19+
for text_to_print in print_text:
20+
print(text_to_print)

src/arguments/markdown.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
from rich.markdown import Markdown
2+
from rich.console import Console
3+
import html as html
4+
5+
6+
class MarkdownRenderer(object):
7+
def __init__(self, markdown_text, console_print=True):
8+
assert isinstance(markdown_text, str), "Expected a string"
9+
10+
markdown_text = html.unescape(markdown_text)
11+
self.markdown_text = markdown_text
12+
self.do_console_print = bool(console_print)
13+
14+
self.console = Console() # rich console
15+
16+
self.render = self.print_mark_down_text()
17+
18+
def print_mark_down_text(self):
19+
rendered_markdown = Markdown(self.markdown_text)
20+
21+
if self.do_console_print:
22+
self.console.print(rendered_markdown)
23+
24+
return rendered_markdown
25+
26+
def __repr__(self):
27+
return str(self.render)
28+
29+
def __len__(self):
30+
if isinstance(self.render, str):
31+
return len(self.render)
32+
return -1
33+
34+
def __str__(self):
35+
return str(self.render)
36+
37+
def __repr__(self):
38+
return str(self.render)

src/arguments/save.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import os as os
2+
import json as json
3+
import uuid as uuid
4+
5+
6+
class SaveSearchResults(object):
7+
def __init__(self, result_json):
8+
self.result_json = self.__get_as_dict(result_json[0])
9+
self.save_results_filename = self.generate_file_name(os.getcwd())
10+
11+
self.save_data_to_file(self.result_json, self.save_results_filename)
12+
13+
def save_data_to_file(self, data, filename):
14+
with open(os.path.join(os.getcwd(), f"{filename}.json"),
15+
"w") as result_writer:
16+
json.dump(data, result_writer, indent=6)
17+
18+
def __get_as_dict(self, json_array):
19+
result_dict = {}
20+
for index, element in enumerate(json_array):
21+
result_dict[index] = json_array[index]
22+
return dict(result_dict)
23+
24+
def generate_file_name(self, directory):
25+
file_list = os.listdir(directory)
26+
filename = str(uuid.uuid4()).replace("-", "_")[:4]
27+
while filename in file_list:
28+
filename = str(uuid.uuid4()).replace("-", "_")[:4]
29+
30+
return filename
31+
32+
def __repr__(self):
33+
return str(self.save_results_filename)

src/arguments/search.py

Lines changed: 37 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,12 @@
22
import argparse
33
import webbrowser
44
from termcolor import colored
5-
from .utility import Utility, SearchError
65
import sys as sys
76

7+
from .error import SearchError
8+
from .utility import Utility
9+
from .save import SaveSearchResults
10+
811

912
class Prompt():
1013
def __init__(self, message):
@@ -24,33 +27,42 @@ def __init__(self, arguments):
2427

2528
def search_args(self):
2629
if self.arguments.search:
27-
queries = ["What do you want to search", "Tags"]
28-
query_solutions = []
29-
30-
# ask quesiton
31-
for each_query in queries:
32-
# Be careful if there are
33-
# KeyBpard Interupts or EOErrors
34-
try:
35-
prompt = Prompt(str(each_query)).prompt()
36-
except:
37-
sys.exit()
38-
39-
query_solutions.append(prompt)
40-
41-
question, tags = query_solutions[0], query_solutions[1]
42-
json_output = self.utility_object.make_request(question, tags)
43-
questions = self.utility_object.get_que(json_output)
44-
if questions == []:
45-
# evoke an error
46-
search_error = SearchError("No answer found",
47-
"Please try reddit")
48-
else:
49-
self.utility_object.get_ans(questions)
50-
30+
self.search_for_results()
31+
elif self.arguments.file:
32+
self.search_for_results(True)
5133
elif self.arguments.new:
5234
url = "https://stackoverflow.com/questions/ask"
5335
if type(self.arguments.new) == str:
5436
webbrowser.open(f"{url}?title={self.arguments.new}")
5537
else:
5638
webbrowser.open(url)
39+
40+
def search_for_results(self, save=False):
41+
queries = ["What do you want to search", "Tags"]
42+
query_solutions = []
43+
44+
# ask quesiton
45+
for each_query in queries:
46+
# Be careful if there are
47+
# KeyBpard Interupts or EOErrors
48+
try:
49+
prompt = Prompt(str(each_query)).prompt()
50+
except:
51+
sys.exit()
52+
53+
query_solutions.append(prompt)
54+
55+
question, tags = query_solutions[0], query_solutions[1]
56+
json_output = self.utility_object.make_request(question, tags)
57+
questions = self.utility_object.get_que(json_output)
58+
if questions == []:
59+
# evoke an error
60+
search_error = SearchError("No answer found", "Please try reddit")
61+
else:
62+
data = self.utility_object.get_ans(questions)
63+
64+
if save:
65+
filename = SaveSearchResults(data)
66+
print(
67+
colored(f"Answers successfully saved into {filename}",
68+
"green"))

src/arguments/utility.py

Lines changed: 8 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -1,60 +1,13 @@
1-
import requests
2-
import html
31
from termcolor import colored
2+
import requests
43
from rich.console import Console
5-
from rich.markdown import Markdown
64
import sys as sys
75

8-
# the rich console
9-
console = Console()
10-
11-
# render markdown text in the terminal
12-
# def print_markdown(markdown):
13-
# md = Markdown(markdown)
14-
# console.print(md)
15-
16-
17-
class MarkdownRenderer(object):
18-
def __init__(self, markdown_text, console_print=True):
19-
assert isinstance(markdown_text, str), "Expected a string"
20-
21-
markdown_text = html.unescape(markdown_text)
22-
self.markdown_text = markdown_text
23-
self.do_console_print = bool(console_print)
24-
25-
self.console = Console() # rich console
26-
27-
self.render = self.print_mark_down_text()
6+
from .error import SearchError
7+
from .save import SaveSearchResults
8+
from .markdown import MarkdownRenderer
289

29-
def print_mark_down_text(self):
30-
rendered_markdown = Markdown(self.markdown_text)
31-
32-
if self.do_console_print:
33-
self.console.print(rendered_markdown)
34-
35-
return rendered_markdown
36-
37-
def __repr__(self):
38-
return str(self.render)
39-
40-
41-
class SearchError():
42-
def __init__(self, error_statement, suggestion="Try again"):
43-
# the error statement
44-
self.error_statement = error_statement
45-
46-
# the suggestion statement
47-
self.suggestion = suggestion
48-
49-
self.evoke_search_error(self.error_statement)
50-
51-
def evoke_search_error(self, error_statement):
52-
print_text = [
53-
colored(error_statement, 'red'),
54-
colored(self.suggestion, 'green')
55-
]
56-
for text_to_print in print_text:
57-
print(text_to_print)
10+
console = Console()
5811

5912

6013
class Utility():
@@ -92,7 +45,7 @@ def get_que(self, json_data):
9245
return que_id
9346

9447
def get_ans(self, questions_list):
95-
# ans = []
48+
ans = []
9649
for questions in range(1):
9750
try:
9851
resp = requests.get(
@@ -131,3 +84,5 @@ def get_ans(self, questions_list):
13184
continue
13285

13386
console.print(output_text)
87+
ans.append(json_ans_data["items"])
88+
return ans

0 commit comments

Comments
 (0)