Repository navigation
Expand file tree
/
Copy pathapk.cppm
More file actions
2724 lines (2578 loc) · 138 KB
/
Copy pathapk.cppm
File metadata and controls
2724 lines (2578 loc) · 138 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
// mcpp.dist.apk -- an application target becomes an installable, signed
// `.apk`, or a signed Android App Bundle (`.aab`), with or without a Java host.
//
// WHY THIS IS NEITHER A RULE NOR A TOOL. A rule states how a translation unit
// is compiled by a compiler mcpp does not drive. A tool states something the
// build program needs that no compiler performs, and does it while the
// program runs. This member does neither: it consumes the LINK OUTPUT of a
// `kind = "app"` target -- a shared object on `*-linux-android` (#622 A3) --
// and produces something a user installs. That is the third category
// `dist/appimage.cppm` establishes.
//
// LEVEL 0 AND LEVEL 1. A `NativeActivity` application needs no Java at all
// (`hasCode="false"`): the manifest, the native library and whatever assets
// were deployed are enough. `options::java_sources` adds a second tier --
// `javac`, `d8`, a real `<activity>` -- for a project that hosts its native
// code from a Java/Kotlin activity. Both tiers share every step below except
// the two that compile and dex Java sources, which level 0 never submits.
//
// THE STEPS, under these ids and in this order. `apk:manifest` compiles
// `options::resources` with aapt2 and is submitted only when that option names
// a directory. `apk:link` links the generated manifest, `-I android.jar` and
// the compiled resources into an unsigned, unaligned `base.apk`. Level 1 adds
// `apk:javac` and `apk:d8`. `apk:libs` adds the native libraries, the deployed
// assets and the dex with `jar` (aapt2 has no flag for native libraries),
// `apk:align` runs `zipalign` and `apk:sign` runs `apksigner`.
//
// `--format aab` SHARES EVERYTHING BUT THE LAST THREE STEPS. `aab:link` asks
// aapt2 for the protocol-buffer form bundletool reads (`--proto-format`);
// `aab:module` lays the linked archive out as a bundle's base module
// (`manifest/`, `dex/`, `lib/<abi>/`, `assets/`); `aab:bundle` runs `bundletool
// build-bundle`; and `aab:sign` signs the bundle with `jarsigner`, because an
// App Bundle carries a JAR signature and not an APK signature scheme.
//
// THE NATIVE CLOSURE COMES FROM THE STAGED TREE (mcpp 2026.9.14.2+). The engine
// reads the application object's closure from the files and stages it: the
// object, every library the graph built for it, and the NDK's
// `libc++_shared.so` when the object needs it, under `lib/` for one triple or
// under `lib/<abi>/` for several, with one `needs` line per name in the stage
// manifest (mcpp's docs/50, "The stage manifest"). This member copies those
// files into the package and reads the manifest to refuse a tree it cannot
// trust: an incomplete closure, a `needs` line whose staged file is absent,
// and a manifest with no `needs` line, which only an engine older than
// 2026.9.14.2 writes. Before that release the member walked `DT_NEEDED` itself
// at command time and recorded the walk in a stamp outside the staged tree, so
// a second pack of an unchanged project found the stamp current and produced a
// package without the dependency's library (measured on 0.9.3). The deployed
// files are staged under the tree's `bin/` on this row as on every other, and
// become `assets/`.
//
// EVERY REFUSAL IS ALSO A `mcpp::warning`. A member that refuses submits no
// action and its build program exits 0, and the engine discards the output of
// a build program that succeeded; its own error, "no action claimed --format
// 'apk'", then named no reason (measured on 0.9.3 with two triples).
//
// SIGNING, THROUGH THE PACKAGE MODEL. The default keystore is
// `xim:android-debug-keystore`'s one `debug.keystore`, whose alias
// (`androiddebugkey`) and password (`android`) are the exact values
// Android's own tooling has published and used since the platform's first
// release -- publishing them discloses nothing (see that package's own
// header). A project that names `options::keystore` as a package (never a
// path) is signing with a key it keeps out of every public index; the
// password reaches `apksigner` as `env:<NAME>` and `jarsigner` as
// `-storepass:env <NAME>`, tokens each tool resolves against its own
// environment at run time, so this member never reads the secret.
//
// KOTLIN, R CLASSES AND LIBRARIES (0.11.0). Level 1 compiles Kotlin beside
// Java (`options::kotlin_sources`, with `kotlinc` from `xim:kotlin`, which the
// `dist-apk-kotlin` feature declares), and links the R classes a project's
// code reads its resources through (`aapt2 link --java`). It takes Android
// libraries the way a Gradle project does: from source (`options::libraries`),
// as local archives (`options::aars`, `options::jars`) and as Maven coordinates
// (`options::maven`). A library's resources link under its own package, its
// manifest is merged into the application's (`merge_manifests` states the
// subset and its rules), its classes are dexed with the application's, and an
// AAR's native libraries and assets join the package.
//
// MAVEN, AND A BUILD THAT DOES NOT REACH THE NETWORK. A build must not reach
// the network (`dist/appimage.cppm`), so a Maven graph is resolved into a lock
// file only when the developer asks -- `MCPP_DIST_APK_MAVEN=update` -- and
// fetched into coursier's cache only when asked -- `MCPP_DIST_APK_MAVEN=fetch`.
// An ordinary build reads the locked artifacts from the cache, checks each
// digest against the lock, and refuses naming the command to run when one is
// missing or the lock no longer matches the project's coordinates.
// `xim:coursier`, which the `dist-apk-maven` feature declares, resolves.
//
// UNSIGNED, WHEN ASKED (0.11.0). `options::sign = false` writes the aligned
// package without a signature: the form a release pipeline that signs
// elsewhere wants, and the form a Gradle release build produces without a
// signing configuration.
//
// WHAT THIS MEMBER DOES NOT DO. It does not run `mcpp run --format apk` --
// that is `adb-run`, a session `xim:android-platform-tools` registers, and
// this member's only obligation to it is `assets/mcpp-run.json`, so the
// runner can start the application without `aapt2` on the machine that runs
// it. It does not resolve an emulator or a device; `ANDROID_SERIAL` is the
// caller's configuration, not this member's (rule 4, 2026-09-12 design
// record: "a name is cache-safe, a path is not").
module;
#include <cstdio>
#if !defined(_WIN32)
#include <sys/wait.h>
#endif
export module mcpp.dist.apk;
import std;
import mcpp;
import mcpp.plugins;
import mcpp.plugins.tool;
// `std::format` is header-only and used throughout; `std::println` is not --
// see `rules/spirv.cppm` for the libc++-on-macOS-14 measurement that this
// collection's every member has followed since.
export namespace mcpp::dist::apk {
// ─── Options ───────────────────────────────────────────────────────────────
// An Android library built from source (0.11.0): what a Gradle library module
// contributes to an application. Paths are manifest-relative or absolute.
struct library {
// The package its R class is generated under. Required when `resources`
// is set; a library whose code reads no resources may leave it empty.
std::string package;
// A `res/`-shaped directory, linked under `package`.
std::string resources;
// An `AndroidManifest.xml` whose declarations are merged into the
// application's.
std::string manifest;
// A directory whose files join the package's `assets/`; a file the build
// program deploys under the same name wins.
std::string assets;
std::vector<std::string> java_sources;
std::vector<std::string> kotlin_sources;
};
struct options {
// The `app` target this member packages. Empty means the package name.
std::string target;
// The manifest's `package` attribute. Empty means `<namespace>.<name>`
// with every `-` replaced by `_` (Android package identifiers may not
// carry one), or `app.<name>` when the project declares no namespace.
std::string application_id;
// `<application android:label>`. Empty means the package name.
std::string label;
// A project file, package-root-relative, that replaces the built-in
// manifest. Six tokens are substituted verbatim wherever they appear --
// `{{application_id}}`, `{{label}}`, `{{activity}}`, `{{lib_name}}`,
// `{{min_sdk}}`, `{{target_sdk}}` -- and everything else in the file is
// the project's, verbatim: permissions, receivers, meta-data, an icon,
// an activity-alias, `configChanges`. This member adds nothing to it
// (design record `2026-09-13-four-upstream-asks-from-a-ui-framework.md`,
// §3.2).
//
// THREE TOKENS ARE REQUIRED, NOT MERELY SUBSTITUTED, because their value
// is also written to `assets/mcpp-run.json`, which `adb-run` reads to
// start the application without `aapt2` on the machine that runs it: a
// template missing `{{application_id}}` or `{{activity}}` is refused at
// plan time, naming the token and that reader; `{{lib_name}}` joins them
// at level 0 (`java_sources` empty), because the manifest's own
// `<meta-data>` element is the only place the loaded library's name is
// recorded. An unknown `{{...}}` token is refused too, naming it -- see
// the render function below for why that check belongs to this member
// and is not proposed for `dist-web`.
//
// Empty means the built-in default, which is `manifest_xml`'s own 0.8.0
// output expressed with these tokens; level 0 with no template renders a
// manifest byte-identical to 0.8.0's (`tests/apk-consumer`).
std::string manifest_template;
// A `res/`-shaped directory `aapt2 compile --dir` compiles and `aapt2
// link` links as the application's OWN resources -- its launcher icon,
// colours, strings. Empty means no resources at all -- a legal, common
// case for a NativeActivity application that draws everything itself.
std::string resources;
// LEVEL 1. One or more directories of `.java` sources; one `javac` over
// every root's files and one `d8` over the result (the member compiles
// what it is given, and a second root is more of the same input, not a
// second step). A project with a path-dependency framework that also
// hosts Java lists that dependency's own directory alongside its own
// rather than merging the two trees itself. Empty (the default) is
// level 0: no Java, `hasCode="false"`, `android.app.NativeActivity` as
// the manifest's activity. A single string is still accepted in a
// `build.mcpp`: a one-element initialiser list is the same spelling.
std::vector<std::string> java_sources;
// LEVEL 1, REQUIRED WHEN `java_sources` IS SET. The fully-qualified
// activity class the manifest names as `<activity android:name>` and the
// launcher intent-filter targets. Ignored at level 0, where the activity
// is always `android.app.NativeActivity`.
std::string activity;
// A package name (`ns:name`), never a path (rule 9, 2026-09-12 design
// record): where the signing keystore comes from. Empty means
// `xim:android-debug-keystore`'s published debug key, whose alias and
// password are hardcoded below because they are the documented, public
// convention and not a secret. A non-empty value is resolved with
// `xpkg_dir` exactly as this member resolves its own declared payloads;
// `keystore_alias` and `keystore_password_env` are then both required,
// because a private key has no convention this member may assume.
std::string keystore;
// THE PAYLOADS THIS MEMBER RUNS (0.19.0, mcpp#755): each a root holding
// that part of the Android pipeline, or the default -- the payload this
// member declares, or an override of it. One named here is not downloaded.
// `platform` is a root carrying `android.jar`; `keystore_package` above
// stays the way a keystore package is named.
mcpp::plugins::tool::choice build_tools, platform, jdk, bundletool_dir, kotlin, coursier;
std::string keystore_alias;
// The NAME of an environment variable `apksigner` itself reads
// (`--ks-pass env:<NAME>`) -- this member never reads the secret; only
// the tool does, at run time, in its own process.
std::string keystore_password_env;
// `false` writes the aligned package unsigned (0.11.0): no `apksigner` for
// an APK and no `jarsigner` for an App Bundle, for a pipeline that signs
// elsewhere. With `keystore` it is refused, because the two say opposite
// things.
bool sign = true;
// `true` packs the native libraries as the engine staged them (0.11.1).
// By default each is stripped with the build's own `llvm-strip
// --strip-unneeded`, which keeps the dynamic symbols the loader reads and
// drops the symbol table and the debug information -- what the Android
// Gradle plugin does to every library it packages, and what `mcpp pack`
// reports it did.
//
// FROM 0.12.0 THE ENGINE'S DECISION GOVERNS AS WELL. An engine that strips
// what the graph built (mcpp 2026.9.16.1, #649 E5) tells a build program
// whether this packaging pass strips (`MCPP_PACK_STRIP`, "1" or "0") and
// where `--debug-symbols` sends the separated debug information
// (`MCPP_PACK_DEBUG_SYMBOLS_DIR`), so `mcpp pack --no-strip` and
// `--debug-symbols <dir>` reach the libraries this member packs as they
// reach the ones the engine stages. A library is stripped unless either
// this option or the engine says to keep it. An older engine publishes
// neither variable, and the member strips as before.
//
// THE ENGINE STRIPS FIRST. That engine strips the libraries the graph built
// when it stages them, before this member reads the tree, so this option
// keeps this member's own strip off and cannot restore what the engine
// removed: `mcpp pack --no-strip` is what ships the symbols. With this
// option set and the engine stripping, the member says so.
bool keep_debug_symbols = false;
// LEVEL 1, KOTLIN (0.11.0). One or more directories of `.kt` sources,
// compiled by `kotlinc` with every Java root as its reference sources,
// before `javac` compiles the Java against the Kotlin classes; the Kotlin
// standard library is dexed into the package. The compiler is
// `xim:kotlin`, which the `dist-apk-kotlin` feature declares -- a project
// names that feature instead of `dist-apk`. Either this or `java_sources`
// makes a level-1 package, and both may be set.
std::vector<std::string> kotlin_sources;
// ANDROID LIBRARIES FROM SOURCE (0.11.0), highest priority first: a library
// listed earlier wins a resource both define, as Gradle's dependency order
// does, and the application's own `resources` win over every library.
std::vector<library> libraries;
// LIBRARIES THE GRAPH CONTRIBUTES (0.12.0). With mcpp 2026.9.16.1 the root
// project's build program receives the resolved graph, and every package in
// it other than the application that states `[package.metadata.dist-apk]`
// contributes a library of the shape above (`package`, `resources`,
// `manifest`, `assets`, `java_sources`, `kotlin_sources`) and archives
// (`jars`, `aars`), its paths relative to that package's directory. A
// framework's library therefore reaches every application that depends on
// it without being listed in the application's build program.
//
// RANKED BELOW THE APPLICATION'S OWN ENTRIES, and among themselves a package
// above the packages it depends on: the graph lists dependencies first, so
// contributions are taken in reverse. An application's `libraries` still win
// a resource any contribution defines, and a library wins over the framework
// beneath it, which is the order a Gradle build gives the same modules.
//
// `false` reads no contribution, for an application that lists every
// library itself. Under an older engine, or in a dependency's own build
// program, there is no graph, and nothing is contributed either way.
bool graph_libraries = true;
// LOCAL ARCHIVES (0.11.0). A JAR joins the classpath and the dex. An AAR
// contributes its classes, its resources (under the package its manifest
// names), its manifest, its native libraries and its assets. Archives
// rank after `libraries`, in the order listed.
std::vector<std::string> jars;
std::vector<std::string> aars;
// MAVEN (0.11.0). `group:artifact:version` coordinates with fixed versions,
// resolved with their transitive dependencies into `maven_lock`; see the
// header's Maven paragraph for when the network is used. Empty
// `maven_repositories` means Google's Maven repository, then Maven
// Central; an empty `maven_lock` means `maven.lock` beside the manifest;
// an empty `maven_cache` means `COURSIER_CACHE`, then coursier's own
// default for this host. Resolved AARs and JARs rank after `aars`.
std::vector<std::string> maven;
std::vector<std::string> maven_repositories;
std::string maven_lock;
std::string maven_cache;
// Where the produced file lands. Empty means `<out_dir>/<target>.apk`, or
// `<out_dir>/<target>.aab` for `--format aab`.
std::string output;
std::string out_dir = std::string(mcpp::out_dir());
};
// ─── The plan ────────────────────────────────────────────────────────────
struct step {
// Owned strings: a library's resource step is named after its position.
std::string id;
const char* role;
std::string description;
std::vector<std::string> argv;
std::vector<std::string> inputs;
std::string output;
// Further files the same command writes that a later step reads -- the R
// classes `aapt2 link --java` generates beside the linked archive.
std::vector<std::string> more_outputs;
};
struct plan {
// False when this build is not `mcpp pack --format apk`, which is every
// ordinary build. `reason` then says which of the several ways.
bool applies = false;
std::string reason;
std::string output; // the final, signed .apk
std::vector<step> steps;
explicit operator bool() const { return applies; }
};
// ─── Internals ─────────────────────────────────────────────────────────────
namespace fs = std::filesystem;
inline bool is_file(const std::string& p) {
std::error_code ec;
return !p.empty() && fs::is_regular_file(p, ec);
}
inline bool is_dir(const std::string& p) {
std::error_code ec;
return !p.empty() && fs::is_directory(p, ec);
}
// Is `root` under the package root, `mcpp::manifest_dir()`, and if so, what
// is its manifest-relative form? A project root is declared with
// `rerun_if_changed_glob` below (a file appearing there re-runs the build
// program); a dependency root is not -- its file set changes only with the
// dependency's version, already in the build's fingerprint, and the glob's
// own walk does not reach outside the package root regardless (design
// record §3.3). Same shape as `mcpp.tools.island`'s overlap check:
// `weakly_canonical` plus `lexically_relative`, never the iterator that
// poisons an importer under GCC 16 / MSVC (`mcpp::plugins::names::
// relative_to`'s own header) -- safe here because this member is its own
// module and imports no sibling that would inherit the instantiation.
//
// THE RETURNED PATH IS MANIFEST-RELATIVE, NOT ABSOLUTE, BECAUSE THE GLOB
// PATTERN MUST BE. The engine matches a glob by comparing the CANDIDATE made
// relative to the package root against the pattern
// (`modules/manifest/src/glob.cppm`, `path_matches_glob`); an absolute
// pattern is compared against a relative candidate and never matches
// anything, so the fingerprint is always the empty set and a `.java` file
// appearing never changes it -- the criterion's "no" reading as silence
// (design record, rule 8). `opt.java_sources`'s own roots are absolute
// (`mcpp::manifest_dir()` composed with a subdirectory), so declaring the
// glob with `root` itself, not this function's return value, was exactly
// that defect.
inline std::optional<std::string> root_in_project(const std::string& root) {
std::error_code ec;
const auto a = fs::weakly_canonical(root, ec);
if (ec) return std::nullopt;
const auto b = fs::weakly_canonical(mcpp::manifest_dir(), ec);
if (ec) return std::nullopt;
const auto rel = a.lexically_relative(b).generic_string();
if (rel.empty() || rel.starts_with("..")) return std::nullopt;
return rel;
}
inline bool write_if_different(const fs::path& path, std::string_view bytes) {
std::error_code ec;
fs::create_directories(path.parent_path(), ec);
if (std::ifstream in(path, std::ios::binary); in) {
std::string old((std::istreambuf_iterator<char>(in)),
std::istreambuf_iterator<char>());
if (old == bytes) return true;
}
std::ofstream out(path, std::ios::binary | std::ios::trunc);
if (!out) return false;
out.write(bytes.data(), static_cast<std::streamsize>(bytes.size()));
return static_cast<bool>(out);
}
inline std::string target_for(const options& opt) {
if (!opt.target.empty()) return opt.target;
const char* n = mcpp::package_name();
return (n && *n) ? std::string(n) : std::string();
}
// `<abi>/`, from the row's arch and no other input -- see `artifact_naming`
// for the engine's own row-decides-the-name principle, applied here to
// Android's own ABI vocabulary rather than a file suffix.
inline std::string abi_for() {
const std::string a = mcpp::target_arch();
if (a == "aarch64") return "arm64-v8a";
if (a == "x86_64") return "x86_64";
return {};
}
// Index loop, not a range-for: GCC 16.1.0 refuses to inline
// `__normal_iterator<char*, basic_string<char>>::operator*() const` when a
// module interface unit that imports `std` also range-for's (or otherwise
// takes `basic_string`'s own iterator over) a `std::string` or
// `std::filesystem::path` --
//
// bits/stl_iterator.h:1089:7: error: inlining failed in call to
// 'always_inline' '... operator*() const'
//
// -- the same family of defect #18 met under MSVC's `_Path_iterator` (see
// `mcpp::plugins::names::relative_to` and `components()` in
// `src/plugins.cppm`), here on `libstdc++`'s `basic_string` iterator instead
// of the filesystem one. `s[i]` indexes the string directly and never forms
// that iterator, so it compiles under both.
inline std::string replace_dashes(std::string s) {
for (std::size_t i = 0; i < s.size(); ++i) if (s[i] == '-') s[i] = '_';
return s;
}
inline std::string application_id_for(const options& opt, const std::string& target) {
if (!opt.application_id.empty()) return opt.application_id;
const char* ns = mcpp::package_namespace();
const char* nm = mcpp::package_name();
const std::string name = (nm && *nm) ? std::string(nm) : target;
if (ns && *ns) return replace_dashes(std::string(ns) + "." + name);
return replace_dashes("app." + name);
}
inline std::string label_for(const options& opt) {
if (!opt.label.empty()) return opt.label;
const char* n = mcpp::package_name();
return (n && *n) ? std::string(n) : std::string("app");
}
// `xim:android-platform`'s own resolved directory is named after the
// version it resolved -- "36-r2", "35-r2", "34-r3" (`pkgs/a/android-
// platform.lua`'s own `extract_dir()` recovers the API level the identical
// way, from the leading digits of its OWN version string) -- so the level a
// project pinned is read back from the directory `xpkg_dir` already
// answered, rather than duplicated as a second option this member could
// disagree with.
inline std::string api_level_from_platform_dir(const std::string& dir) {
if (dir.empty()) return {};
const std::string leaf = fs::path(dir).filename().string();
std::string digits;
for (std::size_t i = 0; i < leaf.size(); ++i) {
if (leaf[i] >= '0' && leaf[i] <= '9') digits += leaf[i];
else break;
}
return digits;
}
inline std::string replace_all_copy(std::string s, std::string_view from, std::string_view to) {
if (from.empty()) return s;
std::size_t pos = 0;
while ((pos = s.find(from, pos)) != std::string::npos) {
s.replace(pos, from.size(), to);
pos += to.size();
}
return s;
}
// The eight tokens a manifest template may use. `version_name` is the
// package version as written; `version_code` is Android's monotonic integer
// derived from its leading numeric segments (`version_code_for`).
inline const std::vector<std::string>& manifest_tokens() {
static const std::vector<std::string> v = {
"application_id", "label", "activity", "lib_name", "min_sdk", "target_sdk",
"version_name", "version_code"};
return v;
}
// `android:versionCode` from a version string: major * 1000000 + minor * 1000
// + patch over the first three dot-separated numeric segments, so that every
// release a project cuts orders after the one before it, and "1" when the
// string starts with no number at all -- Android refuses 0 and a manifest
// without the attribute installs but never updates.
inline std::string version_code_for(const std::string& version) {
long long code = 0, seg = 0;
int segments = 0;
bool digits = false;
const long long weights[3] = {1000000, 1000, 1};
for (std::size_t i = 0; i <= version.size() && segments < 3; ++i) {
const char c = i < version.size() ? version[i] : '\0';
if (c >= '0' && c <= '9') { seg = seg * 10 + (c - '0'); digits = true; continue; }
if (!digits) break;
code += std::min<long long>(seg, 999) * weights[segments] ;
++segments; seg = 0; digits = false;
if (c != '.') break;
}
if (segments == 0) return "1";
if (code <= 0) return "1";
return std::to_string(code);
}
// Every `{{...}}` a template names, in first-appearance order, duplicates
// dropped -- what both checks in `render_manifest` below read.
inline std::vector<std::string> tokens_in(const std::string& text) {
std::vector<std::string> out;
std::size_t i = 0;
while ((i = text.find("{{", i)) != std::string::npos) {
const auto close = text.find("}}", i + 2);
if (close == std::string::npos) break;
std::string name = text.substr(i + 2, close - (i + 2));
if (std::ranges::find(out, name) == out.end()) out.push_back(std::move(name));
i = close + 2;
}
return out;
}
// The tokens `assets/mcpp-run.json` is ALSO written from -- a template that
// omits one silently ships a run sidecar the manifest disagrees with.
// `application_id` and `activity` are required unconditionally; `lib_name`
// joins them at level 0, where the manifest's own `<meta-data>` element is
// the only place the loaded library's name is recorded.
inline std::vector<std::string> required_manifest_tokens(bool has_code, bool native_activity) {
static_cast<void>(has_code);
std::vector<std::string> v = {"application_id", "activity"};
if (native_activity) v.push_back("lib_name");
return v;
}
inline std::vector<std::string> required_manifest_tokens(bool has_code) {
return required_manifest_tokens(has_code, !has_code);
}
// THE BUILT-IN DEFAULT, EXPRESSED WITH THE TOKENS. This is `manifest_xml`'s
// 0.8.0 output verbatim, with every literal value it used to compute
// replaced by the token that value now comes through -- so level 0 with no
// project template renders byte-identical to what 0.8.0 wrote
// (`tests/apk-consumer`). `{{activity}}` carries the level-0 constant
// (`android.app.NativeActivity`) as well as a level-1 project's own class,
// because the run sidecar needs the activity name at both levels and the
// required-token check reads the TEMPLATE TEXT, not the level -- so the same
// token has to appear on both of this function's two branches.
// `{{lib_name}}`'s `<meta-data>` element exists only at level 0: it
// announces which shared object `NativeActivity` should load, and a
// Java-hosted activity finds its own native library another way.
//
// NO XML COMMENT MARKS THE THREE REQUIRED TOKENS IN THIS STRING, ON PURPOSE:
// this exact text is compared byte-for-byte against 0.8.0's output, which
// carried none, and a template with no author to read a comment gains
// nothing from one. The design record's "mark the required tokens" is done
// here instead, in the `REQUIRED` labels on the C++ lines that build them.
// A NATIVE ACTIVITY MAY STILL CARRY CODE (0.11.0): a level-0 application whose
// libraries or archives bring classes keeps `android.app.NativeActivity` and its
// `lib_name` element, with `android:hasCode="true"` so that the dex is loaded.
inline std::string default_manifest_template(bool has_code, bool native_activity) {
std::string a =
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
"<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n"
" package=\"{{application_id}}\">\n" // REQUIRED
" <uses-sdk android:minSdkVersion=\"{{min_sdk}}\" "
"android:targetSdkVersion=\"{{target_sdk}}\"/>\n"
" <application android:label=\"{{label}}\" android:hasCode=\"" +
std::string(has_code ? "true" : "false") + "\">\n"
" <activity android:name=\"{{activity}}\" " // REQUIRED
"android:exported=\"true\">\n";
if (native_activity) {
a += " <meta-data android:name=\"android.app.lib_name\" "
"android:value=\"{{lib_name}}\"/>\n"; // REQUIRED at level 0
}
a += " <intent-filter>\n"
" <action android:name=\"android.intent.action.MAIN\"/>\n"
" <category android:name=\"android.intent.category.LAUNCHER\"/>\n"
" </intent-filter>\n"
" </activity>\n"
" </application>\n"
"</manifest>\n";
return a;
}
inline std::string default_manifest_template(bool has_code) {
return default_manifest_template(has_code, !has_code);
}
// Checks a manifest template and substitutes it, or refuses (returning
// `false` with `reason` and `message` set) naming exactly what is wrong; the
// caller reports `message` (see `refuse`).
//
// THIS CHECK IS `dist-apk`'S OWN, DELIBERATELY NOT `dist-web`'S. A manifest
// has a closed, six-token vocabulary this member itself defines; a web page
// template may legitimately carry `{{ }}` for a front-end framework (Vue,
// Mustache, ...) this member never reads, so `dist-web` leaves an unknown
// token literal for that project's own tooling to read. An unknown token
// here would otherwise reach `aapt2` unsubstituted and fail there with a
// worse message, and the refusal belongs where the name is known -- the same
// rule read against two different facts, not an inconsistency between the
// two members.
inline bool render_manifest(const std::string& templateText, bool has_code, bool native_activity,
const std::string& appId, const std::string& label,
const std::string& activityName, const std::string& libName,
const std::string& minSdk, const std::string& targetSdk,
const std::string& versionName, const std::string& versionCode,
std::string& out, std::string& reason,
std::string& message) {
for (auto const& tok : tokens_in(templateText)) {
if (std::ranges::find(manifest_tokens(), tok) == manifest_tokens().end()) {
message = "mcpp.dist.apk: the manifest template names an unknown "
"token '{{" + tok + "}}'; expected one of application_id, "
"label, activity, lib_name, min_sdk, target_sdk, "
"version_name, version_code.";
reason = "unknown manifest template token '" + tok + "'";
return false;
}
}
for (auto const& tok : required_manifest_tokens(has_code, native_activity)) {
if (templateText.find("{{" + tok + "}}") == std::string::npos) {
message = "mcpp.dist.apk: the manifest template does not use '{{" + tok
+ "}}', and assets/mcpp-run.json, which adb-run starts the "
"application from, is written from the same value: add {{"
+ tok + "}} to the template.";
reason = "manifest template missing required token '" + tok + "'";
return false;
}
}
out = templateText;
out = replace_all_copy(std::move(out), "{{application_id}}", appId);
out = replace_all_copy(std::move(out), "{{label}}", label);
out = replace_all_copy(std::move(out), "{{activity}}", activityName);
out = replace_all_copy(std::move(out), "{{lib_name}}", libName);
out = replace_all_copy(std::move(out), "{{min_sdk}}", minSdk);
out = replace_all_copy(std::move(out), "{{target_sdk}}", targetSdk);
out = replace_all_copy(std::move(out), "{{version_name}}", versionName);
out = replace_all_copy(std::move(out), "{{version_code}}", versionCode);
return true;
}
inline bool render_manifest(const std::string& templateText, bool has_code,
const std::string& appId, const std::string& label,
const std::string& activityName, const std::string& libName,
const std::string& minSdk, const std::string& targetSdk,
const std::string& versionName, const std::string& versionCode,
std::string& out, std::string& reason,
std::string& message) {
return render_manifest(templateText, has_code, !has_code, appId, label, activityName, libName,
minSdk, targetSdk, versionName, versionCode, out, reason, message);
}
inline std::string run_json(const std::string& app_id, const std::string& activity_name) {
// Hand-built, not through a JSON library this collection does not
// depend on: two string fields, neither of which this member lets
// through unescaped input (`app_id` is derived from the package's own
// identifiers, `activity_name` is a Java class name or the literal
// `android.app.NativeActivity`).
return std::format("{{\"package\": \"{}\", \"activity\": \"{}\"}}\n",
app_id, activity_name);
}
// Copies `src` (a file or a directory, recursively) into `dstRoot/relName`,
// listing every regular file it wrote -- so the caller can declare each one
// as an action input rather than the directory itself ("name the input; do
// not harvest a directory", docs/31).
inline void collect_tree(const fs::path& src, const fs::path& dst,
std::vector<std::string>& out) {
std::error_code ec;
if (fs::is_regular_file(src, ec)) {
fs::create_directories(dst.parent_path(), ec);
fs::copy_file(src, dst, fs::copy_options::overwrite_existing, ec);
out.push_back(dst.string());
return;
}
for (auto& e : fs::recursive_directory_iterator(src, ec)) {
if (ec) break;
if (!e.is_regular_file(ec)) continue;
auto rel = fs::relative(e.path(), src, ec);
auto to = dst / rel;
fs::create_directories(to.parent_path(), ec);
fs::copy_file(e.path(), to, fs::copy_options::overwrite_existing, ec);
out.push_back(to.string());
}
}
namespace xml = mcpp::plugins::xml;
// ─── Paths a project names ─────────────────────────────────────────────────
// A project names its directories relative to its manifest; the actions this
// member declares run later, from the build directory, where a relative path
// names nothing (the defect `dist/apple.cppm` measured with `ditto ios-icons`).
// Every path option is therefore resolved here, once, against
// `mcpp::manifest_dir()`; an absolute path is left alone.
inline std::string resolve_path(const std::string& p) {
if (p.empty()) return p;
const fs::path path(p);
if (path.is_absolute()) return p;
return (fs::path(mcpp::manifest_dir()) / path).lexically_normal().string();
}
inline void resolve_paths(std::vector<std::string>& v) {
for (auto& p : v) p = resolve_path(p);
}
// Every regular file under `root` whose extension is `ext`, sorted.
inline std::vector<std::string> files_with_extension(const std::string& root, std::string_view ext) {
std::vector<std::string> out;
std::error_code ec;
for (auto& e : fs::recursive_directory_iterator(root, ec)) {
if (ec) break;
if (e.is_regular_file(ec) && e.path().extension() == ext)
out.push_back(e.path().string());
}
std::ranges::sort(out);
return out;
}
inline bool dir_has_files(const std::string& root) {
std::error_code ec;
for (auto& e : fs::recursive_directory_iterator(root, ec)) {
if (ec) break;
if (e.is_regular_file(ec)) return true;
}
return false;
}
inline std::string read_file(const std::string& path) {
std::ifstream in(path, std::ios::binary);
return std::string((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
}
inline std::string join(const std::vector<std::string>& v, std::string_view sep) {
std::string out;
for (std::size_t i = 0; i < v.size(); ++i) {
if (i) out += sep;
out += v[i];
}
return out;
}
// ─── SHA-256 ───────────────────────────────────────────────────────────────
// FIPS 180-4, over bytes held in memory. Here for one purpose: a Maven lock
// records each artifact's digest, and a build that reads a cached artifact
// checks it against the lock before the file reaches a package. The inputs are
// libraries of a few megabytes, so reading a file whole is the simple choice.
inline std::string sha256_hex(std::string_view data) {
static constexpr std::uint32_t k[64] = {
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2};
std::uint32_t h[8] = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
std::string msg(data);
const std::uint64_t bits = static_cast<std::uint64_t>(data.size()) * 8u;
msg.push_back(static_cast<char>(0x80));
while (msg.size() % 64 != 56) msg.push_back('\0');
for (int i = 7; i >= 0; --i) msg.push_back(static_cast<char>((bits >> (i * 8)) & 0xffu));
const auto rotr = [](std::uint32_t x, int n) -> std::uint32_t { return (x >> n) | (x << (32 - n)); };
for (std::size_t off = 0; off < msg.size(); off += 64) {
std::uint32_t w[64];
for (int i = 0; i < 16; ++i) {
const auto byte = [&](int j) {
return static_cast<std::uint32_t>(static_cast<unsigned char>(msg[off + static_cast<std::size_t>(i * 4 + j)]));
};
w[i] = (byte(0) << 24) | (byte(1) << 16) | (byte(2) << 8) | byte(3);
}
for (int i = 16; i < 64; ++i) {
const std::uint32_t s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >> 3);
const std::uint32_t s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >> 10);
w[i] = w[i - 16] + s0 + w[i - 7] + s1;
}
std::uint32_t a = h[0], b = h[1], c = h[2], d = h[3], e = h[4], f = h[5], g = h[6], hh = h[7];
for (int i = 0; i < 64; ++i) {
const std::uint32_t t1 = hh + (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) + ((e & f) ^ (~e & g)) + k[i] + w[i];
const std::uint32_t t2 = (rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + ((a & b) ^ (a & c) ^ (b & c));
hh = g; g = f; f = e; e = d + t1; d = c; c = b; b = a; a = t1 + t2;
}
h[0] += a; h[1] += b; h[2] += c; h[3] += d; h[4] += e; h[5] += f; h[6] += g; h[7] += hh;
}
std::string hex;
hex.reserve(64);
for (int i = 0; i < 8; ++i) hex += std::format("{:08x}", h[i]);
return hex;
}
inline std::string sha256_file(const std::string& path) {
return is_file(path) ? sha256_hex(read_file(path)) : std::string();
}
// ─── Running a tool at plan time ─────────────────────────────────────────
// POSIX single quotes: the only character that needs care inside them is the
// quote itself. This member runs on the hosts that build Android rows, which
// are Linux and macOS (xim:android-ndk publishes no Windows table).
inline std::string shell_quote(const std::string& s) {
std::string out = "'";
for (std::size_t i = 0; i < s.size(); ++i) {
if (s[i] == '\'') out += "'\\''";
else out += s[i];
}
return out + "'";
}
// Runs `argv` through `/bin/sh`, returning its exit status and its combined
// output -- the same `popen` the rules members use to probe a tool at plan
// time. Only the explicit Maven modes and AAR extraction call it; an ordinary
// build of an unchanged project runs nothing here.
inline int run_capture(const std::vector<std::string>& argv, std::string& output) {
std::string cmd;
for (std::size_t i = 0; i < argv.size(); ++i) {
if (i) cmd += ' ';
cmd += shell_quote(argv[i]);
}
cmd += " 2>&1";
output.clear();
#if defined(_WIN32)
FILE* p = ::_popen(cmd.c_str(), "r");
#else
FILE* p = ::popen(cmd.c_str(), "r");
#endif
if (!p) return -1;
char buf[4096];
std::size_t n;
while ((n = std::fread(buf, 1, sizeof buf, p)) > 0) output.append(buf, n);
#if defined(_WIN32)
// Compiled on every host (`tests/all-rules-compile`); an Android row is
// never packed on Windows, so this branch only has to be well-formed.
return ::_pclose(p);
#else
const int status = ::pclose(p);
return WIFEXITED(status) ? WEXITSTATUS(status) : -1;
#endif
}
// ─── Merging library manifests into the application's ────────────────────
// What `mcpp.dist.apk` merges, and the rules it applies. This is a SUBSET of
// the Android Gradle plugin's manifest merger, stated rather than implied:
//
// - `<uses-permission>`, `<uses-permission-sdk-23>`, `<permission>`,
// `<uses-feature>` and the other children of `<manifest>` are added when
// the application has no element of the same kind and `android:name`;
// `<queries>` children are unioned;
// - the children of a library's `<application>` -- activities, aliases,
// services, receivers, providers, `<meta-data>`, `<uses-library>` -- are
// added the same way; a library's `<application>` attribute the
// application does not state is added;
// - an identical element is not added twice; a DIFFERENT element under the
// same name is refused, naming it, unless the application's own element
// says `tools:node="replace"` (the application's wins) or
// `tools:node="remove"` (neither is kept); a differing `<application>`
// attribute is refused unless the application lists it in `tools:replace`;
// - a library's `<uses-sdk android:minSdkVersion>` above the application's
// floor is refused, as Gradle refuses it;
// - `${applicationId}` is substituted everywhere, and any other `${...}`
// placeholder is refused, naming it -- no placeholder source exists here;
// - every `tools:` attribute and the `xmlns:tools` declaration are removed
// from the result.
//
// Anything a project needs beyond that is stated in its own manifest template,
// which this member never edits except to add what the libraries declare.
struct manifest_source {
std::string label; // what a refusal names: a library, an AAR, a coordinate
std::string text;
};
inline std::string manifest_key(const xml::node& n) {
if (n.name == "uses-feature") {
const std::string nm = xml::attr_of(n, "android:name");
return nm.empty() ? "uses-feature@glEsVersion=" + xml::attr_of(n, "android:glEsVersion")
: "uses-feature:" + nm;
}
return n.name + ":" + xml::attr_of(n, "android:name");
}
inline void strip_tools(xml::node& n) {
std::erase_if(n.attrs, [](const std::pair<std::string, std::string>& a) {
return a.first.starts_with("tools:") || a.first == "xmlns:tools";
});
for (auto& c : n.children) strip_tools(c);
}
inline std::string canonical_xml(xml::node n) {
strip_tools(n);
std::string out;
xml::write(n, out, 0);
return out;
}
inline bool substitute_placeholders(xml::node& n, const std::string& appId,
const std::string& label, std::string& message) {
for (auto& a : n.attrs) {
a.second = replace_all_copy(a.second, "${applicationId}", appId);
const auto p = a.second.find("${");
if (p != std::string::npos) {
const auto e = a.second.find('}', p);
message = std::format(
"mcpp.dist.apk: {} uses the manifest placeholder '{}' in {}=\"{}\"; "
"only ${{applicationId}} is substituted here.", label,
a.second.substr(p, e == std::string::npos ? std::string::npos : e - p + 1),
a.first, a.second);
return false;
}
}
for (auto& c : n.children)
if (!substitute_placeholders(c, appId, label, message)) return false;
return true;
}
inline xml::node* find_child(xml::node& parent, std::string_view name) {
for (auto& c : parent.children) if (c.name == name) return &c;
return nullptr;
}
// Removes every element the application marked `tools:node="remove"`: a marker
// that says "this is not wanted", not an element to ship.
inline void drop_removed(xml::node& n) {
std::erase_if(n.children, [](const xml::node& c) { return xml::attr_of(c, "tools:node") == "remove"; });
for (auto& c : n.children) drop_removed(c);
}
inline bool merge_manifests(std::string& appText, const std::vector<manifest_source>& libs,
const std::string& appId, const std::string& minSdk,
std::string& reason, std::string& message) {
xml::node app;
std::string err;
if (!xml::parse(appText, app, err) || app.name != "manifest") {
reason = "the application manifest cannot be read";
message = "mcpp.dist.apk: the application's manifest cannot be read for merging: "
+ (err.empty() ? std::string("its root element is not <manifest>") : err);
return false;
}
if (!substitute_placeholders(app, appId, "the application's manifest", message)) {
reason = "unknown manifest placeholder";
return false;
}
xml::node* application = find_child(app, "application");
if (!application) {
app.children.push_back(xml::node{"application", {}, {}, {}});
application = &app.children.back();
}
const auto parse_number = [](const std::string& s) {
long v = 0;
for (std::size_t i = 0; i < s.size(); ++i) {
if (s[i] < '0' || s[i] > '9') return -1L;
v = v * 10 + (s[i] - '0');
}
return s.empty() ? -1L : v;
};
for (auto const& lib : libs) {
xml::node m;
if (!xml::parse(lib.text, m, err) || m.name != "manifest") {
reason = "a library manifest cannot be read";
message = std::format("mcpp.dist.apk: the manifest of {} cannot be read: {}", lib.label,
err.empty() ? std::string("its root element is not <manifest>") : err);
return false;
}
if (!substitute_placeholders(m, appId, lib.label, message)) {
reason = "unknown manifest placeholder";
return false;
}
for (auto& c : m.children) {
if (c.name.empty()) continue;
if (c.name == "uses-sdk") {
const long want = parse_number(xml::attr_of(c, "android:minSdkVersion"));
const long have = parse_number(minSdk);
if (want > 0 && have > 0 && want > have) {
reason = "a library needs a higher minSdkVersion";
message = std::format(
"mcpp.dist.apk: {} declares android:minSdkVersion {}, above this "
"application's floor {}. Raise the row's min_api_level, or do not "
"depend on it.", lib.label, want, have);
return false;
}
continue;
}
if (c.name == "application") {
const std::string replaced = xml::attr_of(*application, "tools:replace");
for (auto const& a : c.attrs) {
if (a.first.starts_with("tools:")) continue;
const std::string mine = xml::attr_of(*application, a.first);
if (mine.empty()) { xml::set_attr(*application, a.first, a.second); continue; }
if (mine == a.second) continue;
bool listed = false;
std::size_t start = 0;
while (start <= replaced.size()) {
auto comma = replaced.find(',', start);
if (comma == std::string::npos) comma = replaced.size();
if (xml::trim_copy(replaced.substr(start, comma - start)) == a.first) { listed = true; break; }
start = comma + 1;
}
if (!listed) {
reason = "conflicting <application> attribute";
message = std::format(
"mcpp.dist.apk: <application {}> is \"{}\" in the application and "
"\"{}\" in {}. Add tools:replace=\"{}\" to the application's "
"<application> to keep its value.", a.first, mine, a.second, lib.label, a.first);
return false;