1+ import storage
2+ import microcontroller
3+ import os
4+
5+ # Get all files in the format of .env.xxxxxxxxxx
6+ def enumerate_env_files ():
7+ env_files = []
8+ all_files = os .listdir ("/" )
9+ for file in all_files :
10+ if file [:4 ] == ".env" and len (file ) > 4 :
11+ env_files .append (file )
12+ return env_files
13+
14+ # Compare .env to enumerated env files
15+ def get_current_env_file (env_files ):
16+ with open ('.env' ) as env :
17+ env_lines = env .readlines ()
18+ for env_file in env_files :
19+ with open (env_file ) as f :
20+ lines = f .readlines ()
21+ if len (env_lines ) != len (lines ):
22+ continue
23+ file_may_match = True
24+ for line_no , env_line in enumerate (env_lines ):
25+ if env_line != lines [line_no ]:
26+ file_may_match = False
27+ break
28+ if not file_may_match :
29+ continue
30+ return env_file
31+ return None
32+
33+ # Erase .env then write the contents of the new env file
34+ def change_env_file (env_file ):
35+ try :
36+ storage .remount ("/" , False )
37+ open ('.env' , 'w' ).close ()
38+ with open ('.env' , 'w' ) as env , open (env_file ) as f :
39+ for line in f .readlines ():
40+ env .write (line )
41+ env .close ()
42+ print ("Done. Hard resetting board..." )
43+ microcontroller .reset ()
44+ except RuntimeError :
45+ print ("You can't change the env file with this script while USB is mounted" )
46+
47+ # Return a prettier name than the env file
48+ def pretty_name (env_file ):
49+ name = env_file [5 :]
50+ name = name [0 ].upper () + name [1 :]
51+ return f"{ name } .env file"
52+
53+ env_files = enumerate_env_files ()
54+
55+ if len (env_files ) < 2 :
56+ print ("You need to have at least 2 env files to change" )
57+
58+ result = get_current_env_file (env_files )
59+ if result :
60+ env_files .remove (result )
61+ print ("WARNING: This will overwrite all of your current .env file settings." )
62+ if len (env_files ) == 1 :
63+ answer = input (f"Change to { pretty_name (env_files [0 ])} ? " )
64+ answer = answer .lower ()
65+ if answer == "y" or answer == "yes" :
66+ change_env_file (env_files [0 ])
67+ else :
68+ valid_selection = False
69+ while not valid_selection :
70+ print ("Select an option:" )
71+ for index , file in enumerate (env_files ):
72+ print (f"{ index + 1 } : { pretty_name (file )} " )
73+ answer = input (f"Which option would you like? " )
74+ if answer .isdigit () and 0 < int (answer ) <= len (env_files ):
75+ valid_selection = True
76+ change_env_file (env_files [int (answer ) - 1 ])
77+ print (f"{ answer } was an invalid selection.\n " )
0 commit comments