-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.py
107 lines (96 loc) · 2.9 KB
/
config.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
import os
import re
import configparser
from prompt_toolkit.validation import Validator, ValidationError
from PyInquirer import prompt, print_json
file_config_ini = 'config.ini'
class IPAddressValidator(Validator):
def validate(self, document):
ok = re.match(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$", document.text)
if not ok:
raise ValidationError(message='Please enter a valid IPv4 Address', cursor_position=len(document.text))
# Ask what to do about currently existing config file
opt_overwrite = None
if os.path.exists(file_config_ini):
questions = [
{
'type': 'list',
'name': 'overwrite',
'message': 'A configuration file already exists. What would you like to do?',
'choices': [
'1) Keep Current',
'2) Overwrite existing',
'3) Create new but preserve old (creates config.ini.old)'
]
}
]
answers = prompt(questions)
opt_overwrite = answers['overwrite'][:1]
# Exit if user wishes to keep current config file
if opt_overwrite == '1':
print('Changing nothing, exiting!')
exit(0)
questions = [
{
'type': 'input',
'name': 'bridge_ip',
'message': 'What is the IP Address of the bridge?: ',
'validate': IPAddressValidator
},
{
'type': 'input',
'name': 'device',
'message': 'Give your app''s instance a name:',
'default': 'raspberry_pi'
},
# {
# 'type': 'input',
# 'name': 'uuid',
# 'message': 'Input the UUID for the Hue Bridge API Requests:'
# },
# {
# 'type': 'input',
# 'name': 'light_id',
# 'message': 'What is the light ID:'
# },
{
'type': 'confirm',
'name': 'continue',
'message': 'Are you sure you want to create the config.ini file with these settings?',
'default': False
}
]
answers = prompt(questions)
# Exit immediately if user isn't sure
if not answers['continue']:
print('User Cancelled!')
exit(1)
# Execute overwrite logic
if not opt_overwrite is None:
if opt_overwrite == '2':
os.remove(file_config_ini)
elif opt_overwrite == '3':
# Delete old file first, if it exists
if os.path.exists(file_config_ini + '.old'):
os.remove(file_config_ini + '.old')
os.rename(file_config_ini, file_config_ini + '.old')
else:
print('Unrecongized overwrite command')
exit(1)
# Get answers
bridge_ip = answers['bridge_ip']
uuid = '[Replace_Me]'
light_id = '[Replace_Me]'
device = answers['device']
# Configure the INI object
config = configparser.ConfigParser()
config['DEFAULT'] = {
'ip_address': 'http://' + bridge_ip,
'uuid': uuid,
'light_id': light_id,
'device': device
}
# Write Object to file
with open(file_config_ini, 'w') as conf:
config.write(conf)
print('Successfully created', file_config_ini)