-
Notifications
You must be signed in to change notification settings - Fork 0
/
reactnative-setup.py
1477 lines (1168 loc) · 49.6 KB
/
reactnative-setup.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
#!/env/python
from inspect import currentframe
from urllib.request import urlopen
import argparse
from datetime import datetime
import json
import os
import platform
import re
import shutil
import subprocess
import sys
script_url = 'https://raw.githubusercontent.com/bjmckenz/rn-cli-fixup/main/reactnative-setup.py'
script_version = "1.5.3"
# This script is intended to be run from the root of a React Native project directory.
### TO DO
# TODO: log changes to a tombstone file
# TODO: Clean up filenames, envvars, file contents
# TODO: move data to a file
# TODO: give revised version of .bashrc/.zshrc
# TODO: test gitbash on win for shelltype, file PS vs command PS
# PowerShell: ShellId = Microsoft.PowerShell
# CMD, cygwin,gitbash: OS Windows_NT
# cygwin,gitbsh: SHELL
# gitbash and cygwin can handle \ in paths
# FIXME: https://stackoverflow.com/questions/70258316/how-to-fix-dexoptionsactiondexoptions-unit-is-deprecated-setting-dexopt
# FIXME: https://stackoverflow.com/questions/71365373/software-components-will-not-be-created-automatically-for-maven-publishing-from#:~:text=WARNING%3A%20Software%20Components%20will%20not,use%20the%20new%20publishing%20DSL.
# TODO: output number of tests and modifications
# ENVIRONMENTY STUFF
running_on_windows = platform.system() == 'Windows'
shell_is_unixy = os.environ.get('SHELL') != None
# path separator in commands and paths
# FIXME: Should this include "or shell_shell_is_unixy"? diff between commands we run and report a nd what we write in files
path_separator = '\\' if running_on_windows else '/'
cmd_argument_separator = '/' if shell_is_unixy else '\\'
path_variable_separator = ';' if running_on_windows else ':'
# From command-line Arguments
config = {}
# can be set to false if a test fails
ok_to_proceed_with_modifications = True
# Specify the path to bundletool.jar
bt_dir = 'C:{ps}Program Files{ps}'.format(ps=path_separator) \
if running_on_windows \
else '{home}{ps}Library{ps}'.format(
home=os.environ.get('HOME'),ps=path_separator)
keystore_file = "my-release-key"
store_password = "12345678"
key_alias = "my-key-alias"
key_password = "12345678"
distinguished_name = "CN=MyName, OU=MyOrgUnit, O=MyOrg, L=MyCity, ST=MyStateOrProvince, C=MyCountry"
### vvv NOT INTENDED TO BE CUSTOMIZED (but fix it if needed) vvv ###
bt_jar = 'bundletool-all-1.15.6.jar'
bt_loc = 'https://github.com/google/bundletool'
new_distribution_url = 'https://services.gradle.org/distributions/gradle-8.1-bin.zip'.format(
ps=path_separator)
expected_java_version = "20.0.2"
jdk_download_path = "https://jdk.java.net/archive/"
# This isomorphic with build.gradle format as we parse it
release_signing_config = {
'key': 'release',
'contents': [
{'line': "storeFile file('{keystore_file}')".format(
keystore_file=keystore_file)},
{'line': "storePassword '{store_password}'".format(
store_password=store_password)},
{'line': "keyAlias '{key_alias}'".format(key_alias=key_alias)},
{'line': "keyPassword '{key_password}'".format(
key_password=key_password)},
]
}
gradle_properties_to_add = [
'MYAPP_RELEASE_STORE_FILE={keystore_file}.jks'.format(
keystore_file=keystore_file),
'MYAPP_RELEASE_KEY_ALIAS={key_alias}'.format(key_alias=key_alias),
'MYAPP_RELEASE_STORE_PASSWORD={store_password}'.format(
store_password=store_password),
'MYAPP_RELEASE_KEY_PASSWORD={key_password}'.format(
key_password=key_password),
]
app_tsx_path = 'App.tsx' # Expected for new projects
app_tsx_original_lengths = (2605, 2617)
package_json_path = 'package.json'
# created to specify which apk to extract from apks file
universal_json_path = 'android{ps}universal.json'.format(ps=path_separator)
gradle_properties_path = 'android{ps}gradle.properties'.format(
ps=path_separator)
build_gradle_path = 'android{ps}build.gradle'.format(ps=path_separator)
app_build_gradle_path = 'android{ps}app{ps}build.gradle'.format(ps=path_separator)
gradle_wrapper_properties_path = 'android{ps}gradle{ps}wrapper{ps}gradle-wrapper.properties'.format(
ps=path_separator)
script_output_file = 'reactnative-fixup.txt'
kotlinVersion = "1.7.10"
# reanimated adds about 199 chars to the path, and the max length on Windows
# is 250.
max_windows_project_path_length = 45
dependencies_to_add = {
"@react-native-masked-view/masked-view": "^0.3.0",
"@react-navigation/drawer": "^6.6.6",
"@react-navigation/native": "^6.1.9",
"@react-navigation/native-stack": "^6.9.17",
"@react-navigation/stack": "^6.3.20",
"react-native-asset": "^2.1.1",
"react": "18.2.0",
"react-native": "0.72.7",
"react-native-gesture-handler": "^2.14.0",
"react-native-reanimated": "^3.6.1",
"react-native-safe-area-context": "^4.7.4",
"react-native-screens": "^3.27.0"
}
# Define the contents for universal.json
universal_json_contents = {
"supportedAbis": ["armeabi-v7a", "arm64-v8a", "x86", "x86_64"],
"supportedLocales": ["en", "fr", "de", "es", "it", "ja", "ko", "pt", "ru", "zh-rCN", "zh-rTW"],
"screenDensity": 160,
"sdkVersion": 21
}
release_section_text = """
release {{
signingConfig signingConfigs.release
minifyEnabled enableProguardInReleaseBuilds
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}}
"""
prettier_rc = """
{
"arrowParens": "avoid",
"bracketSameLine": true,
"bracketSpacing": false,
"singleQuote": true,
"trailingComma": "all"
}
"""
welcome_message = """
*******
This script MAY help you. You *should* have run "npx react-native doctor"
and fixed the issues first. This may help you with issues there if you can't figure out why doctor is failing.
BUT DO NOT try to run-android without BOTH "doctor" and this script reporting success.
Note that "WARN:" does not mean "Error", it means "be sure this is correct."
All output from this script will be logged to {of}
***********
""".format(of=script_output_file)
# This is the Hello-Worldiest of Hello-World apps.
app_js_path = 'App.js' # we create this if we remove App.tsx
app_js_content = """
import React from 'react';
import {
Text,
SafeAreaView,
} from 'react-native';
import {SafeAreaProvider} from 'react-native-safe-area-context';
const App = () => {
return (
<SafeAreaProvider>
<SafeAreaView>
<Text>Hello World</Text>
</SafeAreaView>
</SafeAreaProvider>
);
}
export default App;
"""
keystore_path = 'android/app/{keystore_file}.jks'.format(
keystore_file=keystore_file
)
# Note - this is split into lines so we can split into command-line arguments later. One arg per line!
keystore_create_cmd = 'keytool \
-genkeypair \
-v \
-storetype \
PKCS12 \
-keystore \
{keystore_path} \
-keyalg \
RSA \
-keysize \
2048 \
-validity \
10000 \
-alias \
{key_alias} \
-dname \
{distinguished_name} \
-storepass \
{store_password} \
-keypass \
{key_password}'.format(
keystore_path=keystore_path,
store_password=store_password,
key_alias=key_alias,
key_password=key_password,
distinguished_name=distinguished_name
)
build_apks_cmd = re.sub(r' +', ' ',
'java -jar "{bt_dir}{bt_jar}" \
build-apks \
--bundle=app{ps}build{ps}outputs{ps}bundle{ps}release{ps}app-release.aab \
--output=app{ps}build{ps}outputs{ps}apk{ps}release{ps}app-release.apks \
--mode=universal \
--ks=..{ps}{keystore_path} \
--ks-pass=pass:{store_password} \
--ks-key-alias={key_alias} \
--key-pass=pass:{key_password}'.format(
bt_dir=bt_dir,
bt_jar=bt_jar,
keystore_path=keystore_path,
store_password=store_password,
key_alias=key_alias,
key_password=key_password,
ps=cmd_argument_separator))
extract_apk_cmd = re.sub(r' +', ' ',
'java -jar "{bt_dir}{bt_jar}" \
extract-apks \
--apks=app{ps}build{ps}outputs{ps}apk{ps}release{ps}app-release.apks \
--output-dir=app{ps}build{ps}outputs{ps}apk{ps}release{ps} \
--device-spec=..{ps}{universal_json_path}'.format(
bt_dir=bt_dir,
bt_jar=bt_jar,
universal_json_path=universal_json_path,
ps=cmd_argument_separator
))
post_config_steps = '''
$ npm install
$ npx react-native-asset
*FOR IOS Before* your first build (or after you install a new NPM package) you must:
$ sudo gem update cocoapods --pre
$ npx pod-install
$ cd ios && pod update && cd ..
$ npx react-native run-android *(or)* run-ios
[to build an APK]
$ npx react-native-asset
$ cd android && .{ps}gradlew build && .{ps}gradlew bundleRelease
$ {build_apks_cmd}
$ {extract_apk_cmd}
'''.format(
extract_apk_cmd=extract_apk_cmd,
build_apks_cmd=build_apks_cmd,
ps=cmd_argument_separator
)
clean_repo_cmd = 'rnc clean --include "android,metro,npm,watchman,yarn"'
# ideal way to find
android_home = os.environ.get('ANDROID_HOME')
android_sdk_root = android_home if android_home else os.environ.get(
'ANDROID_SDK_ROOT')
font_assets_dir = 'assets/fonts'
sound_assets_dir = 'assets/audio'
react_native_config_path = 'react-native.config.js'
react_native_config_contents = '''
module.exports = {
assets: ['./assets/fonts', './assets/audio'],
dependencies: {
'react-native-vector-icons': {
platforms: {
ios: null,
},
},
},
};
'''
# tests command-line tools
cmdline_tools_path = 'cmdline-tools{ps}latest{ps}bin'.format(
ps=cmd_argument_separator
)
# tests NDK
ndk_version = '23.1.7779620'
# tests buildtools
build_tools_versions = ['30.0.3', '33.0.0', '34.0.0']
# platform-tools
adb_command = 'adb'
# tests tools dir
emu = 'emulator'
java_home = os.environ.get('JAVA_HOME')
osified_java_home_path = java_home.replace('\\', '\\\\') if java_home \
else None
### ^^^ NOT INTENDED TO BE CUSTOMIZED ^^^ ###
# BEGIN UTILITIES
counts = {
'fatal': 0,
'warn': 0,
'error': 0,
'info': 0,
'debug': 0,
'howto': 0
}
def print_counts():
print('*** ({ver}) Message type counts: {fatal} fatal, {warn} warn, {error} error, {info} info, {howto} fixes'.format(
fatal=counts['fatal'],
warn=counts['warn'],
error=counts['error'],
info=counts['info'],
howto=counts['howto'],
ver=script_version))
def report(type, message, include_line=True):
counts[type.lower()] += 1
if config['quiet'] and type.lower() == 'info':
return
if not config['debug'] and type.lower() == 'debug':
return
caller_line = currentframe().f_back.f_lineno
if type.lower() == 'howto':
print("vvvvvv HOW TO FIX vvvvvv\n{message}\n^^^^^^ HOW TO FIX ^^^^^".format(message=message.strip()))
return
message += ' [{ln}]'.format(ln=caller_line) if include_line else ''
print('{type}: {message}'.format(type=type.upper(), message=message))
def current_version_of_script():
try:
for line in urlopen(script_url).read().decode('utf-8').splitlines():
if line.strip().startswith('script_version'):
return line.split('=')[1].strip().strip('"')
report('error','Could not determine current version of script.')
except Exception as e:
report('error','Could not read current version of script.')
print(e)
pass
return None
def versiontuple(v):
return tuple(map(int, (v.split("."))))
#### Decorators and such that automatically collect operations to run
operations_in_order = []
operation_named = {}
def operation_prereqs_met(operation):
if config['ignore_prerequisites']:
return True
for prereq_name in operation['prereqs']:
# if we didn't run it, or we did and it failed
if operation_named[prereq_name]['result'] != True:
return False
return True
def add_operation(func,attrs):
func_name = func.__name__
new_op = {
'func_name': func_name,
'prereqs': [],
# Default true for all except show_newest_script_version
'to_run': func_name != 'show_newest_script_version',
'index': len(operations_in_order),
'result': None,
**attrs}
operation_named[func_name] = new_op
operations_in_order.append(new_op)
return new_op
def operation(attrs={}):
def decorator_internal(func):
op = add_operation(func,attrs)
def if_prereqs_met(*args, **kwargs):
return func(*args, **kwargs) \
if operation_prereqs_met(op) \
else None
op['func'] = if_prereqs_met
return if_prereqs_met
return decorator_internal
def system_test(attrs={}):
return operation({'scope':'system','type':'test', **attrs})
def project_test(attrs={}):
return operation({'scope':'project','type':'test', **attrs})
def project_modification(attrs={}):
return operation({'scope':'project','type':'modification', **attrs})
##### end decorators for operations
# decorator to wrap a function to be executed only once
def do_once(func):
def wrapper(*args, **kwargs):
if not wrapper.has_run:
wrapper.has_run = True
return func(*args, **kwargs)
wrapper.has_run = False
return wrapper
def parse_command_line_arguments():
@do_once
def clear_list_of_tests_to_run():
for op in operations_in_order:
if op['type'] == 'test':
op['to_run'] = False
@do_once
def clear_list_of_modifications_to_run():
for op in operations_in_order:
if op['type'] == 'modification':
op['to_run'] = False
class DoTestModule(argparse.Action):
def __call__(self, parse, namespace, values, option_string=None):
ok_to_proceed_with_modifications = False
clear_list_of_tests_to_run()
operation_named[self.dest]['to_run'] = True
class DoModificationtModule(argparse.Action):
def __call__(self, parse, namespace, values, option_string=None):
clear_list_of_modifications_to_run()
operation_named[self.dest]['to_run'] = True
class SkipModule(argparse.Action):
def __call__(self, parse, namespace, values, option_string=None):
operation_named[self.dest]['to_run'] = False
class NoTests(argparse.Action):
def __call__(self, parse, namespace, values, option_string=None):
clear_list_of_tests_to_run()
class NoMods(argparse.Action):
def __call__(self, parse, namespace, values, option_string=None):
clear_list_of_modifications_to_run()
class NoProject(argparse.Action):
def __call__(self, parse, namespace, values, option_string=None):
for op in operations_in_order:
if op['scope'] == 'project':
op['to_run'] = False
class NoSystem(argparse.Action):
def __call__(self, parse, namespace, values, option_string=None):
for op in operations_in_order:
if op['scope'] == 'system':
op['to_run'] = False
parser = argparse.ArgumentParser(description="React-Native CLI Fixer-Upper",
formatter_class=argparse.
ArgumentDefaultsHelpFormatter,
epilog="v{ver} Contact bjmckenz@gmail.com with bugs, questions, and suggestions.".format(ver=script_version))
parser.add_argument("-q", "--quiet", action=argparse.BooleanOptionalAction,
default=False, help="Shhh! No INFO messages")
parser.add_argument("--debug", action=argparse.BooleanOptionalAction,
default=False, help="Show Debug Messages")
parser.add_argument("-f", "--force", action=argparse.BooleanOptionalAction,
default=False,
help="continue even if after an error")
parser.add_argument("--simulate-modifications", action=argparse.BooleanOptionalAction,
default=False, dest='simulate',
help="simulate modifications, don't actually do them")
parser.add_argument("--show-header-and-trailer", action=argparse.BooleanOptionalAction,
default=not safe_exists(script_output_file),
dest='show-header-and-trailer',
help="display annoying header and trailer every time")
parser.add_argument("--ignore-prerequisites", action='store_true',
default=False,
help="run tests regardless of prerequisites")
parser.add_argument("--no-tests", action=NoTests, nargs=0,
help="skip all tests")
parser.add_argument("--no-project", action=NoProject, nargs=0,
help="skip project-level tests")
parser.add_argument("--no-system", action=NoSystem, nargs=0,
help="skip system-level tests")
parser.add_argument("--no-mods","--no-modifications", action=NoMods, nargs=0,
help="skip modifications")
for op in operations_in_order:
parser.add_argument("--do-"+op['func_name'],
action=DoTestModule if op['type'] == 'test' else DoModificationtModule,
dest=op['func_name'], nargs=0,
help="run "+op['func_name'])
parser.add_argument("--skip-"+op['func_name'],
action=SkipModule, nargs=0,
dest=op['func_name'],
help="(don't) "+op['func_name'])
config = vars(parser.parse_args())
return config
def safe_exists(path):
return os.path.exists(os.path.normcase(path))
def paths_equal(path1, path2):
#print("comparing {p1} to {p2}".format(p1=path1,p2=path2))
return os.path.normcase(path1) == os.path.normcase(path2)
def current_version_of_npm_package(pkg):
url = 'https://unpkg.com/{pkg}/package.json'.format(pkg=pkg)
response = urlopen(url)
package_json = json.loads(response.read())
return package_json['version']
def brew_recipe_installed(item):
brew_output = subprocess.check_output(
["brew", "info", item], stderr=subprocess.STDOUT, text=True)
return 'Not installed' not in brew_output
def read_gradle_file(file_path):
with open(file_path, 'r') as gradle_config:
content = gradle_config.read()
objstack = [ [] ]
processing_conditionals = False
for line in map(str.strip, content.splitlines()):
if processing_conditionals:
objstack[len(objstack)-1].append({'line':line})
if line == '}':
processing_conditionals = False
continue
if line == '}':
objstack.pop()
elif len(line) and (line[0] == '*' or line.startswith('/*') or line.startswith('//')):
# hack for comments -- not really very good but hopefully adequate
objstack[len(objstack)-1].append({'line':line})
elif line.endswith('{'):
key = line.split(' ')[0]
if key == 'if':
processing_conditionals = True
objstack[len(objstack)-1].append({'line':line})
continue
sub = { 'key': key, 'contents':[] }
objstack[len(objstack)-1].append(sub)
objstack.append(sub['contents'])
else:
objstack[len(objstack)-1].append({'line':line})
return {'key':'FILE', 'contents':objstack[0]}
def getSection(nodes, key):
if nodes is None or 'contents' not in nodes:
return None
singlenodelist = list(filter(lambda x: 'key' in x and x['key'] == key, nodes['contents']))
return singlenodelist[0] if len(singlenodelist) else None
def gradle_config_as_str(node,level=0):
lines = []
contents = node['contents']
for element in contents:
if 'line' in element:
text = element['line']
if text == '':
if len(lines) and lines[len(lines)-1] == '':
continue
lines.append('')
continue
lines.append(' '* level + text)
else:
lines.append(' '*level + element['key'] + ' {' )
lines.append(gradle_config_as_str(element,level+1))
lines.append(' '*level + '}')
return '\n'.join(lines) + ('\n' if level==0 else '')
# Logger Class tees all output to output file
class Logger(object):
def __init__(self):
self.terminal = sys.stdout
self.log = open(script_output_file, "a")
def write(self, message):
self.terminal.write(message)
self.log.write(message)
def flush(self):
self.log.flush()
# BEGIN TESTS
@operation({'scope':'meta','type':'debug'})
def print_stats():
report('debug',"*** CONFIG ***")
report('debug',json.dumps(config, indent=4, sort_keys=True))
report('debug',"*** OPERATIONS ***")
report('debug',json.dumps(list(map(lambda x: {**x, 'func':'<func>'},operations_in_order)), indent=4))
return True
@operation({'scope':'meta','type':'meta'})
def script_version_check():
current_vers = current_version_of_script()
if current_vers is None:
report('fatal','Could not determine current version of script.')
for op in operations_in_order:
op['to_run'] = False
return False
#report('info',"Current version of script is {cv}, this version is {dv}".format(cv=current_vers,dv=script_version))
if versiontuple(current_vers) > versiontuple(script_version):
report('fatal','This script (v{dv}) is out of date. Please pull the latest version (v{cv}) from github'.format(dv=script_version,cv=current_vers))
sys.exit()
report('info', 'Script is current version ({cv})'.format(cv=current_vers))
return True
@operation({'scope':'meta','type':'meta'})
def show_newest_script_version():
current_vers = current_version_of_script()
if current_vers is None:
report('error','Could not determine current version of script.')
sys.exit()
report('info','Your version of this script is {this}. Current version on github is {vers}'.format(
vers=current_vers, this=script_version))
sys.exit()
@system_test()
def is_npm_installed():
if shutil.which('npx') != None:
report('info', 'Found npm.')
return True
report('fatal', 'Node.js is not installed (or is not in your PATH).')
return False
@system_test()
def is_java_home_valid():
if not java_home:
report('fatal', 'JAVA_HOME is not defined. Set it in your environment.')
report('info',
'If needed, download and install JDK\n\n {jv}\n\nfrom\n\n {jdp}\n\nand make sure it is in your path, and that JAVA_HOME is set in environment variables.'.format(
jv=expected_java_version, jdp=jdk_download_path))
return False
report('info', 'JAVA_HOME is set to {jhp}'.format(
jhp=java_home))
if safe_exists(java_home):
report('info', 'JAVA_HOME points to an existing directory.')
return True
report('fatal', 'JAVA_HOME set, but does not point to an existing directory.')
return False
@system_test()
def is_java_in_path():
if shutil.which('java') != None:
report('info', 'java is in your path.')
return True
report('fatal', 'java is not in your path. Set it in your environment.')
report('info', 'If needed, download and install JDK\n\n {jv}\n\nfrom\n\n {jdp}\n\nand make sure it is in your path, and that JAVA_HOME is set.'.format(
jv=expected_java_version, jdp=jdk_download_path))
if not running_on_windows:
report('warn','on Mac, JAVA_HOME is not the location of the JDK, but the /Contents/Home directory under it.')
return False
@system_test({'prereqs':['is_java_in_path']})
def is_correct_version_of_java_installed():
# Run the "java -version" command and capture the output
java_version_output = subprocess.check_output(
["java", "-version"], stderr=subprocess.STDOUT, text=True)
# Check if the output contains "java version" followed by "20" (exact match)
match = re.search(r'"([\d.]+)"', java_version_output)
if not match:
return False
installed_version = match.group()
report('info', 'Detected version {iv} of Java.'.format(
iv=installed_version))
if expected_java_version in installed_version:
report('info', "Java version is correct.")
return True
report('error', 'Go download and install JDK {jv}, and make sure it is in your path.'.format(
jv=expected_java_version))
report('info', 'Download link: {jdk_download_path}'.format(
jdk_download_path=jdk_download_path))
return False
@system_test({'prereqs':['is_java_in_path','is_java_home_valid']})
def is_java_from_path_from_java_home():
# Java under the jdk dir
java_executable_location = shutil.which('java')
if java_executable_location.startswith(java_home):
report('info', 'java executable location matches up with JAVA_HOME.')
return True
report('fatal', 'java executable location does not match up with JAVA_HOME. Fix JAVA_HOME in your environment.')
return False
@system_test()
def is_android_sdk_installed():
if not android_sdk_root:
report('fatal', 'ANDROID_HOME and ANDROID_SDK_ROOT are not defined. Set at least one in your environment.')
report('info', "This may indicate you haven't downloaded the ANDROID SDK yet.")
report(
'info', 'Download the Android SDK from https://developer.android.com/studio')
return False
report('info', 'Environment var(s) point to an Android SDK location {asdk}.'.format(
asdk=android_sdk_root))
if safe_exists(android_sdk_root):
report('info', 'Android SDK appears to exist.')
return True
report('fatal', 'ANDROID_SDK_ROOT variable is set but directory does not exist. Set it CORRECTLY in your environment.')
return False
@system_test({'prereqs':['is_android_sdk_installed']})
def are_paths_valid():
existing_path = os.environ.get('PATH').split(path_variable_separator)
found_platform_tools = False
found_tools = False
path_is_good = True
for p in existing_path:
lcp = p.lower()
if paths_equal(p, os.path.join(android_sdk_root, 'platform-tools')):
found_platform_tools = True
elif paths_equal(p, os.path.join(android_sdk_root, 'tools')):
found_tools = True
if found_platform_tools and found_tools:
break
if not found_platform_tools:
report('fatal', 'Ensure that {android_sdk_root}{ps}platform-tools is at the top of your {emphasis}path.'.
format(android_sdk_root=android_sdk_root,
ps=path_separator,
emphasis='SYSTEM ' if running_on_windows else ''))
path_is_good = False
if not found_tools:
report('fatal', 'Ensure that {android_sdk_root}{ps}tools is at the top of your {emphasis}path.'.
format(android_sdk_root=android_sdk_root,
ps=path_separator,
emphasis='SYSTEM ' if running_on_windows else ''))
path_is_good = False
if path_is_good:
report('info', 'SDK and JDK paths appear to be good.')
return path_is_good
@system_test()
def is_homebrew_installed():
if running_on_windows:
report('info','(homebrew is not required on Windows)');
return True
if shutil.which('brew') != None:
report('info','brew exists.');
return True
report('fatal','Brew is necessary for Mac development but is not installed.')
report('info','Install it as shown at https://brew.sh/')
return False
##################################
@project_test()
def is_project_under_git():
if safe_exists('.git'):
report('info', 'Project is git-controlled.')
return True
if subprocess.run(
["git", "rev-parse"], stderr=subprocess.DEVNULL).returncode == 0:
report('info', 'Project is git-controlled.')
return True
report('fatal', 'This project is NOT under git management (!)')
report('howto', "$ git init\n$ git add .\n$ git commit -m\'Initial commit\'")
return False
@project_test({'prereqs':['is_npm_installed']})
def is_npm_project():
if safe_exists(package_json_path):
report('info', 'We are in an NPM project.')
return True
report('fatal', 'package.json does not exist. Run this from an initialized project directory.')
report('howto','''
* Open a terminal/cmd window in a directory where you keep all your projects.
$ npx react-native@latest init MyProject
* Open that folder in VS Code.
''')
return False
@project_test()
def is_project_path_too_long():
if running_on_windows and len(os.getcwd()) > max_windows_project_path_length:
report('fatal', 'Project path is too long. Move it to a shorter path.')
report('howto','''
* Move this directory to a shorter path, such as C:{ps}SOURCE
* Be sure to move rn-cli-fixup to the same directory.
'''.format(ps=cmd_argument_separator))
return False
return True
@project_test()
def is_react_native_project():
if safe_exists("android"):
report('info', 'We are really in a React-native project.')
return True
report('fatal', '"android" does not exist. This does not appear to be a React-Native project dir.')
return False
@project_test({'prereqs':['is_react_native_project']})
def is_react_native_cli_project():
with open(package_json_path, 'r') as package_json_file:
package_json_data = json.load(package_json_file)
dependencies = package_json_data.get("dependencies", {})
if dependencies.get("expo", None) == None:
report('info', 'Confirmed: this is a CLI project.')
return True
report('fatal', 'expo is a dependency. This appears to be an expo project, not a React-Native CLI project dir.')
return False
@project_test({'prereqs':['is_npm_project']})
def is_not_formerly_expo_project():
with open(package_json_path, 'r') as package_json_file:
package_json_data = json.load(package_json_file)
dependencies = package_json_data.get("dependencies", {})
if dependencies.get("expo-splash-screen", None) == None:
report('info', 'Confirmed: this is not an expo rebuild/exported project.')
return True
report('fatal', 'expo-splash-screen is a dependency. This appears to be an exported (prebuild) expo project, not a true CLI project.')
return False
@project_test()
def is_cocoapods_present():
if running_on_windows:
report('info','(Cocoapods is not required on Windows.)')
return True
if brew_recipe_installed('cocoapods'):
report('info', 'Found cocoapods.')
return True
report('fatal', 'cocoapods not found.')
report('howto', '$ brew install cocoapods')
return False
@system_test()
def is_xcode_selected():
if running_on_windows:
report('info','(xcode-select is not required on Windows.)')
return True
xcode_sel_output = subprocess.check_output(
["xcode-select", "--print-path"], stderr=subprocess.STDOUT, text=True)
if xcode_sel_output and '/' in xcode_sel_output:
report('info','Xcode has been selected.')
return True
report('fatal', 'It does not appear that Xcode is selected.')
report('howto','$ sudo xcode-select -s /Applications/Xcode.app')
return False
@system_test()
def is_watchman_present():
if running_on_windows:
report('info','(Watchman is not required on Windows.)')
return True
if shutil.which('watchman'):
report('info', 'Found watchman.')
return True
report('fatal', 'watchman command not found. Set it in your path).')
report('howto','$ brew install watchman')
return False
@system_test()
def is_ios_deploy_present():
if running_on_windows:
report('info','(ios-deploy is not required on Windows.)')
return True
if shutil.which('ios-deploy'):
report('info', 'Found ios-deploy.')
return True
report('fatal', 'ios-deploy command not found. Set it in your path).')
report('howto','$ brew install ios-deploy')
return False
@system_test()
def is_adb_present():
if shutil.which(adb_command):
report('info', 'Found adb.')
return True
report('fatal', 'adb command not found. Set it in your path (install platform-tools if needed).')
if not running_on_windows:
report('howto','$ brew install android-platform-tools')
return False
@system_test({'prereqs':['is_java_in_path']})
def is_keytool_present():
if shutil.which('keytool') != None:
report('info', 'keytool is in path.')
return True
report('fatal', 'keytool command not found. Set it in your path.')
report('info', 'This is usually in {jdk}{ps}bin'.format(
jdk=java_home, ps=path_separator))
return True