nsh-cli 0.1.0

The nsh command line tool: build, package and run apps.
Documentation
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
//! `nsh package`: builds an installable app from the prebuilt runtime, the
//! app bundle and its assets. Needs no Rust; iOS packaging uses Xcode's
//! command line tools (`codesign`, and `actool` for icons), macOS packaging
//! `codesign` and `sips`, Linux packaging `tar`; Windows packaging needs
//! nothing (`windows.rs`). GPUI packages are made as the native backend's
//! of the machine they are made on, with the GPUI release runner.

use std::{
    fs,
    path::{Path, PathBuf},
    process::{Command, Stdio},
};

use anyhow::{Context as _, bail};
use serde::Deserialize;

use crate::{
    runtime::{self, Platform},
    ui,
};

/// Where the app runs.
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub(crate) enum PackageTarget {
    /// iOS devices: a signed `.ipa` (or an unsigned `.app` without `--sign`).
    Ios,
    /// The iOS simulator: an ad hoc signed `.app`.
    IosSimulator,
    /// Android: a signed `.apk`.
    Android,
    /// Linux (GTK): a directory with the runner, the bundle and a `.desktop`
    /// file, and the same as a `.tar.gz`.
    Linux,
    /// macOS (AppKit): an ad hoc signed `.app`.
    Macos,
    /// Windows: a directory with the runner as `<name>.exe` (the app's
    /// icon embedded) and the bundle, and the same as a `.zip`.
    Windows,
    /// GPUI, for this machine's OS: packaged as `linux`, `macos` or
    /// `windows` are, with the GPUI release runner.
    Gpui,
}

impl PackageTarget {
    /// The desktop package `nsh package --target gpui` makes on this
    /// machine, by its OS (`None` off macOS, Windows and Linux).
    fn gpui_layout() -> Option<PackageTarget> {
        if cfg!(target_os = "macos") {
            Some(PackageTarget::Macos)
        } else if cfg!(windows) {
            Some(PackageTarget::Windows)
        } else if cfg!(target_os = "linux") {
            Some(PackageTarget::Linux)
        } else {
            None
        }
    }
}

/// App metadata: `nsh.json` next to the entry, overridden by flags.
#[derive(Debug, Default, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub(crate) struct AppConfig {
    /// Display name.
    pub(crate) name: Option<String>,
    /// Bundle identifier (`com.example.app`).
    pub(crate) id: Option<String>,
    /// User-visible version (`1.2.0`).
    pub(crate) version: Option<String>,
    /// Build number.
    pub(crate) build: Option<u32>,
    /// App icon: a square PNG, ideally 1024×1024, relative to `nsh.json`.
    pub(crate) icon: Option<PathBuf>,
    /// Read and checked by the bundler.
    #[serde(default, rename = "tailwind")]
    _tailwind: Option<serde::de::IgnoredAny>,
    /// Read and checked by the bundler.
    #[serde(default, rename = "capabilities")]
    _capabilities: Option<serde::de::IgnoredAny>,
    /// `"light"` / `"dark"` / `"system"`: the app's appearance (checked by
    /// the bundler, which hands it to the runtime); packages also start in
    /// it (the launch screen, the window's theme).
    pub(crate) appearance: Option<String>,
    /// Read and checked by the bundler.
    #[serde(default, rename = "theme")]
    _theme: Option<serde::de::IgnoredAny>,
    /// The app's Rust crate: its builds are the app's own (`rust_app.rs`).
    #[serde(default, rename = "rust")]
    _rust: Option<serde::de::IgnoredAny>,
}

/// Options of `nsh package`.
pub(crate) struct PackageOptions<'a> {
    pub(crate) entry: &'a Path,
    pub(crate) target: PackageTarget,
    pub(crate) out: &'a Path,
    pub(crate) config: AppConfig,
    /// Code signing identity (device builds).
    pub(crate) sign: Option<&'a str>,
    /// Provisioning profile (device builds).
    pub(crate) profile: Option<&'a Path>,
    /// Android release keystore, key alias and password.
    pub(crate) keystore: Option<(&'a Path, &'a str, &'a str)>,
    /// Install and launch in the simulator or on the device afterwards
    /// (Linux, macOS, Windows: launch it).
    pub(crate) run: bool,
}

