### Target Usage Example Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/types.md Illustrates how to obtain a Target for a given ApplePlatform and access its properties. This example shows how to get the architectures for an iOS target and demonstrates the setup for a universal macOS target. ```rust use cargo_swift::targets::{Target, ApplePlatform}; let target = ApplePlatform::IOS.target(); let archs = target.architectures(); println!("{}", archs.head); // aarch64-apple-ios let macos_target = ApplePlatform::MacOS.target(); // Universal with both intel and arm64 ``` -------------------------------- ### Build Package with All Options CLI Example Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/index.md An advanced example demonstrating the `cargo swift package` command with a comprehensive set of options. This includes specifying platforms with minimum versions, setting the output name, build mode, bundle identifier, privacy manifest, features, and toolchain checks. ```bash cargo swift package \ -p ios@14 macos@11 \ -n MyLib \ --release \ --bundle-identifier com.example.MyLib \ --privacy-manifest ./PrivacyInfo.xcprivacy \ -F myfeature \ --skip-toolchains-check \ -y --silent ``` -------------------------------- ### Usage example for MainSpinner Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/api-reference-console.md Demonstrates constructing, starting, and finishing a MainSpinner. ```rust use cargo_swift::console::{MainSpinner, Ticking}; let spinner = MainSpinner::with_message("Building iOS target".to_string()); spinner.start(); // ... do work ... spinner.finish(); // OR on error: spinner.fail(); ``` -------------------------------- ### Config Usage Examples Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/types.md Illustrates how to instantiate the Config struct for different operational modes. ```rust use cargo_swift::Config; // Interactive mode with spinners let config = Config { silent: false, accept_all: false, }; // Batch/CI mode: silent with auto-accept defaults let batch_config = Config { silent: true, accept_all: true, }; ``` -------------------------------- ### ToolchainTargets Query Example Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/types.md Demonstrates how to query Rust toolchain availability and check if nightly is required for builds. ```rust use cargo_swift::targets::{ToolchainTargets, ApplePlatform}; let targets = vec![ApplePlatform::IOS.target()]; let toolchains = ToolchainTargets::query(&targets); if toolchains.use_nightly() { println!("Building with cargo +nightly"); } for target in &targets { for arch in target.architectures().iter() { if toolchains.needs_build_std(arch) { println!("Using -Z build-std for {}", arch); } } } ``` -------------------------------- ### Usage example for CommandSpinner Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/api-reference-console.md Shows how to create and manage a CommandSpinner for a specific command. ```rust use cargo_swift::console::{CommandSpinner, Ticking}; use std::process::Command; let mut cmd = Command::new("cargo"); cmd.args(&["build", "--target", "aarch64-apple-ios"]); let spinner = CommandSpinner::with_command(&cmd); spinner.start(); // ... execute command ... spinner.finish(); ``` -------------------------------- ### Usage example for info! macro Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/api-reference-console.md Demonstrates how to use the info! macro with a configuration object and a formatted string. ```rust use cargo_swift::{Config, console::info}; let config = Config { silent: false, accept_all: false }; info!(&config, "Building for {} platforms", 2); ``` -------------------------------- ### ApplePlatform Usage Example Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/types.md Demonstrates how to use the ApplePlatform enum to determine build configurations. It shows how to get the target and Info.plist configuration for a platform and checks if a platform uses a versioned bundle layout. ```rust use cargo_swift::targets::ApplePlatform; let platform = ApplePlatform::IOS; let target = platform.target(); let plist_config = platform.info_plist(); assert!(!platform.uses_versioned_bundle()); // iOS uses flat layout let macos = ApplePlatform::MacOS; assert!(macos.uses_versioned_bundle()); // macOS uses Versions/A/ ``` -------------------------------- ### Build Release Package CLI Example Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/index.md Example of how to build a release package for specified platforms using the `cargo swift package` command. This command is used to create distributable artifacts for Swift. ```bash cargo swift package -p ios macos --release ``` -------------------------------- ### Platform Usage Example Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/types.md Shows how to use the Platform enum to get display names and check if a platform is experimental. ```rust use cargo_swift::package::Platform; let ios = Platform::Ios; let display = ios.display_name(); // "iOS" let tvos = Platform::Tvos; assert!(tvos.is_experimental()); println!("{}", tvos.display_name()); // "tvOS (Experimental)" ``` -------------------------------- ### Initialize New Project (Interactive) Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/README.md Example of initializing a new project interactively using the `cargo swift init` command with a specified library name. ```bash # Interactive with git cargo swift init my_lib ``` -------------------------------- ### PlatformSpec package_swift() Example Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/types.md Demonstrates generating Swift Package Manager platform declarations for various platforms and versions. ```rust use cargo_swift::package::PlatformSpec; use cargo_swift::package::Platform; let spec = PlatformSpec { platform: Platform::Ios, min_version: Some("14.0".to_string()), }; assert_eq!(spec.package_swift(), ".iOS(.v14.0)"); // Default version let default_spec = PlatformSpec { platform: Platform::Macos, min_version: None, }; assert_eq!(default_spec.package_swift(), ".macOS(.v10_15)"); ``` -------------------------------- ### Build Release Package (Interactive) Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/README.md Example of building a release package interactively, which will prompt the user for platform, name, and bundle ID. ```bash # Interactive: prompts for platforms, name, bundle ID cargo swift package --release ``` -------------------------------- ### Install cargo-swift Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/README.md Install the cargo-swift plugin using cargo. This is a prerequisite for using the plugin's functionalities. ```bash cargo install cargo-swift ``` -------------------------------- ### Initialize New Project (Batch Mode) Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/README.md Example of initializing a new project in batch mode with explicit options for version control, library type, and silent operation. ```bash # Batch mode with explicit options cargo swift init my_lib \ --vcs git \ --lib-type static \ -y --silent ``` -------------------------------- ### Usage example for warning! macro Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/api-reference-console.md Demonstrates how to use the warning! macro with a configuration object and a formatted string. ```rust use cargo_swift::{Config, console::warning}; let config = Config { silent: false, accept_all: false }; warning!(&config, "Toolchain {} not found", "nightly-aarch64"); ``` -------------------------------- ### Rust Usage Example for Package Command Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/api-reference-package.md Demonstrates how to call the `package::run` function in Rust with specific configurations for platforms, package name, and build settings. Ensure necessary imports are included. ```rust use cargo_swift::package::{self, PlatformSpec, Platform, FeatureOptions}; use cargo_swift::{Config, Mode}; let config = Config { silent: false, accept_all: true, }; let platforms = vec![ PlatformSpec { platform: Platform::Ios, min_version: Some("13.0".to_string()), }, PlatformSpec { platform: Platform::Macos, min_version: None, }, ]; let features = FeatureOptions { features: None, all_features: false, no_default_features: false, }; package::run( Some(platforms), None, Some("MyLibrary".to_string()), None, false, config, Mode::Release, package::LibTypeArg::Automatic, features, false, "5.5", None, Some("com.example.MyLib".to_string()), vec![], )?; ``` -------------------------------- ### Get Single-Line Command Info Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/traits.md Example of using the `info()` method from the `CommandInfo` trait to get a formatted single-line string representation of a command. ```rust use cargo_swift::console::CommandInfo; use std::process::Command; let mut cmd = Command::new("cargo"); cmd.args(&["build", "--target", "aarch64-apple-ios", "--release"]); println!("{}", cmd.info()); // Output: cargo build --target aarch64-apple-ios --release ``` -------------------------------- ### Mode Usage Examples Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/types.md Shows how to create and display Mode enum variants. ```rust use cargo_swift::Mode; let debug_mode = Mode::Debug; println!("{}", debug_mode); // Output: "debug" let release_mode = Mode::Release; println!("{}", release_mode); // Output: "release" ``` -------------------------------- ### Get Multi-Line Command Info Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/traits.md Example demonstrating the `multiline_info()` method from the `CommandInfo` trait. It formats a command string to fit within a specified character limit per line, using backslash continuation. ```rust let multiline = cmd.multiline_info(30); println!("{}", multiline); // Output: // cargo build --target \ // aarch64-apple-ios --release ``` -------------------------------- ### LibType Usage Examples Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/types.md Demonstrates using the LibType enum to get identifiers, file extensions, and parsing from strings. ```rust use cargo_swift::LibType; let static_lib = LibType::Static; assert_eq!(static_lib.identifier(), "staticlib"); assert_eq!(static_lib.file_extension(), "a"); let dynamic_lib = LibType::Dynamic; assert_eq!(dynamic_lib.identifier(), "cdylib"); assert_eq!(dynamic_lib.file_extension(), "dylib"); // From string let lib_type = "staticlib".parse::()?; assert_eq!(lib_type, LibType::Static); ``` -------------------------------- ### Example Usage of Vcs Enum Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/types.md Demonstrates how to instantiate the Vcs enum to specify Git initialization for a new project. ```rust use cargo_swift::commands::init::Vcs; let vcs = Vcs::Git; // Initialize project with git ``` -------------------------------- ### Init Command: Minimal Boilerplate Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/configuration.md When set to true, creates a minimal project structure without extra explanatory code, example code, or inline documentation. ```cli --plain Type: bool Default: false Description: Create minimal boilerplate without explanatory code. Omits example code and inline documentation. ``` -------------------------------- ### Usage example for CommandInfo trait Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/api-reference-console.md Shows how to use the info() and multiline_info() methods on a std::process::Command object. ```rust use cargo_swift::console::CommandInfo; use std::process::Command; let mut cmd = Command::new("cargo"); cmd.args(&["build", "--target", "aarch64-apple-ios", "--release"]); println!("{}", cmd.info()); let multiline = cmd.multiline_info(30); ``` -------------------------------- ### Example Usage of FeatureOptions Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/types.md Demonstrates how to instantiate and use the FeatureOptions struct to configure specific Cargo build features. ```rust use cargo_swift::package::FeatureOptions; let features = FeatureOptions { features: Some(vec!["neon".to_string(), "simd".to_string()]), all_features: false, no_default_features: false, }; // Corresponds to: cargo build --features neon,simd ``` -------------------------------- ### Install Specific cargo-swift Version Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/README.md Install a specific version of cargo-swift that matches your project's UniFFI version. Use the -f flag to force installation if a version is already present. ```bash cargo install cargo-swift@0.X -f ``` -------------------------------- ### cargo_swift::init::run Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/README.md Initializes a new Rust project with Swift integration. This function handles the setup of project files, configuration, and version control integration. ```APIDOC ## `cargo_swift::init::run()` ### Description Initializes a new Rust project with Swift integration. This function handles the setup of project files, configuration, and version control integration. ### Signature ```rust pub fn run( crate_name: String, config: Config, vcs: Vcs, lib_type: LibType, plain: bool, macro_only: bool, ) -> Result<()> ``` ### Parameters - `crate_name` (String) - The name of the crate to initialize. - `config` (Config) - Global execution configuration. - `vcs` (Vcs) - Version control system to use. - `lib_type` (LibType) - The type of library to generate (e.g., static, dynamic). - `plain` (bool) - If true, disables interactive prompts and uses default values. - `macro_only` (bool) - If true, generates only macro-related files. ``` -------------------------------- ### Rust Usage Example for cargo-swift init::run Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/api-reference-init.md Demonstrates how to programmatically initialize a new Rust library crate for Swift using the `init::run` function. Configure settings like crate name, VCS, and library type. ```rust use cargo_swift::{init, Config, LibType}; use cargo_swift::commands::init::Vcs; let config = Config { silent: false, accept_all: false, }; let result = init::run( "my_lib".to_string(), config, Vcs::Git, LibType::Static, false, // plain = include examples false, // macro_only = use .udl files )?; ``` -------------------------------- ### Initialize a New Rust Library Crate Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/README.md Create a new Rust library crate with boilerplate code and UniFFI examples using the 'cargo swift init' command. ```bash cargo swift init ``` -------------------------------- ### Build Specific Architecture Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/README.md Example of building a package for a specific architecture, targeting the iOS device (aarch64-apple-ios) in release mode. ```bash # Only iOS device (aarch64-apple-ios) cargo swift package \ -p ios \ --target aarch64-apple-ios \ --release ``` -------------------------------- ### Build with Privacy Manifest Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/README.md Example of building a package with a privacy manifest file, specifying platforms, bundle identifier, and release mode. ```bash # With Privacy Manifest cargo swift package \ -p ios macos \ --privacy-manifest ./PrivacyInfo.xcprivacy \ --bundle-identifier com.mycompany.lib \ --release ``` -------------------------------- ### Build Release Package (Batch Mode) Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/README.md Example of building a release package in batch mode, specifying all necessary options including platforms, name, release mode, bundle identifier, and silent operation. ```bash # Batch mode: specify all options cargo swift package \ -p ios@14 macos@11 \ -n MyLib \ --release \ --bundle-identifier com.example.MyLib \ -y --silent ``` -------------------------------- ### Trait Composition Example: run_step_with_commands Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/traits.md Illustrates real-world usage of OptionalMultiProgress within the `run_step_with_commands` function for managing command spinners. ```rust use crate::console::{MainSpinner, CommandSpinner, Ticking, OptionalMultiProgress}; use indicatif::MultiProgress; pub fn run_step_with_commands( config: &Config, title: S, commands: &mut [Command], ) -> Result<()> where S: ToString, { let multi = config.silent.not().then(MultiProgress::new); let spinner = config .silent .not() .then_some(MainSpinner::with_message(title.to_string())); multi.add(&spinner); // OptionalMultiProgress trait for command in commands { let step = config .silent .not() .then(|| CommandSpinner::with_command(command)); multi.add(&step); // OptionalMultiProgress trait step.start(); // Ticking trait let output = command .stderr(Stdio::piped()) .stdout(Stdio::null()) .output() .unwrap_or_else(|_| { panic!("Failed to execute command: {}", command.info()) // CommandInfo trait }); if !output.status.success() { step.fail(); // Ticking trait spinner.fail(); return Err(output.stderr.into()); } step.finish(); // Ticking trait } spinner.finish(); Ok(()) } ``` -------------------------------- ### Implementing a Custom Spinner Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/traits.md Provides an example of creating a custom spinner type that implements the `Ticking` and `Spinner` traits. ```rust use cargo_swift::console::{Ticking, Spinner}; use indicatif::ProgressBar; pub struct CustomSpinner { bar: ProgressBar, } impl Ticking for CustomSpinner { fn start(&self) { self.bar.enable_steady_tick(std::time::Duration::from_millis(30)); } fn finish(&self) { self.bar.finish_with_message("Custom ✓"); } fn fail(&self) { self.bar.finish_with_message("Custom ✗"); } } impl Spinner for CustomSpinner { fn spinner(self) -> ProgressBar { self.bar } } ``` -------------------------------- ### Rustup Toolchain and Target Diagnostics Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/errors.md Provides commands to list available Rust toolchains and targets, check for specific target availability, and install missing targets using `rustup`. ```bash # List all available targets (stable) rustup target list # List available targets (nightly) rustup +nightly target list # Check specific target availability rustup target list | grep aarch64-apple-ios # Install missing target rustup target add aarch64-apple-ios ``` -------------------------------- ### Usage Example: Optional Spinner Registration Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/traits.md Demonstrates registering an optional spinner with MultiProgress using the OptionalMultiProgress trait. No type annotations are needed. ```rust use cargo_swift::console::{MainSpinner, OptionalMultiProgress, Ticking}; use indicatif::MultiProgress; let multi = Some(MultiProgress::new()); let spinner = Some(MainSpinner::with_message("Step 1".to_string())); // No type annotations needed; works with optional spinners multi.add(&spinner); // Registers if both are Some spinner.start(); ``` -------------------------------- ### Example Multi-Crate Build Error Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/errors.md Illustrates a typical compiler error message encountered during multi-crate builds, specifically an 'E0425' for a not-found function. This output is usually aggregated and presented to the user. ```text Failed due to the following error: error[E0425]: cannot find function `my_func` in this scope --> src/lib.rs:5:3 | 5 | my_func(); | ^^^^^^^ not found in this scope error: aborting due to 1 previous error ``` -------------------------------- ### Init Command: Version Control System Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/configuration.md Determines the version control system to initialize for the new crate. Defaults to 'git'. ```cli --vcs Type: Vcs (enum: git, none) Default: git Case-insensitive: Yes Description: Version control system to initialize. 'git': Initialize git repository 'none': Skip version control ``` -------------------------------- ### Bash Command Line Usage with All Options for cargo-swift init Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/api-reference-init.md Illustrates a comprehensive command-line usage for the `cargo swift init` command, including options for VCS, library type, plain mode, and UDL file usage. ```bash cargo swift init my_lib \ --vcs none \ --lib-type dynamic \ --plain \ --udl ``` -------------------------------- ### Initialize New Dynamic Library Project Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/configuration.md Initializes a new Swift library project with dynamic library type and version control enabled. Specify the library name and desired type. ```bash cargo swift init my_lib \ --lib-type dynamic \ --vcs git ``` -------------------------------- ### Ticking trait Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/api-reference-console.md A common interface for spinner lifecycle management, allowing for starting, finishing with success, or marking as failed. ```APIDOC ## Trait: Ticking ### Description Common interface for spinner lifecycle: starting animated display, finishing with success, or marking as failed. ### Methods | Method | Effect | |--------|--------| | `start()` | Enable 30ms tick rate for spinner animation. | | `finish()` | Show success symbol (✔) and disable animation. | | `fail()` | Show failure symbol (x) and disable animation. | ### Implementations - `MainSpinner` - Primary step display - `CommandSpinner` - Sub-step command display - `Option` - Optional spinner (no-op if None) - `Option` - Optional command spinner (no-op if None) ### Source - `src/console/spinners.rs:25` ``` -------------------------------- ### CommandInfo trait Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/api-reference-console.md An extension trait for `std::process::Command` that provides methods to get formatted string representations of commands. ```APIDOC ## Trait: CommandInfo ### Description Extension trait for `std::process::Command` providing formatted string representations. ### Methods | Method | Signature | Returns | Description | |--------|-----------|---------|-------------| | `info()` | `fn(&self) -> String` | Single-line command | Program name followed by space-separated arguments. | | `multiline_info()` | `fn(&self, chars_per_line: usize) -> String` | Multi-line with backslashes | Splits command across lines if longer than `chars_per_line`, with continuation backslashes. | ### Usage Example ```rust use cargo_swift::console::CommandInfo; use std::process::Command; let mut cmd = Command::new("cargo"); cmd.args(&["build", "--target", "aarch64-apple-ios", "--release"]); println!("{}", cmd.info()); // Output: cargo build --target aarch64-apple-ios --release let multiline = cmd.multiline_info(30); // Output: // cargo build --target \ // aarch64-apple-ios --release ``` ### Source - `src/console/command.rs:3` ``` -------------------------------- ### Init Command Data Flow Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/architecture.md Details the sequence of operations performed by the 'init' command, from argument parsing to initializing version control. ```text main.rs: init::run() │ ├─ Validate crate name ├─ Create directory structure │ └─ Cargo.toml template │ └─ src/lib.rs template │ └─ build.rs template (if !macro_only) │ └─ src/{crate_name}.udl template (if !macro_only) │ ├─ Write files to disk │ └─ templating.rs (askama rendering) │ └─ Initialize VCS └─ git init (if vcs == Git) ``` -------------------------------- ### Commands Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/index.md Functions for initializing and packaging Rust crates with cargo-swift. ```APIDOC ## `init::run` ### Description Initializes a new Rust crate with specified configurations. ### Signature `pub fn init::run(crate_name: String, config: Config, vcs: Vcs, lib_type: LibType, plain: bool, macro_only: bool) -> Result<()>` ### Parameters - `crate_name`: `String` - The name of the crate to initialize. - `config`: `Config` - The configuration object for the operation. - `vcs`: `Vcs` - The version control system to use. - `lib_type`: `LibType` - The type of library to create (e.g., Static, Dynamic). - `plain`: `bool` - If true, creates a plain project without extra files. - `macro_only`: `bool` - If true, creates a macro-only library. ### Returns - `Result<()>` - Ok(()) on success, or an Error. ## `package::run` ### Description Packages a Rust crate for specified platforms. ### Signature `pub fn package::run(platforms: Option>, build_target: Option<&str>, package_name: Option, xcframework_name: Option, disable_warnings: bool, config: Config, mode: Mode, lib_type_arg: LibTypeArg, features: FeatureOptions, skip_toolchains_check: bool, swift_tools_version: &str, privacy_manifest: Option, bundle_identifier: Option, exclude_arch: Vec) -> Result<()>` ### Parameters - `platforms`: `Option>` - Platforms to build for. - `build_target`: `Option<&str>` - Specific build target. - `package_name`: `Option` - Name of the package. - `xcframework_name`: `Option` - Name for the XCFramework. - `disable_warnings`: `bool` - Disable warnings during the build. - `config`: `Config` - The configuration object. - `mode`: `Mode` - Build mode (Debug or Release). - `lib_type_arg`: `LibTypeArg` - Argument specifying library type. - `features`: `FeatureOptions` - Options for crate features. - `skip_toolchains_check`: `bool` - Skip checking Swift toolchains. - `swift_tools_version`: `&str` - Swift tools version. - `privacy_manifest`: `Option` - Path to the privacy manifest file. - `bundle_identifier`: `Option` - Bundle identifier for the package. - `exclude_arch`: `Vec` - Architectures to exclude. ### Returns - `Result<()>` - Ok(()) on success, or an Error. ``` -------------------------------- ### Exclude Tier-3 Architectures Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/README.md Example of excluding specific architectures, such as the x86_64 architecture for tvOS simulators, when building a package in release mode. ```bash # tvOS simulator without Intel x86_64 cargo swift package \ -p tvos \ --exclude-arch x86_64-apple-tvos \ --release ``` -------------------------------- ### Use Ticking Trait for Spinner Management Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/traits.md Example demonstrating how to use the Ticking trait with MainSpinner. Ensure the Ticking trait is in scope. ```rust use cargo_swift::console::{MainSpinner, Ticking}; let spinner = MainSpinner::with_message("Building".to_string()); spinner.start(); // ... work ... spinner.finish(); // or spinner.fail() ``` -------------------------------- ### Use Specific Cargo Features Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/api-reference-package.md This command demonstrates how to use specific Cargo features or all available features for the build. ```bash cargo swift package \ -F feature1 feature2 \ --all-features \ --release ``` -------------------------------- ### Example Usage of LibTypeArg Enum Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/types.md Shows how to use the LibTypeArg enum to specify a dynamic library type override and convert it to an Option. ```rust use cargo_swift::package::LibTypeArg; let override_arg = LibTypeArg::Dynamic; let lib_type_option: Option<_> = override_arg.into(); // lib_type_option = Some(LibType::Dynamic) ``` -------------------------------- ### Build Dynamic Library with Bundle Identifier Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/api-reference-package.md Use this command to build a dynamic library and specify a bundle identifier for the framework. ```bash cargo swift package \ --lib-type dynamic \ --bundle-identifier com.example.MyLib \ --release ``` -------------------------------- ### Template Rendering for Cargo.toml and Lib.rs Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/architecture.md Demonstrates the use of Askama templates for generating `Cargo.toml` and `src/lib.rs` files during project initialization. The rendered content is written to the specified file path. ```rust // src/templating.rs pub struct CargoToml<'a> { /* fields */ } impl Template for CargoToml { /* template! macro */ } pub struct LibRs { /* fields */ } impl Template for LibRs { /* template! macro */ } // Render to String let content = cargo_toml.render().unwrap(); write(path, content)?; ``` -------------------------------- ### Specify Target Platforms and Minimum Versions Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/configuration.md Use the `-p` or `--platforms` flag to specify target platforms and their optional minimum OS versions. Multiple platforms can be specified, and omitting the version uses the platform's default. If omitted, the user is prompted interactively. ```bash --platforms (-p) [PLATFORM[@MIN_VERSION]]... Values: ios, macos, tvos, watchos, visionos, maccatalyst Min versions: ios@13, macos@10_15, tvos@13, watchos@6, visionos@1 Examples: -p ios macos -p ios@14 macos@11_0 tvos@13 ``` -------------------------------- ### Use Spinner Trait to Access ProgressBar Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/traits.md Example showing how to consume a MainSpinner and obtain its underlying ProgressBar. This allows direct manipulation using the indicatif API. ```rust use cargo_swift::console::{MainSpinner, Spinner}; use indicatif::ProgressBar; let spinner = MainSpinner::with_message("Advanced work".to_string()); let bar: ProgressBar = spinner.spinner(); // consume spinner bar.tick(); // Use indicatif API directly bar.finish_with_message("Done"); ``` -------------------------------- ### Ticking Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/traits.md Spinner lifecycle management trait for progress display. Provides a unified interface for starting, finishing, and failing spinners regardless of the underlying spinner type. ```APIDOC ## Ticking ### Description Spinner lifecycle management trait for progress display. ### Methods - `start()`: Enable 30ms tick rate; show animated spinner. - `finish()`: Show success symbol (✔); stop animation. - `fail()`: Show failure symbol (x); stop animation. ### Implementations - MainSpinner - CommandSpinner - Option - Option ### Usage Example ```rust use cargo_swift::console::{MainSpinner, Ticking}; let spinner = MainSpinner::with_message("Building".to_string()); spinner.start(); // ... work ... spinner.finish(); // or spinner.fail() ``` ``` -------------------------------- ### Init Command: UDL File Usage Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/configuration.md Enables the use of .udl files instead of macros for FFI declarations. When enabled, the generated project will include src/lib.udl and a build.rs file for UniFFI code generation. ```cli --udl Type: bool Default: false Description: Use .udl files instead of macros for FFI declarations. When set, generated project includes src/lib.udl and build.rs for UniFFI code generation. ``` -------------------------------- ### Init Command: Macro Mode (Deprecated) Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/configuration.md This option is deprecated and ignored. It previously controlled UDL vs macro mode, but macro mode is now the default. ```cli --macro (deprecated) Type: bool Default: false Description: Deprecated. Previously controlled UDL vs macro mode. Now ignored; macro mode (with optional .udl) is default. ``` -------------------------------- ### Manual Cargo Build for Detailed Errors Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/errors.md Shows how to manually run `cargo build` with specific targets and features to reproduce and inspect detailed compiler errors outside of the cargo-swift wrapper. ```bash # For target triple from error cargo build --target aarch64-apple-ios --release # For specific feature combination cargo build --target aarch64-apple-ios --all-features --release # With nightly cargo +nightly build --target aarch64-apple-tvos-sim --release -Z build-std ``` -------------------------------- ### Define Vcs Enum for Version Control Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/types.md Defines an enum to select the version control system for project initialization. Supports Git initialization or skipping VCS setup. ```rust #[derive(ValueEnum, Debug, Clone)] pub enum Vcs { Git, None, } ``` -------------------------------- ### cargo_swift::init::run Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/api-reference-init.md Initializes a new Rust library crate with boilerplate code for Swift interoperability via UniFFI. It sets up the project structure, including Cargo.toml, src/lib.rs, and UniFFI-related files. ```APIDOC ## Function: `run` Initializes a new Rust library crate with boilerplate code for Swift interoperability via UniFFI. ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * **crate_name** (String) - Required - Name of the Rust crate to create. Underscores will be added to the module namespace automatically. * **config** (Config) - Required - Configuration object controlling output behavior (silent mode, auto-accept prompts). * **vcs** (Vcs) - Required - Version control system to initialize. Either `Vcs::Git` or `Vcs::None`. * **lib_type** (LibType) - Required - Library type: `LibType::Static` (staticlib) or `LibType::Dynamic` (cdylib). * **plain** (bool) - Required - When `true`, creates minimal boilerplate without explanatory code comments and examples. * **macro_only** (bool) - Required - When `true`, uses macro-only approach without .udl files for UniFFI declarations. ### Request Example ```rust use cargo_swift::{init, Config, LibType}; use cargo_swift::commands::init::Vcs; let config = Config { silent: false, accept_all: false, }; let result = init::run( "my_lib".to_string(), config, Vcs::Git, LibType::Static, false, // plain = include examples false, // macro_only = use .udl files )?; ``` ### Response #### Success Response (200) * **Result<()>** - Returns `Ok(())` on successful project creation, or `Err(Error)` if initialization fails. #### Response Example ``` Ok(()) ``` ### Errors * **"Could not create directory for crate!"** - Unable to create the project directory (permissions or filesystem issue). * **Git initialization error** - Failure to initialize git repository when `vcs = Vcs::Git`. * **File write error** - Failure to write project template files (Cargo.toml, lib.rs, build.rs, etc.). ``` -------------------------------- ### Example Usage of Custom Error Type Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/types.md Shows how to use the custom Result type and handle errors, including returning an error using the ? operator and printing errors to stderr. ```rust use cargo_swift::Result; fn my_operation() -> Result<()> { Err("Operation failed")?; Ok(()) } // With error printing match my_operation() { Ok(_) => println!("Success"), Err(e) => e.print(), } ``` -------------------------------- ### Package Command Data Flow Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/architecture.md Outlines the comprehensive process for the 'package' command, covering metadata loading, platform selection, building, and artifact generation. ```text main.rs: package::run() │ ├─ Load cargo metadata (src/metadata.rs) │ └─ Current crate detection │ └─ Library target validation │ ├─ Determine library type │ ├─ Read crate-types from Cargo.toml │ ├─ Apply --lib-type override if provided │ └─ Prompt user if ambiguous │ ├─ Select platforms (src/targets.rs) │ ├─ Parse -p arguments or prompt interactively │ ├─ Expand Platform → ApplePlatform variants │ ├─ Create Target objects (Single/Universal) │ └─ Validate selections │ ├─ Query toolchains (src/targets.rs: ToolchainTargets) │ ├─ Query stable rustup targets │ ├─ Query nightly rustup targets │ ├─ Detect tier-3 architectures │ └─ Determine if nightly required │ ├─ Build phase (src/targets.rs: Target::commands()) │ ├─ For each Target (platform): │ │ ├─ For each architecture: │ │ │ ├─ Generate cargo build command │ │ │ ├─ Select toolchain (stable or nightly) │ │ │ ├─ Apply feature flags │ │ │ └─ Execute build │ │ │ │ │ └─ For Universal targets: │ │ ├─ Combine architectures with lipo │ │ └─ Produce single library file per platform │ │ │ └─ (via run_step_with_commands, nested spinners) │ ├─ Generate bindings (src/bindings.rs) │ └─ uniffi_bindgen generate Swift code │ ├─ Create XCFramework (src/xcframework.rs) │ ├─ Create {name}.xcframework bundle structure │ ├─ Copy binaries per platform │ ├─ Generate Info.plist per platform │ │ └─ Platform-specific keys from src/targets.rs │ ├─ Create/update install_name_tool for dylibs │ └─ Embed privacy manifest if provided │ ├─ Generate Package.swift (src/swiftpackage.rs) │ ├─ Create package manifest │ ├─ Declare platforms (via PlatformSpec::package_swift) │ ├─ Link XCFramework products │ └─ Set bundle properties │ └─ Result: Ok(()) or Err(ErrorMessage) ``` -------------------------------- ### Define Spinner Lifecycle with Ticking Trait Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/traits.md Implement this trait to manage the start, finish, and fail states of spinners. It provides a unified interface for progress display across different spinner types. ```rust pub trait Ticking { fn start(&self); fn finish(&self); fn fail(&self); } ``` -------------------------------- ### Catching Init Command Errors Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/errors.md Demonstrates how to handle potential errors returned by the `init::run` function. Errors are printed to stderr using `e.print()`, and further handling can be based on the error message content. ```rust use cargo_swift::init; match init::run(crate_name, config, vcs, lib_type, plain, !udl) { Ok(_) => println!("Project created successfully"), Err(e) => { e.print(); // Prints to stderr // Handle based on error message content } } ``` -------------------------------- ### Build Artifact Directory Structure Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/architecture.md Illustrates the typical directory layout for build artifacts, including per-architecture release builds and the final universal or XCFramework structures. ```tree target/ ├── aarch64-apple-ios/ │ └── release/ │ └── libmylib.a (or .dylib) │ ├── x86_64-apple-ios/ │ └── release/ │ └── libmylib.a (or .dylib) │ ├── universal-ios/ │ └── release/ │ └── libmylib.a (or .dylib) ← Combined by lipo │ └── aarch64-apple-darwin/ └── release/ └── libmylib.a (or .dylib) MyLibrary.xcframework/ ├── ios-aarch64/ │ ├── MyLibrary.framework/ │ │ ├── MyLibrary (binary) │ │ ├── Info.plist │ │ └── ... │ └── Info.plist (XCFramework metadata) │ ├── ios-arm64-x86_64-simulator/ │ ├── MyLibrary.framework/ │ │ ├── MyLibrary (universal binary) │ │ ├── Info.plist │ │ └── ... │ └── Info.plist │ ├── macos-arm64-x86_64/ │ ├── MyLibrary.framework/ │ │ ├── Versions/ │ │ │ └── A/ │ │ │ ├── MyLibrary (universal binary) │ │ │ ├── Info.plist │ │ │ └── ... │ │ ├── MyLibrary → Versions/A/MyLibrary (symlink) │ │ └── ... (symlinks) │ └── Info.plist │ └── Info.plist (master XCFramework metadata) ``` -------------------------------- ### Skip Toolchain Validation Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/configuration.md The `--skip-toolchains-check` flag bypasses validation of installed Rust toolchains. This is useful in offline or CI environments where `rustup` might be unavailable or unreliable. The build will fail at compile time if a toolchain is missing. ```bash --skip-toolchains-check Description: Skip validation of installed Rust toolchains. Useful for offline/CI environments where rustup is unavailable or unreliable. Build will fail at compile time if toolchain missing. ``` -------------------------------- ### Init Command: Library Type Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/configuration.md Sets the library binding type for the Cargo.toml crate-types. Choose between 'static' (linked into app) or 'dynamic' (wrapped in .framework bundle). ```cli --lib-type Type: LibType (enum: static, dynamic) Default: static Case-insensitive: Yes Description: Library binding type for Cargo.toml crate-types. 'static': staticlib (linked into app) 'dynamic': cdylib (wrapped in .framework bundle) ``` -------------------------------- ### Generic Function with Ticking Trait Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/traits.md This generic function accepts any type implementing the Ticking trait, allowing for flexible spinner integration in various workflows. It handles spinner start, finish, and fail logic based on the work's result. ```rust fn run_with_progress( spinner: &T, work: impl FnOnce() -> Result<()>, ) -> Result<()> { spinner.start(); let result = work(); match result { Ok(_) => spinner.finish(), Err(_) => spinner.fail(), } result } ``` -------------------------------- ### Bash Command Line Usage for cargo-swift init Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/api-reference-init.md Shows basic command-line invocation for initializing a new Rust project with specified version control and library type. ```bash cargo swift init my_lib --vcs git --lib-type static ``` -------------------------------- ### Enable Specific Cargo Features Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/configuration.md Use the `-F` or `--features` flag to enable specific Cargo features for the build. Multiple features can be specified, and this option is passed directly to `cargo build --features feat1,feat2`. Example: `-F neon simd`. ```bash --features (-F) ... Description: Specific Cargo features to enable. Passed to cargo build --features feat1,feat2 Example: -F neon simd ``` -------------------------------- ### Init Command: Crate Name Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/configuration.md Specifies the name of the Rust crate to be created. Underscores will be automatically added to the module namespace. ```cli Type: String Required: Yes Description: Name of the Rust crate to create. Underscores are automatically added to module namespace. Example: my-lib → my_lib (namespace) ``` -------------------------------- ### run_step Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/api-reference-console.md Executes a closure with a visual spinner showing progress and completion status. The spinner displays a checkmark on success or an 'x' on failure. It respects the silent mode in the Config, suppressing output when true. ```APIDOC ## run_step ### Description Executes a closure with a visual spinner showing progress and completion status. Spinner shows checkmark (✔) on success, x on failure. Suppressed in silent mode. ### Signature ```rust pub fn run_step(config: &Config, title: S, execute: E) -> Result where E: FnOnce() -> Result, S: ToString, ``` ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * None ### Parameters * **config** (&Config) - Required - Configuration controlling spinner visibility (silent mode). * **title** (S) - Required - Display text shown next to spinner during execution. * **execute** (E) - Required - Closure returning `Result` to execute with spinner feedback. ### Request Example ```rust use cargo_swift::{Config, console::run_step}; let config = Config { silent: false, accept_all: false }; let result: i32 = run_step(&config, "Building binaries", || { // Long-running operation Ok(42) })?; ``` ### Response #### Success Response (200) * **T** - The result from the closure. #### Response Example ```json // Example response depends on the closure's return type T ``` #### Error Response * **Error** - An error encountered during the execution of the closure. ``` -------------------------------- ### Enable Verbose Output for Debugging Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/errors.md Demonstrates how to enable verbose output and backtraces for debugging cargo-swift commands by setting the `RUST_BACKTRACE` environment variable. ```bash RUST_BACKTRACE=1 cargo swift package -y --silent -p ios --release ``` -------------------------------- ### Rust Function Signature for Init Command Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/api-reference-init.md This is the function signature for initializing a new Rust project for Swift interoperability. It outlines the parameters required for project creation. ```rust pub fn run( crate_name: String, config: Config, vcs: Vcs, lib_type: LibType, plain: bool, macro_only: bool, ) -> Result<()> ``` -------------------------------- ### Bash Command Line Usage for Package Command Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/api-reference-package.md Shows basic and advanced command-line invocations for the `cargo swift package` command. Use flags to specify platforms, names, and build modes. ```bash # Basic usage with interactive prompts cargo swift package --release # Specify platforms and build mode cargo swift package \ -p ios@13 macos@10_15 \ -n MyLibrary \ --release ``` -------------------------------- ### run_step_with_commands Source: https://github.com/antoniusnaumann/cargo-swift/blob/main/_autodocs/api-reference-console.md Executes a sequence of shell commands with nested progress indicators for each command. It displays a main spinner for the step and nested spinners for each command, capturing and returning stderr on failure. ```APIDOC ## run_step_with_commands ### Description Executes a sequence of shell commands with nested progress indicators for each command. Displays main spinner with title and nested spinners for each command. Captures stderr and stdout, returning stderr on any command failure. ### Signature ```rust pub fn run_step_with_commands(config: &Config, title: S, commands: &mut [Command]) -> Result<()> where S: ToString, ``` ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * None ### Parameters * **config** (&Config) - Required - Controls visual output (silent mode suppresses spinners). * **title** (S) - Required - Main step title displayed above command output. * **commands** (&mut [Command]) - Required - Mutable slice of `std::process::Command` objects to execute sequentially. ### Request Example ```rust use cargo_swift::{Config, console::run_step_with_commands}; use std::process::Command; let config = Config { silent: false, accept_all: false }; let mut commands = vec![ Command::new("cargo"), Command::new("rustc"), ]; commands[0].args(&["build", "--target", "aarch64-apple-ios"]); commands[1].args(&["--version"]); run_step_with_commands(&config, "Compiling for iOS", &mut commands)?; ``` ### Response #### Success Response (200) * **()** - Indicates all commands succeeded. #### Response Example ```json // No response body on success ``` #### Error Response * **Error** - Contains stderr if any command fails. ```