Skip to content

Commit ee40530

Browse files
committed
use click instead of argparse to build command line tools
1 parent 3a2965a commit ee40530

File tree

1 file changed

+22
-71
lines changed

1 file changed

+22
-71
lines changed

inoreader/main.py

Lines changed: 22 additions & 71 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,12 @@
66
import sys
77
import json
88
import codecs
9-
import argparse
109
from datetime import datetime
1110
from collections import defaultdict
1211
from configparser import ConfigParser
1312

1413
import yaml
14+
import click
1515
from inoreader import InoreaderClient
1616
from inoreader.filter import get_filter
1717

@@ -67,26 +67,14 @@ def get_client():
6767
return client
6868

6969

70-
class SubcommandHelpFormatter(argparse.RawDescriptionHelpFormatter):
71-
def _format_action(self, action):
72-
parts = super(argparse.RawDescriptionHelpFormatter, self)._format_action(action)
73-
if action.nargs == argparse.PARSER:
74-
parts = "\n".join(parts.split("\n")[1:])
75-
return parts
76-
77-
78-
class CmdParser(argparse.ArgumentParser):
79-
def error(self, message):
80-
sys.stderr.write('error: %s\n\n' % message)
81-
self.print_help()
82-
sys.exit(1)
83-
84-
85-
def add_login_parser(subparsers):
86-
subparsers.add_parser('login', help="Login to Inoreader")
70+
@click.group(context_settings=dict(help_option_names=['-h', '--help']))
71+
def main():
72+
pass
8773

8874

75+
@main.command()
8976
def login():
77+
"""Login to your inoreader account"""
9078
client = InoreaderClient(None, None)
9179

9280
username = input("EMAIL: ").strip()
@@ -112,43 +100,35 @@ def login():
112100
sys.exit(1)
113101

114102

115-
def add_folders_list_parser(subparsers):
116-
subparsers.add_parser('list-folders', help="List all folders")
117-
118-
103+
@main.command("list-folders")
119104
def list_folders():
105+
"""List all folders"""
120106
client = get_client()
121107
res = client.get_folders()
122108
print("unread\tfolder")
123109
for item in res:
124110
print("{}\t{}".format(item['unread_count'], item['name']))
125111

126112

127-
def add_tags_list_parser(subparsers):
128-
subparsers.add_parser('list-tags', help="List all tags")
129-
130-
113+
@main.command("list-tags")
131114
def list_tags():
115+
"""List all tags"""
132116
client = get_client()
133117
res = client.get_tags()
134118
for item in res:
135119
print("{}\t{}".format(item['unread_count'], item['name']))
136120

137121

138-
def add_unread_fetch_parser(subparsers):
139-
parser = subparsers.add_parser('fetch-unread', help='Fetch unread articles')
140-
parser.add_argument("-f", "--folder", required=True, help='Folder which articles belong to')
141-
parser.add_argument("-t", "--tags", help="Tag(s) for filtering, seprate with comma")
142-
parser.add_argument("-o", "--outfile", required=True, help="Filename to save articles")
143-
parser.add_argument(
144-
"--out-format",
145-
choices=['json', 'csv', 'plain', 'markdown', 'org-mode'],
146-
default='json',
147-
help='Format of output file, default: json'
148-
)
149-
150-
122+
@main.command("fetch-unread")
123+
@click.option("-f", "--folder", required=True, help='Folder which articles belong to')
124+
@click.option("-t", "--tags", help="Tag(s) for filtering, seprate with comma")
125+
@click.option("-o", "--outfile", required=True, help="Filename to save articles")
126+
@click.option("--out-format",
127+
type=click.Choice(['json', 'csv', 'plain', 'markdown', 'org-mode']),
128+
default='json',
129+
help='Format of output file, default: json')
151130
def fetch_unread(folder, tags, outfile, out_format):
131+
"""Fetch unread articles"""
152132
client = get_client()
153133

154134
tag_list = [] if not tags else tags.split(',')
@@ -179,11 +159,6 @@ def fetch_unread(folder, tags, outfile, out_format):
179159
fout.close()
180160

181161

182-
def add_filter_parser(subparsers):
183-
parser = subparsers.add_parser('filter', help='Select articles and do something')
184-
parser.add_argument("-r", "--rules", required=True, help='YAML file with your rules')
185-
186-
187162
def apply_action(articles, client, action, tags):
188163
if action == 'tag':
189164
for tag in tags.split(','):
@@ -209,7 +184,10 @@ def apply_action(articles, client, action, tags):
209184
print("Starred article: {}".format(article.title))
210185

211186

187+
@main.command("filter")
188+
@click.option("-r", "--rules-file", required=True, help='YAML file with your rules')
212189
def filter_articles(rules_file):
190+
"""Select articles and do something"""
213191
client = get_client()
214192
filters = []
215193
for rule in yaml.load(open(rules_file)):
@@ -275,32 +253,5 @@ def filter_articles(rules_file):
275253
apply_action([article], client, 'tag', action['tags'])
276254

277255

278-
def main():
279-
parser = CmdParser(
280-
usage="inoreader [-h] <command> ...",
281-
formatter_class=SubcommandHelpFormatter
282-
)
283-
subparsers = parser.add_subparsers(title="commands", dest='command')
284-
subparsers.required = True
285-
286-
add_login_parser(subparsers)
287-
add_folders_list_parser(subparsers)
288-
add_tags_list_parser(subparsers)
289-
add_unread_fetch_parser(subparsers)
290-
add_filter_parser(subparsers)
291-
292-
args = parser.parse_args()
293-
if args.command == 'login':
294-
login()
295-
elif args.command == 'list-folders':
296-
list_folders()
297-
elif args.command == 'list-tags':
298-
list_tags()
299-
elif args.command == 'fetch-unread':
300-
fetch_unread(args.folder, args.tags, args.outfile, args.out_format)
301-
elif args.command == 'filter':
302-
filter_articles(args.rules)
303-
304-
305256
if __name__ == '__main__':
306257
main()

0 commit comments

Comments
 (0)