forked from RGB-Tools/iris-wallet-desktop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuild_script.py
223 lines (182 loc) · 7.31 KB
/
build_script.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
"""
This module handles the build process for the Iris Wallet, including different
platform builds, network settings, and saving build information.
"""
from __future__ import annotations
import argparse
import json
import os
import platform
import subprocess
import sys
import threading
import time
import shutil
from src.version import __version__
CONSTANT_PATH = os.path.join('src','utils', 'constant.py')
TEMP_CONSTANT_PATH = os.path.join('src', 'temp_build_constant.py')
def parse_arguments():
"""Parse command-line arguments for the build script."""
parser = argparse.ArgumentParser(
description='Build Iris Wallet for a specified network and distribution.',
)
parser.add_argument(
'--network',
choices=['mainnet', 'testnet', 'regtest'],
required=True,
help="Specify the network to build for: 'mainnet', 'testnet', or 'regtest'.",
)
parser.add_argument(
'--ldk-port',
required=False,
help='Specify the LDK Port (Optional).',
)
parser.add_argument(
'--app-name',
required=False,
help='Specify the app name to run multiple instances (Optional).',
)
if platform.system() == 'Linux':
# Define the --distribution argument with a help message
parser.add_argument(
'--distribution',
choices=['appimage', 'deb'],
required=True,
help="Specify the Linux distribution type: 'appimage' or 'deb'.",
)
return parser.parse_args()
def modify_constant_file(app_name: str | None):
"""Modify constant.py to include the app name as a suffix."""
if not app_name:
return # Skip modification if no app name provided
# Create a temporary copy of the constant file
shutil.copy(CONSTANT_PATH, TEMP_CONSTANT_PATH)
with open(CONSTANT_PATH, 'r') as file:
lines = file.readlines()
new_lines = []
suffix = f"_{app_name}"
for line in lines:
if line.strip().startswith(('ORGANIZATION_NAME', 'APP_NAME', 'ORGANIZATION_DOMAIN',
'MNEMONIC_KEY', 'WALLET_PASSWORD_KEY',
'NATIVE_LOGIN_ENABLED', 'IS_NATIVE_AUTHENTICATION_ENABLED')):
# Append suffix to relevant constants
key, value = line.split(' = ')
new_lines.append(f"{key} = {value.strip()[:-1]}{suffix}'\n")
else:
new_lines.append(line)
# Write modified content back to the file
with open(CONSTANT_PATH, 'w') as file:
file.writelines(new_lines)
def restore_constant_file():
"""Restore the original constant.py from the temporary copy."""
if os.path.exists(TEMP_CONSTANT_PATH):
shutil.move(TEMP_CONSTANT_PATH, CONSTANT_PATH)
def loading_animation(stop_event):
"""Simple loading spinner."""
spinner = '|/-\\'
idx = 0
while not stop_event.is_set():
sys.stdout.write(f"\rBuild process started, please wait... {spinner[idx % len(spinner)]}")
sys.stdout.flush()
idx += 1
time.sleep(0.1)
def save_build_info_to_json(args, machine_arch, os_type, arch_type):
"""Save the build information to a JSON file."""
build_info = {
'build_flavour': args.network,
'machine_arch': machine_arch,
'os_type': os_type,
'arch_type': arch_type,
'app-version': __version__,
}
if os_type == 'Linux':
build_info['distribution'] = args.distribution
with open('build_info.json', 'w') as json_file:
json.dump(build_info, json_file, indent=4)
print('\nBuild information saved to build_info.json')
def save_app_config(network: str, ldk_port: int | None = None, app_name: str | None = None):
"""Save the network, port, and app name suffix settings to a Python file."""
FLAVOUR_FILE = os.path.join(
os.path.dirname(os.path.abspath(__file__)), 'src', 'flavour.py',
)
# If the file doesn't exist, create it with initial values.
if not os.path.exists(FLAVOUR_FILE):
with open(FLAVOUR_FILE, 'w') as file:
file.write(f"__network__ = '{network}'\n")
file.write(f"__ldk_port__ = '{ldk_port}'\n" if ldk_port else "__ldk_port__ = None\n")
file.write(f"__app_name_suffix__ = '{app_name}'\n" if app_name else "__app_name_suffix__ = None\n")
file.write("__port__ = None\n")
return
# If the file exists, read its contents and modify as needed.
with open(FLAVOUR_FILE) as file:
lines = file.readlines()
# Create a new list of lines with updated values.
new_lines = []
for line in lines:
if line.startswith('__network__'):
new_lines.append(f"__network__ = '{network}'\n")
elif line.startswith('__ldk_port__'):
new_lines.append(f"__ldk_port__ = '{ldk_port}'\n" if ldk_port else "__ldk_port__ = None\n")
elif line.startswith('__app_name_suffix__'):
new_lines.append(f"__app_name_suffix__ = '{app_name}'\n" if app_name else "__app_name_suffix__ = None\n")
else:
new_lines.append(line)
# Write the modified lines back to the file.
with open(FLAVOUR_FILE, 'w') as file:
file.writelines(new_lines)
def reset_app_config_on_exit():
"""Ensure __port__ and __app_name__ are set to None on exit or Ctrl+C."""
save_app_config('regtest', None, None)
def main():
"""Main function to handle the build process."""
args = parse_arguments()
os_type = platform.system()
machine_arch = platform.machine()
arch_type = platform.architecture()[0]
print('\n\nBuild Summary:')
if args.app_name:
print(f"App Name: {args.app_name}")
print(f"Build Type: {args.network}")
if args.ldk_port:
print(f"LDK Port: {args.ldk_port}")
print(f"Machine Architecture: {machine_arch}")
print(f"OS Type: {os_type}")
print(f"Architecture Type: {arch_type}")
if os_type == 'Linux':
print(f"Distribution: {args.distribution}")
try:
modify_constant_file(args.app_name)
save_build_info_to_json(args, machine_arch, os_type, arch_type)
save_app_config(args.network, args.ldk_port,args.app_name)
stop_event = threading.Event()
loading_thread = threading.Thread(target=loading_animation, args=(stop_event,))
loading_thread.start()
if os_type == 'Linux':
if args.distribution == 'appimage':
result = subprocess.run(
['bash', 'build_appimage.sh'], capture_output=True, text=True,
)
else:
result = subprocess.run(
['bash', 'build_linux.sh'], capture_output=True, text=True,
)
elif os_type == 'Windows':
result = subprocess.run(
['pyinstaller', 'iris_wallet_desktop.spec'], capture_output=True, text=True,
)
elif os_type == 'Darwin':
result = subprocess.run(
['bash', 'build_macos.sh'], capture_output=True, text=True,
)
finally:
stop_event.set()
loading_thread.join()
restore_constant_file()
reset_app_config_on_exit()
print('\nOutput:', result.stdout)
print('Error:', result.stderr)
print('Return Code:', result.returncode)
if result.stderr and result.returncode != 0:
os.remove('build_info.json')
if __name__ == '__main__':
main()