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
use std::collections::HashMap;
use std::fs;
use std::fs::OpenOptions;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::Command;
use tempfile::tempdir;
pub struct CreatePackageConfig {
    pub bridge_dir: PathBuf,
    pub paths: HashMap<ApplePlatform, PathBuf>,
    pub out_dir: PathBuf,
    pub package_name: String,
}
impl CreatePackageConfig {
    pub fn new(
        bridge_dir: PathBuf,
        paths: HashMap<ApplePlatform, PathBuf>,
        out_dir: PathBuf,
        package_name: String,
    ) -> Self {
        Self {
            bridge_dir,
            paths,
            out_dir,
            package_name,
        }
    }
}
#[derive(Debug, Eq, PartialEq, Hash, Copy, Clone)]
pub enum ApplePlatform {
    IOS,
    Simulator,
    MacOS,
    MacCatalyst,
    TvOS,
    WatchOS,
    WatchOSSimulator,
    CarPlayOS,
    CarPlayOSSimulator,
}
impl ApplePlatform {
    pub fn dir_name(&self) -> &str {
        match self {
            ApplePlatform::IOS => "ios",
            ApplePlatform::Simulator => "simulator",
            ApplePlatform::MacOS => "macos",
            ApplePlatform::MacCatalyst => "mac-catalyst",
            ApplePlatform::TvOS => "tvos",
            ApplePlatform::WatchOS => "watchos",
            ApplePlatform::WatchOSSimulator => "watchos-simulator",
            ApplePlatform::CarPlayOS => "carplay",
            ApplePlatform::CarPlayOSSimulator => "carplay-simulator",
        }
    }
    pub const ALL: &'static [Self] = &[
        ApplePlatform::IOS,
        ApplePlatform::Simulator,
        ApplePlatform::MacOS,
        ApplePlatform::MacCatalyst,
        ApplePlatform::TvOS,
        ApplePlatform::WatchOS,
        ApplePlatform::WatchOSSimulator,
        ApplePlatform::CarPlayOS,
        ApplePlatform::CarPlayOSSimulator,
    ];
}
pub fn create_package(config: CreatePackageConfig) {
    let output_dir: &Path = config.out_dir.as_ref();
    if !&output_dir.exists() {
        fs::create_dir_all(&output_dir).expect("Couldn't create output directory");
    }
    gen_xcframework(&output_dir, &config);
    gen_package(&output_dir, &config);
}
fn gen_xcframework(output_dir: &Path, config: &CreatePackageConfig) {
    let temp_dir = tempdir().expect("Couldn't create temporary directory");
    let tmp_framework_path = &temp_dir.path().join("swiftbridge._tmp_framework");
    fs::create_dir(&tmp_framework_path).expect("Couldn't create framework directory");
    let include_dir = tmp_framework_path.join("include");
    if !include_dir.exists() {
        fs::create_dir(&include_dir).expect("Couldn't create inlcude directory for xcframework");
    }
    let modulemap_path = include_dir.join("module.modulemap");
    fs::write(
        &modulemap_path,
        "module RustXcframework {\n    header \"SwiftBridgeCore.h\"\n",
    )
    .expect("Couldn't write modulemap file");
    let mut modulemap_file = OpenOptions::new()
        .write(true)
        .append(true)
        .open(&modulemap_path)
        .expect("Couldn't open modulemap file for writing");
    let bridge_dir: &Path = config.bridge_dir.as_ref();
    fs::copy(
        bridge_dir.join("SwiftBridgeCore.h"),
        &include_dir.join("SwiftBridgeCore.h"),
    )
    .expect("Couldn't copy SwiftBirdgeCore header file");
    let bridge_project_dir = fs::read_dir(&bridge_dir)
        .expect("Couldn't read generated directory")
        .find_map(|file| {
            let file = file.unwrap().path();
            if file.is_dir() {
                Some(file)
            } else {
                None
            }
        })
        .expect("Couldn't find project directory inside of generated directory");
    let bridge_project_header_dir = fs::read_dir(&bridge_project_dir)
        .expect("Couldn't read generated directory")
        .find_map(|file| {
            let file = file.unwrap().path();
            if file.extension().unwrap() == "h" {
                Some(file)
            } else {
                None
            }
        })
        .expect("Couldn't find project's header file");
    fs::copy(
        &bridge_project_header_dir,
        &include_dir.join(&bridge_project_header_dir.file_name().unwrap()),
    )
    .expect("Couldn't copy project's header file");
    writeln!(
        modulemap_file,
        "    header \"{}\"",
        bridge_project_header_dir
            .file_name()
            .unwrap()
            .to_str()
            .unwrap()
    )
    .expect("Couldn't write to modulemap");
    writeln!(modulemap_file, "    export *\n}}").expect("Couldn't write to modulemap");
    for platform in &config.paths {
        let platform_path = &tmp_framework_path.join(platform.0.dir_name());
        if !platform_path.exists() {
            fs::create_dir(&platform_path).expect(&format!(
                "Couldn't create directory for target {:?}",
                platform.0
            ));
        }
        let lib_path: &Path = platform.1.as_ref();
        fs::copy(lib_path, platform_path.join(lib_path.file_name().unwrap())).expect(&format!(
            "Couldn't copy library for platform {:?}",
            platform.0
        ));
    }
    let xcframework_dir = output_dir.join("RustXcframework.xcframework");
    if xcframework_dir.exists() {
        fs::remove_dir_all(&xcframework_dir).expect("Couldn't delete previous xcframework file");
    }
    fs::create_dir(&xcframework_dir).expect("Couldn't create directory for xcframework");
    let mut args: Vec<String> = Vec::new();
    args.push("-create-xcframework".to_string());
    for platform in &config.paths {
        let file_path = Path::new(platform.0.dir_name())
            .join((platform.1.as_ref() as &Path).file_name().unwrap());
        args.push("-library".to_string());
        args.push(file_path.to_str().unwrap().trim().to_string());
        args.push("-headers".to_string());
        args.push("include".to_string());
    }
    args.push("-output".to_string());
    args.push(
        fs::canonicalize(xcframework_dir)
            .expect("Couldn't convert output directory to absolute path")
            .as_path()
            .to_str()
            .unwrap()
            .to_string(),
    );
    let output = Command::new("xcodebuild")
        .current_dir(&tmp_framework_path)
        .args(args)
        .spawn()
        .expect("Failed to spawn xcodebuild")
        .wait_with_output()
        .expect("Failed to execute xcodebuild");
    if !output.status.success() {
        let stderr = std::str::from_utf8(&output.stderr).unwrap();
        panic!("{}", stderr);
    }
    let temp_dir_string = temp_dir.path().to_str().unwrap().to_string();
    if let Err(err) = temp_dir.close() {
        eprintln!(
            "Couldn't close temporary directory {} - {}",
            temp_dir_string, err
        );
    }
}
fn gen_package(output_dir: &Path, config: &CreatePackageConfig) {
    let sources_dir = output_dir.join("Sources").join(&config.package_name);
    if !sources_dir.exists() {
        fs::create_dir_all(&sources_dir).expect("Couldn't create directory for source files");
    }
    let bridge_dir: &Path = config.bridge_dir.as_ref();
    fs::write(
        sources_dir.join("SwiftBridgeCore.swift"),
        format!(
            "import RustXcframework\n{}",
            fs::read_to_string(&bridge_dir.join("SwiftBridgeCore.swift"))
                .expect("Couldn't read core bridging swift file")
        ),
    )
    .expect("Couldn't write core bridging swift file");
    let bridge_project_dir = fs::read_dir(&bridge_dir)
        .expect("Couldn't read generated directory")
        .find_map(|file| {
            let file = file.unwrap().path();
            if file.is_dir() {
                Some(file)
            } else {
                None
            }
        })
        .expect("Couldn't find project directory inside of generated directory");
    let bridge_project_swift_dir = fs::read_dir(&bridge_project_dir)
        .expect("Couldn't read generated directory")
        .find_map(|file| {
            let file = file.unwrap().path();
            if file.extension().unwrap() == "swift" {
                Some(file)
            } else {
                None
            }
        })
        .expect("Couldn't find project's bridging swift file");
    fs::write(
        sources_dir.join(&bridge_project_swift_dir.file_name().unwrap()),
        format!(
            "import RustXcframework\n{}",
            fs::read_to_string(&bridge_project_swift_dir)
                .expect("Couldn't read project's bridging swift file")
        ),
    )
    .expect("Couldn't copy project's bridging swift file to the package");
    let package_name = &config.package_name;
    let package_swift = format!(
        r#"// swift-tools-version:5.5.0
import PackageDescription
let package = Package(
	name: "{package_name}",
	products: [
		.library(
			name: "{package_name}",
			targets: ["{package_name}"]),
	],
	dependencies: [],
	targets: [
		.binaryTarget(
			name: "RustXcframework",
			path: "RustXcframework.xcframework"
		),
		.target(
			name: "{package_name}",
			dependencies: ["RustXcframework"])
	]
)
	"#
    );
    fs::write(output_dir.join("Package.swift"), package_swift)
        .expect("Couldn't write Package.swift file");
}