/// Reads `nsh.json` next to `entry`, if any; relative paths become absolute.
pub(crate) fn read_config(entry: &Path) -> anyhow::Result<AppConfig> {
    let dir = entry.parent().unwrap_or(Path::new("."));
    let path = dir.join("nsh.json");
    let Ok(text) = fs::read_to_string(&path) else {
        return Ok(AppConfig::default());
    };
    let mut config: AppConfig =
        serde_json::from_str(&text).with_context(|| format!("invalid {}", path.display()))?;
    config.icon = config.icon.map(|icon| dir.join(icon));
    Ok(config)
}

/// The app's display name and id: from the config, else the entry's
/// directory name and `com.example.<name>`.
pub(crate) fn name_and_id(entry: &Path, config: &AppConfig) -> (String, String) {
    let name = config.name.clone().unwrap_or_else(|| {
        entry
            .parent()
            .and_then(|d| d.file_name())
            .map(|n| n.to_string_lossy().into_owned())
            .unwrap_or_else(|| "App".to_owned())
    });
    let id = config.id.clone().unwrap_or_else(|| {
        let slug: String = name
            .chars()
            .filter(|c| c.is_ascii_alphanumeric())
            .collect::<String>()
            .to_lowercase();
        format!("com.example.{slug}")
    });
    (name, id)
}

pub(crate) fn package(options: PackageOptions<'_>) -> anyhow::Result<()> {
    let entry = dunce::canonicalize(options.entry)?;
    let config = &options.config;
    let (name, id) = name_and_id(&entry, config);
    let executable: String = name.chars().filter(|c| c.is_ascii_alphanumeric()).collect();
    let executable = if executable.is_empty() {
        "App".to_owned()
    } else {
        executable
    };

    let built = crate::build::compile(&entry, true).map_err(|e| e.into_error(&entry))?;
    ui::done(format!("built {} {}", ui::path(&entry), built.summary("")));
    // GPUI apps are packaged as this OS's native ones, with another runner.
    let (target, runner) = match options.target {
        PackageTarget::Gpui => (
            PackageTarget::gpui_layout()
                .context("GPUI apps are packaged on macOS, Windows or Linux")?,
            Platform::Gpui,
        ),
        PackageTarget::Linux => (PackageTarget::Linux, Platform::Linux),
        PackageTarget::Macos => (PackageTarget::Macos, Platform::MacOs),
        PackageTarget::Windows => (PackageTarget::Windows, Platform::Windows),
        other => (other, Platform::IphoneOs),
    };
    let platform = match target {
        PackageTarget::Ios => Platform::IphoneOs,
        PackageTarget::IosSimulator => Platform::IphoneSimulator,
        PackageTarget::Android => {
            return package_android(&options, config, &name, &id, &built);
        }
        PackageTarget::Linux => {
            let app = App {
                name: &name,
                id: &id,
                executable: &executable,
                runner,
            };
            return package_linux(&options, config, &app, &built);
        }
        PackageTarget::Macos => {
            let app = App {
                name: &name,
                id: &id,
                executable: &executable,
                runner,
            };
            return package_macos(&options, config, &app, &built);
        }
        PackageTarget::Windows => {
            return crate::windows::package(&options, config, &name, &id, runner, &built);
        }
        PackageTarget::Gpui => unreachable!("packaged as this OS's apps are"),
    };
    let runner = runtime::file(platform, true)?;

    fs::create_dir_all(options.out)?;
    let app = options.out.join(format!("{name}.app"));
    if app.exists() {
        fs::remove_dir_all(&app)?;
    }
    let resources = app.join("nsh");
    fs::create_dir_all(&resources)?;
    fs::copy(&runner, app.join(&executable))
        .with_context(|| format!("copy {}", runner.display()))?;
    fs::write(resources.join("bundle.nshc"), &built.bytecode)?;
    if let Some(json) = built.capabilities_json() {
        fs::write(resources.join("capabilities.json"), json)?;
    }
    for asset in &built.assets {
        let dest = resources.join("assets").join(&asset.path);
        if let Some(dir) = dest.parent() {
            fs::create_dir_all(dir)?;
        }
        fs::copy(&asset.source, &dest).with_context(|| format!("copy {}", asset.path))?;
    }

    let sdk = match options.target {
        PackageTarget::Ios => "iphoneos",
        PackageTarget::IosSimulator
        | PackageTarget::Android
        | PackageTarget::Linux
        | PackageTarget::Macos
        | PackageTarget::Windows
        | PackageTarget::Gpui => "iphonesimulator",
    };
    let mut info = info_plist(&name, &id, &executable, config, sdk);
    if let Some(icon) = &config.icon {
        let partial = compile_icon(icon, &app, sdk)?;
        for (key, value) in partial {
            info.insert(key, value);
        }
    }
    plist::Value::Dictionary(info).to_file_xml(app.join("Info.plist"))?;

    match options.target {
        PackageTarget::IosSimulator => {
            codesign(&app, "-", None)?;
            ui::done(format!("packaged {}", ui::path(&app)));
            if options.run {
                let udid = crate::run::simulator(None)?;
                let step = ui::Step::start(format!("installing {id} in the simulator"));
                crate::run::simctl(&["install", &udid, &app.to_string_lossy()])?;
                crate::run::simctl(&["launch", "--terminate-running-process", &udid, &id])?;
                step.done(format!("launched {id} in the simulator"));
            }
        }
        PackageTarget::Android
        | PackageTarget::Linux
        | PackageTarget::Macos
        | PackageTarget::Windows
        | PackageTarget::Gpui => {
            unreachable!("packaged above")
        }
        PackageTarget::Ios => {
            if options.run {
                bail!("--run only applies to the simulator and Android");
            }
            let (Some(identity), Some(profile)) = (options.sign, options.profile) else {
                ui::warn(format!(
                    "{} is unsigned: pass --sign <identity> and --profile <file.mobileprovision> to install it on devices",
                    ui::path(&app)
                ));
                return Ok(());
            };
            fs::copy(profile, app.join("embedded.mobileprovision"))
                .with_context(|| format!("copy {}", profile.display()))?;
            let entitlements = entitlements(profile, &id)?;
            let path = options.out.join(format!("{executable}.entitlements"));
            entitlements.to_file_xml(&path)?;
            codesign(&app, identity, Some(&path))?;
            let ipa = options.out.join(format!("{name}.ipa"));
            make_ipa(&app, &ipa)?;
            ui::done(format!("packaged {}", ui::path(&ipa)));
        }
    }
    Ok(())
}

