bundling: fs/process stdlib + post-link callback + Apple .app in sx
Campaign Weeks 3-6 of /Users/agra/.claude/plans/lets-plan-to-move-splendid-pumpkin.md
land in one push: the bundling pipeline that used to live in
src/target.zig (createBundle, embedFramework, extractEntitlements,
buildInfoPlist, codesign) now lives in
library/modules/platform/bundle.sx and runs in the IR interpreter
after target.link() returns.
New language-side surface:
- library/modules/fs.sx — POSIX libc bindings (open/read/write/close,
mkdir/unlink/rmdir, chmod, rename, access, basename/dirname). Variadic
open() lowers to C's varargs via the new args: ..T form. Direct libc
calls bypass *File method dispatch so they work from the post-link
IR interpreter.
- library/modules/process.sx — popen-based run(cmd) returning
ProcessResult{ exit_code, stdout }, plus env() and find_executable().
- library/modules/std.sx — xml_escape(s) and variadic path_join(parts).
- library/modules/compiler.sx — BuildOptions grows
set_post_link_callback / set_post_link_module / binary_path
accessors; bundle_path/bundle_id/codesign_identity/provisioning_profile
setters + accessors; per-target predicates is_macos/is_ios/
is_ios_device/is_ios_simulator + target_triple; framework_count /
framework_at(i) / framework_path_count / framework_path_at(i);
add_asset_dir(src, dest) + asset_dir_count / src_at / dest_at.
Compiler-side wiring:
- src/ir/compiler_hooks.zig — BuildConfig now carries post_link_callback_fn,
post_link_module, binary_path, bundle_*, target_triple,
target_frameworks, target_framework_paths, asset_dirs. Hook registry
exposes every accessor; getters return "" / 0 for unset fields so
bundle.sx can treat absent values uniformly.
- src/ir/host_ffi.zig (new) — dlsym(RTLD_DEFAULT) + arity-switched cdecl
trampolines so #foreign("c") declarations resolve through the host
libc during #run / post-link interpretation.
- src/ir/interp.zig — callForeign dispatch; build_config pointer
injection so accessor hooks see live state during re-entry.
- src/core.zig — keeps the IR module alive past generateCode; exposes
invokeByName / invokeByFuncId so main.zig can re-enter the
interpreter after linking.
- src/main.zig — wires bundle/codesign/provisioning CLI flags +
target_triple + framework lists into BuildConfig; invokes the
post-link callback (by FuncId or by <module>.bundle_main lookup) once
target.link() returns. When --bundle is set but no callback is
registered, auto-falls-back to post_link_module = "platform.bundle"
so the legacy --bundle CLI keeps working for any program that imports
modules/platform/bundle.sx.
Apple .app bundler (library/modules/platform/bundle.sx):
- Single bundle_main entry covers macOS, iOS simulator, iOS device.
Per-target Info.plist switch keys off is_ios()/is_ios_simulator() —
iOS emits UIDeviceFamily / LSRequiresIPhoneOS /
UIApplicationSceneManifest / DTPlatformName (iPhoneOS or
iPhoneSimulator); macOS emits the minimal CFBundle* set.
- iOS-only steps:
- Provisioning embed: fs.read_file + fs.write_file to
<bundle>/embedded.mobileprovision.
- Framework embed: recursive cp -R per -F search path into
<bundle>/Frameworks/<Name>.framework/ (until fs.sx grows list_dir).
- Entitlements extraction: four process.run calls (security cms -D,
plutil -extract Entitlements xml1, plutil -extract
ApplicationIdentifierPrefix.0, plutil -replace application-identifier)
resolving the wildcard <TEAM>.* -> <TEAM>.<bundle_id>.
- Real codesign with --entitlements when present.
- Asset dirs (add_asset_dir): recursive cp -R src/. into <bundle>/dest/.
Missing src is treated as "nothing to do" so projects can register
add_asset_dir("assets", "assets") unconditionally.
Parser:
- parseStmt() now accepts #import \"path\"; and #framework \"Name\"; as
statement-position tokens. Needed for top-level
inline if OS == .android { #import \"modules/platform/android.sx\"; }
blocks (issue-0042 flatten pass surfaces them); chess's
inline-if-with-#import was rejected at parse time before this fix.
Removals from src/target.zig:
- createBundle, embedFramework, extractEntitlements, buildInfoPlist,
codesign (~210 lines). main.zig no longer calls createBundle after
link(); the sx callback is the single entry point.
Tests / regression markers (all run under sx run host JIT):
- examples/115-post-link-callback.sx — callback registration round-trip.
- examples/116-fs-roundtrip.sx — fs.write_file -> fs.read_file -> exists.
- examples/117-process-roundtrip.sx — process.run + env + find_executable.
- examples/118-macos-bundle.sx — macOS .app via bundle_main callback.
- examples/119-interp-cast-ptr-cmp.sx — cast(T) val under interpreter.
- examples/120-interp-variadic-any.sx — variadic ..Any indexing in IR
interpreter.
- examples/121-ios-sim-bundle.sx — iOS-sim cross-compile + .app with
iOS-shaped Info.plist (added to tests/cross_compile.sh as the
ios-sim tuple).
- examples/122-ios-device-bundle.sx — iOS device cross-compile +
full codesign pipeline (provisioning embed + entitlements
extraction + --entitlements codesign). Manually verified end-to-end:
installed via xcrun devicectl device install app + launched
successfully on iPhone 17 Pro.
- examples/123-inline-if-import-in-body.sx — locks in the parser fix.
zig build && zig build test && bash tests/run_examples.sh => 141 passed,
0 failed; bash tests/cross_compile.sh => 7 passed, 0 failed.
This commit is contained in:
@@ -5,11 +5,71 @@ OS : OperatingSystem = .unknown;
|
||||
ARCH : Architecture = .unknown;
|
||||
POINTER_SIZE : s64 = 8;
|
||||
|
||||
BuildOptions :: struct {
|
||||
add_link_flag :: (self: BuildOptions, flag: [:0]u8) #compiler;
|
||||
add_framework :: (self: BuildOptions, name: [:0]u8) #compiler;
|
||||
set_output_path :: (self: BuildOptions, path: [:0]u8) #compiler;
|
||||
set_wasm_shell :: (self: BuildOptions, path: [:0]u8) #compiler;
|
||||
BuildOptions :: struct #compiler {
|
||||
add_link_flag :: (self: BuildOptions, flag: [:0]u8);
|
||||
add_framework :: (self: BuildOptions, name: [:0]u8);
|
||||
set_output_path :: (self: BuildOptions, path: [:0]u8);
|
||||
set_wasm_shell :: (self: BuildOptions, path: [:0]u8);
|
||||
|
||||
// Register a directory of runtime assets to bundle alongside the
|
||||
// binary. `src` is the path on disk (relative to the CWD at build
|
||||
// time); `dest` is the relative location inside the bundle / APK.
|
||||
// Apple .app: copied to `<bundle>/<dest>/`. Android APK (Week 7):
|
||||
// zipped under `<dest>/` at the APK root. Idiomatic chess form is
|
||||
// `opts.add_asset_dir("assets", "assets")`.
|
||||
add_asset_dir :: (self: BuildOptions, src: [:0]u8, dest: [:0]u8);
|
||||
asset_dir_count :: (self: BuildOptions) -> s64;
|
||||
asset_dir_src_at :: (self: BuildOptions, i: s64) -> string;
|
||||
asset_dir_dest_at :: (self: BuildOptions, i: s64) -> string;
|
||||
|
||||
// Post-link callback. Registers a sx function the compiler will
|
||||
// invoke after `target.link()` returns. Used by the sx-side
|
||||
// bundler (`platform.bundle.bundle_main`) and by user programs
|
||||
// that want custom post-build steps. Return `false` to fail the build.
|
||||
set_post_link_callback :: (self: BuildOptions, cb: () -> bool);
|
||||
|
||||
// Name-based alternative to `set_post_link_callback`. The
|
||||
// compiler resolves `<module_name>.bundle_main` after linking.
|
||||
set_post_link_module :: (self: BuildOptions, module_name: [:0]u8);
|
||||
|
||||
// Path of the freshly-linked binary, only meaningful while a
|
||||
// post-link callback is running. Returns "" before linking.
|
||||
binary_path :: (self: BuildOptions) -> string;
|
||||
|
||||
// Apple `.app` / Android `.apk` bundling parameters. Accessors
|
||||
// return "" when unset so the bundler can use a single string
|
||||
// type. macOS bundling needs `bundle_path` and `bundle_id`;
|
||||
// codesign / provisioning are iOS-device-only.
|
||||
set_bundle_path :: (self: BuildOptions, path: [:0]u8);
|
||||
set_bundle_id :: (self: BuildOptions, id: [:0]u8);
|
||||
set_codesign_identity :: (self: BuildOptions, identity: [:0]u8);
|
||||
set_provisioning_profile :: (self: BuildOptions, path: [:0]u8);
|
||||
|
||||
bundle_path :: (self: BuildOptions) -> string;
|
||||
bundle_id :: (self: BuildOptions) -> string;
|
||||
codesign_identity :: (self: BuildOptions) -> string;
|
||||
provisioning_profile :: (self: BuildOptions) -> string;
|
||||
|
||||
// Target accessors. Empty triple before linking; predicates mirror
|
||||
// TargetConfig.is{MacOS,IOS,IOSDevice,IOSSimulator}() on the Zig
|
||||
// side. Used by the sx bundler to switch Info.plist shape and
|
||||
// codesigning ceremony per platform.
|
||||
target_triple :: (self: BuildOptions) -> string;
|
||||
is_macos :: (self: BuildOptions) -> bool;
|
||||
is_ios :: (self: BuildOptions) -> bool;
|
||||
is_ios_device :: (self: BuildOptions) -> bool;
|
||||
is_ios_simulator :: (self: BuildOptions) -> bool;
|
||||
|
||||
// Framework list accessors. The bundler walks `framework_count() *
|
||||
// framework_at(i)` to find each `-framework` name and recursively
|
||||
// copies its `<Name>.framework` directory from one of
|
||||
// `framework_path_at(0..framework_path_count())` into
|
||||
// `<bundle>/Frameworks/`. Slice returns aren't natively expressible
|
||||
// through the compiler-hook bridge yet, hence the indexed form.
|
||||
framework_count :: (self: BuildOptions) -> s64;
|
||||
framework_at :: (self: BuildOptions, i: s64) -> string;
|
||||
framework_path_count :: (self: BuildOptions) -> s64;
|
||||
framework_path_at :: (self: BuildOptions, i: s64) -> string;
|
||||
}
|
||||
|
||||
build_options :: () -> BuildOptions #compiler;
|
||||
|
||||
268
library/modules/fs.sx
Normal file
268
library/modules/fs.sx
Normal file
@@ -0,0 +1,268 @@
|
||||
#import "std.sx";
|
||||
|
||||
// =====================================================================
|
||||
// fs.sx — file system stdlib (POSIX backend, macOS values).
|
||||
//
|
||||
// Allocation contract: every returned `string` or slice is allocated
|
||||
// from `context.allocator`. Callers are responsible for releasing it
|
||||
// (typically via an arena reset).
|
||||
//
|
||||
// Handle ownership: `File` is a small value-typed handle wrapping the
|
||||
// POSIX file descriptor. Methods are provided for read/write/close;
|
||||
// the value is invalid (fd == -1) after `close()`.
|
||||
//
|
||||
// Scope (Phase 1A): file I/O + directory creation/deletion + path
|
||||
// helpers needed for `.app` bundling. Recursive walkers, `stat`, and
|
||||
// the full path module land in subsequent phases.
|
||||
// =====================================================================
|
||||
|
||||
libc :: #library "c";
|
||||
|
||||
// ── Low-level libc bindings ─────────────────────────────────────────
|
||||
// These declare the actual libc symbols and must use the libc names
|
||||
// verbatim (no prefix), so they live at module top-level. The public
|
||||
// API below wraps them. Users should not call these directly.
|
||||
//
|
||||
// macOS `open` is variadic in C (`int open(const char*, int, ...)`);
|
||||
// declared with `args: ..s32` so the mode is passed via the C
|
||||
// variadic tail. Without that, the mode arg goes to the wrong
|
||||
// register on arm64 and the file ends up with mode 0.
|
||||
|
||||
open :: (path: [:0]u8, flags: s32, args: ..s32) -> s32 #foreign libc;
|
||||
close :: (fd: s32) -> s32 #foreign libc;
|
||||
read :: (fd: s32, buf: [*]u8, count: usize) -> isize #foreign libc;
|
||||
write :: (fd: s32, buf: [*]u8, count: usize) -> isize #foreign libc;
|
||||
lseek :: (fd: s32, offset: s64, whence: s32) -> s64 #foreign libc;
|
||||
unlink :: (path: [:0]u8) -> s32 #foreign libc;
|
||||
rmdir :: (path: [:0]u8) -> s32 #foreign libc;
|
||||
mkdir :: (path: [:0]u8, mode: u32) -> s32 #foreign libc;
|
||||
access :: (path: [:0]u8, mode: s32) -> s32 #foreign libc;
|
||||
chmod :: (path: [:0]u8, mode: u32) -> s32 #foreign libc;
|
||||
rename :: (oldp: [:0]u8, newp: [:0]u8) -> s32 #foreign libc;
|
||||
|
||||
// macOS POSIX constants. Linux values differ; split into platform-
|
||||
// conditional includes when we gain a Linux host.
|
||||
O_RDONLY :s32: 0x0000;
|
||||
O_WRONLY :s32: 0x0001;
|
||||
O_RDWR :s32: 0x0002;
|
||||
O_APPEND :s32: 0x0008;
|
||||
O_CREAT :s32: 0x0200;
|
||||
O_TRUNC :s32: 0x0400;
|
||||
|
||||
SEEK_SET :s32: 0;
|
||||
SEEK_CUR :s32: 1;
|
||||
SEEK_END :s32: 2;
|
||||
|
||||
F_OK :s32: 0;
|
||||
|
||||
// ── Public types ─────────────────────────────────────────────────────
|
||||
|
||||
OpenMode :: enum {
|
||||
read; // O_RDONLY
|
||||
write; // O_WRONLY | O_CREAT | O_TRUNC
|
||||
append; // O_WRONLY | O_CREAT | O_APPEND
|
||||
read_write; // O_RDWR
|
||||
}
|
||||
|
||||
SeekFrom :: enum { set; current; end; }
|
||||
|
||||
File :: struct {
|
||||
fd: s32 = -1;
|
||||
|
||||
is_valid :: (self: *File) -> bool { self.fd >= 0; }
|
||||
|
||||
close :: (self: *File) -> bool {
|
||||
if self.fd < 0 { return false; }
|
||||
rc := close(self.fd);
|
||||
self.fd = -1;
|
||||
rc == 0;
|
||||
}
|
||||
|
||||
read :: (self: *File, buf: string) -> s64 {
|
||||
if self.fd < 0 { return -1; }
|
||||
n := read(self.fd, buf.ptr, xx buf.len);
|
||||
cast(s64) n;
|
||||
}
|
||||
|
||||
write :: (self: *File, data: string) -> s64 {
|
||||
if self.fd < 0 { return -1; }
|
||||
n := write(self.fd, data.ptr, xx data.len);
|
||||
cast(s64) n;
|
||||
}
|
||||
|
||||
seek :: (self: *File, offset: s64, whence: SeekFrom) -> s64 {
|
||||
if self.fd < 0 { return -1; }
|
||||
w := SEEK_SET;
|
||||
if whence == .current { w = SEEK_CUR; }
|
||||
if whence == .end { w = SEEK_END; }
|
||||
lseek(self.fd, offset, w);
|
||||
}
|
||||
}
|
||||
|
||||
// ── High-level file API ─────────────────────────────────────────────
|
||||
// Named `open_file` (not `open`) so they don't shadow libc's `open`
|
||||
// symbol; the latter is needed for `#foreign libc` to resolve. Same
|
||||
// idea for `delete_file`/`delete_dir` vs libc's `unlink`/`rmdir`,
|
||||
// `set_mode` vs libc's `chmod`, etc.
|
||||
|
||||
mode_to_flags :: (m: OpenMode) -> s32 {
|
||||
if m == .read { return O_RDONLY; }
|
||||
if m == .write { return O_WRONLY | O_CREAT | O_TRUNC; }
|
||||
if m == .append { return O_WRONLY | O_CREAT | O_APPEND; }
|
||||
if m == .read_write { return O_RDWR; }
|
||||
O_RDONLY;
|
||||
}
|
||||
|
||||
open_file :: (path: [:0]u8, mode: OpenMode) -> ?File {
|
||||
fd := open(path, mode_to_flags(mode), 420); // 0o644 = 420
|
||||
if fd < 0 { return null; }
|
||||
File.{ fd = fd };
|
||||
}
|
||||
|
||||
// One-shot read: opens, slurps the whole file into a fresh buffer,
|
||||
// closes. Returns null on any failure. Uses libc directly (not File
|
||||
// methods) so it remains callable from the post-link IR interpreter,
|
||||
// which doesn't yet handle `*Self` method dispatch on locally-
|
||||
// unwrapped optionals.
|
||||
read_file :: (path: [:0]u8) -> ?string {
|
||||
fd := open(path, O_RDONLY, 0);
|
||||
if fd < 0 { return null; }
|
||||
size := lseek(fd, 0, SEEK_END);
|
||||
if size < 0 { close(fd); return null; }
|
||||
lseek(fd, 0, SEEK_SET);
|
||||
buf := cstring(size);
|
||||
n := read(fd, buf.ptr, xx size);
|
||||
close(fd);
|
||||
if cast(s64) n != size { return null; }
|
||||
buf;
|
||||
}
|
||||
|
||||
// One-shot write: creates / truncates and writes the whole buffer.
|
||||
write_file :: (path: [:0]u8, data: string) -> bool {
|
||||
fd := open(path, O_WRONLY | O_CREAT | O_TRUNC, 420); // 0o644
|
||||
if fd < 0 { return false; }
|
||||
n := write(fd, data.ptr, xx data.len);
|
||||
close(fd);
|
||||
cast(s64) n == cast(s64) data.len;
|
||||
}
|
||||
|
||||
append_file :: (path: [:0]u8, data: string) -> bool {
|
||||
fd := open(path, O_WRONLY | O_CREAT | O_APPEND, 420);
|
||||
if fd < 0 { return false; }
|
||||
n := write(fd, data.ptr, xx data.len);
|
||||
close(fd);
|
||||
cast(s64) n == cast(s64) data.len;
|
||||
}
|
||||
|
||||
// ── Single-syscall ops ───────────────────────────────────────────────
|
||||
|
||||
exists :: (path: [:0]u8) -> bool {
|
||||
access(path, F_OK) == 0;
|
||||
}
|
||||
|
||||
delete_file :: (path: [:0]u8) -> bool {
|
||||
unlink(path) == 0;
|
||||
}
|
||||
|
||||
delete_dir :: (path: [:0]u8) -> bool {
|
||||
rmdir(path) == 0;
|
||||
}
|
||||
|
||||
create_dir :: (path: [:0]u8) -> bool {
|
||||
mkdir(path, 493) == 0; // 0o755 = 493
|
||||
}
|
||||
|
||||
set_mode :: (path: [:0]u8, mode: u32) -> bool {
|
||||
chmod(path, mode) == 0;
|
||||
}
|
||||
|
||||
move :: (oldp: [:0]u8, newp: [:0]u8) -> bool {
|
||||
rename(oldp, newp) == 0;
|
||||
}
|
||||
|
||||
// Recursive mkdir -p. Walks the path and creates each missing
|
||||
// segment. Treats existing directories as success.
|
||||
create_dir_all :: (path: [:0]u8) -> bool {
|
||||
if path.len == 0 { return true; }
|
||||
if exists(path) { return true; }
|
||||
last := path.len - 1;
|
||||
while last > 0 {
|
||||
if path[last] == 47 { break; }
|
||||
last -= 1;
|
||||
}
|
||||
if last > 0 {
|
||||
parent := cstring(last);
|
||||
memcpy(parent.ptr, path.ptr, last);
|
||||
if !create_dir_all(parent) { return false; }
|
||||
}
|
||||
create_dir(path);
|
||||
}
|
||||
|
||||
// Copy a file by streaming through a 64KB buffer. Uses libc directly
|
||||
// (not File methods) — same interpreter-compat reason as read_file.
|
||||
// No metadata is preserved beyond what `open` creates (mode 0644).
|
||||
// Caller is responsible for setting executable bits with `set_mode`.
|
||||
copy_file :: (src: [:0]u8, dst: [:0]u8) -> bool {
|
||||
src_fd := open(src, O_RDONLY, 0);
|
||||
if src_fd < 0 { return false; }
|
||||
dst_fd := open(dst, O_WRONLY | O_CREAT | O_TRUNC, 420);
|
||||
if dst_fd < 0 {
|
||||
close(src_fd);
|
||||
return false;
|
||||
}
|
||||
ok := true;
|
||||
buf := cstring(65536);
|
||||
loop := true;
|
||||
while loop {
|
||||
n := read(src_fd, buf.ptr, 65536);
|
||||
if n < 0 { ok = false; loop = false; }
|
||||
if n == 0 { loop = false; }
|
||||
if n > 0 {
|
||||
w := write(dst_fd, buf.ptr, xx n);
|
||||
if w != cast(isize) n { ok = false; loop = false; }
|
||||
}
|
||||
}
|
||||
close(src_fd);
|
||||
close(dst_fd);
|
||||
ok;
|
||||
}
|
||||
|
||||
// ── Path helpers ─────────────────────────────────────────────────────
|
||||
// `path_join` is in std.sx (used widely beyond fs). These are the
|
||||
// fs-adjacent helpers — basename/dirname operate purely on text.
|
||||
|
||||
basename :: (p: string) -> string {
|
||||
if p.len == 0 { return ""; }
|
||||
last := p.len - 1;
|
||||
while last > 0 {
|
||||
if p[last] != 47 { break; }
|
||||
last -= 1;
|
||||
}
|
||||
end := last + 1;
|
||||
while last > 0 {
|
||||
if p[last - 1] == 47 { return substr(p, last, end - last); }
|
||||
last -= 1;
|
||||
}
|
||||
substr(p, 0, end);
|
||||
}
|
||||
|
||||
dirname :: (p: string) -> string {
|
||||
if p.len == 0 { return ""; }
|
||||
last := p.len - 1;
|
||||
while last > 0 {
|
||||
if p[last] != 47 { break; }
|
||||
last -= 1;
|
||||
}
|
||||
while last > 0 {
|
||||
if p[last] == 47 {
|
||||
while last > 0 {
|
||||
if p[last - 1] != 47 { break; }
|
||||
last -= 1;
|
||||
}
|
||||
return substr(p, 0, last);
|
||||
}
|
||||
last -= 1;
|
||||
}
|
||||
if p[0] == 47 { return "/"; }
|
||||
".";
|
||||
}
|
||||
519
library/modules/platform/bundle.sx
Normal file
519
library/modules/platform/bundle.sx
Normal file
@@ -0,0 +1,519 @@
|
||||
#import "../std.sx";
|
||||
#import "../compiler.sx";
|
||||
#import "../fs.sx";
|
||||
#import "../process.sx";
|
||||
|
||||
// =====================================================================
|
||||
// platform.bundle — sx-side Apple `.app` bundler.
|
||||
//
|
||||
// Covers all three Apple targets from a single `bundle_main` entry:
|
||||
// macOS, iOS simulator, iOS device. Per-platform branching is keyed
|
||||
// off `BuildOptions.is_macos()` / `is_ios_simulator()` / `is_ios_device()`
|
||||
// so the bundle layout, Info.plist shape, framework embedding,
|
||||
// provisioning, entitlements, and codesigning ceremony all match what
|
||||
// the Zig `createBundle` used to produce.
|
||||
//
|
||||
// Wiring: users opt in by registering `bundle_main` as the post-link
|
||||
// callback in their own `#run` block. Example:
|
||||
//
|
||||
// #run {
|
||||
// opts := build_options();
|
||||
// opts.set_bundle_path("MyApp.app");
|
||||
// opts.set_bundle_id("co.example.myapp");
|
||||
// opts.set_post_link_callback(platform.bundle.bundle_main);
|
||||
// }
|
||||
// =====================================================================
|
||||
|
||||
bundle_main :: () -> bool {
|
||||
opts := build_options();
|
||||
binary := opts.binary_path();
|
||||
bundle := opts.bundle_path();
|
||||
bid := opts.bundle_id();
|
||||
|
||||
if bundle.len == 0 {
|
||||
// No bundle requested — nothing to do. Build succeeded.
|
||||
return true;
|
||||
}
|
||||
if bid.len == 0 {
|
||||
out("error: bundle requires bundle_id (set via set_bundle_id() or --bundle-id)\n");
|
||||
return false;
|
||||
}
|
||||
if binary.len == 0 {
|
||||
out("error: bundle: empty binary_path (compiler bug)\n");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Device builds without a real identity will be rejected by the
|
||||
// device, so fail fast with a clear hint — matches what the legacy
|
||||
// Zig path did at the top of createBundle.
|
||||
if opts.is_ios_device() {
|
||||
if opts.codesign_identity().len == 0 {
|
||||
out("error: --target ios requires --codesign-identity (e.g. \"Apple Development: ...\") and --provisioning-profile <path>\n");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bundle_z := str_to_cstr(bundle);
|
||||
|
||||
// Clean previous bundle. `rm -rf` via shell until fs.sx grows
|
||||
// `delete_dir_all`.
|
||||
rm_cmd := concat("rm -rf ", bundle);
|
||||
rm_z := str_to_cstr(rm_cmd);
|
||||
if r := run(rm_z) {
|
||||
if r.exit_code != 0 {
|
||||
out("error: bundle: failed to clean ");
|
||||
out(bundle);
|
||||
out("\n");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if !create_dir_all(bundle_z) {
|
||||
out("error: bundle: cannot create dir ");
|
||||
out(bundle);
|
||||
out("\n");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Copy the linked binary into the bundle as `<exe_name>`. Flat
|
||||
// layout (binary + Info.plist at bundle root) matches the legacy
|
||||
// Zig path for every Apple target — the canonical macOS
|
||||
// `Contents/MacOS/` layout is a follow-up.
|
||||
exe_name := basename(binary);
|
||||
binary_z := str_to_cstr(binary);
|
||||
exe_dest := concat(bundle, "/");
|
||||
exe_dest = concat(exe_dest, exe_name);
|
||||
exe_dest_z := str_to_cstr(exe_dest);
|
||||
if !copy_file(binary_z, exe_dest_z) {
|
||||
out("error: bundle: copy binary failed\n");
|
||||
return false;
|
||||
}
|
||||
set_mode(exe_dest_z, 493); // 0o755 = preserve executable bit
|
||||
|
||||
// Write Info.plist. Per-target shape — iOS needs UIDeviceFamily +
|
||||
// UIApplicationSceneManifest + DTPlatformName, macOS doesn't.
|
||||
plist := build_info_plist(opts, exe_name, bid);
|
||||
plist_path := concat(bundle, "/Info.plist");
|
||||
plist_path_z := str_to_cstr(plist_path);
|
||||
if !write_file(plist_path_z, plist) {
|
||||
out("error: bundle: write Info.plist failed\n");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Embed the provisioning profile if supplied. Required for device
|
||||
// installs; harmless (and usually omitted) elsewhere.
|
||||
profile := opts.provisioning_profile();
|
||||
if profile.len > 0 {
|
||||
if !embed_provisioning_profile(profile, bundle) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Copy any user-registered asset directories into the bundle.
|
||||
// Apple .app puts them at `<bundle>/<dest>/`. Android (Week 7) will
|
||||
// zip them into the APK at the same relative path. Recursive copy
|
||||
// shells out to `cp -R` until fs.sx grows `list_dir`.
|
||||
asset_count := opts.asset_dir_count();
|
||||
j : s64 = 0;
|
||||
while j < asset_count {
|
||||
src := opts.asset_dir_src_at(j);
|
||||
dest := opts.asset_dir_dest_at(j);
|
||||
if !copy_asset_dir(src, dest, bundle) {
|
||||
out("error: bundle: failed to copy asset dir '");
|
||||
out(src);
|
||||
out("'\n");
|
||||
return false;
|
||||
}
|
||||
j += 1;
|
||||
}
|
||||
|
||||
// iOS apps load dynamic frameworks from
|
||||
// `<bundle>.app/Frameworks/<Name>.framework/<Name>` via the
|
||||
// `@executable_path/Frameworks` rpath set at link time. Recursive
|
||||
// copy lives in `embed_framework` until fs.sx grows `list_dir`.
|
||||
if opts.is_ios() {
|
||||
fw_count := opts.framework_count();
|
||||
if fw_count > 0 {
|
||||
fw_dir := concat(bundle, "/Frameworks");
|
||||
fw_dir_z := str_to_cstr(fw_dir);
|
||||
if !create_dir_all(fw_dir_z) {
|
||||
out("error: bundle: cannot create Frameworks dir\n");
|
||||
return false;
|
||||
}
|
||||
i : s64 = 0;
|
||||
while i < fw_count {
|
||||
fw_name := opts.framework_at(i);
|
||||
if !embed_framework(opts, fw_name, fw_dir) {
|
||||
// embed_framework emits its own diagnostic; on
|
||||
// failure we print a warning (matching the legacy
|
||||
// Zig path) and continue — the link may still have
|
||||
// resolved the framework against the SDK.
|
||||
out("warning: framework '");
|
||||
out(fw_name);
|
||||
out("' not embedded; runtime load may fail\n");
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Codesign. Device builds need real identity + extracted
|
||||
// entitlements; sim/macOS default to ad-hoc ("-").
|
||||
identity := opts.codesign_identity();
|
||||
if identity.len == 0 { identity = "-"; }
|
||||
ent_path := "";
|
||||
if opts.is_ios_device() {
|
||||
if profile.len > 0 {
|
||||
if e := extract_entitlements(profile, bid) {
|
||||
ent_path = e;
|
||||
} else {
|
||||
out("error: bundle: failed to extract entitlements from provisioning profile\n");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
if !codesign(bundle, identity, ent_path) {
|
||||
return false;
|
||||
}
|
||||
|
||||
out("bundled: ");
|
||||
out(bundle);
|
||||
out("\n");
|
||||
true;
|
||||
}
|
||||
|
||||
// ── Helpers ──────────────────────────────────────────────────────────
|
||||
|
||||
// Copy a sx string (slice) into a freshly-allocated null-terminated
|
||||
// buffer for libc / `[:0]u8` callees. Allocated from
|
||||
// `context.allocator` like the rest of the bundling stage.
|
||||
str_to_cstr :: (s: string) -> [:0]u8 {
|
||||
buf := cstring(s.len);
|
||||
memcpy(buf.ptr, s.ptr, s.len);
|
||||
buf;
|
||||
}
|
||||
|
||||
// Minimum iOS version baked into the Info.plist — matches what the
|
||||
// Zig path emitted for years. Lift to a setter when a real consumer
|
||||
// needs a higher floor.
|
||||
IOS_MIN_OS : string : "14.0";
|
||||
|
||||
// Build the Info.plist body for the current target. iOS-shaped plists
|
||||
// carry the keys the iOS launcher needs (UIDeviceFamily,
|
||||
// LSRequiresIPhoneOS, UIApplicationSceneManifest, DTPlatformName,
|
||||
// MinimumOSVersion); macOS doesn't need any of those.
|
||||
build_info_plist :: (opts: BuildOptions, exe_name: string, bundle_id: string) -> string {
|
||||
if opts.is_ios() {
|
||||
platform_key := if opts.is_ios_simulator() then "iPhoneSimulator" else "iPhoneOS";
|
||||
return format(#string PLIST
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>{}</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>{}</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>{}</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>APPL</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>1</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>0.1</string>
|
||||
<key>MinimumOSVersion</key>
|
||||
<string>{}</string>
|
||||
<key>UIDeviceFamily</key>
|
||||
<array>
|
||||
<integer>1</integer>
|
||||
</array>
|
||||
<key>LSRequiresIPhoneOS</key>
|
||||
<true/>
|
||||
<key>UILaunchScreen</key>
|
||||
<dict/>
|
||||
<key>UIApplicationSceneManifest</key>
|
||||
<dict>
|
||||
<key>UIApplicationSupportsMultipleScenes</key>
|
||||
<false/>
|
||||
<key>UISceneConfigurations</key>
|
||||
<dict>
|
||||
<key>UIWindowSceneSessionRoleApplication</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>UISceneConfigurationName</key>
|
||||
<string>Default Configuration</string>
|
||||
<key>UISceneDelegateClassName</key>
|
||||
<string>SxSceneDelegate</string>
|
||||
</dict>
|
||||
</array>
|
||||
</dict>
|
||||
</dict>
|
||||
<key>DTPlatformName</key>
|
||||
<string>{}</string>
|
||||
</dict>
|
||||
</plist>
|
||||
PLIST, xml_escape(bundle_id), xml_escape(exe_name), xml_escape(exe_name), IOS_MIN_OS, platform_key);
|
||||
}
|
||||
|
||||
// macOS (and any non-iOS Apple target) — the minimal plist both
|
||||
// launchers will accept.
|
||||
format(#string PLIST
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>{}</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>{}</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>{}</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>APPL</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>1</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>0.1</string>
|
||||
</dict>
|
||||
</plist>
|
||||
PLIST, xml_escape(bundle_id), xml_escape(exe_name), xml_escape(exe_name));
|
||||
}
|
||||
|
||||
// Read a `.mobileprovision` and write it to
|
||||
// `<bundle>/embedded.mobileprovision`. iOS device installer rejects
|
||||
// the app without this file when a profile-bound identity is used.
|
||||
embed_provisioning_profile :: (profile: string, bundle: string) -> bool {
|
||||
profile_z := str_to_cstr(profile);
|
||||
if data := read_file(profile_z) {
|
||||
dest := concat(bundle, "/embedded.mobileprovision");
|
||||
dest_z := str_to_cstr(dest);
|
||||
if !write_file(dest_z, data) {
|
||||
out("error: bundle: failed to write embedded.mobileprovision\n");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
out("error: bundle: cannot read provisioning profile: ");
|
||||
out(profile);
|
||||
out("\n");
|
||||
false;
|
||||
}
|
||||
|
||||
// Recursive-copy `<src_dir>` (relative to the build CWD) into
|
||||
// `<bundle>/<dest>/`. Creates intermediate dirs as needed. Returns
|
||||
// true if `src_dir` doesn't exist (callers can register optional
|
||||
// asset trees without failing the build). Shells out to `cp -R`
|
||||
// because fs.sx Phase 1A doesn't expose `list_dir` / `walk` yet.
|
||||
copy_asset_dir :: (src: string, dest: string, bundle: string) -> bool {
|
||||
src_z := str_to_cstr(src);
|
||||
if !exists(src_z) {
|
||||
// Treating missing src as "nothing to do" lets a project
|
||||
// register `add_asset_dir("assets", "assets")` unconditionally
|
||||
// and only ship assets when the dir is present.
|
||||
return true;
|
||||
}
|
||||
dest_full := concat(bundle, "/");
|
||||
dest_full = concat(dest_full, dest);
|
||||
// Parent of dest_full must exist for `cp -R src dest_full` to
|
||||
// place src as dest_full's contents. We pre-create dest_full so cp
|
||||
// works in "copy src contents into existing dir" mode by appending
|
||||
// a trailing `/` to src.
|
||||
dest_full_z := str_to_cstr(dest_full);
|
||||
if !create_dir_all(dest_full_z) {
|
||||
out("error: bundle: cannot create asset dest '");
|
||||
out(dest_full);
|
||||
out("'\n");
|
||||
return false;
|
||||
}
|
||||
// `cp -R src/. dest/` copies the contents of src into dest. The
|
||||
// `.` is critical: `cp -R src/ dest/` on macOS BSD cp places src
|
||||
// *inside* dest as `dest/src/`, which is the wrong shape.
|
||||
cmd := concat("cp -R \"", src);
|
||||
cmd = concat(cmd, "/.\" \"");
|
||||
cmd = concat(cmd, dest_full);
|
||||
cmd = concat(cmd, "\" 2>&1");
|
||||
cmd_z := str_to_cstr(cmd);
|
||||
if r := run(cmd_z) {
|
||||
if r.exit_code != 0 {
|
||||
out("error: cp -R failed:\n");
|
||||
out(r.stdout);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
out("error: cp -R spawn failed\n");
|
||||
false;
|
||||
}
|
||||
|
||||
// Recursive-copy `<name>.framework` from one of the user's `-F` search
|
||||
// paths into `<dest_dir>`. Walks the framework paths in order; first
|
||||
// hit wins. Falls back to a `cp -R` subprocess because fs.sx Phase 1A
|
||||
// doesn't expose `list_dir` / `walk` yet.
|
||||
embed_framework :: (opts: BuildOptions, name: string, dest_dir: string) -> bool {
|
||||
subdir := concat(name, ".framework");
|
||||
path_count := opts.framework_path_count();
|
||||
i : s64 = 0;
|
||||
while i < path_count {
|
||||
base := opts.framework_path_at(i);
|
||||
candidate := concat(base, "/");
|
||||
candidate = concat(candidate, subdir);
|
||||
candidate_z := str_to_cstr(candidate);
|
||||
if exists(candidate_z) {
|
||||
dest := concat(dest_dir, "/");
|
||||
dest = concat(dest, subdir);
|
||||
// Shell-quoting is conservative — paths may contain
|
||||
// spaces (e.g. user's home dir on macOS). Wrap each path
|
||||
// in double quotes; we trust them not to contain `"`.
|
||||
cmd := concat("cp -R \"", candidate);
|
||||
cmd = concat(cmd, "\" \"");
|
||||
cmd = concat(cmd, dest);
|
||||
cmd = concat(cmd, "\"");
|
||||
cmd_z := str_to_cstr(cmd);
|
||||
if r := run(cmd_z) {
|
||||
if r.exit_code != 0 {
|
||||
out("error: cp -R ");
|
||||
out(candidate);
|
||||
out(" -> ");
|
||||
out(dest);
|
||||
out(" failed\n");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
out("error: cp -R failed to spawn\n");
|
||||
return false;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
false;
|
||||
}
|
||||
|
||||
// Extract entitlements XML from a `.mobileprovision` and resolve the
|
||||
// `application-identifier` wildcard (`<TEAM>.*`) to the concrete
|
||||
// bundle ID. Required for iOS device installs — without this
|
||||
// substitution the device installer rejects the app with
|
||||
// `MIInstallerErrorDomain error 13` / `0xe8008015`.
|
||||
// Writes the resolved entitlements to `.sx-tmp/entitlements.plist`
|
||||
// and returns that path on success.
|
||||
extract_entitlements :: (profile: string, bundle_id: string) -> ?string {
|
||||
sx_tmp := str_to_cstr(".sx-tmp");
|
||||
create_dir_all(sx_tmp);
|
||||
|
||||
profile_plist := ".sx-tmp/profile.plist";
|
||||
ent_path := ".sx-tmp/entitlements.plist";
|
||||
|
||||
// 1. security cms -D -i <profile> -o profile.plist
|
||||
cmd1 := concat("security cms -D -i \"", profile);
|
||||
cmd1 = concat(cmd1, "\" -o \"");
|
||||
cmd1 = concat(cmd1, profile_plist);
|
||||
cmd1 = concat(cmd1, "\" 2>&1");
|
||||
cmd1_z := str_to_cstr(cmd1);
|
||||
if r := run(cmd1_z) {
|
||||
if r.exit_code != 0 {
|
||||
out("error: failed to decode provisioning profile:\n");
|
||||
out(r.stdout);
|
||||
return null;
|
||||
}
|
||||
} else {
|
||||
out("error: security cms spawn failed\n");
|
||||
return null;
|
||||
}
|
||||
|
||||
// 2. plutil -extract Entitlements xml1 -o entitlements.plist profile.plist
|
||||
cmd2 := concat("plutil -extract Entitlements xml1 -o \"", ent_path);
|
||||
cmd2 = concat(cmd2, "\" \"");
|
||||
cmd2 = concat(cmd2, profile_plist);
|
||||
cmd2 = concat(cmd2, "\" 2>&1");
|
||||
cmd2_z := str_to_cstr(cmd2);
|
||||
if r := run(cmd2_z) {
|
||||
if r.exit_code != 0 {
|
||||
out("error: failed to extract entitlements:\n");
|
||||
out(r.stdout);
|
||||
return null;
|
||||
}
|
||||
} else {
|
||||
out("error: plutil extract spawn failed\n");
|
||||
return null;
|
||||
}
|
||||
|
||||
// 3. Read the team identifier from
|
||||
// `ApplicationIdentifierPrefix.0`. Using
|
||||
// `com.apple.developer.team-identifier` would confuse plutil —
|
||||
// dots in plutil paths are interpreted as path separators.
|
||||
cmd3 := concat("plutil -extract ApplicationIdentifierPrefix.0 raw -o - \"", profile_plist);
|
||||
cmd3 = concat(cmd3, "\"");
|
||||
cmd3_z := str_to_cstr(cmd3);
|
||||
team := "";
|
||||
if r := run(cmd3_z) {
|
||||
if r.exit_code != 0 {
|
||||
out("error: profile missing ApplicationIdentifierPrefix:\n");
|
||||
out(r.stdout);
|
||||
return null;
|
||||
}
|
||||
team = r.stdout;
|
||||
// Strip trailing whitespace.
|
||||
while team.len > 0 {
|
||||
last := team[team.len - 1];
|
||||
if last == 10 { team = substr(team, 0, team.len - 1); }
|
||||
else if last == 13 { team = substr(team, 0, team.len - 1); }
|
||||
else if last == 32 { team = substr(team, 0, team.len - 1); }
|
||||
else if last == 9 { team = substr(team, 0, team.len - 1); }
|
||||
else { break; }
|
||||
}
|
||||
} else {
|
||||
out("error: plutil ApplicationIdentifierPrefix spawn failed\n");
|
||||
return null;
|
||||
}
|
||||
if team.len == 0 {
|
||||
out("error: provisioning profile has empty ApplicationIdentifierPrefix\n");
|
||||
return null;
|
||||
}
|
||||
|
||||
// 4. plutil -replace application-identifier -string "<team>.<bundle_id>" entitlements.plist
|
||||
resolved_app_id := concat(team, ".");
|
||||
resolved_app_id = concat(resolved_app_id, bundle_id);
|
||||
cmd4 := concat("plutil -replace application-identifier -string \"", resolved_app_id);
|
||||
cmd4 = concat(cmd4, "\" \"");
|
||||
cmd4 = concat(cmd4, ent_path);
|
||||
cmd4 = concat(cmd4, "\" 2>&1");
|
||||
cmd4_z := str_to_cstr(cmd4);
|
||||
if r := run(cmd4_z) {
|
||||
if r.exit_code != 0 {
|
||||
out("error: failed to resolve application-identifier:\n");
|
||||
out(r.stdout);
|
||||
return null;
|
||||
}
|
||||
} else {
|
||||
out("error: plutil replace spawn failed\n");
|
||||
return null;
|
||||
}
|
||||
|
||||
ent_path;
|
||||
}
|
||||
|
||||
// Codesign the bundle. Empty `ent_path` means no `--entitlements`
|
||||
// flag (macOS / iOS-sim / ad-hoc). Folds stderr into stdout so a
|
||||
// failing run hands the user a useful diagnostic.
|
||||
codesign :: (bundle: string, identity: string, ent_path: string) -> bool {
|
||||
cmd := concat("codesign --force --sign \"", identity);
|
||||
cmd = concat(cmd, "\" --timestamp=none");
|
||||
if ent_path.len > 0 {
|
||||
cmd = concat(cmd, " --entitlements \"");
|
||||
cmd = concat(cmd, ent_path);
|
||||
cmd = concat(cmd, "\"");
|
||||
}
|
||||
cmd = concat(cmd, " \"");
|
||||
cmd = concat(cmd, bundle);
|
||||
cmd = concat(cmd, "\" 2>&1");
|
||||
cmd_z := str_to_cstr(cmd);
|
||||
if r := run(cmd_z) {
|
||||
if r.exit_code != 0 {
|
||||
out("error: codesign failed:\n");
|
||||
out(r.stdout);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
out("error: codesign spawn failed\n");
|
||||
false;
|
||||
}
|
||||
118
library/modules/process.sx
Normal file
118
library/modules/process.sx
Normal file
@@ -0,0 +1,118 @@
|
||||
#import "std.sx";
|
||||
|
||||
// =====================================================================
|
||||
// process.sx — subprocess + environment stdlib (POSIX backend).
|
||||
//
|
||||
// Scope (Phase 1A): one entry point `run(cmd)` that shells out to
|
||||
// /bin/sh, captures stdout, returns exit code + stdout. Plus
|
||||
// `env(name)` / `find_executable(name)`. The bundler uses these to
|
||||
// invoke `codesign`, `plutil`, `security`, `aapt2`, `javac`, `d8`,
|
||||
// `keytool`, `apksigner`.
|
||||
//
|
||||
// Roadmap: phase 1B replaces `popen` with `posix_spawn` + pipes so
|
||||
// we can capture stderr separately and pass argv without shell
|
||||
// quoting. Until then, callers responsible for quoting + use 2>&1
|
||||
// to fold stderr into the captured stream.
|
||||
// =====================================================================
|
||||
|
||||
libc :: #library "c";
|
||||
|
||||
// ── Low-level libc bindings ─────────────────────────────────────────
|
||||
|
||||
popen :: (cmd: [:0]u8, mode: [:0]u8) -> *void #foreign libc;
|
||||
pclose :: (stream: *void) -> s32 #foreign libc;
|
||||
fread :: (ptr: [*]u8, size: usize, nmemb: usize, stream: *void) -> usize #foreign libc;
|
||||
feof :: (stream: *void) -> s32 #foreign libc;
|
||||
getenv :: (name: [:0]u8) -> *u8 #foreign libc;
|
||||
strlen :: (s: *u8) -> usize #foreign libc;
|
||||
system :: (cmd: [:0]u8) -> s32 #foreign libc;
|
||||
|
||||
// ── Public types ─────────────────────────────────────────────────────
|
||||
|
||||
ProcessResult :: struct {
|
||||
/// Exit code as reported by `WEXITSTATUS(status)`. 0 = success.
|
||||
/// Note: doesn't distinguish "killed by signal" from "exited
|
||||
/// non-zero"; phase 1B will return a tagged union.
|
||||
exit_code: s32;
|
||||
stdout: string;
|
||||
}
|
||||
|
||||
// ── Public API ───────────────────────────────────────────────────────
|
||||
|
||||
// Run a shell command, capture stdout, wait for exit. Returns null if
|
||||
// the shell itself couldn't be spawned. A non-zero exit_code with
|
||||
// valid stdout means the command ran and exited non-zero — distinct
|
||||
// from spawn failure.
|
||||
//
|
||||
// `cmd` is interpreted by /bin/sh — callers MUST quote arguments
|
||||
// containing spaces or shell metacharacters. To capture stderr along
|
||||
// with stdout, append " 2>&1" to the command.
|
||||
run :: (cmd: [:0]u8) -> ?ProcessResult {
|
||||
f := popen(cmd, "r");
|
||||
if cast(s64) f == 0 { return null; }
|
||||
|
||||
out := "";
|
||||
buf := cstring(4096);
|
||||
loop := true;
|
||||
while loop {
|
||||
n := fread(buf.ptr, 1, 4096, f);
|
||||
if n == 0 { loop = false; }
|
||||
if n > 0 {
|
||||
chunk : string = ---;
|
||||
chunk.ptr = buf.ptr;
|
||||
chunk.len = cast(s64) n;
|
||||
out = concat(out, chunk);
|
||||
}
|
||||
}
|
||||
raw_status := pclose(f);
|
||||
if raw_status < 0 { return null; }
|
||||
// POSIX wait(2) status encoding: low byte = signal (if signaled),
|
||||
// next byte = exit code (if normally exited). For our MVP we just
|
||||
// surface the exit-code byte; the signal case is folded into the
|
||||
// non-zero return.
|
||||
exit_code := (raw_status >> 8) & 0xFF;
|
||||
if exit_code == 0 {
|
||||
if (raw_status & 0x7F) != 0 {
|
||||
// Killed by signal — surface as a non-zero exit.
|
||||
exit_code = 128 + (raw_status & 0x7F);
|
||||
}
|
||||
}
|
||||
ProcessResult.{ exit_code = exit_code, stdout = out };
|
||||
}
|
||||
|
||||
// Read an environment variable. Returns null if unset; an empty
|
||||
// string if set to "".
|
||||
env :: (name: [:0]u8) -> ?string {
|
||||
p := getenv(name);
|
||||
addr : s64 = xx p;
|
||||
if addr == 0 { return null; }
|
||||
n := strlen(p);
|
||||
if n == 0 { return ""; }
|
||||
buf := cstring(cast(s64) n);
|
||||
memcpy(buf.ptr, xx p, cast(s64) n);
|
||||
buf;
|
||||
}
|
||||
|
||||
// Locate an executable by walking `$PATH`. Returns the absolute path
|
||||
// to the first hit, or null if not found anywhere. Uses `command -v`
|
||||
// under the shell; cheap and matches what the bundler ultimately
|
||||
// shells out to anyway.
|
||||
find_executable :: (name: [:0]u8) -> ?string {
|
||||
// Compose `command -v <name>` — name is assumed shell-safe
|
||||
// (executable names like `codesign`, `javac`, `aapt2`).
|
||||
cmd := concat("command -v ", name);
|
||||
// Need null-terminated for popen.
|
||||
cmd_z := cstring(cmd.len);
|
||||
memcpy(cmd_z.ptr, cmd.ptr, cmd.len);
|
||||
if r := run(cmd_z) {
|
||||
if r.exit_code != 0 { return null; }
|
||||
// Strip the trailing newline that `command -v` emits.
|
||||
out := r.stdout;
|
||||
if out.len > 0 {
|
||||
if out[out.len - 1] == 10 { out = substr(out, 0, out.len - 1); }
|
||||
}
|
||||
if out.len == 0 { return null; }
|
||||
return out;
|
||||
}
|
||||
null;
|
||||
}
|
||||
@@ -152,6 +152,67 @@ substr :: (s: string, start: s64, len: s64) -> string {
|
||||
buf;
|
||||
}
|
||||
|
||||
// Replace XML special characters with their entity references. Used
|
||||
// when emitting Info.plist / AndroidManifest content from sx values
|
||||
// that may contain user-supplied text (bundle id, app name, etc).
|
||||
xml_escape :: (s: string) -> string {
|
||||
result := "";
|
||||
i := 0;
|
||||
seg_start := 0;
|
||||
while i < s.len {
|
||||
c := s[i];
|
||||
// 38='&', 60='<', 62='>', 34='"', 39='\''
|
||||
ent := "";
|
||||
if c == 38 { ent = "&"; }
|
||||
if c == 60 { ent = "<"; }
|
||||
if c == 62 { ent = ">"; }
|
||||
if c == 34 { ent = """; }
|
||||
if c == 39 { ent = "'"; }
|
||||
if ent.len > 0 {
|
||||
if i > seg_start {
|
||||
result = concat(result, substr(s, seg_start, i - seg_start));
|
||||
}
|
||||
result = concat(result, ent);
|
||||
seg_start = i + 1;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
if seg_start < s.len {
|
||||
result = concat(result, substr(s, seg_start, s.len - seg_start));
|
||||
}
|
||||
result;
|
||||
}
|
||||
|
||||
// Join path components with the POSIX separator ('/'). Skips empty
|
||||
// components and collapses duplicate separators at component
|
||||
// boundaries. Used for bundle paths where Apple .app and Android APK
|
||||
// both expect POSIX-style paths.
|
||||
path_join :: (parts: ..string) -> string {
|
||||
result := "";
|
||||
i := 0;
|
||||
while i < parts.len {
|
||||
p := parts[i];
|
||||
if p.len > 0 {
|
||||
if result.len > 0 {
|
||||
tail := result[result.len - 1];
|
||||
head := p[0];
|
||||
if tail == 47 {
|
||||
if head == 47 {
|
||||
p = substr(p, 1, p.len - 1);
|
||||
}
|
||||
} else {
|
||||
if head != 47 {
|
||||
result = concat(result, "/");
|
||||
}
|
||||
}
|
||||
}
|
||||
result = concat(result, p);
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
result;
|
||||
}
|
||||
|
||||
struct_to_string :: (s: $T) -> string {
|
||||
result := concat(type_name(T), "{");
|
||||
i := 0;
|
||||
|
||||
Reference in New Issue
Block a user