tessera-mobile 0.0.0

Rust on mobile made easy.
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
mod raw;

use std::{
    fmt::{self, Display},
    path::{Path, PathBuf},
    str::FromStr,
};

use serde::{Deserialize, Serialize};
use thiserror::Error;

use crate::{
    config::app::App,
    util::{
        self, Pod, VersionDouble, VersionDoubleError, VersionTriple, VersionTripleError,
        cli::Report,
    },
};

pub use self::raw::*;

static DEFAULT_PROJECT_DIR: &str = "gen/apple";
const DEFAULT_BUNDLE_VERSION: &str = "1.0.0";
const DEFAULT_IOS_VERSION: &str = "13.0";
const DEFAULT_MACOS_VERSION: &str = "11.0";

#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub struct BuildScript {
    #[serde(skip_serializing_if = "Option::is_none")]
    path: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    script: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    input_files: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    output_files: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    input_file_lists: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    output_file_lists: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    shell: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    show_env_vars: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    run_only_when_installing: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    based_on_dependency_analysis: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    discovered_dependency_file: Option<String>,
}

#[derive(Debug, Default, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub struct Platform {
    #[serde(default)]
    pub no_default_features: bool,
    pub cargo_args: Option<Vec<String>>,
    pub features: Option<Vec<String>>,
    pub libraries: Option<Vec<String>>,
    pub frameworks: Option<Vec<String>>,
    pub valid_archs: Option<Vec<String>>,
    pub vendor_frameworks: Option<Vec<String>>,
    pub vendor_sdks: Option<Vec<String>>,
    pub asset_catalogs: Option<Vec<PathBuf>>,
    pub pods: Option<Vec<Pod>>,
    pub pod_options: Option<Vec<String>>,
    pub additional_targets: Option<Vec<PathBuf>>,
    pub pre_build_scripts: Option<Vec<BuildScript>>,
    pub post_compile_scripts: Option<Vec<BuildScript>>,
    pub post_build_scripts: Option<Vec<BuildScript>>,
    pub command_line_arguments: Option<Vec<String>>,
}

impl Platform {
    pub fn no_default_features(&self) -> bool {
        self.no_default_features
    }

    pub fn cargo_args(&self) -> Option<&[String]> {
        self.cargo_args.as_deref()
    }

    pub fn features(&self) -> Option<&[String]> {
        self.features.as_deref()
    }

    pub fn libraries(&self) -> &[String] {
        self.libraries.as_deref().unwrap_or(&[])
    }

    pub fn frameworks(&self) -> &[String] {
        self.frameworks.as_deref().unwrap_or(&[])
    }

    pub fn valid_archs(&self) -> Option<&[String]> {
        self.valid_archs.as_deref()
    }

    pub fn vendor_frameworks(&self) -> &[String] {
        self.vendor_frameworks.as_deref().unwrap_or(&[])
    }

    pub fn vendor_sdks(&self) -> &[String] {
        self.vendor_sdks.as_deref().unwrap_or(&[])
    }

    pub fn asset_catalogs(&self) -> Option<&[PathBuf]> {
        self.asset_catalogs.as_deref()
    }

    pub fn pods(&self) -> Option<&[Pod]> {
        self.pods.as_deref()
    }

    pub fn pod_options(&self) -> Option<&[String]> {
        self.pod_options.as_deref()
    }

    pub fn additional_targets(&self) -> Option<&[PathBuf]> {
        self.additional_targets.as_deref()
    }

    pub fn pre_build_scripts(&self) -> Option<&[BuildScript]> {
        self.pre_build_scripts.as_deref()
    }

    pub fn post_compile_scripts(&self) -> Option<&[BuildScript]> {
        self.post_compile_scripts.as_deref()
    }

    pub fn post_build_scripts(&self) -> Option<&[BuildScript]> {
        self.post_build_scripts.as_deref()
    }

    pub fn command_line_arguments(&self) -> &[String] {
        self.command_line_arguments.as_deref().unwrap_or_default()
    }
}

const fn default_true() -> bool {
    true
}

