]> git.armaanb.net Git - lightcards.git/blob - lightcards/runner.py
Reduce number of screen refreshes
[lightcards.git] / lightcards / runner.py
1 # Markdown flashcard utility
2 # Armaan Bhojwani 2021
3
4 import argparse
5 from curses import wrapper
6 import os
7 import pkg_resources
8 from random import shuffle
9 import sys
10
11 from . import parse, progress
12 from .display import Display
13 from .deck import Status
14
15
16 def parse_args():
17     """Parse command line arguments"""
18     parser = argparse.ArgumentParser(
19         description="Terminal flashcards from Markdown"
20     )
21     parser.add_argument("inp", metavar="input file", type=str, nargs=1)
22     parser.add_argument(
23         "-a",
24         "--alphabetize",
25         action="store_true",
26         help="alphabetize card order",
27     )
28     parser.add_argument(
29         "-f", "--flip", action="store_true", help="show second column first"
30     )
31     parser.add_argument(
32         "-p",
33         "--purge",
34         action="store_true",
35         help="don't check cached info before starting",
36     )
37     parser.add_argument(
38         "-r", "--reverse", action="store_true", help="reverse card order"
39     )
40     parser.add_argument(
41         "-s", "--shuffle", action="store_true", help="shuffle card order"
42     )
43     parser.add_argument(
44         "-v",
45         "--version",
46         action="version",
47         version=f"lightcards {pkg_resources.require('lightcards')[0].version}",
48     )
49     return parser.parse_args()
50
51
52 def show(args, stack, headers):
53     """
54     Get objects from cache, manipulate deck according to passed arguments, and
55     send it to the display functions
56     """
57     # Purge caches if asked
58     if args.purge:
59         progress.purge(stack)
60
61     # Check for caches
62     idx = Status()
63     cache = progress.dive(get_orig()[1])
64     if cache:
65         (stack) = cache
66
67     # Manipulate deck
68     if args.shuffle:
69         shuffle(stack)
70     if args.alphabetize:
71         stack.sort(key=lambda x: x.front)
72     if args.reverse:
73         stack.reverse()
74     if args.flip:
75         for x in stack:
76             x[0], x[1] = x[1], x[0]
77         headers[0], headers[1] = headers[1], headers[0]
78
79     # Send to display
80     win = Display(stack, headers, idx)
81     wrapper(win.run)
82
83
84 def reparse():
85     """Parse arguments and input file again"""
86     args = parse_args()
87     os.system(f"$EDITOR {args.inp[0]}"),
88     return parse.parse_html(parse.md2html(args.inp[0]))
89
90
91 def get_orig():
92     """Return original header and stack"""
93     return (headers, stack)
94
95
96 def main(args=sys.argv):
97     args = parse_args()
98     global headers, stack
99     (headers, stack) = parse.parse_html(parse.md2html(args.inp[0]))
100     show(args, stack, headers)
101
102
103 if __name__ == "__main__":
104     main()