-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsync_resources.py
More file actions
executable file
·1418 lines (1161 loc) · 56 KB
/
Copy pathsync_resources.py
File metadata and controls
executable file
·1418 lines (1161 loc) · 56 KB
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
"""
Artsorakel Resource Sync Script
This script synchronizes shared resources between Android and iOS platforms
"""
import os
import sys
import subprocess
import json
import re
import csv
import shutil
import xml.etree.ElementTree as ET
import xml.sax.saxutils as saxutils
import html
from pathlib import Path
from typing import Dict, List, Tuple, Optional
# ANSI color codes
class Colors:
RED = '\033[0;31m'
GREEN = '\033[0;32m'
YELLOW = '\033[1;33m'
NC = '\033[0m' # No Color
# Paths
SCRIPT_DIR = Path(__file__).parent.resolve()
SHARED_DIR = SCRIPT_DIR / 'shared'
ANDROID_DIR = SCRIPT_DIR / 'Android'
IOS_DIR = SCRIPT_DIR / 'iOS'
def print_section(message: str):
print(f"{Colors.YELLOW}{message}{Colors.NC}")
def print_success(message: str):
# Success messages are suppressed to reduce verbosity
# Uncomment to see all operations:
# print(f" ✅ {message}")
pass
def print_error(message: str):
print(f" {Colors.RED}❌ {message}{Colors.NC}")
def print_warning(message: str):
print(f" {Colors.YELLOW}⚠️ {message}{Colors.NC}")
def print_info(message: str):
print(f" ℹ️ {message}")
def cleanup_build_artifacts():
"""Remove iOS build artifacts that should not be in source tree"""
print_section("🧹 Cleaning up build artifacts...")
ios_artsorakel_dir = IOS_DIR / 'Artsorakel' / 'Artsorakel'
# Remove .xctestproducts directories
for item in ios_artsorakel_dir.glob('*.xctestproducts'):
if item.is_dir():
shutil.rmtree(item, ignore_errors=True)
print_success(f"Removed {item.name}")
# Remove archive directories (timestamp directories)
for item in ios_artsorakel_dir.glob('Artsorakel 20*'):
if item.is_dir():
shutil.rmtree(item, ignore_errors=True)
print_success(f"Removed {item.name}")
def sync_config():
"""Sync configuration files and update version info"""
print_section("📋 Syncing configuration...")
config_file = SHARED_DIR / 'config' / 'app_config.json'
secrets_file = SHARED_DIR / 'config' / 'secrets.json'
# Check secrets file
if not secrets_file.exists():
print_warning("WARNING: secrets.json not found!")
print(f" {Colors.YELLOW} Please copy secrets.json.template to secrets.json and add your bearer token.{Colors.NC}")
print(f" {Colors.YELLOW} cp shared/config/secrets.json.template shared/config/secrets.json{Colors.NC}")
print(f" {Colors.YELLOW} Then edit shared/config/secrets.json and replace YOUR_BEARER_TOKEN_HERE{Colors.NC}")
else:
print_success("Secrets file found")
if not config_file.exists():
print_error(f"CRITICAL: Config file not found at {config_file}")
print_error(" Cannot proceed without app configuration")
sys.exit(1)
# Read config
with open(config_file, 'r') as f:
config = json.load(f)
version = config['version']
version_code = config['versionCode']
# Update Android build.gradle.kts (only version, URLs are read directly from config)
android_gradle = ANDROID_DIR / 'app' / 'build.gradle.kts'
if android_gradle.exists():
with open(android_gradle, 'r') as f:
content = f.read()
# Update version info (versionCode is calculated dynamically from epoch in build.gradle.kts)
content = re.sub(r'versionName = ".*?"', f'versionName = "{version}"', content)
with open(android_gradle, 'w') as f:
f.write(content)
print_success(f"Updated Android version to {version}")
# Update iOS version
ios_plist = IOS_DIR / 'Artsorakel' / 'Info.plist'
if ios_plist.exists():
# Try plistlib (available in Python 3)
try:
import plistlib
with open(ios_plist, 'rb') as f:
plist_data = plistlib.load(f)
plist_data['CFBundleShortVersionString'] = version
plist_data['CFBundleVersion'] = str(version_code)
# Always set encryption export compliance to false (app doesn't use encryption)
plist_data['ITSAppUsesNonExemptEncryption'] = False
with open(ios_plist, 'wb') as f:
plistlib.dump(plist_data, f)
print_success(f"Updated iOS version to {version} ({version_code})")
print_success("Set ITSAppUsesNonExemptEncryption to false")
except Exception as e:
print_error(f"CRITICAL: Could not update iOS plist: {e}")
sys.exit(1)
else:
print_info("iOS uses modern project configuration (no Info.plist) - version managed in Xcode")
# Update iOS ShareExtension version to match main app
share_ext_plist = IOS_DIR / 'Artsorakel' / 'ShareExtension' / 'Info.plist'
if share_ext_plist.exists():
try:
import plistlib
with open(share_ext_plist, 'rb') as f:
plist_data = plistlib.load(f)
plist_data['CFBundleShortVersionString'] = version
plist_data['CFBundleVersion'] = str(version_code)
with open(share_ext_plist, 'wb') as f:
plistlib.dump(plist_data, f)
print_success(f"Updated ShareExtension version to {version} ({version_code})")
except Exception as e:
print_error(f"CRITICAL: Could not update ShareExtension plist: {e}")
sys.exit(1)
# Update Xcode project MARKETING_VERSION to match (Xcode overrides Info.plist with this)
ios_project = IOS_DIR / 'Artsorakel' / 'Artsorakel.xcodeproj' / 'project.pbxproj'
if ios_project.exists():
try:
with open(ios_project, 'r') as f:
project_content = f.read()
# Replace all MARKETING_VERSION entries
project_content = re.sub(
r'MARKETING_VERSION = [^;]+;',
f'MARKETING_VERSION = {version};',
project_content
)
with open(ios_project, 'w') as f:
f.write(project_content)
print_success(f"Updated Xcode MARKETING_VERSION to {version}")
except Exception as e:
print_error(f"CRITICAL: Could not update Xcode project version: {e}")
sys.exit(1)
# Copy config files to iOS Config directory
ios_config_dir = IOS_DIR / 'Artsorakel' / 'Artsorakel' / 'Config'
ios_config_dir.mkdir(parents=True, exist_ok=True)
# Copy app_config.json
ios_config_file = ios_config_dir / 'app_config.json'
shutil.copy2(config_file, ios_config_file)
print_success(f"Copied app_config.json to iOS")
# Copy secrets.json if it exists
if secrets_file.exists():
ios_secrets_file = ios_config_dir / 'secrets.json'
shutil.copy2(secrets_file, ios_secrets_file)
print_success(f"Copied secrets.json to iOS")
else:
print_warning("Skipped copying secrets.json (file not found)")
def sync_strings():
"""Sync localization strings from shared CSV to platform-specific formats"""
print_section("🌐 Syncing localization strings from shared CSV...")
csv_file = SHARED_DIR / 'strings.csv'
if not csv_file.exists():
print_error(f"CRITICAL: CSV file not found at {csv_file}")
print_error(" Cannot proceed without localization strings")
sys.exit(1)
# Read CSV
with open(csv_file, 'r', encoding='utf-8') as f:
reader = csv.DictReader(f)
rows = list(reader)
if not rows:
print_error("CRITICAL: No data in CSV file")
print_error(" Cannot proceed with empty localization strings")
sys.exit(1)
# Get language codes
languages = [col for col in reader.fieldnames if col != 'key']
# Process each language
for lang in languages:
# Android language mapping
android_lang_map = {
'en': 'values',
'nb': 'values-nb',
'nn': 'values-nn',
'nl': 'values-nl',
'es': 'values-es',
'sv': 'values-sv'
}
android_lang = android_lang_map.get(lang, f'values-{lang}')
# Generate Android strings.xml
android_strings_dir = ANDROID_DIR / 'app' / 'src' / 'main' / 'res' / android_lang
android_strings_dir.mkdir(parents=True, exist_ok=True)
with open(android_strings_dir / 'strings.xml', 'w', encoding='utf-8') as f:
f.write('<?xml version="1.0" encoding="utf-8"?>\n')
f.write('<resources>\n')
f.write(' <!-- Auto-generated from shared CSV. Do not edit directly. -->\n')
f.write(' <string name="app_name" translatable="false">Artsorakel</string>\n')
for row in rows:
key = row['key']
value = row[lang]
if value:
escaped_value = saxutils.escape(value)
escaped_value = escaped_value.replace("'", "\\'")
escaped_value = escaped_value.replace("'", "\\'")
f.write(f' <string name="{key}">{escaped_value}</string>\n')
f.write('</resources>\n')
print_success(f"Generated Android strings for {lang}")
# Generate iOS Localizable.strings in app target directory
ios_strings_dir = IOS_DIR / 'Artsorakel' / 'Artsorakel' / f'{lang}.lproj'
ios_strings_dir.mkdir(parents=True, exist_ok=True)
with open(ios_strings_dir / 'Localizable.strings', 'w', encoding='utf-8') as f:
f.write('/* Auto-generated from shared CSV. Do not edit directly. */\n')
for row in rows:
key = row['key']
value = row[lang]
if value:
escaped_value = value.replace('"', '\\"').replace('\n', '\\n')
f.write(f'"{key}" = "{escaped_value}";\n')
print_success(f"Generated iOS strings for {lang}")
print(f"\n{Colors.GREEN}✅ Successfully processed {len(languages)} languages from CSV{Colors.NC}")
return True
def sync_images():
"""Sync images to both platforms"""
print_section("🖼️ Syncing images...")
# Ensure Android assets directory exists
android_assets = ANDROID_DIR / 'app' / 'src' / 'main' / 'assets'
android_assets.mkdir(parents=True, exist_ok=True)
# Copy SVG logos to Android assets (exclude .inkscape.svg source files)
images_dir = SHARED_DIR / 'images'
if images_dir.exists():
for svg in images_dir.glob('*.svg'):
if not svg.name.endswith('.inkscape.svg'):
shutil.copy(svg, android_assets)
print_success(f"Copied {svg.name} to Android assets")
# For iOS, copy to Resources/Images directory
ios_images = IOS_DIR / 'Artsorakel' / 'Artsorakel' / 'Resources' / 'Images'
ios_images.mkdir(parents=True, exist_ok=True)
shutil.copy(svg, ios_images)
print_success(f"Copied {svg.name} to iOS Resources/Images")
# Copy vector SVGs from shared/vectors to iOS
vectors_dir = SHARED_DIR / 'vectors'
if vectors_dir.exists():
ios_vectors = IOS_DIR / 'Artsorakel' / 'Artsorakel' / 'Resources' / 'Vectors'
ios_vectors.mkdir(parents=True, exist_ok=True)
for svg in vectors_dir.glob('*.svg'):
if not svg.name.endswith('.inkscape.svg'):
shutil.copy(svg, ios_vectors)
print_success(f"Copied vector {svg.name} to iOS Resources/Vectors")
# Copy PDF files as iOS image assets (for inline use with Text)
assets_dir = IOS_DIR / 'Artsorakel' / 'Artsorakel' / 'Assets.xcassets'
assets_dir.mkdir(parents=True, exist_ok=True)
for pdf in vectors_dir.glob('*.pdf'):
# Create imageset directory
imageset_name = pdf.stem # e.g., "ic_external_link"
imageset_dir = assets_dir / f'{imageset_name}.imageset'
imageset_dir.mkdir(parents=True, exist_ok=True)
# Copy the PDF file
shutil.copy(pdf, imageset_dir / pdf.name)
# Create Contents.json with template rendering and preserve vector data
contents = {
"images": [
{
"filename": pdf.name,
"idiom": "universal"
}
],
"info": {
"author": "xcode",
"version": 1
},
"properties": {
"preserves-vector-representation": True,
"template-rendering-intent": "template"
}
}
contents_file = imageset_dir / 'Contents.json'
contents_file.write_text(json.dumps(contents, indent=2))
print_success(f"Created iOS image asset {imageset_name} from PDF")
def check_svg_for_transforms(svg_file: Path) -> bool:
"""Check if SVG contains transform attributes"""
with open(svg_file, 'r') as f:
content = f.read()
if 'transform=' in content:
print_error(f"ERROR: SVG file '{svg_file.name}' contains transform attributes!")
print(f"{Colors.YELLOW} Transform attributes found:{Colors.NC}")
# Show some examples
for i, line in enumerate(content.split('\n')):
if 'transform=' in line and i < 5:
print(f" {line.strip()}")
print(f"\n{Colors.YELLOW} The SVG file must be flattened before it can be converted to Android VectorDrawable.{Colors.NC}")
print(f"{Colors.YELLOW} Please use Inkscape to:{Colors.NC}")
print(f"{Colors.YELLOW} 1. Open the file in Inkscape{Colors.NC}")
print(f"{Colors.YELLOW} 2. Select all (Ctrl+A){Colors.NC}")
print(f"{Colors.YELLOW} 3. Ungroup multiple times until nothing is grouped{Colors.NC}")
print(f"{Colors.YELLOW} 4. Path → Object to Path{Colors.NC}")
print(f"{Colors.YELLOW} 5. Path → Stroke to Path{Colors.NC}")
print(f"{Colors.YELLOW} 6. Save as Optimized SVG with 10 decimal places{Colors.NC}\n")
return False
return True
def run_vdtool(input_file: Path, output_dir: Path) -> Optional[Path]:
"""Run vd-tool to convert SVG to Android VectorDrawable XML"""
try:
# Set up environment with JAVA_HOME for macOS
env = os.environ.copy()
if shutil.which('brew'):
java_home = subprocess.run(['brew', '--prefix', 'openjdk'], capture_output=True, text=True)
if java_home.returncode == 0:
env['JAVA_HOME'] = java_home.stdout.strip()
env['PATH'] = f"{java_home.stdout.strip()}/bin:{env.get('PATH', '')}"
result = subprocess.run(
['vd-tool', '-c', '-in', str(input_file), '-out', str(output_dir)],
check=True,
capture_output=True,
text=True,
env=env
)
# vd-tool creates file with same base name but .xml extension
expected_outputs = [
output_dir / f"{input_file.stem}.xml",
output_dir / f"{input_file.stem}.optimized.xml"
]
for output in expected_outputs:
if output.exists():
return output
return None
except subprocess.CalledProcessError as e:
# Check if it's a Java-related error
if 'Java' in e.stderr or 'java' in e.stderr:
return 'java_missing'
return None
except FileNotFoundError:
return None
def sync_vectors():
"""Sync vector assets (SVG → Android VectorDrawable XML)"""
print_section("🎨 Syncing vector assets (SVG → Android VectorDrawable XML)...")
drawable_dir = ANDROID_DIR / 'app' / 'src' / 'main' / 'res' / 'drawable'
drawable_night_dir = ANDROID_DIR / 'app' / 'src' / 'main' / 'res' / 'drawable-night'
drawable_dir.mkdir(parents=True, exist_ok=True)
drawable_night_dir.mkdir(parents=True, exist_ok=True)
# Check if vd-tool is available
vdtool_available = shutil.which('vd-tool') is not None
# Generate launcher icon background
print(" 🚀 Generating launcher icon drawables...")
launcher_bg = drawable_dir / 'ic_launcher_background.xml'
launcher_bg.write_text('''<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<path
android:fillColor="#495e2e"
android:pathData="M0,0h108v108h-108z" />
</vector>
''')
print_success("Generated ic_launcher_background.xml")
# Generate launcher foreground from logo
logo_svg = SHARED_DIR / 'images' / 'artsorakel_owl_optimized.svg'
if not logo_svg.exists():
print_error(f"ERROR: Logo SVG not found at {logo_svg}")
print_error(" Cannot generate launcher foreground without logo SVG")
sys.exit(1)
if not vdtool_available:
print_error("CRITICAL: vd-tool not found - cannot generate Android launcher icons")
print(f" {Colors.YELLOW} Install with: npm install -g vd-tool{Colors.NC}")
sys.exit(1)
result = run_vdtool(logo_svg, drawable_dir)
if result == 'java_missing':
print_error("CRITICAL: vd-tool requires Java - cannot generate Android launcher icons")
print(f" {Colors.YELLOW} Install Java from: https://www.java.com{Colors.NC}")
sys.exit(1)
elif not result:
print_error("CRITICAL: vd-tool conversion failed for launcher foreground")
print_error(f" Unable to convert {logo_svg}")
print_error(f" This is likely due to:")
print_error(f" - Spaces or special characters in filename")
print_error(f" - Invalid SVG structure")
print_error(f" - Transform attributes in SVG (run check_svg_for_transforms)")
sys.exit(1)
# Rename to launcher foreground
launcher_fg = drawable_dir / 'ic_launcher_foreground.xml'
result.rename(launcher_fg)
# Adjust the vector drawable to work as adaptive icon foreground
with open(launcher_fg, 'r') as f:
content = f.read()
# Set physical dimensions to 108dp but keep original viewport for proper scaling
content = re.sub(r'android:width="[^"]*"', 'android:width="108dp"', content)
content = re.sub(r'android:height="[^"]*"', 'android:height="108dp"', content)
with open(launcher_fg, 'w') as f:
f.write(content)
print_success("Generated ic_launcher_foreground.xml from logo")
# Process light/dark SVG pairs
converted_any = False
conversion_failed = False
images_dir = SHARED_DIR / 'images'
if images_dir.exists():
for light_svg in list(images_dir.glob('*_light.svg')) + list(images_dir.glob('*_light.optimized.svg')):
# Extract base name
if light_svg.name.endswith('_light.optimized.svg'):
base_name = light_svg.name[:-len('_light.optimized.svg')]
is_optimized = True
else:
base_name = light_svg.name[:-len('_light.svg')]
is_optimized = False
# Convert to Android resource name
base_name_lower = base_name.lower().replace('-', '_')
android_name = base_name_lower if base_name_lower.startswith('ic_') else f'ic_{base_name_lower}'
# Check and convert light version
if not check_svg_for_transforms(light_svg):
print_error(f" ⛔ Aborting conversion of {light_svg.name}")
conversion_failed = True
continue
light_output = drawable_dir / f'{android_name}.xml'
result = run_vdtool(light_svg, drawable_dir)
if result:
if result != light_output:
result.rename(light_output)
converted_any = True
print_success(f"Generated {light_output.name}")
# Look for dark version
dark_svg_candidates = [
images_dir / f'{base_name}_dark.optimized.svg',
images_dir / f'{base_name}_dark.svg'
]
dark_svg = None
for candidate in dark_svg_candidates:
if candidate.exists():
dark_svg = candidate
break
if dark_svg:
if not check_svg_for_transforms(dark_svg):
print_error(f" ⛔ Aborting conversion of {dark_svg.name}")
conversion_failed = True
continue
dark_output = drawable_night_dir / f'{android_name}.xml'
result = run_vdtool(dark_svg, drawable_night_dir)
if result:
if result != dark_output:
result.rename(dark_output)
print_success(f"Generated light/dark pair for {android_name}")
else:
conversion_failed = True
else:
print_error(f"CRITICAL: No dark variant found for {base_name}")
print_error(" Every light SVG must have a matching dark variant")
sys.exit(1)
else:
conversion_failed = True
if conversion_failed:
print_error("CRITICAL: Some conversions failed due to transform attributes")
print_error(" Please fix the SVG files and remove transform attributes")
print_error(" See error messages above for specific files")
sys.exit(1)
# Note: It's OK if there are no light/dark SVG pairs - they're optional
# Process other vector files
vectors_dir = SHARED_DIR / 'vectors'
if vectors_dir.exists():
for svg in vectors_dir.glob('*.svg'):
# Replace Norwegian characters for Android drawable names
name = svg.stem
name = name.replace('æ', 'ae').replace('ø', 'oe').replace('å', 'aa')
name = name.replace('Æ', 'Ae').replace('Ø', 'Oe').replace('Å', 'Aa')
out = drawable_dir / f'{name}.xml'
if not check_svg_for_transforms(svg):
print_error(f" ⛔ Skipping conversion of {svg.name}")
continue
if vdtool_available:
result = run_vdtool(svg, drawable_dir)
if result and result != out:
result.rename(out)
if out.exists():
print_success(f"Generated {out.name}")
else:
print_error(f"CRITICAL: Failed to convert {svg.name}")
sys.exit(1)
else:
print_error("CRITICAL: vd-tool not found")
print_error(" Install with: npm install -g vd-tool")
sys.exit(1)
return True
def download_fonts():
"""Download fonts from Fontsource CDN if missing or older than a week"""
print_section("📥 Checking/downloading fonts...")
fonts_dir = SHARED_DIR / 'fonts'
fonts_dir.mkdir(parents=True, exist_ok=True)
# Font mappings: local filename -> (weight, style)
font_mappings = {
'chivo_regular.ttf': ('400', 'normal'),
'chivo_italic.ttf': ('400', 'italic'),
'chivo_bold.ttf': ('700', 'normal'),
'chivo_bolditalic.ttf': ('700', 'italic'),
}
base_url = 'https://cdn.jsdelivr.net/fontsource/fonts/chivo@latest'
one_week_seconds = 7 * 24 * 60 * 60
import time
for local_name, (weight, style) in font_mappings.items():
local_path = fonts_dir / local_name
needs_download = False
if not local_path.exists():
needs_download = True
reason = "missing"
else:
file_age = time.time() - local_path.stat().st_mtime
if file_age > one_week_seconds:
needs_download = True
reason = "older than a week"
if not needs_download:
continue
url = f"{base_url}/latin-{weight}-{style}.ttf"
print_info(f"Downloading {local_name} ({reason})...")
try:
import urllib.request
urllib.request.urlretrieve(url, local_path)
print_success(f"Downloaded {local_name}")
except Exception as e:
print_error(f"Failed to download {local_name}: {e}")
print_error(f" URL: {url}")
sys.exit(1)
def sync_fonts():
"""Sync fonts to both platforms"""
print_section("🔤 Syncing fonts...")
# First ensure fonts are downloaded
download_fonts()
fonts_dir = SHARED_DIR / 'fonts'
# Copy to Android
android_fonts = ANDROID_DIR / 'app' / 'src' / 'main' / 'res' / 'font'
android_fonts.mkdir(parents=True, exist_ok=True)
for font in fonts_dir.glob('*.ttf'):
shutil.copy(font, android_fonts)
print_success(f"Copied {font.name} to Android fonts")
# Copy to iOS
ios_fonts = IOS_DIR / 'Artsorakel' / 'Artsorakel' / 'Resources' / 'Fonts'
ios_fonts.mkdir(parents=True, exist_ok=True)
for font in fonts_dir.glob('*.ttf'):
shutil.copy(font, ios_fonts)
print_success(f"Copied {font.name} to iOS Resources/Fonts")
def sync_content():
"""Sync HTML content and FAQ JSON files"""
print_section("📄 Syncing HTML content...")
content_dir = SHARED_DIR / 'content'
if not content_dir.exists():
return
# Ensure Android assets directory exists
android_assets = ANDROID_DIR / 'app' / 'src' / 'main' / 'assets'
android_assets.mkdir(parents=True, exist_ok=True)
# Copy all content files (HTML, JSON, SVG) to Android assets
for content_file in content_dir.glob('*'):
if content_file.is_file() and content_file.suffix in ['.html', '.json', '.svg']:
shutil.copy(content_file, android_assets)
print_success(f"Copied {content_file.name} to Android assets")
# Copy all content files (HTML, JSON, SVG) to iOS resources
ios_content = IOS_DIR / 'Artsorakel' / 'Artsorakel' / 'Resources' / 'Content'
ios_content.mkdir(parents=True, exist_ok=True)
for content_file in content_dir.glob('*'):
if content_file.is_file() and content_file.suffix in ['.html', '.json', '.svg']:
shutil.copy(content_file, ios_content)
print_success(f"Copied {content_file.name} to iOS resources")
def sync_design_system():
"""Sync design system colors and themes"""
print_section("🎨 Syncing design system colors and themes...")
design_dir = SHARED_DIR / 'designsystem'
if not design_dir.exists():
print_error("CRITICAL: Design system directory not found")
print_error(f" Expected at: {design_dir}")
sys.exit(1)
# Process Variables primitives.txt to generate colors.xml
vars_file = design_dir / 'Variables primitives.txt'
if vars_file.exists():
content = vars_file.read_text()
# Extract color variables
color_map = {}
pattern = r'--([a-z-]+(?:-\d+|-base-positive|-base-negative|-base)?)\s*:\s*(#[A-F0-9]{6})'
matches = re.findall(pattern, content, re.IGNORECASE)
for name, value in matches:
# Convert CSS var name to Android resource name
android_name = name.replace('-', '_')
color_map[android_name] = value.upper()
# Read Variables listcategories.txt if it exists
listcat_file = design_dir / 'Variables listcategories.txt'
listcat_colors = {}
if listcat_file.exists():
listcat_content = listcat_file.read_text()
# Extract invasive, redlist, and gauge colors
listcat_pattern = r'--((?:invasive|redlist|gauge)-[a-z0-9]+)\s*:\s*(#[A-F0-9]{6})'
listcat_matches = re.findall(listcat_pattern, listcat_content, re.IGNORECASE)
for name, value in listcat_matches:
# Convert CSS var name to Android resource name
android_name = name.replace('-', '_')
color_map[android_name] = value.upper()
listcat_colors[android_name] = value.upper()
print_success(f"Found {len(listcat_matches)} list category colors")
# Generate iOS color assets for list category colors
assets_dir = IOS_DIR / 'Artsorakel' / 'Artsorakel' / 'Assets.xcassets'
assets_dir.mkdir(parents=True, exist_ok=True)
for color_name, hex_value in listcat_colors.items():
# Convert to iOS asset name (e.g., invasive_se -> Color_invasiveSe)
parts = color_name.split('_')
camel_case = parts[0] + ''.join(word.capitalize() for word in parts[1:])
ios_name = f'Color_{camel_case}'
colorset_dir = assets_dir / f'{ios_name}.colorset'
colorset_dir.mkdir(parents=True, exist_ok=True)
# Convert hex to RGB
hex_color = hex_value.lstrip('#')
r = int(hex_color[0:2], 16) / 255.0
g = int(hex_color[2:4], 16) / 255.0
b = int(hex_color[4:6], 16) / 255.0
# Same color for light and dark mode
contents = {
"colors": [
{
"color": {
"color-space": "srgb",
"components": {
"alpha": "1.000",
"blue": f"{b:.3f}",
"green": f"{g:.3f}",
"red": f"{r:.3f}"
}
},
"idiom": "universal"
}
],
"info": {
"author": "xcode",
"version": 1
}
}
contents_file = colorset_dir / 'Contents.json'
contents_file.write_text(json.dumps(contents, indent=2))
print_success(f"Generated {len(listcat_colors)} iOS color assets for list categories")
# Read existing colors.xml from designsystem
existing_colors = {}
colors_file = design_dir / 'colors.xml'
if colors_file.exists():
colors_content = colors_file.read_text()
# Extract existing colors
color_pattern = r'<color name="([^"]+)">([^<]+)</color>'
for match in re.findall(color_pattern, colors_content):
existing_colors[match[0]] = match[1]
# Read functional colors
func_colors_file = design_dir / 'functional_colors.xml'
if func_colors_file.exists():
func_content = func_colors_file.read_text()
# Extract functional colors
color_pattern = r'<color name="([^"]+)">([^<]+)</color>'
for match in re.findall(color_pattern, func_content):
existing_colors[match[0]] = match[1]
# Merge new primitive colors with existing
all_colors = {**color_map, **existing_colors}
# Generate colors.xml
colors_xml = '<?xml version="1.0" encoding="utf-8"?>\n<resources>\n'
# Add primitive colors from Variables
colors_xml += ' <!-- Primitive colors from design system -->\n'
for name, value in sorted(color_map.items()):
colors_xml += f' <color name="{name}">{value}</color>\n'
colors_xml += '\n <!-- Existing colors -->\n'
# Add remaining colors from the existing file (avoiding duplicates)
for name, value in sorted(existing_colors.items()):
if name not in color_map:
colors_xml += f' <color name="{name}">{value}</color>\n'
colors_xml += '</resources>\n'
# Write to Android colors.xml
android_colors_dir = ANDROID_DIR / 'app' / 'src' / 'main' / 'res' / 'values'
android_colors_dir.mkdir(parents=True, exist_ok=True)
android_colors_file = android_colors_dir / 'colors.xml'
android_colors_file.write_text(colors_xml)
print_success(f"Generated colors.xml with {len(all_colors)} colors")
# Process Semantic tokens.txt to add semantic color references and generate themes
semantic_file = design_dir / 'Semantic tokens.txt'
if semantic_file.exists() and vars_file.exists():
# First, read all primitive colors from Variables primitives.txt
primitives = {}
content = vars_file.read_text()
pattern = r'--([a-z-]+(?:-\d+|-base-positive|-base-negative|-base)?)\s*:\s*(#[A-F0-9]{6})'
for match in re.findall(pattern, content, re.IGNORECASE):
name = match[0].replace('-', '_')
primitives[name] = match[1].upper()
# Read the Semantic tokens file
content = semantic_file.read_text()
# Extract semantic tokens for light and dark modes
light_tokens = {}
dark_tokens = {}
# Parse light mode tokens
light_section = re.search(r':root\s*{([^}]+)}', content, re.DOTALL)
if light_section:
# Match both var() references and direct primitives - include numbers in pattern
token_pattern = r'--([a-z0-9-]+)\s*:\s*(?:var\(--([a-z0-9-]+)\)|([^;]+))'
for match in re.findall(token_pattern, light_section.group(1)):
token_name = match[0].replace('-', '_')
if match[1]: # var() reference
ref_name = match[1].replace('-', '_')
light_tokens[token_name] = ref_name
elif match[2]: # direct value
light_tokens[token_name] = match[2].strip()
# Parse dark mode tokens
dark_section = re.search(r'\[data-theme="dark"\]\s*{([^}]+)}', content, re.DOTALL)
if dark_section:
token_pattern = r'--([a-z0-9-]+)\s*:\s*(?:var\(--([a-z0-9-]+)\)|([^;]+))'
for match in re.findall(token_pattern, dark_section.group(1)):
token_name = match[0].replace('-', '_')
if match[1]: # var() reference
ref_name = match[1].replace('-', '_')
dark_tokens[token_name] = ref_name
elif match[2]: # direct value
dark_tokens[token_name] = match[2].strip()
# Create attrs.xml with all semantic attributes
attrs_xml = '<?xml version="1.0" encoding="utf-8"?>\n<resources>\n'
attrs_xml += ' <!-- Semantic design tokens -->\n'
# Get all unique token names
all_token_names = set(list(light_tokens.keys()) + list(dark_tokens.keys()))
for token in sorted(all_token_names):
attrs_xml += f' <attr name="{token}" format="color|reference" />\n'
# Add existing RSS attributes
attrs_xml += '\n <!-- RSS Category attributes -->\n'
rss_attrs = [
'rssDangerBackground', 'rssDangerBorder', 'rssDangerText',
'rssWarningBackground', 'rssWarningBorder', 'rssWarningText',
'rssInfoBackground', 'rssInfoBorder', 'rssInfoText'
]
for attr in rss_attrs:
attrs_xml += f' <attr name="{attr}" format="color|reference" />\n'
# Add app-specific attributes from app_attrs.xml if it exists
app_attrs_file = design_dir / 'app_attrs.xml'
if app_attrs_file.exists():
import xml.etree.ElementTree as ET
tree = ET.parse(app_attrs_file)
root = tree.getroot()
for attr in root.findall('.//attr'):
attr_name = attr.get('name')
attr_format = attr.get('format', 'color|reference')
if attr_name not in all_token_names and attr_name not in rss_attrs:
attrs_xml += f' <attr name="{attr_name}" format="{attr_format}" />\n'
attrs_xml += '</resources>\n'
# Write attrs.xml
attrs_file = ANDROID_DIR / 'app' / 'src' / 'main' / 'res' / 'values' / 'attrs.xml'
attrs_file.write_text(attrs_xml)
print_success("Generated attrs.xml with semantic attributes")
# Helper function to resolve color references
def resolve_color_reference(token_value, primitives, light_tokens, dark_tokens):
"""Resolve a color reference to an actual color resource"""
# Skip numeric values - they can't be color resources
try:
float(token_value)
return None
except (ValueError, TypeError):
pass
# If it references another token, resolve that first
if token_value in light_tokens or token_value in dark_tokens:
# This is a reference to another semantic token, use attr reference
return f"?attr/{token_value}"
# If it's a primitive color
if token_value in primitives:
return f"@color/{token_value}"
# If it's a direct color value
if token_value.startswith('#'):
return token_value
else:
# Default to trying as a color reference
return f"@color/{token_value}"
# Read the shared theme file
shared_theme_file = design_dir / 'themes_shared.xml'
# Generate light theme
if shared_theme_file.exists():
import xml.etree.ElementTree as ET
tree = ET.parse(shared_theme_file)
root = tree.getroot()
# Find the Theme.Artsorakel style element
for style in root.findall('.//style[@name="Theme.Artsorakel"]'):
# Add semantic token mappings for light mode
for token_name, ref_value in light_tokens.items():
# Check if item already exists
existing = False
for item in style.findall('item'):
if item.get('name') == token_name:
existing = True
break
if not existing:
# Add the new item if it has a valid color reference
resolved = resolve_color_reference(ref_value, primitives, light_tokens, dark_tokens)
if resolved:
new_item = ET.SubElement(style, 'item')
new_item.set('name', token_name)
new_item.text = resolved
# Write the light theme with proper formatting
ET.indent(tree, space=" ", level=0)
themes_file = ANDROID_DIR / 'app' / 'src' / 'main' / 'res' / 'values' / 'themes.xml'
tree.write(themes_file, encoding='utf-8', xml_declaration=True)
print_success("Generated light theme with semantic tokens")
# Generate dark theme from the same shared base
dark_tree = ET.parse(shared_theme_file)
dark_root = dark_tree.getroot()
# Find the Theme.Artsorakel style element
for style in dark_root.findall('.//style[@name="Theme.Artsorakel"]'):
# Replace/add semantic token mappings for dark mode
for token_name, ref_value in dark_tokens.items():
# Check if item already exists
existing = False
for item in style.findall('item'):
if item.get('name') == token_name:
# Update existing item
resolved = resolve_color_reference(ref_value, primitives, light_tokens, dark_tokens)
if resolved:
item.text = resolved
existing = True
break
if not existing:
# Add the new item if it has a valid color reference