/// A desktop app to package: its name, id, executable file name and
/// release runner (the native backend's or GPUI's).
#[derive(Clone, Copy)]
struct App<'a> {
    name: &'a str,
    id: &'a str,
    executable: &'a str,
    runner: Platform,
}

/// An APK with the release runtime: `AppActivity` runs `assets/nsh/bundle.nshc`.
fn package_android(
    options: &PackageOptions<'_>,
    config: &AppConfig,
    name: &str,
    id: &str,
    built: &crate::build::Built,
) -> anyhow::Result<()> {
    use crate::android::{self, Apk, Signing};
    let sdk = android::Sdk::find()?;
    let runtime = runtime::android(false)?;
    let mut assets = vec![("nsh/bundle.nshc".to_owned(), built.bytecode.clone())];
    if let Some(json) = built.capabilities_json() {
        assets.push(("nsh/capabilities.json".to_owned(), json.into_bytes()));
    }
    for asset in &built.assets {
        let bytes = fs::read(&asset.source).with_context(|| format!("read {}", asset.path))?;
        assets.push((format!("nsh/assets/{}", asset.path), bytes));
    }
    let signing = match options.keystore {
        Some((path, alias, password)) => Signing::Keystore {
            path: path.to_path_buf(),
            alias: alias.to_owned(),
            password: password.to_owned(),
        },
        None => {
            ui::warn("signing with the debug key: pass --keystore for store releases");
            Signing::Debug
        }
    };
    fs::create_dir_all(options.out)?;
    let apk_path = options.out.join(format!("{name}.apk"));
    let version = config.version.as_deref().unwrap_or("1.0.0");
    let step = ui::Step::start(format!("packaging {}", ui::path(&apk_path)));
    android::build_apk(
        &sdk,
        &Apk {
            package: id,
            label: name,
            version_name: version,
            version_code: config.build.unwrap_or(1),
            activity: "com.longbridge.nsh.AppActivity",
            dev: false,
            dark: config.appearance.as_deref() == Some("dark"),
            runtime: &runtime,
            icon: config.icon.as_deref(),
            assets,
            signing,
        },
        &apk_path,
    )?;
    step.done(format!("packaged {}", ui::path(&apk_path)));
    if options.run {
        let serial = android::device(&sdk)?;
        let step = ui::Step::start(format!("installing {id} on {serial}"));
        android::adb(
            &sdk,
            &serial,
            &["install", "-r", &apk_path.to_string_lossy()],
        )?;
        android::adb(
            &sdk,
            &serial,
            &[
                "shell",
                "am",
                "start",
                "-n",
                &format!("{id}/com.longbridge.nsh.AppActivity"),
            ],
        )?;
        step.done(format!("launched {id} on {serial}"));
    }
    Ok(())
}

