FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
pythonnative/src/pythonnative/project/builder.py at main · pythonnative/pythonnative · GitHub
pythonnative
/
pythonnative
Public
Notifications
You must be signed in to change notification settings
Fork
23
Star
131
Code
Issues
11
Pull requests
4
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
pythonnative
/
src
/
pythonnative
/
project
/
builder.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
851 lines (721 loc) · 32.5 KB
Breadcrumbs
pythonnative
/
src
/
pythonnative
/
project
/
builder.py
Copy path
File metadata and controls
851 lines (721 loc) · 32.5 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
"""Build orchestration for PythonNative projects.
The [`Builder`][pythonnative.project.builder.Builder] ties the pieces
together: it stages the bundled native template, runs the platform
[`configurators`][pythonnative.project.android], stages the Python
sources and (on iOS) the embedded CPython runtime into the native
project, and invokes the native toolchains (Gradle / Xcode).
On iOS, the staged project is self-contained: ``Python.xcframework`` is
linked at build time and an Xcode build phase installs the standard
library and app code into the bundle, so ``xcodebuild`` output is
directly runnable and archivable with no post-build patching.
Third-party packages are resolved per destination (see
[`deps`][pythonnative.project.deps]) into ``app_packages.iphoneos`` and
``app_packages.iphonesimulator``; the build phase installs the slice
matching the SDK being built.
All shell-outs go through a small
[`CommandRunner`][pythonnative.project.builder.CommandRunner] abstraction
so the orchestration logic can be unit tested with a recording fake
instead of a real device toolchain. The default
[`SubprocessRunner`][pythonnative.project.builder.SubprocessRunner] simply
delegates to :mod:`subprocess`.
Device interaction that genuinely needs a device (booting simulators,
installing, launching, streaming logs, hot reload) lives in the CLI; the
builder stops at producing installable/archivable artifacts.
"""
from
__future__
import
annotations
import
compileall
import
json
import
os
import
platform
as
platform_module
import
re
import
shutil
import
subprocess
import
sys
from
dataclasses
import
dataclass
,
field
from
importlib
import
resources
from
pathlib
import
Path
from
typing
import
Callable
,
List
,
Optional
,
Sequence
,
Union
from
..
import
assets
from
.
import
android
as
android_config
from
.
import
artifacts
,
deps
,
runtime_assets
from
.
import
ios
as
ios_config
from
.
import
plugins
as
native_plugins
from
.
android
import
AndroidLayout
from
.
bundle
import
copy_library
from
.
config
import
AppConfig
from
.
ios
import
IOSLayout
Logger
=
Callable
[[
str
],
None
]
class
BuildError
(
Exception
):
"""Raised when a native build step fails.
Carries a user-facing message; the CLI prints it and exits non-zero.
"""
# ======================================================================
# Command runner abstraction
# ======================================================================
@
dataclass
class
CommandResult
:
"""The outcome of a single command invocation.
Attributes:
returncode: Process exit status.
stdout: Captured standard output (empty unless captured).
stderr: Captured standard error (empty unless captured).
"""
returncode
:
int
stdout
:
str
=
""
stderr
:
str
=
""
@
property
def
ok
(
self
)
->
bool
:
"""Whether the command exited successfully (return code 0)."""
return
self
.
returncode
==
0
class
CommandRunner
:
"""Protocol for running external commands.
Implementations execute a command and return a
[`CommandResult`][pythonnative.project.builder.CommandResult]. Tests
provide a recording fake; production uses
[`SubprocessRunner`][pythonnative.project.builder.SubprocessRunner].
"""
def
run
(
self
,
args
:
Sequence
[
str
],
*
,
cwd
:
Optional
[
Path
]
=
None
,
env
:
Optional
[
dict
]
=
None
,
capture
:
bool
=
False
,
)
->
CommandResult
:
"""Run a command.
Args:
args: The command and its arguments.
cwd: Working directory, or ``None`` for the current one.
env: Full environment mapping, or ``None`` to inherit.
capture: Whether to capture and return stdout/stderr.
Returns:
A [`CommandResult`][pythonnative.project.builder.CommandResult].
"""
raise
NotImplementedError
class
SubprocessRunner
(
CommandRunner
):
"""A [`CommandRunner`][pythonnative.project.builder.CommandRunner] backed by :mod:`subprocess`."""
def
run
(
self
,
args
:
Sequence
[
str
],
*
,
cwd
:
Optional
[
Path
]
=
None
,
env
:
Optional
[
dict
]
=
None
,
capture
:
bool
=
False
,
)
->
CommandResult
:
"""Execute ``args`` with :func:`subprocess.run`."""
completed
=
subprocess
.
run
(
list
(
args
),
cwd
=
str
(
cwd
)
if
cwd
else
None
,
env
=
env
,
capture_output
=
capture
,
text
=
True
,
)
return
CommandResult
(
returncode
=
completed
.
returncode
,
stdout
=
completed
.
stdout
or
""
if
capture
else
""
,
stderr
=
completed
.
stderr
or
""
if
capture
else
""
,
)
# ======================================================================
# Result/state dataclasses
# ======================================================================
@
dataclass
class
PreparedProject
:
"""A staged, configured project ready to build.
Attributes:
platform: ``"android"`` or ``"ios"``.
build_dir: The ``build/<platform>`` directory.
project_dir: The staged native project directory.
app_id: The resolved application id / bundle id for the platform.
android: Android layout (when ``platform == "android"``).
ios: iOS layout (when ``platform == "ios"``).
"""
platform
:
str
build_dir
:
Path
project_dir
:
Path
app_id
:
str
android
:
Optional
[
AndroidLayout
]
=
None
ios
:
Optional
[
IOSLayout
]
=
None
@
dataclass
class
BuildArtifacts
:
"""Paths to artifacts produced by a release/standalone build.
Attributes:
paths: Output artifact paths (APK/AAB/IPA/.app).
"""
paths
:
List
[
Path
]
=
field
(
default_factory
=
list
)
# ======================================================================
# Template staging
# ======================================================================
_TEMPLATE_NAMES
=
{
"android"
:
"android_template"
,
"ios"
:
"ios_template"
}
# A source checkout accumulates Gradle, SwiftPM, and Xcode outputs next to
# the native library sources; a staged project must start from a clean tree.
_TEMPLATE_IGNORE
=
shutil
.
ignore_patterns
(
"build"
,
".build"
,
".gradle"
,
".cxx"
,
".kotlin"
,
".swiftpm"
,
"xcuserdata"
,
"DerivedData"
,
"__pycache__"
,
"*.pyc"
,
".DS_Store"
,
)
def
template_name
(
platform
:
str
)
->
str
:
"""The bundled template directory name for ``platform``.
Raises:
BuildError: For an unknown platform.
"""
try
:
return
_TEMPLATE_NAMES
[
platform
]
except
KeyError
:
raise
BuildError
(
f"Unknown platform:
{
platform
!r
}
(expected 'android' or 'ios')."
)
from
None
def
template_source
(
platform
:
str
)
->
Path
:
"""Where the bundled template for ``platform`` lives in this installation."""
return
Path
(
__file__
).
resolve
().
parents
[
1
]
/
"templates"
/
template_name
(
platform
)
def
stage_template
(
template_name
:
str
,
destination
:
Path
)
->
Path
:
"""Copy a bundled native template into ``destination``.
Resolution order mirrors the historical CLI: a local source checkout
first (so dev edits take effect immediately), then installed package
data via :mod:`importlib.resources`.
Args:
template_name: ``"android_template"`` or ``"ios_template"``.
destination: Parent directory; the template lands at
``destination/<template_name>``.
Returns:
The path to the staged template directory.
Raises:
BuildError: If no bundled copy can be located.
"""
dest_path
=
destination
/
template_name
destination
.
mkdir
(
parents
=
True
,
exist_ok
=
True
)
# Dev-first: local source package templates.
local
=
Path
(
__file__
).
resolve
().
parents
[
1
]
/
"templates"
/
template_name
if
local
.
is_dir
():
shutil
.
copytree
(
local
,
dest_path
,
dirs_exist_ok
=
True
,
ignore
=
_TEMPLATE_IGNORE
)
_stage_runtime
(
template_name
,
dest_path
)
return
dest_path
try
:
candidate
=
resources
.
files
(
"pythonnative"
).
joinpath
(
"templates"
).
joinpath
(
template_name
)
with
resources
.
as_file
(
candidate
)
as
resolved
:
if
Path
(
resolved
).
is_dir
():
shutil
.
copytree
(
resolved
,
dest_path
,
dirs_exist_ok
=
True
,
ignore
=
_TEMPLATE_IGNORE
)
_stage_runtime
(
template_name
,
dest_path
)
return
dest_path
except
(
ModuleNotFoundError
,
FileNotFoundError
,
OSError
):
pass
raise
BuildError
(
f"Could not find bundled template
{
template_name
!r
}
. Reinstall pythonnative or run from a source checkout."
)
def
_stage_runtime
(
name
:
str
,
destination
:
Path
)
->
None
:
platform
=
name
.
removesuffix
(
"_template"
)
source
=
Path
(
__file__
).
resolve
().
parents
[
1
]
/
"native"
runtime_name
=
"PythonNativeKit"
if
platform
==
"ios"
else
"pythonnative"
managed
=
"Sources/PythonNativeKit"
if
platform
==
"ios"
else
"src/main/java/com/pythonnative/runtime"
staged_sources
=
destination
/
runtime_name
/
managed
if
staged_sources
.
exists
():
for
path
in
staged_sources
.
rglob
(
"*"
):
rel
=
path
.
relative_to
(
staged_sources
)
if
path
.
is_file
()
and
rel
.
parts
[
0
]
not
in
{
"Plugins"
,
"PluginResources"
,
"Generated"
,
"plugins"
}:
if
not
(
source
/
platform
/
managed
/
rel
).
exists
():
path
.
unlink
()
shutil
.
copytree
(
source
/
platform
,
destination
/
runtime_name
,
dirs_exist_ok
=
True
,
ignore
=
_TEMPLATE_IGNORE
)
shutil
.
copytree
(
source
/
"yoga"
,
destination
/
"yoga"
,
dirs_exist_ok
=
True
,
ignore
=
_TEMPLATE_IGNORE
)
from
..
sdk
.
codegen
import
generate
generated
=
destination
/
"contracts"
generate
(
generated
)
if
platform
==
"ios"
:
output
=
destination
/
runtime_name
/
"Sources/PythonNativeKit/Generated"
extension
=
"swift"
else
:
output
=
destination
/
runtime_name
/
"src/main/java/com/pythonnative/generated"
extension
=
"kt"
output
.
mkdir
(
parents
=
True
,
exist_ok
=
True
)
for
name
in
(
"PNContracts"
,
"NativeProps"
,
"NativeModules"
,
"NativeValues"
):
shutil
.
copy2
(
generated
/
f"
{
name
}
.
{
extension
}
"
,
output
/
f"
{
name
}
.
{
extension
}
"
)
# ======================================================================
# The builder
# ======================================================================
class
Builder
:
"""Stages, configures, and builds a PythonNative project.
Args:
config: The validated app configuration.
runner: Command runner (defaults to
[`SubprocessRunner`][pythonnative.project.builder.SubprocessRunner]).
log: Progress logger (defaults to :func:`print`).
build_root: Override for the ``build/`` directory.
dev_lib_root: Override for the ``pythonnative`` package directory
to bundle (defaults to the running package).
"""
def
__init__
(
self
,
config
:
AppConfig
,
*
,
runner
:
Optional
[
CommandRunner
]
=
None
,
log
:
Optional
[
Logger
]
=
None
,
build_root
:
Optional
[
Path
]
=
None
,
dev_lib_root
:
Optional
[
Path
]
=
None
,
)
->
None
:
self
.
config
=
config
self
.
runner
=
runner
or
SubprocessRunner
()
self
.
log
:
Logger
=
log
or
print
self
.
build_root
=
build_root
or
(
config
.
project_root
/
"build"
)
# The currently-running pythonnative package is bundled into the app
# (works for both a source checkout and a pip install).
self
.
dev_lib_root
=
dev_lib_root
or
Path
(
__file__
).
resolve
().
parents
[
1
]
# -- Preparation ----------------------------------------------------
def
prepare
(
self
,
platform
:
str
,
*
,
release
:
bool
=
False
,
ios_sdks
:
Sequence
[
str
]
=
deps
.
IOS_SDKS
,
)
->
PreparedProject
:
"""Stage and configure the native project for ``platform``.
Args:
platform: ``"android"`` or ``"ios"``.
release: Prepare for a release/store build: byte-compile
the staged Python code and drop the ``.py`` sources from
the bundle (on Android through Chaquopy's ``pyc.src``).
Debug builds keep the sources so tracebacks show code and
the on-device dev client can see what it already runs.
ios_sdks: Which iOS SDKs to resolve third-party packages
for: ``"iphoneos"`` (devices, archives) and/or
``"iphonesimulator"``. Each becomes an
``app_packages.<sdk>`` slice in the staged project.
Defaults to both; the CLI narrows it to the destination
it is about to build so a package that only has a
Simulator wheel doesn't block a Simulator run.
Returns:
A [`PreparedProject`][pythonnative.project.builder.PreparedProject].
Raises:
BuildError: For an unknown platform, a staging failure, or a
requirement with no wheel for a requested iOS SDK.
"""
if
platform
not
in
_TEMPLATE_NAMES
:
raise
BuildError
(
f"Unknown platform:
{
platform
!r
}
(expected 'android' or 'ios')."
)
targets
=
(
deps
.
android_targets
(
self
.
config
)
if
platform
==
"android"
else
deps
.
ios_targets
(
self
.
config
,
sdks
=
ios_sdks
)
)
if
release
:
if
platform
==
"android"
and
self
.
config
.
android
.
target_sdk
<
36
:
raise
BuildError
(
"Android release builds require target_sdk >= 36."
)
if
self
.
config
.
requirements
:
from
.
lockfile
import
requirements
try
:
locked
=
requirements
(
self
.
config
,
targets
)
except
deps
.
DependencyError
as
error
:
raise
BuildError
(
str
(
error
))
from
error
if
locked
is
None
:
raise
BuildError
(
f"Release dependencies need pn.lock. Run 'pn deps
{
platform
}
--lock' first."
)
build_dir
=
self
.
build_root
/
platform
build_dir
.
mkdir
(
parents
=
True
,
exist_ok
=
True
)
project_dir
=
stage_template
(
_TEMPLATE_NAMES
[
platform
],
build_dir
)
plugins
=
self
.
_discover_plugins
(
targets
)
if
platform
==
"android"
:
layout
=
android_config
.
configure
(
project_dir
,
self
.
config
,
dev_lib_root
=
self
.
dev_lib_root
,
release
=
release
,
log
=
self
.
log
,
)
native_plugins
.
stage_android_plugins
(
project_dir
,
plugins
,
log
=
self
.
log
)
self
.
_stage_contracts
(
project_dir
,
platform
,
plugins
, [
layout
.
python_root
/
"pythonnative"
])
return
PreparedProject
(
platform
=
platform
,
build_dir
=
build_dir
,
project_dir
=
project_dir
,
app_id
=
layout
.
application_id
,
android
=
layout
,
)
ios_layout
=
ios_config
.
configure
(
project_dir
,
self
.
config
,
release
=
release
,
log
=
self
.
log
)
native_plugins
.
stage_ios_plugins
(
project_dir
,
plugins
,
log
=
self
.
log
)
self
.
_stage_ios_python
(
project_dir
,
release
=
release
,
sdks
=
ios_sdks
)
self
.
_stage_contracts
(
project_dir
,
platform
,
plugins
,
[
project_dir
/
target
.
slice_name
/
"pythonnative"
for
target
in
targets
],
)
self
.
_link_ios_runtime
(
project_dir
)
return
PreparedProject
(
platform
=
platform
,
build_dir
=
build_dir
,
project_dir
=
project_dir
,
app_id
=
ios_layout
.
bundle_id
,
ios
=
ios_layout
,
)
def
_stage_contracts
(
self
,
project_dir
:
Path
,
platform
:
str
,
plugins
:
Sequence
[
native_plugins
.
NativePlugin
],
python_roots
:
Sequence
[
Path
],
)
->
None
:
from
..
sdk
import
schema
from
..
sdk
.
codegen
import
generate
components
,
modules
=
dict
(
schema
.
COMPONENTS
),
dict
(
schema
.
MODULES
)
try
:
for
plugin
in
plugins
:
if
plugin
.
contracts
is
not
None
:
schema
.
load_manifest
(
json
.
loads
((
plugin
.
root
/
plugin
.
contracts
).
read_text
(
encoding
=
"utf-8"
)))
generated
=
project_dir
/
"contracts"
generate
(
generated
)
output
=
project_dir
/
(
"PythonNativeKit/Sources/PythonNativeKit/Generated"
if
platform
==
"ios"
else
"pythonnative/src/main/java/com/pythonnative/generated"
)
extension
=
"swift"
if
platform
==
"ios"
else
"kt"
for
name
in
(
"PNContracts"
,
"NativeProps"
,
"NativeModules"
,
"NativeValues"
):
shutil
.
copy2
(
generated
/
f"
{
name
}
.
{
extension
}
"
,
output
/
f"
{
name
}
.
{
extension
}
"
)
for
root
in
python_roots
:
root
.
mkdir
(
parents
=
True
,
exist_ok
=
True
)
shutil
.
copy2
(
generated
/
"schema.json"
,
root
/
"_native_contracts.json"
)
finally
:
schema
.
COMPONENTS
.
clear
()
schema
.
COMPONENTS
.
update
(
components
)
schema
.
MODULES
.
clear
()
schema
.
MODULES
.
update
(
modules
)
def
_discover_plugins
(
self
,
targets
:
Sequence
[
deps
.
Target
]
=
())
->
List
[
native_plugins
.
NativePlugin
]:
"""Collect native plugins from entry points and ``[plugins].paths``.
Raises:
BuildError: If a project-local plugin directory is invalid.
"""
try
:
installed
=
native_plugins
.
discover_target_plugins
(
self
.
config
,
targets
,
self
.
runner
)
local
=
native_plugins
.
discover_plugins
(
include_environment
=
False
,
extra_paths
=
[
self
.
config
.
resolve_path
(
p
)
for
p
in
self
.
config
.
plugin_paths
],
log
=
self
.
log
,
)
names
=
{
plugin
.
name
for
plugin
in
installed
}
if
any
(
plugin
.
name
in
names
for
plugin
in
local
):
raise
native_plugins
.
PluginError
(
"A plugin appears in both target requirements and [plugins].paths"
)
return
installed
+
local
except
native_plugins
.
PluginError
as
exc
:
raise
BuildError
(
f"Invalid native plugin:
{
exc
}
"
)
from
exc
def
_stage_ios_python
(
self
,
project_dir
:
Path
,
*
,
release
:
bool
,
sdks
:
Sequence
[
str
])
->
None
:
"""Stage ``app/`` and one ``app_packages.<sdk>/`` slice per SDK.
``app/`` is a bundle resource. The package slices are not: the
"Install Python runtime" build phase copies the slice matching
``EFFECTIVE_PLATFORM_NAME`` into the bundle as ``app_packages``
and converts any binary modules inside it into signed
frameworks. Every slice carries the ``pythonnative`` package
(pure Python) plus the project's requirements resolved for that
SDK's wheel tags.
"""
app_dir
=
project_dir
/
"app"
if
app_dir
.
exists
():
shutil
.
rmtree
(
app_dir
)
for
stale
in
project_dir
.
glob
(
"app_packages*"
):
if
stale
.
is_dir
():
shutil
.
rmtree
(
stale
)
else
:
stale
.
unlink
()
app_src
=
self
.
config
.
project_root
/
"app"
if
not
app_src
.
is_dir
():
raise
BuildError
(
f"No app/ directory found at
{
app_src
}
; nothing to bundle."
)
shutil
.
copytree
(
app_src
,
app_dir
,
ignore
=
shutil
.
ignore_patterns
(
"__pycache__"
,
"*.pyc"
,
".*"
))
# ``app/`` is a folder reference in the Xcode project, so
# ``app/assets/`` lands in the bundle as is; the manifest lets the
# runtime resolve density variants and register fonts.
assets
.
write_manifest
(
app_dir
/
assets
.
ASSETS_DIR
,
log
=
self
.
log
)
slices
:
List
[
Path
]
=
[]
for
target
in
deps
.
ios_targets
(
self
.
config
,
sdks
=
sdks
):
packages_dir
=
project_dir
/
target
.
slice_name
packages_dir
.
mkdir
(
parents
=
True
,
exist_ok
=
True
)
slices
.
append
(
packages_dir
)
# The framework has no Python-side native dependencies (the
# bridge into PythonNativeKit is ctypes), so it is copied
# verbatim into every slice.
if
self
.
dev_lib_root
.
is_dir
():
copy_library
(
self
.
dev_lib_root
,
packages_dir
/
"pythonnative"
,
release
=
release
)
if
self
.
config
.
requirements
:
self
.
log
(
f"Resolving
{
len
(
self
.
config
.
requirements
)
}
requirement(s) for
{
target
.
label
}
..."
)
try
:
deps
.
install
(
self
.
config
,
target
,
packages_dir
,
runner
=
self
.
runner
)
except
deps
.
DependencyError
as
exc
:
raise
BuildError
(
str
(
exc
))
from
exc
if
release
:
self
.
_compile_ios_bytecode
(
app_dir
,
*
slices
)
def
_compile_ios_bytecode
(
self
,
*
roots
:
Path
)
->
None
:
"""Byte-compile staged Python code and drop the ``.py`` sources.
Ships ``.pyc`` only: smaller bundles, faster cold start, and no
plain-text source in the store artifact. Requires the host
interpreter to match ``app.python_version``, since bytecode is
version-specific.
"""
host_version
=
f"
{
sys
.
version_info
[
0
]
}
.
{
sys
.
version_info
[
1
]
}
"
if
host_version
!=
self
.
config
.
python_version
:
self
.
log
(
f"Skipping bytecode compilation: the build host runs Python
{
host_version
}
"
f"but app.python_version is
{
self
.
config
.
python_version
}
, and bytecode is "
"version-specific. The app will ship .py sources. Run pn with Python "
f"
{
self
.
config
.
python_version
}
to ship bytecode."
)
return
for
root
in
roots
:
# legacy=True writes module.pyc next to module.py (no
# __pycache__), which the embedded interpreter imports
# directly once the .py files are gone.
if
not
compileall
.
compile_dir
(
str
(
root
),
quiet
=
1
,
legacy
=
True
,
optimize
=
1
):
raise
BuildError
(
f"Byte-compiling
{
root
}
failed; fix the syntax error above."
)
for
source
in
root
.
rglob
(
"*.py"
):
source
.
unlink
()
self
.
log
(
"Compiled Python sources to bytecode for release."
)
def
_link_ios_runtime
(
self
,
project_dir
:
Path
)
->
None
:
"""Make ``Python.xcframework`` available at the project root.
A symlink into the shared runtime cache is preferred (the
framework is hundreds of megabytes); staging falls back to a
copy when symlinks are unavailable.
"""
runtime
=
self
.
_ios_runtime
()
link
=
project_dir
/
"Python.xcframework"
if
link
.
is_symlink
()
or
link
.
is_file
():
link
.
unlink
()
elif
link
.
is_dir
():
shutil
.
rmtree
(
link
)
try
:
link
.
symlink_to
(
runtime
.
xcframework_dir
,
target_is_directory
=
True
)
except
OSError
:
shutil
.
copytree
(
runtime
.
xcframework_dir
,
link
)
self
.
log
(
f"Linked Python.xcframework (Python
{
self
.
config
.
python_version
}
)."
)
# -- Android builds -------------------------------------------------
def
install_android_debug
(
self
,
prepared
:
PreparedProject
)
->
None
:
"""Build and install the debug APK on a connected device/emulator.
Args:
prepared: A prepared Android project.
Raises:
BuildError: If the Gradle build fails.
"""
self
.
_gradlew
(
prepared
, [
"installDebug"
])
def
android_debug_apk
(
self
,
prepared
:
PreparedProject
)
->
Optional
[
Path
]:
"""The debug APK produced by the last Gradle build, if it exists."""
outputs
=
prepared
.
project_dir
/
"app"
/
"build"
/
"outputs"
candidates
=
_existing
(
outputs
.
rglob
(
"*-debug.apk"
))
return
candidates
[
0
]
if
candidates
else
None
def
build_android
(
self
,
prepared
:
PreparedProject
,
*
,
debug
:
bool
=
False
)
->
BuildArtifacts
:
"""Assemble standalone Android artifacts (APK + AAB).
Args:
prepared: A prepared Android project.
debug: Build the debug variant instead of release.
Returns:
The produced artifact paths.
Raises:
BuildError: If the Gradle build fails.
"""
if
debug
:
self
.
_gradlew
(
prepared
, [
"assembleDebug"
])
outputs
=
prepared
.
project_dir
/
"app"
/
"build"
/
"outputs"
return
BuildArtifacts
(
paths
=
_existing
(
outputs
.
rglob
(
"*-debug.apk"
)))
self
.
_gradlew
(
prepared
, [
"assembleRelease"
,
"bundleRelease"
])
outputs
=
prepared
.
project_dir
/
"app"
/
"build"
/
"outputs"
candidates
=
list
(
outputs
.
rglob
(
"*-release.apk"
))
+
list
(
outputs
.
rglob
(
"*-release.aab"
))
if
not
config_has_android_signing
(
self
.
config
):
candidates
+=
list
(
outputs
.
rglob
(
"*-release-unsigned.apk"
))
paths
=
_existing
(
candidates
)
if
not
paths
:
raise
BuildError
(
"Gradle succeeded but produced no release artifacts"
)
try
:
for
path
in
paths
:
checked
=
artifacts
.
android
(
path
)
self
.
log
(
f"Verified
{
checked
}
native libraries in
{
path
.
name
}
for 16 KB pages."
)
except
artifacts
.
ArtifactError
as
exc
:
raise
BuildError
(
str
(
exc
))
from
exc
return
BuildArtifacts
(
paths
=
paths
)
def
_gradlew
(
self
,
prepared
:
PreparedProject
,
tasks
:
Sequence
[
str
])
->
None
:
gradlew
=
prepared
.
project_dir
/
"gradlew"
if
gradlew
.
exists
():
os
.
chmod
(
gradlew
,
0o755
)
env
=
self
.
_android_env
()
result
=
self
.
runner
.
run
([
"./gradlew"
,
*
tasks
],
cwd
=
prepared
.
project_dir
,
env
=
env
)
if
not
result
.
ok
:
raise
BuildError
(
f"Gradle build failed (
{
' '
.
join
(
tasks
)
}
). See output above."
)
def
_android_env
(
self
)
->
dict
:
env
=
dict
(
os
.
environ
)
if
sys
.
platform
==
"darwin"
and
not
env
.
get
(
"JAVA_HOME"
):
try
:
jdk
=
subprocess
.
check_output
([
"brew"
,
"--prefix"
,
"openjdk@17"
],
text
=
True
).
strip
()
if
jdk
:
env
[
"JAVA_HOME"
]
=
jdk
except
Exception
:
pass
return
env
# -- iOS builds -----------------------------------------------------
def
build_ios_simulator
(
self
,
prepared
:
PreparedProject
)
->
Path
:
"""Build the iOS app for the simulator.
The Xcode build produces a complete, runnable ``.app``: the
Python framework is linked and the "Install Python runtime"
build phase embeds the standard library and staged sources.
Args:
prepared: A prepared iOS project.
Returns:
Path to the built ``.app``.
Raises:
BuildError: If the build fails.
"""
derived
=
prepared
.
project_dir
/
"build"
settings
=
ios_config
.
build_settings
(
self
.
config
)
# The simulator runs on the host CPU, and BeeWare's runtime
# install script requires a single-architecture build (its
# stdlib layout is per-arch), so pin ARCHS to the host.
host_arch
=
"arm64"
if
platform_module
.
machine
()
==
"arm64"
else
"x86_64"
settings
.
append
(
f"ARCHS=
{
host_arch
}
"
)
result
=
self
.
runner
.
run
(
[
"xcodebuild"
,
"-project"
,
ios_config
.
PROJECT_FILE
,
"-scheme"
,
ios_config
.
PROJECT_NAME
,
"-configuration"
,
"Debug"
,
"-destination"
,
"generic/platform=iOS Simulator"
,
"-derivedDataPath"
,
str
(
derived
),
"build"
,
*
settings
,
],
cwd
=
prepared
.
project_dir
,
)
if
not
result
.
ok
:
raise
BuildError
(
"xcodebuild (simulator) failed. See output above."
)
app_path
=
derived
/
"Build"
/
"Products"
/
"Debug-iphonesimulator"
/
ios_config
.
APP_BUNDLE_NAME
if
not
app_path
.
is_dir
():
raise
BuildError
(
f"Built app not found at
{
app_path
}
."
)
return
app_path
def
build_ios_device
(
self
,
prepared
:
PreparedProject
)
->
Path
:
"""Build a signed Debug app for a physical iOS device.
Requires ``[ios].development_team`` for automatic signing.
Args:
prepared: A prepared iOS project.
Returns:
Path to the built ``.app``.
Raises:
BuildError: If the build fails or signing is not set up.
"""
if
not
self
.
config
.
ios
.
development_team
:
raise
BuildError
(
"Running on a physical iOS device requires code signing. "
"Set [ios].development_team in pythonnative.toml."
)
derived
=
prepared
.
project_dir
/
"build"
settings
=
ios_config
.
build_settings
(
self
.
config
)
settings
.
append
(
"-allowProvisioningUpdates"
)
result
=
self
.
runner
.
run
(
[
"xcodebuild"
,
"-project"
,
ios_config
.
PROJECT_FILE
,
"-scheme"
,
ios_config
.
PROJECT_NAME
,
"-configuration"
,
"Debug"
,
"-destination"
,
"generic/platform=iOS"
,
"-derivedDataPath"
,
str
(
derived
),
"build"
,
*
settings
,
],
cwd
=
prepared
.
project_dir
,
)
if
not
result
.
ok
:
raise
BuildError
(
"xcodebuild (device) failed. See output above."
)
app_path
=
derived
/
"Build"
/
"Products"
/
"Debug-iphoneos"
/
ios_config
.
APP_BUNDLE_NAME
if
not
app_path
.
is_dir
():
raise
BuildError
(
f"Built app not found at
{
app_path
}
."
)
return
app_path
def
build_ios_archive
(
self
,
prepared
:
PreparedProject
,
*
,
upload
:
bool
=
False
)
->
BuildArtifacts
:
"""Archive the iOS app and export a signed IPA (or upload it).
Args:
prepared: A prepared iOS project (use ``release=True``).
upload: Upload directly to App Store Connect instead of
exporting a local ``.ipa`` (requires
``export_method = "app-store"`` and stored ASC
credentials in Xcode).
Returns:
The produced ``.ipa`` (and ``.xcarchive``) paths.
Raises:
BuildError: If archiving or export fails.
"""
version
=
self
.
runner
.
run
([
"xcodebuild"
,
"-version"
],
capture
=
True
)
major
=
re
.
search
(
r"Xcode (\d+)"
,
version
.
stdout
)
if
not
version
.
ok
or
major
is
None
or
int
(
major
.
group
(
1
))
<
26
:
raise
BuildError
(
"iOS release archives require Xcode 26 or later. Run 'pn doctor ios'."
)
archive_path
=
prepared
.
build_dir
/
"ios_template.xcarchive"
settings
=
ios_config
.
build_settings
(
self
.
config
,
for_archive
=
True
)
result
=
self
.
runner
.
run
(
[
"xcodebuild"
,
"-project"
,
ios_config
.
PROJECT_FILE
,
"-scheme"
,
ios_config
.
PROJECT_NAME
,
"-configuration"
,
"Release"
,
"-destination"
,
"generic/platform=iOS"
,
"-archivePath"
,
str
(
archive_path
),
"-allowProvisioningUpdates"
,
"archive"
,
*
settings
,
],
cwd
=
prepared
.
project_dir
,
)
if
not
result
.
ok
:
raise
BuildError
(
"xcodebuild archive failed. See output above."
)
try
:
count
=
artifacts
.
ios_archive
(
archive_path
)
self
.
log
(
f"Verified
{
count
}
bundled privacy manifests."
)
except
artifacts
.
ArtifactError
as
exc
:
raise
BuildError
(
str
(
exc
))
from
exc
export_dir
=
prepared
.
build_dir
/
"export"
options
=
ios_config
.
write_export_options
(
self
.
config
,
prepared
.
build_dir
/
"exportOptions.plist"
,
upload
=
upload
)
result
=
self
.
runner
.
run
(
[
"xcodebuild"
,
"-exportArchive"
,
"-archivePath"
,
str
(
archive_path
),
"-exportOptionsPlist"
,
str
(
options
),
"-exportPath"
,
str
(
export_dir
),
"-allowProvisioningUpdates"
,
],
cwd
=
prepared
.
project_dir
,
)
if
not
result
.
ok
:
raise
BuildError
(
"xcodebuild -exportArchive failed. Check signing settings in [ios.signing]."
)
return
BuildArtifacts
(
paths
=
_existing
(
list
(
export_dir
.
rglob
(
"*.ipa"
))
+
[
archive_path
]))
def
_ios_runtime
(
self
)
->
runtime_assets
.
IOSRuntime
:
cache
=
self
.
build_root
/
"ios_runtime"
try
:
return
runtime_assets
.
prepare_ios_runtime
(
cache
,
self
.
config
.
python_version
,
log
=
self
.
log
)
except
RuntimeError
as
exc
:
raise
BuildError
(
str
(
exc
))
from
exc
# ======================================================================
# Helpers
# ======================================================================
def
config_has_android_signing
(
config
:
AppConfig
)
->
bool
:
"""Return whether the config defines an Android release signing key.
Args:
config: The app configuration.
Returns:
``True`` if a keystore and alias are configured.
"""
return
config
.
android
.
signing
.
is_configured
def
_existing
(
paths
:
Union
[
Sequence
[
Path
],
object
])
->
List
[
Path
]:
result
:
List
[
Path
]
=
[]
for
path
in
paths
:
# type: ignore[union-attr]
candidate
=
Path
(
path
)
if
candidate
.
exists
()
and
candidate
not
in
result
:
result
.
append
(
candidate
)
return
result
Back
|
FazBrowse Home
|
New Git URL