22Generate two factor authentication codes on the command line
33"""
44import argparse
5+ import sys
56from pyauthenticator .share import (
67 list_services ,
78 load_config ,
1112)
1213
1314
14- def command_line_parser ():
15+ def command_line_parser (cmd_args = None ):
1516 """
1617 Main function primarly used for the command line interface
1718 """
19+ if cmd_args is None :
20+ cmd_args = sys .argv [1 :]
1821 parser = argparse .ArgumentParser (prog = "pyauthenticator" )
1922 config_dict = load_config ()
20- parser .add_argument (
21- "service" ,
22- help = "Service to generate optauth code for. Available services are: "
23- + str (list_services (config_dict = config_dict )),
24- )
23+ if len (config_dict ) > 0 :
24+ parser .add_argument (
25+ "service" ,
26+ help = "Service to generate optauth code for. The config file ~/.pyauthenticator contains the following services: "
27+ + ", " .join (list_services (config_dict = config_dict )),
28+ )
29+ else :
30+ parser .add_argument (
31+ "service" ,
32+ help = "Service to generate optauth code for. Currently no service is defined in the ~/.pyauthenticator config file." ,
33+ )
2534 parser .add_argument (
2635 "-qr" ,
2736 "--qrcode" ,
@@ -31,18 +40,41 @@ def command_line_parser():
3140 parser .add_argument (
3241 "-a" ,
3342 "--add" ,
34- help = "Add service by providing the qrcode png file as additional argument." ,
43+ help = "Add service by providing the < qrcode. png> file as additional argument." ,
3544 )
36- args = parser .parse_args ()
45+ args = parser .parse_args (args = cmd_args )
3746 if args .qrcode :
3847 generate_qrcode (key = args .service , config_dict = config_dict )
48+ print ("The qrcode file <" + args .service + ".png> was generated." )
3949 elif args .add :
4050 add_service (
4151 key = args .service , qrcode_png_file_name = args .add , config_dict = config_dict
4252 )
43- print (args .service , "added." )
53+ print (
54+ "The service '"
55+ + args .service
56+ + "' was added, from file <"
57+ + args .add
58+ + ">."
59+ )
4460 else :
45- print (get_two_factor_code (key = args .service , config_dict = config_dict ))
61+ try :
62+ print (get_two_factor_code (key = args .service , config_dict = config_dict ))
63+ except ValueError :
64+ if len (config_dict ) > 0 :
65+ print (
66+ 'The service "'
67+ + args .service
68+ + '" does not exist.\n \n The config file ~/.pyauthenticator contains the following services:'
69+ )
70+ for service in list_services (config_dict = config_dict ):
71+ print (" * " + service )
72+ print ("\n Choose one of these or add a new service using:" )
73+ else :
74+ print (
75+ "The config file ~/.pyauthenticator does not contain any services. To add a new service use:"
76+ )
77+ print (" pyauthenticator --add <qr-code.png> <servicename>\n " )
4678
4779
4880if __name__ == "__main__" :
0 commit comments