/// A directory `<out>/<name>`: the release runner as `<executable>`, the
/// bundle and assets in `nsh/` (where the runner looks, next to itself),
/// `nsh/app.json` (the window's title, the application id and the app's
/// appearance, which the window opens in), a
/// `<id>.desktop` entry and the icon; then the same as `<name>.tar.gz`.
fn package_linux(
    options: &PackageOptions<'_>,
    config: &AppConfig,
    app: &App<'_>,
    built: &crate::build::Built,
) -> anyhow::Result<()> {
    let App {
        name,
        id,
        executable,
        runner,
    } = *app;
    let runner = runtime::file(runner, true)?;
    let dir = options.out.join(name);
    let step = ui::Step::start(format!("packaging {}", ui::path(&dir)));
    if dir.exists() {
        fs::remove_dir_all(&dir)?;
    }
    let resources = dir.join("nsh");
    fs::create_dir_all(&resources)?;
    fs::copy(&runner, dir.join(executable))
        .with_context(|| format!("copy {}", runner.display()))?;
    fs::write(resources.join("bundle.nshc"), &built.bytecode)?;
    if let Some(json) = built.capabilities_json() {
        fs::write(resources.join("capabilities.json"), json)?;
    }
    for asset in &built.assets {
        let dest = resources.join("assets").join(&asset.path);
        if let Some(parent) = dest.parent() {
            fs::create_dir_all(parent)?;
        }
        fs::copy(&asset.source, &dest).with_context(|| format!("copy {}", asset.path))?;
    }
    let version = config.version.as_deref().unwrap_or("1.0.0");
    let mut info = serde_json::json!({ "name": name, "id": id, "version": version });
    if let Some(appearance) = &config.appearance {
        info["appearance"] = appearance.as_str().into();
    }
    fs::write(resources.join("app.json"), info.to_string())?;
    if let Some(icon) = &config.icon {
        fs::copy(icon, dir.join(format!("{id}.png")))
            .with_context(|| format!("copy {}", icon.display()))?;
    }
    fs::write(
        dir.join(format!("{id}.desktop")),
        desktop_entry(name, id, executable, config.icon.is_some()),
    )?;
    let archive = options.out.join(format!("{name}.tar.gz"));
    let _ = fs::remove_file(&archive);
    let output = Command::new("tar")
        .arg("-czf")
        .arg(&archive)
        .arg("-C")
        .arg(options.out)
        .arg(name)
        .output()
        .context("run tar")?;
    if !output.status.success() {
        bail!(
            "creating {} failed: {}",
            archive.display(),
            String::from_utf8_lossy(&output.stderr).trim()
        );
    }
    step.done(format!(
        "packaged {} and {}",
        ui::path(&dir),
        ui::path(&archive)
    ));
    if options.run {
        let exe = dir.join(executable);
        Command::new(&exe)
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .spawn()
            .with_context(|| format!("launch {}", exe.display()))?;
        ui::done(format!("launched {name}"));
    }
    Ok(())
}

