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
//! Project management and build utilities for `WaterUI` CLI.
use cargo_toml::Manifest as CargoManifest;
use color_eyre::eyre;
use tracing::info;
use crate::backend::Backend;
/// Represents a `WaterUI` project with its manifest and crate information.
#[derive(Debug, Clone)]
pub struct Project {
root: PathBuf,
manifest: Manifest,
crate_name: String,
target_dir: PathBuf,
}
impl Project {
/// Run the `WaterUI` project on the specified device.
///
/// This method handles building, packaging, and running the project.
///
/// # Errors
/// - If any step in the build, package, or run process fails.
pub async fn run(&self, device: impl Device, hot_reload: bool) -> Result<Running, FailToRun> {
use crate::debug::hot_reload::{DEFAULT_PORT, HotReloadServer};
let platform = device.platform();
// Build rust library for the target platform
platform
.build(self, BuildOptions::new(false, hot_reload))
.await
.map_err(FailToRun::Build)?;
// Package the build artifacts for the target platform
let artifact = platform
.package(self, PackageOptions::new(false, true))
.await
.map_err(FailToRun::Package)?;
// Set up run options with hot reload environment variables if enabled
let mut run_options = RunOptions::new();
let server = if hot_reload {
// Start the hot reload server
let server = HotReloadServer::launch(DEFAULT_PORT)
.await
.map_err(FailToRun::HotReload)?;
// Set environment variables for the app to connect back
run_options.insert_env_var("WATERUI_HOT_RELOAD_HOST".to_string(), server.host());
run_options.insert_env_var(
"WATERUI_HOT_RELOAD_PORT".to_string(),
server.port().to_string(),
);
info!(
"Hot reload server started on {}:{}",
server.host(),
server.port()
);
Some(server)
} else {
None
};
info!("Running on device");
let mut running = device.run(artifact, run_options).await?;
if let Some(server) = server {
running.retain(server);
}
Ok(running)
}
/// Get the root path of the project.
///
/// Same as the directory containing `Water.toml`.
#[must_use]
pub fn root(&self) -> &Path {
&self.root
}
/// Get the target directory for Rust build artifacts.
#[must_use]
pub fn target_dir(&self) -> &Path {
&self.target_dir
}
/// Get the backends configured for the project.
#[must_use]
pub const fn backends(&self) -> &Backends {
&self.manifest.backends
}
/// Get the crate name of the project.
#[must_use]
pub fn crate_name(&self) -> &str {
&self.crate_name
}
/// Get the Apple backend configuration if available.
#[must_use]
pub const fn apple_backend(&self) -> Option<&AppleBackend> {
self.manifest.backends.apple()
}
/// Get the full path to a backend directory.
///
/// Returns `project.root() / backends.path / B::DEFAULT_PATH`.
#[must_use]
pub fn backend_path<B: Backend>(&self) -> PathBuf {
self.root
.join(self.manifest.backends.path())
.join(B::DEFAULT_PATH)
}
/// Get the relative path to a backend directory from project root.
///
/// Returns `backends.path / B::DEFAULT_PATH`.
#[must_use]
pub fn backend_relative_path<B: Backend>(&self) -> PathBuf {
self.manifest.backends.path().join(B::DEFAULT_PATH)
}
/// Get the Android backend configuration if available.
#[must_use]
pub const fn android_backend(&self) -> Option<&AndroidBackend> {
self.manifest.backends.android()
}
/// Get the manifest of the project.
#[must_use]
pub const fn manifest(&self) -> &Manifest {
&self.manifest
}
/// Get the bundle identifier of the project.
#[must_use]
pub const fn bundle_identifier(&self) -> &str {
self.manifest.package.bundle_identifier.as_str()
}
/// Clean build artifacts for the project on the specified platform.
///
/// # Errors
///
/// Returns an error if cleaning fails.
pub async fn clean(&self, platform: impl Platform) -> Result<(), eyre::Report> {
// Parrelly clean rust build artifacts and platform specific build artifacts
platform.clean(self).await
}
/// Clean all build artifacts for the project.
///
/// This cleans:
/// - Rust target directory
/// - Apple build artifacts (if backend configured)
/// - Android build artifacts (if backend configured)
///
/// # Errors
///
/// Returns an error if any cleaning operation fails.
pub async fn clean_all(&self) -> Result<(), eyre::Report> {
use crate::{
android::platform::AndroidPlatform, apple::platform::ApplePlatform, platform::Platform,
};
// Clean Rust target directory
let target_dir = self.root.join("target");
if target_dir.exists() {
smol::fs::remove_dir_all(&target_dir).await?;
}
// Clean Apple backend if configured
if self.apple_backend().is_some() {
// Use a default platform for cleaning - the actual platform doesn't matter
// since clean() operates on the project-level build artifacts
ApplePlatform::macos().clean(self).await?;
}
// Clean Android backend if configured
if self.android_backend().is_some() {
AndroidPlatform::arm64().clean(self).await?;
}
Ok(())
}
/// Package the project for the specified platform.
///
/// # Errors
///
/// Returns an error if packaging fails.
pub async fn package(
&self,
platform: impl Platform,
options: PackageOptions,
) -> Result<Artifact, eyre::Report> {
platform.package(self, options).await
}
}
/// Errors that can occur when opening a `WaterUI` project.
#[derive(Debug, thiserror::Error)]
pub enum FailToOpenProject {
/// Failed to open the Water.toml manifest.
#[error("Failed to open project manifest: {0}")]
Manifest(FailToOpenManifest),
/// Failed to read the Cargo.toml file.
#[error("Failed to read Cargo.toml: {0}")]
CargoManifest(cargo_toml::Error),
/// Failed to get Cargo metadata.
#[error("Failed to get Cargo metadata: {0}")]
TargetDirError(#[from] cargo_metadata::Error),
/// Missing crate name in Cargo.toml.
#[error("Invalid Cargo.toml: missing crate name")]
MissingCrateName,
/// Project permissions are not allowed in non-playground projects.
#[error("Project permissions are not allowed in non-playground projects")]
PermissionsNotAllowedInNonPlayground,
/// Backends configuration is not allowed in playground manifests.
#[error("Backends configuration is not allowed in playground projects")]
BackendsNotAllowedInPlayground,
/// Failed to initialize backend for playground project.
#[error("Failed to initialize backend: {0}")]
BackendInit(#[from] crate::backend::FailToInitBackend),
}
/// Errors that can occur when creating a new `WaterUI` project.
#[derive(Debug, thiserror::Error)]
pub enum FailToCreateProject {
/// The project directory already exists.
#[error("Directory already exists: {0}")]
DirectoryExists(PathBuf),
/// Failed to create project directory.
#[error("Failed to create directory: {0}")]
CreateDir(std::io::Error),
/// Failed to scaffold project files.
#[error("Failed to scaffold project: {0}")]
Scaffold(std::io::Error),
/// Failed to save manifest.
#[error("Failed to save manifest: {0}")]
SaveManifest(#[from] FailToSaveManifest),
/// Failed to get Cargo metadata.
#[error("Failed to get Cargo metadata: {0}")]
TargetDirError(#[from] cargo_metadata::Error),
/// Failed to initialize git repository.
#[error("Failed to initialize git repository: {0}")]
GitInit(std::io::Error),
}
/// Options for creating a new `WaterUI` project.
#[derive(Debug, Clone)]
pub struct CreateOptions {
/// Application display name (e.g., "Water Example").
pub name: String,
/// Bundle identifier (e.g., "com.example.waterexample").
pub bundle_identifier: String,
/// Whether to create a playground project.
pub playground: bool,
/// Path to local `WaterUI` repository for development.
pub waterui_path: Option<PathBuf>,
/// Author name for Cargo.toml.
pub author: String,
}
impl Project {
/// Create a new `WaterUI` project at the specified path.
///
/// This creates the project directory, scaffolds root files (Cargo.toml, src/lib.rs),
/// and saves the Water.toml manifest. Use `init_apple_backend()` and `init_android_backend()`
/// to scaffold platform backends after creation.
///
/// # Errors
/// - `FailToCreateProject::DirectoryExists`: If the directory already exists.
/// - `FailToCreateProject::CreateDir`: If creating the directory fails.
/// - `FailToCreateProject::Scaffold`: If scaffolding files fails.
/// - `FailToCreateProject::SaveManifest`: If saving the manifest fails.
pub async fn create(
path: impl AsRef<Path>,
options: CreateOptions,
) -> Result<Self, FailToCreateProject> {
let path = path.as_ref().to_path_buf();
// Check if directory already exists
if path.exists() {
return Err(FailToCreateProject::DirectoryExists(path));
}
// Create project directory
smol::fs::create_dir_all(&path)
.await
.map_err(FailToCreateProject::CreateDir)?;
// Derive crate name from display name
let crate_name = options
.name
.chars()
.map(|c| {
if c.is_alphanumeric() {
c.to_ascii_lowercase()
} else {
'_'
}
})
.collect::<String>();
// Build template context for root files
let ctx = TemplateContext {
app_display_name: options.name.clone(),
app_name: options.name.replace(' ', ""),
crate_name: crate_name.clone(),
bundle_identifier: options.bundle_identifier.clone(),
author: options.author.clone(),
android_backend_path: options
.waterui_path
.as_ref()
.map(|p| p.join("backends/android")),
use_remote_dev_backend: options.waterui_path.is_none(),
waterui_path: options.waterui_path.clone(),
backend_project_path: None, // Root files don't need this
android_permissions: Vec::new(),
};
// Scaffold root files (Cargo.toml, src/lib.rs, .gitignore)
templates::root::scaffold(&path, &ctx)
.await
.map_err(FailToCreateProject::Scaffold)?;
// Build manifest
let package_type = if options.playground {
PackageType::Playground
} else {
PackageType::App
};
let manifest = Manifest {
package: Package {
package_type,
name: options.name.clone(),
bundle_identifier: options.bundle_identifier.clone(),
},
backends: Backends::default(),
waterui_path: options
.waterui_path
.as_ref()
.map(|p| p.display().to_string()),
permissions: HashMap::default(),
};
// Save Water.toml
manifest.save(&path).await?;
// Initialize git repository if not already in one
Self::ensure_git_init(&path).await?;
let target_dir = get_target_dir(&path)
.await
.map_err(FailToCreateProject::TargetDirError)?;
Ok(Self {
root: path,
manifest,
crate_name,
target_dir,
})
}
/// Ensure the project is initialized with git.
///
/// Checks if the project directory is already part of a git repository.
/// If not, initializes a new git repository.
async fn ensure_git_init(path: &Path) -> Result<(), FailToCreateProject> {
// Check if already in a git repository
let mut cmd = Command::new("git");
let is_in_git = command(&mut cmd)
.args(["rev-parse", "--git-dir"])
.current_dir(path)
.output()
.await
.map(|output| output.status.success())
.unwrap_or(false);
if !is_in_git {
// Initialize a new git repository
let mut cmd = Command::new("git");
command(&mut cmd)
.args(["init"])
.current_dir(path)
.status()
.await
.map_err(FailToCreateProject::GitInit)?;
}
Ok(())
}
/// Initialize the Apple backend for this project.
///
/// This scaffolds the Apple backend files and updates the manifest.
///
/// # Errors
/// Returns an error if scaffolding fails.
pub async fn init_apple_backend(&mut self) -> Result<(), crate::backend::FailToInitBackend> {
use crate::backend::Backend;
let backend = AppleBackend::init(self).await?;
self.manifest.backends.set_apple(backend);
self.manifest
.save(&self.root)
.await
.map_err(|e| crate::backend::FailToInitBackend::Io(std::io::Error::other(e)))?;
Ok(())
}
/// Initialize the Android backend for this project.
///
/// This scaffolds the Android backend files and updates the manifest.
///
/// # Errors
/// Returns an error if scaffolding fails.
pub async fn init_android_backend(&mut self) -> Result<(), crate::backend::FailToInitBackend> {
use crate::backend::Backend;
let backend = AndroidBackend::init(self).await?;
self.manifest.backends.set_android(backend);
self.manifest
.save(&self.root)
.await
.map_err(|e| crate::backend::FailToInitBackend::Io(std::io::Error::other(e)))?;
Ok(())
}
/// Open a `WaterUI` project located at the specified path.
///
/// This loads both the `Water.toml` manifest and the `Cargo.toml` file.
/// For playground projects, backends are automatically initialized if not configured.
///
/// # Errors
/// - `FailToOpenProject::Manifest`: If there was an error opening the `Water.toml` manifest.
/// - `FailToOpenProject::CargoManifest`: If there was an error reading the `Cargo.toml` file.
/// - `FailToOpenProject::MissingCrateName`: If the crate name is missing in `Cargo.toml`.
pub async fn open(path: impl AsRef<Path>) -> Result<Self, FailToOpenProject> {
use crate::backend::Backend;
let path = path.as_ref().to_path_buf();
let mut manifest = Manifest::open(path.join("Water.toml"))
.await
.map_err(FailToOpenProject::Manifest)?;
let cargo_path = path.join("Cargo.toml");
let cargo_manifest = unblock(move || CargoManifest::from_path(cargo_path))
.await
.map_err(FailToOpenProject::CargoManifest)?;
let crate_name = cargo_manifest
.package
.map(|p| p.name)
.ok_or(FailToOpenProject::MissingCrateName)?;
let is_playground = manifest.package.package_type == PackageType::Playground;
// Check that permissions are only set for playground projects
if !is_playground && !manifest.permissions.is_empty() {
return Err(FailToOpenProject::PermissionsNotAllowedInNonPlayground);
}
// Check that backends are not configured in playground manifests
if is_playground && !manifest.backends.is_empty() {
return Err(FailToOpenProject::BackendsNotAllowedInPlayground);
}
// For playground projects, backends are stored in .water directory
if is_playground {
manifest.backends.set_path(".water");
}
let target_dir = get_target_dir(&path)
.await
.map_err(FailToOpenProject::TargetDirError)?;
let mut project = Self {
root: path,
manifest,
crate_name,
target_dir,
};
// For playground projects, auto-initialize backends
// Always re-scaffold templates on each run to pick up manifest changes (e.g., permissions)
// Build cache (build/, .gradle/, DerivedData/) is preserved since scaffold only writes template files
//
// Skip backend initialization when:
// 1. Running inside Xcode's sandboxed build script phase (WATERUI_SKIP_RUST_BUILD=1)
// 2. Running inside any sandbox (sandbox-exec sets __XCODE_BUILT_PRODUCTS_DIR_PATHS or similar)
// 3. Xcode is the current build tool (ACTION env var is set by Xcode)
let skip_backend_init = std::env::var("WATERUI_SKIP_RUST_BUILD")
.map(|v| v == "1")
.unwrap_or(false)
|| std::env::var("ACTION").is_ok() // Xcode sets this during builds
|| std::env::var("XCODE_PRODUCT_BUILD_VERSION").is_ok();
if is_playground && !skip_backend_init {
// Apple backend - always re-scaffold to pick up manifest changes
let apple_backend = AppleBackend::init(&project)
.await
.map_err(FailToOpenProject::BackendInit)?;
project.manifest.backends.set_apple(apple_backend);
// Android backend - always re-scaffold to pick up manifest changes
let android_backend = AndroidBackend::init(&project)
.await
.map_err(FailToOpenProject::BackendInit)?;
project.manifest.backends.set_android(android_backend);
}
Ok(project)
}
}
async fn get_target_dir(current_dir: &Path) -> Result<PathBuf, cargo_metadata::Error> {
let current_dir = current_dir.to_path_buf();
let metadata = unblock(|| {
cargo_metadata::MetadataCommand::new()
.no_deps()
.current_dir(current_dir)
.exec()
})
.await?;
let target_dir = metadata.target_directory.as_std_path();
Ok(target_dir.to_path_buf())
}
use std::{
collections::HashMap,
path::{Path, PathBuf},
};
use serde::{Deserialize, Serialize};
use smol::{fs::read_to_string, process::Command, unblock};
use crate::{
android::backend::AndroidBackend,
apple::backend::AppleBackend,
backend::Backends,
build::BuildOptions,
device::{Artifact, Device, FailToRun, RunOptions, Running},
platform::{PackageOptions, Platform},
templates::{self, TemplateContext},
utils::command,
};
/// Configuration for a `WaterUI` project persisted to `Water.toml`.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Manifest {
/// Package information.
pub package: Package,
/// Backend configurations for various platforms.
#[serde(default, skip_serializing_if = "Backends::is_empty")]
pub backends: Backends,
/// Path to local `WaterUI` repository for dev mode.
/// When set, all backends will use this path instead of the published versions.
#[serde(skip_serializing_if = "Option::is_none")]
pub waterui_path: Option<String>,
/// Permission configuration for playground projects.
#[serde(default, skip_serializing_if = "HashMap::is_empty")]
pub permissions: HashMap<String, PermissionEntry>,
}
/// Permission entry for playground projects.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct PermissionEntry {
enable: bool,
/// Explain why this permission is needed.
description: String,
}
impl PermissionEntry {
/// Check if this permission is enabled.
#[must_use]
pub const fn is_enabled(&self) -> bool {
self.enable
}
}
/// Errors that can occur when opening a `Water.toml` manifest file.
#[derive(Debug, thiserror::Error)]
pub enum FailToOpenManifest {
/// Failed to read the manifest file from the filesystem.
#[error("Failed to read manifest file: {0}")]
ReadError(std::io::Error),
/// The manifest file is invalid or malformed.
#[error("Invalid manifest file: {0}")]
InvalidManifest(toml::de::Error),
/// The manifest file was not found at the specified path.
#[error("Manifest file not found at the specified path")]
NotFound,
}
/// Errors that can occur when saving a `Water.toml` manifest file.
#[derive(Debug, thiserror::Error)]
pub enum FailToSaveManifest {
/// Failed to serialize the manifest to TOML.
#[error("Failed to serialize manifest: {0}")]
Serialize(toml::ser::Error),
/// Failed to write the manifest file to disk.
#[error("Failed to write manifest file: {0}")]
Write(std::io::Error),
}
impl Manifest {
/// Open and parse a `Water.toml` manifest file from the specified path.
///
/// # Errors
/// - `FailToOpenManifest::ReadError`: If there was an error reading the file.
/// - `FailToOpenManifest::InvalidManifest`: If the file contents are not valid TOML.
/// - `FailToOpenManifest::NotFound`: If the file does not exist at the specified path.
pub async fn open(path: impl AsRef<Path>) -> Result<Self, FailToOpenManifest> {
let path = path.as_ref();
let result = read_to_string(path).await;
match result {
Ok(c) => toml::from_str(&c).map_err(FailToOpenManifest::InvalidManifest),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Err(FailToOpenManifest::NotFound),
Err(e) => Err(FailToOpenManifest::ReadError(e)),
}
}
/// Save the manifest to a `Water.toml` file at the specified directory.
///
/// # Errors
/// - If there was an error serializing the manifest to TOML.
/// - If there was an error writing the file.
pub async fn save(&self, dir: impl AsRef<Path>) -> Result<(), FailToSaveManifest> {
let path = dir.as_ref().join("Water.toml");
let content = toml::to_string_pretty(self).map_err(FailToSaveManifest::Serialize)?;
smol::fs::write(&path, content)
.await
.map_err(FailToSaveManifest::Write)
}
/// Create a new `Manifest` with the specified package information.
#[must_use]
pub fn new(package: Package) -> Self {
Self {
package,
backends: Backends::default(),
waterui_path: None,
permissions: HashMap::default(),
}
}
}
/// `[package]` section in `Water.toml`.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Package {
/// Type of the package (e.g., "app").
#[serde(rename = "type")]
pub package_type: PackageType,
/// Human-readable name of the application (e.g., "Water Demo").
pub name: String,
/// Bundle identifier for the application (e.g., "com.example.waterdemo").
pub bundle_identifier: String,
}
/// Package type indicating what kind of project this is.
#[derive(Debug, Serialize, Deserialize, Clone, Copy, Default, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum PackageType {
/// A standalone application with platform-specific backends.
#[default]
App,
/// A playground project for quick experimentation.
/// Platform projects are created in a temporary directory.
Playground,
}