Skip to content

Commit

Permalink
use click instead of argparse to build command line tools
Browse files Browse the repository at this point in the history
  • Loading branch information
Linusp committed Jul 20, 2019
1 parent 3a2965a commit ee40530
Showing 1 changed file with 22 additions and 71 deletions.
93 changes: 22 additions & 71 deletions inoreader/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@
import sys
import json
import codecs
import argparse
from datetime import datetime
from collections import defaultdict
from configparser import ConfigParser

import yaml
import click
from inoreader import InoreaderClient
from inoreader.filter import get_filter

Expand Down Expand Up @@ -67,26 +67,14 @@ def get_client():
return client


class SubcommandHelpFormatter(argparse.RawDescriptionHelpFormatter):
def _format_action(self, action):
parts = super(argparse.RawDescriptionHelpFormatter, self)._format_action(action)
if action.nargs == argparse.PARSER:
parts = "\n".join(parts.split("\n")[1:])
return parts


class CmdParser(argparse.ArgumentParser):
def error(self, message):
sys.stderr.write('error: %s\n\n' % message)
self.print_help()
sys.exit(1)


def add_login_parser(subparsers):
subparsers.add_parser('login', help="Login to Inoreader")
@click.group(context_settings=dict(help_option_names=['-h', '--help']))
def main():
pass


@main.command()
def login():
"""Login to your inoreader account"""
client = InoreaderClient(None, None)

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


def add_folders_list_parser(subparsers):
subparsers.add_parser('list-folders', help="List all folders")


@main.command("list-folders")
def list_folders():
"""List all folders"""
client = get_client()
res = client.get_folders()
print("unread\tfolder")
for item in res:
print("{}\t{}".format(item['unread_count'], item['name']))


def add_tags_list_parser(subparsers):
subparsers.add_parser('list-tags', help="List all tags")


@main.command("list-tags")
def list_tags():
"""List all tags"""
client = get_client()
res = client.get_tags()
for item in res:
print("{}\t{}".format(item['unread_count'], item['name']))


def add_unread_fetch_parser(subparsers):
parser = subparsers.add_parser('fetch-unread', help='Fetch unread articles')
parser.add_argument("-f", "--folder", required=True, help='Folder which articles belong to')
parser.add_argument("-t", "--tags", help="Tag(s) for filtering, seprate with comma")
parser.add_argument("-o", "--outfile", required=True, help="Filename to save articles")
parser.add_argument(
"--out-format",
choices=['json', 'csv', 'plain', 'markdown', 'org-mode'],
default='json',
help='Format of output file, default: json'
)


@main.command("fetch-unread")
@click.option("-f", "--folder", required=True, help='Folder which articles belong to')
@click.option("-t", "--tags", help="Tag(s) for filtering, seprate with comma")
@click.option("-o", "--outfile", required=True, help="Filename to save articles")
@click.option("--out-format",
type=click.Choice(['json', 'csv', 'plain', 'markdown', 'org-mode']),
default='json',
help='Format of output file, default: json')
def fetch_unread(folder, tags, outfile, out_format):
"""Fetch unread articles"""
client = get_client()

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


def add_filter_parser(subparsers):
parser = subparsers.add_parser('filter', help='Select articles and do something')
parser.add_argument("-r", "--rules", required=True, help='YAML file with your rules')


def apply_action(articles, client, action, tags):
if action == 'tag':
for tag in tags.split(','):
Expand All @@ -209,7 +184,10 @@ def apply_action(articles, client, action, tags):
print("Starred article: {}".format(article.title))


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


def main():
parser = CmdParser(
usage="inoreader [-h] <command> ...",
formatter_class=SubcommandHelpFormatter
)
subparsers = parser.add_subparsers(title="commands", dest='command')
subparsers.required = True

add_login_parser(subparsers)
add_folders_list_parser(subparsers)
add_tags_list_parser(subparsers)
add_unread_fetch_parser(subparsers)
add_filter_parser(subparsers)

args = parser.parse_args()
if args.command == 'login':
login()
elif args.command == 'list-folders':
list_folders()
elif args.command == 'list-tags':
list_tags()
elif args.command == 'fetch-unread':
fetch_unread(args.folder, args.tags, args.outfile, args.out_format)
elif args.command == 'filter':
filter_articles(args.rules)


if __name__ == '__main__':
main()

0 comments on commit ee40530

Please sign in to comment.