/// `<out>/<name>.app`, a macOS app bundle: the release runner as
/// `Contents/MacOS/<executable>`, the bundle and assets in
/// `Contents/Resources/nsh/` (where the runner looks), `nsh/app.json` (the
/// window's title and the app's appearance, which the window opens in),
/// the icon as `AppIcon.icns`; signed ad hoc (Apple silicon runs no
/// unsigned code; distribute it signed with a Developer ID instead).
fn package_macos(
    options: &PackageOptions<'_>,
    config: &AppConfig,
    app: &App<'_>,
    built: &crate::build::Built,
) -> anyhow::Result<()> {
    let App {
        name,
        id,
        executable,
        runner,
    } = *app;
    let runner = runtime::file(runner, true)?;
    let app = options.out.join(format!("{name}.app"));
    let step = ui::Step::start(format!("packaging {}", ui::path(&app)));
    if app.exists() {
        fs::remove_dir_all(&app)?;
    }
    let contents = app.join("Contents");
    let macos = contents.join("MacOS");
    let resources = contents.join("Resources");
    let nsh = resources.join("nsh");
    fs::create_dir_all(&macos)?;
    fs::create_dir_all(&nsh)?;
    fs::copy(&runner, macos.join(executable))
        .with_context(|| format!("copy {}", runner.display()))?;
    fs::write(nsh.join("bundle.nshc"), &built.bytecode)?;
    if let Some(json) = built.capabilities_json() {
        fs::write(nsh.join("capabilities.json"), json)?;
    }
    for asset in &built.assets {
        let dest = nsh.join("assets").join(&asset.path);
        if let Some(parent) = dest.parent() {
            fs::create_dir_all(parent)?;
        }
        fs::copy(&asset.source, &dest).with_context(|| format!("copy {}", asset.path))?;
    }
    let version = config.version.as_deref().unwrap_or("1.0.0");
    let mut info = serde_json::json!({ "name": name, "id": id, "version": version });
    if let Some(appearance) = &config.appearance {
        info["appearance"] = appearance.as_str().into();
    }
    fs::write(nsh.join("app.json"), info.to_string())?;
    let icon = match &config.icon {
        Some(icon) => {
            macos_icns(icon, &resources.join("AppIcon.icns"))?;
            true
        }
        None => false,
    };
    plist::Value::Dictionary(macos_info_plist(name, id, executable, config, icon))
        .to_file_xml(contents.join("Info.plist"))
        .context("write Info.plist")?;
    let output = Command::new("codesign")
        .args(["--force", "--sign", "-", "--timestamp=none"])
        .arg(&app)
        .output()
        .context("run codesign")?;
    if !output.status.success() {
        bail!(
            "codesign failed for {}: {}",
            app.display(),
            String::from_utf8_lossy(&output.stderr).trim()
        );
    }
    step.done(format!("packaged {}", ui::path(&app)));
    if options.run {
        let status = Command::new("open")
            .arg(&app)
            .status()
            .context("run open")?;
        if !status.success() {
            bail!("cannot open {}", app.display());
        }
        ui::done(format!("launched {name}"));
    }
    Ok(())
}

/// Converts `icon` (a PNG) to `icns`: an iconset of every size macOS
/// uses, scaled by `sips`, packed by `iconutil`. `sips -s format icns`
/// alone fails on 1024-pixel images, the size app icons are drawn at.
fn macos_icns(icon: &Path, icns: &Path) -> anyhow::Result<()> {
    let set = icns.with_extension("iconset");
    fs::create_dir_all(&set)?;
    let run = |cmd: &mut Command, what: &str| -> anyhow::Result<()> {
        let output = cmd.output().with_context(|| format!("run {what}"))?;
        if !output.status.success() {
            bail!(
                "converting {} to an icon failed ({what}): {}",
                icon.display(),
                String::from_utf8_lossy(&output.stderr).trim()
            );
        }
        Ok(())
    };
    let result = (|| {
        for size in [16u32, 32, 128, 256, 512] {
            for (scale, suffix) in [(1, ""), (2, "@2x")] {
                let px = (size * scale).to_string();
                run(
                    Command::new("sips")
                        .args(["-s", "format", "png", "-z", &px, &px])
                        .arg(icon)
                        .arg("--out")
                        .arg(set.join(format!("icon_{size}x{size}{suffix}.png"))),
                    "sips",
                )?;
            }
        }
        run(
            Command::new("iconutil")
                .args(["-c", "icns"])
                .arg(&set)
                .arg("-o")
                .arg(icns),
            "iconutil",
        )
    })();
    let _ = fs::remove_dir_all(&set);
    result
}

