-
Notifications
You must be signed in to change notification settings - Fork 5
/
flutter_workspace.py
executable file
·2252 lines (1709 loc) · 69.9 KB
/
flutter_workspace.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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
#
# SPDX-FileCopyrightText: (C) 2020-2023 meta-flutter contributors
#
# SPDX-License-Identifier: Apache-2.0
#
#
# Script that creates a Flutter Workspace
#
# A Flutter Workspace includes:
#
# .config/flutter
# .config/flutter_workspace
# .config/flutter_workspace/pub_cache
# .config/flutter_workspace/flutter-engine
# .config/flutter_workspace/<platform id>
# .vscode
# app
# flutter
# setup_env.sh
#
#
# One runs this script to create the workspace, then from working terminal
# set up the environment:
#
# "source ./setup_env.sh" or ". ./setup_env.sh"
#
# if QEMU image is loaded type `run-<platform id>` to run QEMU image
#
import io
import json
import os
import platform
import shlex
import signal
import subprocess
import sys
import time
import zipfile
from platform import system
import create_aot
from fw_common import check_python_version
from fw_common import compare_sha256
from fw_common import download_https_file
from fw_common import fetch_https_binary_file
from fw_common import handle_ctrl_c
from fw_common import make_sure_path_exists
from fw_common import print_banner
from fw_common import write_sha256_file
from pubspec import Pubspec
def main():
# check python version
check_python_version()
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--clean', default=False,
action='store_true', help='Wipes workspace clean')
parser.add_argument('--config', default='configs', type=str,
help='Selects custom workspace configuration folder')
parser.add_argument('--flutter-version', default='', type=str,
help='Select flutter version. Overrides config file key:'
' flutter-version')
parser.add_argument('--github-token', default='', type=str,
help='Set github-token. Overrides _globals.json key/value')
parser.add_argument('--cookie-file', default='', type=str,
help='Set cookie-file to use. Overrides _globals.json key/value')
parser.add_argument('--fetch-engine', default=False,
action='store_true', help='Fetch Engine artifacts')
parser.add_argument('--version-files', default='', type=str,
help='Create JSON files correlating Flutter SDK to Engine and Dart commits')
parser.add_argument('--find-working-commit', default=False, action='store_true',
help='Use to finding GIT commit where flutter analyze returns true')
parser.add_argument('--plex', default='', type=str,
help='Platform Load Excludes')
parser.add_argument('--fastboot', default='', type=str,
help='Update the selected platform using fastboot')
parser.add_argument('--mask-rom', default='', type=str,
help='Update the selected platform using Mask ROM')
parser.add_argument('--device-id', default='', type=str, help='device id for flashing')
parser.add_argument('--stdin-file', default='', type=str,
help='Use for passing stdin for debugging')
parser.add_argument('--pubspec-path', default='', type=str, help='return pubspec.yaml info')
parser.add_argument('--plugin-platform', default='linux', type=str, help='specify plugin platform type')
parser.add_argument('--create-aot', default=False, action='store_true', help='Generate AOT')
parser.add_argument('--app-path', default='', type=str, help='Specify Application path')
args = parser.parse_args()
if args.create_aot:
if args.app_path == '':
sys.exit("Must specify value for --app-path")
#
# pubspec parsing
#
if len(args.pubspec_path):
pubspec = Pubspec(args.pubspec_path, args.plugin_platform)
pubspec.print_plugins()
return
#
# Find GIT Commit where flutter analyze returns true
#
if args.find_working_commit:
flutter_analyze_git_commits()
return
# reset sudo timestamp
subprocess.check_call(['sudo', '-k'], stdout=subprocess.DEVNULL)
# validate sudo user timestamp
if os.path.exists(args.stdin_file):
stdin_file = open(args.stdin_file)
subprocess.check_call(['sudo', '-S', '-v'],
stdout=subprocess.DEVNULL, stdin=stdin_file)
else:
subprocess.check_call(['sudo', '-v'], stdout=subprocess.DEVNULL)
#
# Target Folder
#
if "FLUTTER_WORKSPACE" in os.environ:
workspace = os.environ.get('FLUTTER_WORKSPACE')
else:
workspace = os.getcwd()
print_banner("Setting up Flutter Workspace in: %s" % workspace)
#
# Install minimum package
#
install_minimum_runtime_deps()
#
# Install required modules
#
# upgrade pip
python = sys.executable
subprocess.check_call([python, '-m', 'pip', 'install',
'--upgrade', 'pip'], stdout=subprocess.DEVNULL)
#
# Control+C handler
#
signal.signal(signal.SIGINT, handle_ctrl_c)
#
# Create Workspace
#
is_exist = os.path.exists(workspace)
if not is_exist:
os.makedirs(workspace)
if os.path.exists(workspace):
os.environ['FLUTTER_WORKSPACE'] = workspace
#
# Fetch Engine Artifacts
#
if args.fetch_engine:
print_banner("Fetching Engine Artifacts")
get_flutter_engine_runtime(True)
return
#
# Version Files
#
if args.version_files:
print_banner("Generating Version files")
get_version_files(args.version_files)
return
#
# Workspace Configuration
#
config = get_workspace_config(args.config)
globals_ = config.get('globals')
platforms = config.get('platforms')
for platform_ in platforms:
if not validate_platform_config(platform_):
print("Invalid platform configuration")
exit(1)
app_folder = os.path.join(workspace, 'app')
flutter_sdk_folder = os.path.join(workspace, 'flutter')
config_folder = os.path.join(workspace, '.config')
vscode_folder = os.path.join(workspace, '.vscode')
clean_workspace = False
if args.clean:
clean_workspace = args.clean
if clean_workspace:
print_banner("Cleaning Workspace")
if clean_workspace:
try:
os.remove(os.path.join(workspace, 'setup_env.sh'))
except FileNotFoundError:
pass
try:
os.remove(os.path.join(workspace, 'qemu_run.scpt'))
except FileNotFoundError:
pass
clear_folder(config_folder)
clear_folder(app_folder)
clear_folder(flutter_sdk_folder)
clear_folder(vscode_folder)
#
# Generate Release/Profile AOT
#
if args.create_aot:
if args.app_path != '':
create_aot.create_platform_aot(args.app_path)
else:
sys.exit("Must specify value for --app-path")
return
#
# Fast Boot
#
if args.fastboot:
print_banner("Fastboot Flash")
flash_fastboot(args.fastboot, args.device_id, platforms)
return
#
# Mask ROM
#
if args.mask_rom:
flash_mask_rom(args.mask_rom, args.device_id, platforms)
return
#
# App folder setup
#
is_exist = os.path.exists(app_folder)
if not is_exist:
os.makedirs(app_folder)
get_workspace_repos(app_folder, config)
#
# Get Flutter SDK
#
if args.flutter_version:
flutter_version = args.flutter_version
else:
if 'flutter-version' in globals_:
flutter_version = globals_.get('flutter-version')
else:
flutter_version = "master"
print_banner("Flutter Version: %s" % flutter_version)
flutter_sdk_path = get_flutter_sdk(flutter_version)
flutter_bin_path = os.path.join(flutter_sdk_path, 'bin')
# force tool rebuild
force_tool_rebuild(flutter_sdk_folder)
# Enable custom devices in dev and stable
if flutter_version != "master":
patch_flutter_sdk(flutter_sdk_folder)
#
# Configure Workspace
#
os.environ['PATH'] = '%s:%s' % (os.environ.get('PATH'), flutter_bin_path)
os.environ['PUB_CACHE'] = os.path.join(os.environ.get('FLUTTER_WORKSPACE'), '.config', 'flutter_workspace',
'pub_cache')
os.environ['XDG_CONFIG_HOME'] = os.path.join(
os.environ.get('FLUTTER_WORKSPACE'), '.config', 'flutter')
print("PATH=%s" % os.environ.get('PATH'))
print("PUB_CACHE=%s" % os.environ.get('PUB_CACHE'))
print("XDG_CONFIG_HOME=%s" % os.environ.get('XDG_CONFIG_HOME'))
#
# Trigger upgrade on Channel if version is all letters
#
if flutter_version.isalpha():
cmd = ["flutter", "upgrade", flutter_version]
print_banner("Upgrading `%s` Channel" % flutter_version)
subprocess.check_call(cmd, cwd=flutter_sdk_path)
#
# Configure SDK
#
configure_flutter_sdk()
#
# Flutter Engine Runtime
#
get_flutter_engine_runtime(clean_workspace)
#
# Create environmental setup script
#
write_env_script_header(workspace)
#
# Setup Platform(s)
#
github_token = globals_.get('github_token')
if args.github_token:
github_token = args.github_token
cookie_file = globals_.get('cookie_file')
if args.cookie_file:
cookie_file = args.cookie_file
setup_platforms(platforms, github_token, cookie_file, args.plex)
#
# Display the custom devices list
#
if flutter_version == "master":
cmd = ['flutter', 'custom-devices', 'list']
subprocess.check_call(cmd)
#
# Recursively change ownership to $SUDO_USER
#
user = os.environ.get('SUDO_USER')
flutter_workspace = os.environ.get('FLUTTER_WORKSPACE')
cmd = ['sudo', 'chown', '-R', f'{user}:{user}', '.']
subprocess.check_call(cmd, cwd=flutter_workspace)
#
# Done
#
print_banner("Setup Flutter Workspace - Complete")
def clear_folder(dir_):
""" Clears folder specified """
import shutil
if os.path.exists(dir_):
shutil.rmtree(dir_)
def get_workspace_config(path):
""" Returns workspace config """
if os.path.isdir(path):
data = {'globals': None, 'repos': None, 'platforms': []}
import glob
for filename in glob.glob(os.path.join(path, '*.json')):
with open(os.path.join(os.getcwd(), filename), 'r') as f:
_head, tail = os.path.split(filename)
if tail == '_repos.json':
try:
data['repos'] = json.load(f)
except json.decoder.JSONDecodeError:
print("Invalid JSON in %s" % f)
exit(1)
elif tail == '_globals.json':
try:
data['globals'] = json.load(f)
except json.decoder.JSONDecodeError:
print("Invalid JSON in %s" % f)
exit(1)
else:
try:
platform_ = json.load(f)
if 'load' in platform_:
if not platform_['load']:
continue
data['platforms'].append(platform_)
except json.decoder.JSONDecodeError:
print("Invalid JSON in %s" % f)
exit(1)
elif os.path.isfile(path):
with open(path, 'r') as f:
try:
data = json.load(f)
except json.decoder.JSONDecodeError:
print("Invalid JSON in %s" % f)
exit(1)
return data
def validate_platform_config(platform_):
""" Validates Platform Configuration returning bool """
if 'id' not in platform_:
print_banner("Missing 'id' key in platform config")
return False
if 'load' not in platform_:
print_banner("Missing 'load' key in platform config")
return False
if 'supported_archs' not in platform_:
print_banner("Missing 'supported_archs' key in platform config")
return False
if 'supported_host_types' not in platform_:
print_banner("Missing 'supported_host_types' key in platform config")
return False
if 'type' not in platform_:
print_banner("Missing 'type' key in platform config")
return False
else:
if platform_['type'] == 'generic':
if 'runtime' not in platform_:
print_banner("Missing 'runtime' key in platform config")
return False
elif platform_['type'] == 'qemu':
if 'runtime' not in platform_:
print_banner("Missing 'runtime' key in platform config")
return False
if 'custom-device' not in platform_:
print_banner("Missing 'custom-device' key in platform config")
return False
if 'config' not in platform_['runtime']:
print_banner("Missing 'config' key in platform config")
return False
if 'artifacts' not in platform_['runtime']:
print_banner("Missing 'artifacts' key in platform config")
return False
if 'qemu' not in platform_['runtime']:
print_banner("Missing 'qemu' key in platform config")
return False
elif platform_['type'] == 'docker':
if 'runtime' not in platform_:
print_banner("Missing 'runtime' key in platform config")
return False
if 'flutter_runtime' not in platform_:
print_banner(
"Missing 'flutter_runtime' key in platform config")
return False
if 'custom-device' not in platform_:
print_banner("Missing 'custom-device' key in platform config")
return False
if 'overwrite-existing' not in platform_:
print_banner(
"Missing 'overwrite-existing' key in platform config")
return False
elif platform_['type'] == 'host':
if 'runtime' not in platform_:
print_banner("Missing 'runtime' key in platform config")
return False
if 'flutter_runtime' not in platform_:
print_banner(
"Missing 'flutter_runtime' key in platform config")
return False
if 'custom-device' not in platform_:
print_banner("Missing 'custom-device' key in platform config")
return False
if 'overwrite-existing' not in platform_:
print_banner(
"Missing 'overwrite-existing' key in platform config")
return False
elif platform_['type'] == 'remote':
if 'runtime' not in platform_:
print_banner("Missing 'runtime' key in platform config")
return False
if 'flutter_runtime' not in platform_:
print_banner(
"Missing 'flutter_runtime' key in platform config")
return False
if 'custom-device' not in platform_:
print_banner("Missing 'custom-device' key in platform config")
return False
if 'overwrite-existing' not in platform_:
print_banner(
"Missing 'overwrite-existing' key in platform config")
return False
else:
print("platform type %s is not currently supported." %
(platform_['type']))
return False
print("Platform ID: %s" % (platform_['id']))
return True
def validate_custom_device_config(config):
""" Validates custom-device Configuration returning bool """
if 'id' not in config:
print_banner("Missing 'id' key in custom-device config")
return False
if 'label' not in config:
print_banner("Missing 'label' key in custom-device config")
return False
if 'sdkNameAndVersion' not in config:
print_banner("Missing 'sdkNameAndVersion' key in custom-device config")
return False
if 'platform' not in config:
print_banner("Missing 'platform' key in custom-device config")
return False
if 'enabled' not in config:
print_banner("Missing 'enabled' key in custom-device config")
return False
if 'ping' not in config:
print_banner("Missing 'ping' key in custom-device config")
return False
if 'pingSuccessRegex' not in config:
print_banner("Missing 'pingSuccessRegex' key in custom-device config")
return False
if 'postBuild' not in config:
print_banner("Missing 'postBuild' key in custom-device config")
return False
if 'install' not in config:
print_banner("Missing 'install' key in custom-device config")
return False
if 'uninstall' not in config:
print_banner("Missing 'uninstall' key in custom-device config")
return False
if 'runDebug' not in config:
print_banner("Missing 'runDebug' key in custom-device config")
return False
if 'forwardPort' not in config:
print_banner("Missing 'forwardPort' key in custom-device config")
return False
if 'forwardPortSuccessRegex' not in config:
print_banner(
"Missing 'forwardPortSuccessRegex' key in custom-device config")
return False
if 'screenshot' not in config:
print_banner("Missing 'screenshot' key in custom-device config")
return False
return True
def get_repo(base_folder, uri, branch, rev):
""" Clone Git Repo """
if not uri:
print("repo entry needs a 'uri' key. Skipping")
return
if not branch:
print("repo entry needs a 'branch' key. Skipping")
return
# get repo folder name
repo_name = uri.rsplit('/', 1)[-1]
repo_name = repo_name.split(".")
repo_name = repo_name[0]
git_folder = os.path.join(base_folder, repo_name)
git_folder_git = os.path.join(base_folder, repo_name, '.git')
is_exist = os.path.exists(git_folder_git)
if is_exist:
cmd = ['git', 'reset', '--hard']
subprocess.check_call(cmd, cwd=git_folder)
cmd = ['git', 'fetch', '--all']
subprocess.check_call(cmd, cwd=git_folder)
cmd = ['git', 'checkout', branch]
subprocess.check_call(cmd, cwd=git_folder)
else:
cmd = ['git', 'clone', uri, '-b', branch, repo_name]
subprocess.check_call(cmd, cwd=base_folder)
if rev:
cmd = ['git', 'reset', '--hard', rev]
subprocess.check_call(cmd, cwd=git_folder)
# get lfs
git_lfs_file = os.path.join(base_folder, repo_name, '.gitattributes')
if os.path.exists(git_lfs_file):
cmd = ['git', 'lfs', 'fetch', '--all']
subprocess.check_call(cmd, cwd=git_folder)
# get all submodules
git_submodule_file = os.path.join(base_folder, repo_name, '.gitmodules')
if os.path.exists(git_submodule_file):
cmd = ['git', 'submodule', 'update', '--init', '--recursive']
subprocess.check_call(cmd, cwd=git_folder)
def get_workspace_repos(base_folder, config):
""" Clone GIT repos referenced in config repos dict to base_folder """
import concurrent.futures
if 'repos' not in config:
return
repos = config['repos']
with concurrent.futures.ThreadPoolExecutor() as executor:
futures = []
for repo in repos:
futures.append(executor.submit(get_repo, base_folder=base_folder, uri=repo.get(
'uri'), branch=repo.get('branch'), rev=repo.get('rev')))
subprocess.check_call(['sudo', '-v'], stdout=subprocess.DEVNULL)
for _future in concurrent.futures.as_completed(futures):
subprocess.check_call(['sudo', '-v'], stdout=subprocess.DEVNULL)
print_banner("Repos Cloned")
# reset sudo timeout
subprocess.check_call(['sudo', '-v'], stdout=subprocess.DEVNULL)
#
# Create vscode startup tasks
#
platform_ids = get_platform_ids(config.get('platforms'))
create_vscode_launch_file(repos, platform_ids)
def get_platform_ids(platforms: dict) -> list:
res = []
for platform_ in platforms:
res.append(platform_['id'])
return res
def get_flutter_settings_folder():
""" Returns the path of the Custom Config json file """
if "XDG_CONFIG_HOME" in os.environ:
settings_folder = os.path.join(os.environ.get('XDG_CONFIG_HOME'))
else:
settings_folder = os.path.join(
os.environ.get('HOME'), '.config', 'flutter')
make_sure_path_exists(settings_folder)
return settings_folder
def get_flutter_custom_config_path():
""" Returns the path of the Flutter Custom Config json file """
folder = get_flutter_settings_folder()
# print("folder: %s" % folder)
return os.path.join(folder, 'custom_devices.json')
def get_flutter_custom_devices():
""" Returns the Flutter custom_devices.json as dict """
custom_config = get_flutter_custom_config_path()
if os.path.exists(custom_config):
f = open(custom_config)
try:
data = json.load(f)
except json.decoder.JSONDecodeError:
# in case json is invalid
print("Invalid JSON in %s" % custom_config)
exit(1)
f.close()
if 'custom-devices' in data:
return data['custom-devices']
print("%s not present in filesystem." % custom_config)
return {}
def remove_flutter_custom_devices_id(id_):
""" Removes Flutter custom devices that match given id from the
configuration file """
# print("Removing custom-device with ID: %s" % id_)
custom_config = get_flutter_custom_config_path()
if os.path.exists(custom_config):
f = open(custom_config, "r")
try:
obj = json.load(f)
except json.decoder.JSONDecodeError:
print_banner("Invalid JSON in %s" %
custom_config) # in case json is invalid
exit(1)
f.close()
new_device_list = []
if 'custom-devices' in obj:
devices = obj['custom-devices']
for device in devices:
if 'id' in device and id_ != device['id']:
new_device_list.append(device)
custom_devices = {'custom-devices': new_device_list}
if 'custom-devices' not in custom_devices:
print("Removing empty file: %s" % custom_config)
os.remove(custom_config)
return
with open(custom_config, "w") as outfile:
json.dump(custom_devices, outfile, indent=2)
return
def patch_string_array(find_token, replace_token, list_):
return [w.replace(find_token, replace_token) for w in list_]
def patch_custom_device_strings(devices, flutter_runtime):
""" Patch custom device string environmental variables to use literal
values """
workspace = os.getenv('FLUTTER_WORKSPACE')
bundle_folder = os.getenv('BUNDLE_FOLDER')
host_arch = get_host_machine_arch()
for device in devices:
token = '${FLUTTER_WORKSPACE}'
if device.get('label'):
if '${MACHINE_ARCH}' in device['label']:
device['label'] = device['label'].replace(
'${MACHINE_ARCH}', host_arch)
if device.get('platform'):
if host_arch == 'x86_64':
device['platform'] = 'linux-x64'
elif host_arch == 'arm64':
device['platform'] = 'linux-arm64'
if device.get('sdkNameAndVersion'):
if '${FLUTTER_RUNTIME}' in device['sdkNameAndVersion']:
sdk_name_and_version = device['sdkNameAndVersion'].replace(
'${FLUTTER_RUNTIME}', flutter_runtime)
device['sdkNameAndVersion'] = sdk_name_and_version
if '${MACHINE_ARCH_HYPHEN}' in device['sdkNameAndVersion']:
device['sdkNameAndVersion'] = device['sdkNameAndVersion'].replace('${MACHINE_ARCH_HYPHEN}',
host_arch.replace('_', '-'))
if device.get('postBuild'):
device['postBuild'] = patch_string_array(
token, workspace, device['postBuild'])
if device.get('runDebug'):
device['runDebug'] = patch_string_array(
token, workspace, device['runDebug'])
token = '${BUNDLE_FOLDER}'
if device.get('install'):
device['install'] = patch_string_array(
token, bundle_folder, device['install'])
return devices
def fixup_custom_device(obj):
""" Patch custom device string environmental variables to use literal values """
obj['id'] = os.path.expandvars(obj['id'])
obj['label'] = os.path.expandvars(obj['label'])
obj['sdkNameAndVersion'] = os.path.expandvars(obj['sdkNameAndVersion'])
obj['platform'] = os.path.expandvars(obj['platform'])
obj['ping'] = os.path.expandvars(obj['ping'])
obj['ping'] = shlex.split(obj['ping'])
obj['pingSuccessRegex'] = os.path.expandvars(obj['pingSuccessRegex'])
if obj['postBuild']:
obj['postBuild'] = os.path.expandvars(obj['postBuild'])
obj['postBuild'] = shlex.split(obj['postBuild'])
if obj['install']:
obj['install'] = os.path.expandvars(obj['install'])
obj['install'] = shlex.split(obj['install'])
if obj['uninstall']:
obj['uninstall'] = os.path.expandvars(obj['uninstall'])
obj['uninstall'] = shlex.split(obj['uninstall'])
if obj['runDebug']:
obj['runDebug'] = os.path.expandvars(obj['runDebug'])
obj['runDebug'] = shlex.split(obj['runDebug'])
if obj['forwardPort']:
obj['forwardPort'] = os.path.expandvars(obj['forwardPort'])
obj['forwardPort'] = shlex.split(obj['forwardPort'])
if obj['forwardPortSuccessRegex']:
obj['forwardPortSuccessRegex'] = os.path.expandvars(
obj['forwardPortSuccessRegex'])
if obj['screenshot']:
obj['screenshot'] = os.path.expandvars(obj['screenshot'])
obj['screenshot'] = shlex.split(obj['screenshot'])
return obj
def add_flutter_custom_device(device_config, flutter_runtime):
""" Add a single Flutter custom device from json string """
if not validate_custom_device_config(device_config):
exit(1)
# print("Adding custom-device: %s" % device_config)
custom_devices_file = get_flutter_custom_config_path()
new_device_list = []
if os.path.exists(custom_devices_file):
f = open(custom_devices_file, "r")
try:
obj = json.load(f)
except json.decoder.JSONDecodeError:
print_banner("Invalid JSON in %s" %
custom_devices_file) # in case json is invalid
exit(1)
f.close()
id_ = device_config['id']
if 'custom-devices' in obj:
devices = obj['custom-devices']
for device in devices:
if 'id' in device and id_ != device['id']:
new_device_list.append(device)
new_device_list.append(device_config)
patched_device_list = patch_custom_device_strings(
new_device_list, flutter_runtime)
custom_devices = {'custom-devices': patched_device_list}
print("custom_devices_file: %s" % custom_devices_file)
with open(custom_devices_file, "w+") as outfile:
json.dump(custom_devices, outfile, indent=4)
return
def add_flutter_custom_device_ex(custom_device, _flutter_runtime):
""" Add a single Flutter custom device from json string """
if not validate_custom_device_config(custom_device):
sys.exit("Invalid Custom Device configuration")
device_config = fixup_custom_device(custom_device)
# print("Adding custom-device: %s" % device_config)
custom_devices_file = get_flutter_custom_config_path()
new_device_list = []
if os.path.exists(custom_devices_file):
f = open(custom_devices_file, "r")
try:
obj = json.load(f)
except json.decoder.JSONDecodeError:
print_banner("Invalid JSON in %s" %
custom_devices_file) # in case json is invalid
exit(1)
f.close()
id_ = device_config['id']
if 'custom-devices' in obj:
devices = obj['custom-devices']
for device in devices:
if 'id' in device and id_ != device['id']:
new_device_list.append(device)
new_device_list.append(device_config)
# patched_device_list = patch_custom_device_strings_ex(new_device_list)
custom_devices = {'custom-devices': new_device_list}
print("custom_devices_file: %s" % custom_devices_file)
with open(custom_devices_file, "w+") as outfile:
json.dump(custom_devices, outfile, indent=4)
return
def handle_custom_devices(platform_):
""" Updates the custom_devices.json with platform config """
if "custom-device" not in platform_:
return
custom_devices = get_flutter_custom_devices()
overwrite_existing = platform_.get('overwrite-existing')
# check if id already exists, remove if overwrite enabled, otherwise skip
if custom_devices:
for custom_device in custom_devices:
if 'id' in custom_device:
id_ = custom_device['id']
if overwrite_existing and (id_ == platform_['id']):
# print("attempting to remove custom-device: %s" % id_)
remove_flutter_custom_devices_id(id_)
add_flutter_custom_device_ex(
platform_['custom-device'], platform_['flutter_runtime'])
def configure_flutter_sdk():
settings = {"enable-web": False, "enable-android": False, "enable-ios": False, "enable-fuchsia": False,
"enable-custom-devices": True}
host = get_host_type()
if host == 'darwin':
settings['enable-linux-desktop'] = False
settings['enable-macos-desktop'] = True
settings['enable-windows-desktop'] = False
elif host == 'linux':
settings['enable-linux-desktop'] = True
settings['enable-macos-desktop'] = False
settings['enable-windows-desktop'] = False
elif host == 'windows':
settings['enable-linux-desktop'] = False
settings['enable-macos-desktop'] = False
settings['enable-windows-desktop'] = True
settings_file = os.path.join(get_flutter_settings_folder(), 'settings')
with open(settings_file, "w+") as outfile:
json.dump(settings, outfile, indent=2)
cmd = ['flutter', 'config', '--no-analytics']
subprocess.check_call(cmd)
cmd = ['dart', '--disable-analytics']
subprocess.check_call(cmd)
cmd = ['flutter', 'doctor']
subprocess.check_call(cmd)
def force_tool_rebuild(flutter_sdk_folder):
tool_script = os.path.join(
flutter_sdk_folder, 'bin', 'cache', 'flutter_tools.snapshot')
if os.path.exists(tool_script):
print_banner("Cleaning Flutter Tool")
cmd = ["rm", tool_script]
subprocess.check_call(cmd, cwd=flutter_sdk_folder)
def patch_flutter_sdk(flutter_sdk_folder):
host = get_host_type()
if host == "linux":
print_banner("Patching Flutter SDK")
cmd = ["bash", "-c", "sed -i -e \"/const Feature flutterCustomDevicesFeature/a const"
" Feature flutterCustomDevicesFeature = Feature\\(\\n name: "
"\\\'Early support for custom device types\\\',\\n configSetting:"
" \\\'enable-custom-devices\\\',\\n environmentOverride: "
"\\\'FLUTTER_CUSTOM_DEVICES\\\',\\n master: FeatureChannelSetting"
"(\\n available: true,\\n \\),\\n beta: FeatureChannelSetting"
"\\(\\n available: true,\\n \\),\\n stable: "
"FeatureChannelSetting(\\n available: true,\\n \\)\\n);\" -e "
"\"/const Feature flutterCustomDevicesFeature/,/);/d\" packages/"
"flutter_tools/lib/src/features.dart"]
subprocess.check_call(cmd, cwd=flutter_sdk_folder)
# Check for flutter SDK path. Pull if exists. Create dir and clone sdk if not.
def get_flutter_sdk(version):
""" Get Flutter SDK clone """
workspace = os.environ.get('FLUTTER_WORKSPACE')
flutter_sdk_path = os.path.join(workspace, 'flutter')
#
# GIT repo
#
if is_repo(flutter_sdk_path):
print('Checking out %s' % version)