-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcli.py
59 lines (45 loc) · 2.76 KB
/
cli.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# pyastest:
# a command line tool to parse, modify, and compare Python ASTs
#
# cli.py:
# parsing functions for cli arguments
#
# @jwiaduck 6 March 2022
#
import argparse
import os
from ast_helpers import ast_diff, ast_info
# command line argument parsing
def parse_arguments():
# create top-level parser
parser = argparse.ArgumentParser(prog='pyastest',
description='a command line tool to parse, modify, and compare Python ASTs',
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('--version', action='version', version='%(prog)s v0.1')
subparsers = parser.add_subparsers(title='Subcommands',
description='Valid Subcommands',
help='''current subcommands: diff, info
''')
# create the parser for the "diff" command
parser_diff = subparsers.add_parser('diff', help='''diff check the ASTs of two files\nusage: pyastest diff path/to/ORIGINAL.py path/to/CHANGED.py
''', formatter_class=argparse.RawTextHelpFormatter, description='diff the ASTs of two Python source code files\n', usage='pyastest diff [-h] ORIGINAL CHANGED')
parser_diff.add_argument('diff', metavar = 'ORIGINAL, CHANGED', nargs=2, type=argparse.FileType('r', encoding='UTF-8'),
help='paths to files to be diff\'d\nusage: pyastest diff path/to/ORIGINAL.py path/to/CHANGED.py')
# if `diff`, set args.func to ast_diff (this works so we can have others set their fxns respectively)
parser_diff.set_defaults(func=ast_diff)
# create the parser for the "info" command
parser_diff = subparsers.add_parser('info', help='''get info for the AST nodes from a file\nusage: pyastest info path/to/SOURCE.py
''', formatter_class=argparse.RawTextHelpFormatter, description='get info for the AST nodes from a Python source code file\n', usage='pyastest info [-h] SOURCE')
parser_diff.add_argument('info', metavar = 'SOURCE', nargs=1, type=argparse.FileType('r', encoding='UTF-8'),
help='path to file to be analyzed\nusage: pyastest info path/to/SOURCE.py')
# if `diff`, set args.func to ast_diff (this works so we can have others set their fxns respectively)
parser_diff.set_defaults(func=ast_info)
# parse the args and return Namespace object
args = parser.parse_args()
# print(vars(args))
# if args Namespace object is empty, print help and exit(1) (essentially calling pyatest -h)
# TODO: #1 see if theres a more elegant way to do this?
if len(vars(args)) == 0:
parser.print_help()
exit(1)
return args