/// The `Info.plist` of a macOS app.
fn macos_info_plist(
    name: &str,
    id: &str,
    executable: &str,
    config: &AppConfig,
    icon: bool,
) -> plist::Dictionary {
    use plist::Value;
    let mut d = plist::Dictionary::new();
    let s = |v: &str| Value::String(v.to_owned());
    d.insert("CFBundleDevelopmentRegion".into(), s("en"));
    d.insert("CFBundleExecutable".into(), s(executable));
    d.insert("CFBundleIdentifier".into(), s(id));
    d.insert("CFBundleName".into(), s(name));
    d.insert("CFBundleDisplayName".into(), s(name));
    d.insert("CFBundlePackageType".into(), s("APPL"));
    d.insert(
        "CFBundleShortVersionString".into(),
        s(config.version.as_deref().unwrap_or("1.0.0")),
    );
    d.insert(
        "CFBundleVersion".into(),
        s(&config.build.unwrap_or(1).to_string()),
    );
    d.insert(
        "CFBundleSupportedPlatforms".into(),
        Value::Array(vec![s("MacOSX")]),
    );
    d.insert("LSMinimumSystemVersion".into(), s(MACOS_MINIMUM));
    d.insert("NSHighResolutionCapable".into(), true.into());
    d.insert("NSPrincipalClass".into(), s("NSApplication"));
    if icon {
        d.insert("CFBundleIconFile".into(), s("AppIcon"));
    }
    d
}

/// The oldest macOS the AppKit runtime runs on (its display links are
/// `NSView`'s, new in macOS 14).
const MACOS_MINIMUM: &str = "14.0";

/// The app's desktop entry. Desktops match windows to it by the file's
/// name and `StartupWMClass`, which GTK sets from the application id.
/// `Exec` names the executable on the `PATH` (install the package
/// directory, or a link to the executable, there).
fn desktop_entry(name: &str, id: &str, executable: &str, icon: bool) -> String {
    let icon = if icon {
        format!("Icon={id}\n")
    } else {
        String::new()
    };
    format!(
        "[Desktop Entry]\nType=Application\nName={name}\nExec={executable}\n{icon}StartupWMClass={id}\nTerminal=false\nCategories=Utility;\n"
    )
}

fn info_plist(
    name: &str,
    id: &str,
    executable: &str,
    config: &AppConfig,
    sdk: &str,
) -> plist::Dictionary {
    use plist::Value;
    let mut d = plist::Dictionary::new();
    let s = |v: &str| Value::String(v.to_owned());
    d.insert("CFBundleDevelopmentRegion".into(), s("en"));
    d.insert("CFBundleExecutable".into(), s(executable));
    d.insert("CFBundleIdentifier".into(), s(id));
    d.insert("CFBundleName".into(), s(name));
    d.insert("CFBundleDisplayName".into(), s(name));
    d.insert("CFBundlePackageType".into(), s("APPL"));
    d.insert(
        "CFBundleShortVersionString".into(),
        s(config.version.as_deref().unwrap_or("1.0.0")),
    );
    d.insert(
        "CFBundleVersion".into(),
        s(&config.build.unwrap_or(1).to_string()),
    );
    d.insert(
        "CFBundleSupportedPlatforms".into(),
        Value::Array(vec![s(if sdk == "iphoneos" {
            "iPhoneOS"
        } else {
            "iPhoneSimulator"
        })]),
    );
    d.insert("MinimumOSVersion".into(), s(MINIMUM_OS));
    d.insert(
        "UIDeviceFamily".into(),
        Value::Array(vec![1.into(), 2.into()]),
    );
    d.insert("LSRequiresIPhoneOS".into(), true.into());
    // A launch screen entry opts into the full screen (no letterboxing).
    d.insert(
        "UILaunchScreen".into(),
        Value::Dictionary(Default::default()),
    );
    d.insert("UIApplicationSupportsMultipleScenes".into(), false.into());
    // The app's own appearance, from the launch screen on.
    match config.appearance.as_deref() {
        Some("light") => d.insert("UIUserInterfaceStyle".into(), s("Light")),
        Some("dark") => d.insert("UIUserInterfaceStyle".into(), s("Dark")),
        _ => None,
    };
    d.insert(
        "UISupportedInterfaceOrientations".into(),
        Value::Array(vec![
            s("UIInterfaceOrientationPortrait"),
            s("UIInterfaceOrientationLandscapeLeft"),
            s("UIInterfaceOrientationLandscapeRight"),
        ]),
    );
    d.insert(
        "UISupportedInterfaceOrientations~ipad".into(),
        Value::Array(vec![
            s("UIInterfaceOrientationPortrait"),
            s("UIInterfaceOrientationPortraitUpsideDown"),
            s("UIInterfaceOrientationLandscapeLeft"),
            s("UIInterfaceOrientationLandscapeRight"),
        ]),
    );
    d
}