#[derive(Debug, Deserialize)]
pub struct Metadata {
    #[serde(default = "default_true")]
    pub supported: bool,
    #[serde(default)]
    pub ios: Platform,
    #[serde(default)]
    pub macos: Platform,
}

impl Default for Metadata {
    fn default() -> Self {
        Self {
            supported: true,
            ios: Default::default(),
            macos: Default::default(),
        }
    }
}

impl Metadata {
    pub const fn supported(&self) -> bool {
        self.supported
    }

    pub fn ios(&self) -> &Platform {
        &self.ios
    }

    pub fn macos(&self) -> &Platform {
        &self.macos
    }
}

#[derive(Debug)]
pub enum ProjectDirInvalid {
    NormalizationFailed {
        project_dir: String,
        cause: util::NormalizationError,
    },
    OutsideOfAppRoot {
        project_dir: String,
        root_dir: PathBuf,
    },
}

impl Display for ProjectDirInvalid {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::NormalizationFailed { project_dir, cause } => write!(
                f,
                "Xcode project dir {project_dir:?} couldn't be normalized: {cause}"
            ),
            Self::OutsideOfAppRoot {
                project_dir,
                root_dir,
            } => write!(
                f,
                "Xcode project dir {project_dir:?} is outside of the app root dir {root_dir:?}",
            ),
        }
    }
}

#[derive(Debug, Error)]
pub enum Error {
    #[error("`apple.development-team` must be specified")]
    DevelopmentTeamMissing,
    #[error("`apple.development-team` is empty")]
    DevelopmentTeamEmpty,
    #[error("`apple.project-dir` invalid: {0}")]
    ProjectDirInvalid(ProjectDirInvalid),
    #[error("`apple.bundle-version` can only contain numbers, separated by `.`")]
    BundleVersionInvalid,
    #[error("`apple.bundle-version-short` invalid: {0}")]
    BundleVersionShortInvalid(VersionTripleError),
    #[error("`apple.ios-version` invalid: {0}")]
    IosVersionInvalid(VersionDoubleError),
    #[error("`apple.macos-version` invalid: {0}")]
    MacOsVersionInvalid(VersionDoubleError),
    #[error("Identifier cannot contain underscores on iOS")]
    IdentifierCannotContainUnderscores,
}

impl Error {
    pub fn report(&self, msg: &str) -> Report {
        Report::error(msg, self)
    }
}

#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct Config {
    #[serde(skip_serializing)]
    app: App,
    development_team: Option<String>,
    project_dir: String,
    bundle_version: String,
    bundle_version_short: String,
    ios_version: String,
    macos_version: String,
    use_legacy_build_system: bool,
    plist_pairs: Vec<PListPair>,
    enable_bitcode: bool,
    export_options_plist_path: PathBuf,
}

