44import argparse
55import sys
66import shutil
7+ from collections import defaultdict
78from importlib import resources
9+ from importlib .abc import Traversable
10+
11+
12+ def get_definitions_or_raise (board : str ) -> Traversable :
13+ """Get the definitions file for a board given its name."""
14+
15+ path = resources .files ("board_definitions" ).joinpath (board )
16+
17+ file = path .joinpath ("__init__.pyi" )
18+ if not file .is_file ():
19+ sys .stderr .write (f"Definitions for: '{ board } ' were not found\n " )
20+ sys .exit (1 )
21+
22+ return file
23+
24+
25+ def get_doc_or_raise (board : str ) -> str :
26+ """Get the docstring for a board given its name."""
27+
28+ with get_definitions_or_raise (board ).open ("r" ) as f :
29+ return f .read ().split ('"""' )[1 ]
30+
31+
32+ def header (txt : str ) -> str :
33+ """Helper text formatter."""
34+ return txt + "\n " + "-" * len (txt ) + "\n "
835
936
1037def set_board ():
@@ -18,25 +45,48 @@ def set_board():
1845 args = parser .parse_args ()
1946
2047 if args .list :
21- sys . stdout . write ( "Available boards are: \n " )
48+ port_boards : defaultdict [ str , list [ str ]] = defaultdict ( list )
2249
2350 for board in resources .files ("board_definitions" ).iterdir ():
24- sys .stdout .write (f"{ board .name } \n " )
51+ # NOTE: For the hand-crafted finding of port in the docstring, its
52+ # format is assumed to be:
53+ #
54+ # <empty line>
55+ # Board stub for ...
56+ # - port: ...
57+ # - board_id: ...
58+ # - NVM size: ...
59+ # - Included modules: ...
60+ # - Frozen libraries: ...
61+ #
62+
63+ lines = get_doc_or_raise (board ).split ("\n " )
64+ port = lines [2 ].split ("-" )[1 ].split (":" )[1 ].strip ()
65+
66+ port_boards [port ].append (board .name )
67+
68+ sys .stdout .write ("Available boards are: \n " )
69+ # sort by port name
70+ for port , boards in sorted (port_boards .items (), key = lambda kv : kv [0 ]):
71+ sys .stdout .write (
72+ header (port )
73+ + " * "
74+ # sort by board name
75+ + "\n * " .join (sorted (boards ))
76+ + "\n \n "
77+ )
2578
2679 sys .exit (0 )
2780
2881 if args .chosen_board is None :
29- sys .stderr .write ("Must select a board" )
82+ sys .stderr .write ("Must select a board\n " )
3083 sys .exit (1 )
3184
32- print ( f"setting board: { args .chosen_board } " )
85+ board_definitions_file = get_definitions_or_raise ( args .chosen_board )
3386
3487 board_stubs_file = resources .files ("board-stubs" ).joinpath ("__init__.pyi" )
35- board_definitions_path = resources .files ("board_definitions" ).joinpath (args .chosen_board )
36- board_definitions_file = board_definitions_path .joinpath ("__init__.pyi" )
37-
38- if not board_definitions_file .is_file ():
39- print (f"Board: '{ args .chosen_board } ' was not found" )
40- sys .exit (1 )
41-
4288 shutil .copyfile (board_definitions_file , board_stubs_file )
89+
90+ sys .stdout .write (
91+ header ("Information about the board" ) + get_doc_or_raise (args .chose_board ) + "\n "
92+ )
0 commit comments