/// The deployment target the runtime is built for (`cargo xtask dist`).
const MINIMUM_OS: &str = "15.0";

/// Compiles `icon` into the app's asset catalog (`Assets.car`) with
/// `actool`, returning the Info.plist keys it produces.
fn compile_icon(icon: &Path, app: &Path, sdk: &str) -> anyhow::Result<plist::Dictionary> {
    let work = app.with_extension("xcassets-work");
    let set = work.join("Assets.xcassets/AppIcon.appiconset");
    fs::create_dir_all(&set)?;
    fs::copy(icon, set.join("icon.png")).with_context(|| format!("copy {}", icon.display()))?;
    fs::write(
        work.join("Assets.xcassets/Contents.json"),
        r#"{"info":{"author":"nsh","version":1}}"#,
    )?;
    // One 1024 pt image; actool derives every size (Xcode 14+ catalogs).
    fs::write(
        set.join("Contents.json"),
        r#"{"images":[{"filename":"icon.png","idiom":"universal","platform":"ios","size":"1024x1024"}],"info":{"author":"nsh","version":1}}"#,
    )?;
    let partial = work.join("partial.plist");
    let output = Command::new("xcrun")
        .args(["actool", "--compile"])
        .arg(app)
        .args(["--platform", sdk, "--minimum-deployment-target", MINIMUM_OS])
        .args(["--app-icon", "AppIcon", "--output-partial-info-plist"])
        .arg(&partial)
        .args([
            "--target-device",
            "iphone",
            "--target-device",
            "ipad",
            "--output-format",
            "human-readable-text",
        ])
        .arg(work.join("Assets.xcassets"))
        .output()
        .context("run xcrun actool (is Xcode installed?)")?;
    if !output.status.success() || !partial.exists() {
        bail!(
            "actool failed: {}{}",
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr)
        );
    }
    let keys = plist::Value::from_file(&partial)?
        .into_dictionary()
        .unwrap_or_default();
    fs::remove_dir_all(&work)?;
    Ok(keys)
}

fn codesign(app: &Path, identity: &str, entitlements: Option<&Path>) -> anyhow::Result<()> {
    let mut cmd = Command::new("codesign");
    cmd.args(["--force", "--sign", identity]);
    if identity == "-" {
        cmd.arg("--timestamp=none");
    }
    if let Some(e) = entitlements {
        cmd.arg("--entitlements").arg(e);
    }
    let output = cmd
        .arg(app)
        .stdout(Stdio::null())
        .output()
        .context("run codesign")?;
    if !output.status.success() {
        bail!(
            "codesign failed: {}",
            String::from_utf8_lossy(&output.stderr).trim()
        );
    }
    Ok(())
}

/// The entitlements a provisioning profile grants, checked against `id`.
fn entitlements(profile: &Path, id: &str) -> anyhow::Result<plist::Value> {
    let output = Command::new("security")
        .args(["cms", "-D", "-i"])
        .arg(profile)
        .output()
        .context("run security cms")?;
    if !output.status.success() {
        bail!("cannot read provisioning profile {}", profile.display());
    }
    let profile = plist::Value::from_reader_xml(output.stdout.as_slice())?;
    let entitlements = profile
        .as_dictionary()
        .and_then(|d| d.get("Entitlements"))
        .cloned()
        .context("the provisioning profile has no entitlements")?;
    let app_id = entitlements
        .as_dictionary()
        .and_then(|d| d.get("application-identifier"))
        .and_then(|v| v.as_string())
        .unwrap_or_default();
    if !profile_allows(app_id, id) {
        bail!("the provisioning profile is for {app_id}, not {id}");
    }
    Ok(entitlements)
}

/// Whether a profile's `application-identifier` (`TEAMID.com.example.app`,
/// or a wildcard such as `TEAMID.*`) covers bundle id `id`.
fn profile_allows(app_id: &str, id: &str) -> bool {
    app_id
        .split_once('.')
        .map(|(_, pattern)| match pattern.strip_suffix('*') {
            Some(prefix) => id.starts_with(prefix),
            None => pattern == id,
        })
        .unwrap_or(false)
}