impl Config {
    pub fn from_raw(app: App, raw: Option<Raw>) -> Result<Self, Error> {
        if app.identifier().contains('_') {
            return Err(Error::IdentifierCannotContainUnderscores);
        }

        let raw = raw.ok_or(Error::DevelopmentTeamMissing)?;

        if raw
            .development_team
            .as_ref()
            .map(|t| t.is_empty())
            .unwrap_or_default()
        {
            return Err(Error::DevelopmentTeamEmpty);
        }

        let project_dir = raw
            .project_dir
            .map(|project_dir| {
                if project_dir == DEFAULT_PROJECT_DIR {
                    log::warn!("`{}.project-dir` is set to the default value; you can remove it from your config", super::NAME);
                }
                if util::under_root(&project_dir, app.root_dir())
                    .map_err(|cause| Error::ProjectDirInvalid(ProjectDirInvalid::NormalizationFailed {
                        project_dir: project_dir.clone(),
                        cause,
                    }))?
                {
                    Ok(project_dir)
                } else {
                    Err(Error::ProjectDirInvalid(ProjectDirInvalid::OutsideOfAppRoot {
                        project_dir,
                        root_dir: app.root_dir().to_owned(),
                    }))
                }
            }).unwrap_or_else(|| {
                Ok(DEFAULT_PROJECT_DIR.to_owned())
            })?;

        let bundle_version = raw
            .bundle_version
            .unwrap_or_else(|| DEFAULT_BUNDLE_VERSION.to_string());
        if bundle_version
            .split('.')
            .any(|part| part.parse::<usize>().is_err())
        {
            return Err(Error::BundleVersionInvalid);
        }

        let bundle_version_short = raw.bundle_version_short.unwrap_or_else(|| {
            bundle_version
                .split('.')
                .take(3)
                .collect::<Vec<_>>()
                .join(".")
        });
        if let Err(e) = VersionTriple::from_str(&bundle_version_short) {
            return Err(Error::BundleVersionShortInvalid(e));
        }

        let export_options_plist_path = raw
            .export_options_plist_path
            .map(PathBuf::from)
            .unwrap_or_else(|| "ExportOptions.plist".into());

        Ok(Self {
            app,
            development_team: raw.development_team,
            project_dir,
            bundle_version,
            bundle_version_short,
            ios_version: raw
                .ios_version
                .map(|str| VersionDouble::from_str(&str))
                .transpose()
                .map_err(Error::IosVersionInvalid)?
                .map(|v| v.to_string())
                .unwrap_or_else(|| DEFAULT_IOS_VERSION.to_string()),
            macos_version: raw
                .macos_version
                .map(|str| VersionDouble::from_str(&str))
                .transpose()
                .map_err(Error::MacOsVersionInvalid)?
                .map(|v| v.to_string())
                .unwrap_or_else(|| DEFAULT_MACOS_VERSION.to_string()),
            use_legacy_build_system: raw.use_legacy_build_system.unwrap_or(true),
            plist_pairs: raw.plist_pairs.unwrap_or_default(),
            enable_bitcode: raw.enable_bitcode.unwrap_or(false),
            export_options_plist_path,
        })
    }

    pub fn set_export_options_plist_path<P: AsRef<Path>>(&mut self, path: P) {
        self.export_options_plist_path = path.as_ref().to_path_buf();
    }

    pub fn app(&self) -> &App {
        &self.app
    }

    pub fn project_dir(&self) -> PathBuf {
        self.app.prefix_path(&self.project_dir)
    }

    pub fn project_dir_exists(&self) -> bool {
        self.project_dir().is_dir()
    }

    pub fn workspace_path(&self) -> PathBuf {
        let root_workspace = self
            .project_dir()
            .join(format!("{}.xcworkspace/", self.app.name()));
        if root_workspace.exists() {
            root_workspace
        } else {
            self.project_dir().join(format!(
                "{}.xcodeproj/project.xcworkspace/",
                self.app.name()
            ))
        }
    }

    pub fn archive_dir(&self) -> PathBuf {
        self.project_dir().join("build")
    }

    pub fn export_dir(&self) -> PathBuf {
        self.project_dir().join("build")
    }

    pub fn export_plist_path(&self) -> PathBuf {
        self.project_dir().join(&self.export_options_plist_path)
    }

    pub fn ipa_path(&self) -> Result<PathBuf, (PathBuf, PathBuf)> {
        let path = |tail: &str| self.export_dir().join(format!("{tail}.ipa"));
        let old = path(&self.scheme());
        // It seems like the format changed recently?
        let new = path(self.app.stylized_name());
        std::iter::once(&old)
            .chain(std::iter::once(&new))
            .find(|path| path.is_file())
            .cloned()
            .ok_or((old, new))
    }

    pub fn app_path(&self) -> PathBuf {
        self.export_dir()
            .join(format!("Payload/{}.app", self.app.stylized_name()))
    }

    pub fn scheme(&self) -> String {
        format!("{}_iOS", self.app.name())
    }

    pub fn bundle_version(&self) -> &str {
        &self.bundle_version
    }

    pub fn bundle_version_short(&self) -> &str {
        &self.bundle_version_short
    }

    pub fn development_team(&self) -> Option<&str> {
        self.development_team.as_deref()
    }
}