/// `Payload/<App>.app` zipped, keeping permissions and symlinks.
fn make_ipa(app: &Path, ipa: &Path) -> anyhow::Result<()> {
    let staging = ipa.with_extension("payload");
    let payload = staging.join("Payload");
    if staging.exists() {
        fs::remove_dir_all(&staging)?;
    }
    fs::create_dir_all(&payload)?;
    let status = Command::new("ditto")
        .arg(app)
        .arg(payload.join(app.file_name().context("app name")?))
        .status()?;
    if !status.success() {
        bail!("copying the app failed");
    }
    let _ = fs::remove_file(ipa);
    // `--keepParent`: entries start with `Payload/`; `--norsrc`: no
    // `__MACOSX/` resource forks.
    let status = Command::new("ditto")
        .args(["-c", "-k", "--norsrc", "--keepParent"])
        .arg(&payload)
        .arg(ipa)
        .status()?;
    fs::remove_dir_all(&staging)?;
    if !status.success() {
        bail!("creating {} failed", ipa.display());
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    /// App icons are drawn at 1024 pixels, which `sips` alone cannot
    /// convert.
    #[cfg(target_os = "macos")]
    #[test]
    fn converts_large_icons() {
        let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
        let dir = std::env::temp_dir().join(format!("nsh-icns-{}", std::process::id()));
        fs::create_dir_all(&dir).unwrap();
        let icns = dir.join("AppIcon.icns");
        macos_icns(&root.join("examples/gallery/icon.png"), &icns).unwrap();
        assert!(fs::metadata(&icns).unwrap().len() > 0);
        assert!(!dir.join("AppIcon.iconset").exists());
        fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn profiles_match_bundle_ids() {
        assert!(profile_allows(
            "ABCDE12345.com.example.app",
            "com.example.app"
        ));
        assert!(!profile_allows(
            "ABCDE12345.com.example.app",
            "com.example.other"
        ));
        assert!(profile_allows("ABCDE12345.*", "com.example.app"));
        assert!(profile_allows(
            "ABCDE12345.com.example.*",
            "com.example.app"
        ));
        assert!(!profile_allows("ABCDE12345.com.other.*", "com.example.app"));
        assert!(!profile_allows("", "com.example.app"));
    }

    #[test]
    fn gpui_packages_are_laid_out_as_this_oss_apps() {
        use clap::ValueEnum as _;

        use super::PackageTarget;
        assert_eq!(
            PackageTarget::from_str("gpui", false).unwrap(),
            PackageTarget::Gpui
        );
        let expected = if cfg!(target_os = "macos") {
            Some(PackageTarget::Macos)
        } else if cfg!(windows) {
            Some(PackageTarget::Windows)
        } else if cfg!(target_os = "linux") {
            Some(PackageTarget::Linux)
        } else {
            None
        };
        assert_eq!(PackageTarget::gpui_layout(), expected);
    }

    #[test]
    fn desktop_entries_match_windows_by_the_app_id() {
        assert_eq!(
            desktop_entry("Counter", "com.example.counter", "Counter", true),
            "[Desktop Entry]\nType=Application\nName=Counter\nExec=Counter\n\
             Icon=com.example.counter\nStartupWMClass=com.example.counter\nTerminal=false\n\
             Categories=Utility;\n"
        );
        assert!(!desktop_entry("A", "com.example.a", "A", false).contains("Icon="));
    }

    // `ditto` is macOS's.
    #[cfg(target_os = "macos")]
    #[test]
    fn ipa_holds_the_app_under_payload() {
        let dir = std::env::temp_dir().join(format!("nsh-ipa-{}", std::process::id()));
        let app = dir.join("Demo.app");
        fs::create_dir_all(app.join("nsh")).unwrap();
        fs::write(app.join("Demo"), b"binary").unwrap();
        fs::write(app.join("nsh/bundle.nshc"), b"code").unwrap();
        let ipa = dir.join("Demo.ipa");
        make_ipa(&app, &ipa).unwrap();
        let listing = Command::new("unzip").arg("-Z1").arg(&ipa).output().unwrap();
        let listing = String::from_utf8(listing.stdout).unwrap();
        let mut entries: Vec<&str> = listing.lines().collect();
        entries.sort_unstable();
        assert_eq!(
            entries,
            [
                "Payload/",
                "Payload/Demo.app/",
                "Payload/Demo.app/Demo",
                "Payload/Demo.app/nsh/",
                "Payload/Demo.app/nsh/bundle.nshc"
            ]
        );
        fs::remove_dir_all(&dir).unwrap();
    }
}