### Run cargo-make with Caching on CircleCI Source: https://github.com/sagiegurari/cargo-make/blob/master/docs/_includes/content.md This CircleCI example shows how to set up caching for cargo, conditionally install cargo-make, and run the 'ci-flow'. ```yaml - restore_cache: key: project-cache # .... - run: name: install cargo-make command: which cargo-make || cargo install cargo-make - run: name: ci flow command: cargo make ci-flow # .... - save_cache: key: project-cache paths: - "~/.cargo" ``` -------------------------------- ### Installing Pure Source Rustup Components in cargo-make TOML Source: https://github.com/sagiegurari/cargo-make/blob/master/docs/_includes/content.md Sets up installation for Rustup components like rust-src that lack binaries, so no verification test is possible. Cargo-make always attempts installation on task run. Requires rustup; installs sources without binary checks. ```toml [tasks.install-rust-src] install_crate = { rustup_component_name = "rust-src" } ``` -------------------------------- ### Install cargo-make using Cargo (Shell) Source: https://github.com/sagiegurari/cargo-make/blob/master/docs/api/src/cargo_make/main.rs.html This shell command installs the cargo-make tool via Cargo package manager. It requires Cargo to be installed on the system and an internet connection. Inputs: None. Outputs: Installs cargo-make binary to ~/.cargo/bin. Limitations: Must have Cargo available and may require PATH configuration. ```shell cargo install cargo-make ``` -------------------------------- ### Azure Pipelines Integration Source: https://github.com/sagiegurari/cargo-make/blob/master/docs/_includes/content.md Demonstrates integrating cargo-make into Azure Pipelines for installing and running the ci-flow. Provides examples for both standard and workspace configurations. Requires an azure-pipelines.yml file. ```yaml - script: cargo install --debug cargo-make displayName: install cargo-make - script: cargo make ci-flow displayName: ci flow ``` ```yaml - script: cargo install --debug cargo-make displayName: install cargo-make - script: cargo make --no-workspace workspace-ci-flow displayName: ci flow ``` -------------------------------- ### Handle Multiple Crate Installations in TOML Source: https://github.com/sagiegurari/cargo-make/blob/master/docs/_includes/content.md This TOML configuration demonstrates installing multiple crates and components using dependency tasks. It ensures items like cargo plugins and rustup components are installed once via task dependencies. Limitations include no automatic multiple installations in a single task. ```toml [tasks.install-rls] # install rls-preview only if needed install_crate = { rustup_component_name = "rls-preview", binary = "rls", test_arg = "--help" } [tasks.install-rust-src] # always install rust-src via rustup component add install_crate = { rustup_component_name = "rust-src" } [tasks.xbuild1] # run cargo xbuild, if xbuild is not installed, it will be automatically installed for you command = "cargo" args = [ "xbuild", "some arg" ] dependencies = [ "install-rls", "install-rust-src" ] [tasks.xbuild2] ``` -------------------------------- ### Run cargo-make with Caching on Travis CI Source: https://github.com/sagiegurari/cargo-make/blob/master/docs/_includes/content.md This example demonstrates how to conditionally install cargo-make and run the 'ci-flow' on Travis CI while utilizing cargo caching for faster builds. ```yaml cache: cargo script: - which cargo-make || cargo install cargo-make - cargo make ci-flow ``` -------------------------------- ### Install and Run cargo-make on Travis CI Source: https://github.com/sagiegurari/cargo-make/blob/master/docs/_includes/content.md This snippet shows the basic installation and execution of cargo-make for the 'ci-flow' within a Travis CI environment. ```yaml script: - cargo install --debug cargo-make - cargo make ci-flow ``` -------------------------------- ### Installing Native Dependencies with Script in cargo-make TOML Source: https://github.com/sagiegurari/cargo-make/blob/master/docs/_includes/content.md Uses install_script attribute for custom shell script to check and install native tools like kcov. Supports platform overrides (e.g., windows_alias). Script handles directory setup, dependency checks via help output, downloads, builds, and installs; uses environment variables for customization. ```toml [tasks.coverage-kcov] windows_alias = "empty" install_script = ''' KCOV_INSTALLATION_DIRECTORY="" KCOV_BINARY_DIRECTORY="" if [ -n "CARGO_MAKE_KCOV_INSTALLATION_DIRECTORY" ]; then mkdir -p ${CARGO_MAKE_KCOV_INSTALLATION_DIRECTORY} cd ${CARGO_MAKE_KCOV_INSTALLATION_DIRECTORY} KCOV_INSTALLATION_DIRECTORY="$(pwd)/" cd - echo "Kcov Installation Directory: ${KCOV_INSTALLATION_DIRECTORY}" KCOV_BINARY_DIRECTORY="${KCOV_INSTALLATION_DIRECTORY}/build/src/" echo "Kcov Binary Directory: ${KCOV_BINARY_DIRECTORY}" fi # get help info to fetch all supported command line arguments KCOV_HELP_INFO=`${KCOV_BINARY_DIRECTORY}kcov --help` || true # check needed arguments are supported, else install if [[ $KCOV_HELP_INFO != *"--include-pattern"* ]] || [[ $KCOV_HELP_INFO != *"--exclude-line"* ]] || [[ $KCOV_HELP_INFO != *"--exclude-region"* ]]; then # check we are on a supported platform if [ "$(grep -Ei 'debian|buntu|mint' /etc/*release)" ]; then echo "Installing/Upgrading kcov..." sudo apt-get update || true sudo apt-get install -y libcurl4-openssl-dev libelf-dev libdw-dev cmake gcc binutils-dev mkdir -p ${CARGO_MAKE_KCOV_DOWNLOAD_DIRECTORY} cd ${CARGO_MAKE_KCOV_DOWNLOAD_DIRECTORY} KCOV_DOWNLOAD_DIRECTORY=$(pwd) wget https://github.com/SimonKagstrom/kcov/archive/v${CARGO_MAKE_KCOV_VERSION}.zip unzip v${CARGO_MAKE_KCOV_VERSION}.zip cd kcov-${CARGO_MAKE_KCOV_VERSION} mkdir -p build cd ./build cmake .. make # if custom installation directory, leave kcov as local if [ -n "CARGO_MAKE_KCOV_INSTALLATION_DIRECTORY" ]; then cd ${KCOV_DOWNLOAD_DIRECTORY}/kcov-${CARGO_MAKE_KCOV_VERSION} mv ./* ${KCOV_INSTALLATION_DIRECTORY} else sudo make install cd ../.. rm -rf kcov-${CARGO_MAKE_KCOV_VERSION} fi fi fi ''' ``` -------------------------------- ### Install Rustup Component Source: https://github.com/sagiegurari/cargo-make/blob/master/docs/api/src/cli/installer/rustup_component_installer.rs.html This function installs a specified rustup component. It first checks if the component is already installed by verifying the presence and testability of its binary. If not installed, it invokes `invoke_rustup_install` and optionally validates the installation, reporting errors if validation fails. ```rust pub(crate) fn install( toolchain: &Option, info: &InstallRustupComponentInfo, validate: bool, ) -> bool { let mut installed = match info.binary { Some(ref binary) => match info.test_arg { Some(ref test_arg) => is_installed(&toolchain, binary, test_arg), None => false, }, None => false, }; if !installed { debug!( "Rustup Component: {} not installed.", &info.rustup_component_name ); installed = invoke_rustup_install(&toolchain, &info); if validate && !installed { error!( "Failed to add rustup component: {}", &info.rustup_component_name ); } installed } else { true } } ``` -------------------------------- ### Installing Third-Party Crates in cargo-make TOML Source: https://github.com/sagiegurari/cargo-make/blob/master/docs/_includes/content.md Defines tasks to verify and install crates like rustfmt-nightly or cargo-travis if binaries are missing. Uses rustup components if specified, falls back to cargo install. Tests binary availability with test_arg (string or array), then runs the command with args. ```toml [tasks.rustfmt] install_crate = { crate_name = "rustfmt-nightly", rustup_component_name = "rustfmt-preview", binary = "rustfmt", test_arg = "--help" } command = "rustfmt" ``` ```toml [tasks.doc-upload] install_crate = { crate_name = "cargo-travis", binary = "cargo", test_arg = ["doc-upload", "--help"] } command = "cargo" args = ["doc-upload"] ``` -------------------------------- ### Install Cargo Plugin from Command Info Source: https://github.com/sagiegurari/cargo-make/blob/master/docs/api/src/cli/installer/mod.rs.html Handles the installation of a cargo plugin by extracting command and crate name information. Uses cargo_plugin_installer to perform the actual installation. Requires a valid task configuration and toolchain reference. ```rust None => match get_cargo_plugin_info_from_command(&task_config) { Some((cargo_command, crate_name)) => { cargo_plugin_installer::install_crate( &toolchain, Some(&cargo_command), &crate_name, &task_config.install_crate_args, validate, &None, &None, &None, )?; } None => debug!("No installation script defined."), }, ``` -------------------------------- ### Install and Run cargo-make on AppVeyor Source: https://github.com/sagiegurari/cargo-make/blob/master/docs/_includes/content.md Basic configuration for AppVeyor CI to install cargo-make and execute the 'ci-flow'. ```yaml build: false test_script: - cargo install --debug cargo-make - cargo make ci-flow ``` -------------------------------- ### Installing Rustup Components with Binary in cargo-make TOML Source: https://github.com/sagiegurari/cargo-make/blob/master/docs/_includes/content.md Configures installation of Rustup components like rls-preview that provide executable binaries. Cargo-make checks binary availability via test_arg before installing the component. Depends on rustup; no crate fallback. ```toml [tasks.install-rls] install_crate = { rustup_component_name = "rls-preview", binary = "rls", test_arg = "--help" } ``` -------------------------------- ### Install cargo-make on Multiple Platforms Source: https://context7.com/sagiegurari/cargo-make/llms.txt Install cargo-make from crates.io with optional minimal features or from Arch Linux repositories. Supports force installation and default feature selection for different deployment needs. ```bash cargo install --force cargo-make ``` ```bash cargo install --no-default-features --force cargo-make ``` ```bash sudo pacman -S cargo-make ``` -------------------------------- ### Zsh Shell Completion Setup for cargo-make Source: https://github.com/sagiegurari/cargo-make/blob/master/docs/_includes/content.md Instructions for enabling Zsh shell completion for cargo-make tasks. Includes loading bash completion scripts and initializing completion systems. ```shell autoload -U +X compinit && compinit autoload -U +X bashcompinit && bashcompinit source ./extra/shell/makers-completion.bash ``` -------------------------------- ### Profile-Based Task Configuration with Echo Example - TOML Config Source: https://github.com/sagiegurari/cargo-make/blob/master/docs/_includes/content.md Complete example showing profile-based environment configuration with a task that demonstrates profile-specific variables. Includes COMMON variable, PROFILE_NAME using CARGO_MAKE_PROFILE, and profile-specific IS_DEV/IS_PROD boolean variables. The echo task prints all environment variables to verify profile activation. ```toml [env] COMMON = "COMMON" PROFILE_NAME = "${CARGO_MAKE_PROFILE}" [env.development] IS_DEV = true IS_PROD = false [env.production] IS_DEV = false IS_PROD = true [tasks.echo] script = [ ''' echo COMMON: ${COMMON} echo PROFILE_NAME: ${PROFILE_NAME} echo IS_DEV: ${IS_DEV} echo IS_PROD: ${IS_PROD} ''' ] ``` -------------------------------- ### Install and Run cargo-make on GitHub Actions Source: https://github.com/sagiegurari/cargo-make/blob/master/docs/_includes/content.md This snippet shows how to install cargo-make using the actions-rs/cargo action and then run the 'ci-flow'. It's designed for GitHub Actions workflows. ```yaml - name: Install cargo-make uses: actions-rs/cargo@v1 with: command: install args: --debug cargo-make - name: Run CI uses: actions-rs/cargo@v1 with: command: make args: ci-flow ``` -------------------------------- ### Install Rust crate with version validation Source: https://github.com/sagiegurari/cargo-make/blob/master/docs/api/src/cli/installer/cargo_plugin_installer.rs.html Main function responsible for installing Rust crates with comprehensive validation logic. Checks if crate is already installed, validates minimum version requirements, and executes installation with proper toolchain support. Supports force installation and custom installation commands. ```rust pub(crate) fn install_crate( toolchain: &Option, cargo_command: Option<&str>, crate_name: &str, args: &Option>, validate: bool, min_version: &Option, install_command: &Option, allow_force: &Option, ) -> Result<(), CargoMakeError> { let installed = match cargo_command { Some(cargo_command) => is_crate_installed(&toolchain, cargo_command), None => Ok(false), }?; let mut force = false; let allow_force_value = allow_force.unwrap_or(true); let run_installation = if !installed { true } else if toolchain.is_none() { match *min_version { Some(ref version) => { if crate_version_check::is_min_version_valid(&crate_name, version, None) { false } else { force = allow_force_value; true } } None => false, } } else { false }; if run_installation { let install_args = get_install_crate_args(crate_name, force, args, &min_version, install_command); match toolchain { Some(ref toolchain_string) => { let command_spec = wrap_command(&toolchain_string, "cargo", &Some(install_args)); command::run_command(&command_spec.command, &command_spec.args, validate)? } None => command::run_command("cargo", &Some(install_args), validate)?, }; } Ok(()) } ``` -------------------------------- ### Install and Run cargo-make on CircleCI Source: https://github.com/sagiegurari/cargo-make/blob/master/docs/_includes/content.md Basic CircleCI configuration to install cargo-make and execute the 'ci-flow' command. ```yaml - run: name: install cargo-make command: cargo install --debug cargo-make - run: name: ci flow command: cargo make ci-flow ``` -------------------------------- ### Install and Run cargo-make on GitLab CI Source: https://github.com/sagiegurari/cargo-make/blob/master/docs/_includes/content.md This snippet demonstrates the standard way to install cargo-make and run the 'ci-flow' within a GitLab CI configuration. ```yaml test:cargo: script: - cargo install --debug cargo-make - cargo make ci-flow ``` -------------------------------- ### Running cargo-make Tasks Source: https://context7.com/sagiegurari/cargo-make/llms.txt Examples of how to execute cargo-make tasks from the command line, including specifying environment variables for task execution. ```bash cargo make test-routing ``` ```bash cargo make --env IF_UNDEFINED=defined_from_cli echo-env ``` -------------------------------- ### Use Alternate Install Command in TOML Source: https://github.com/sagiegurari/cargo-make/blob/master/docs/_includes/content.md This TOML configuration specifies custom install commands like plugins for crate installation. It includes options for crate name and automatically adds the --force flag by default. Dependencies include the cargo-make environment. ```toml [tasks.alt-command-example1] install_crate = { install_command = "custom-install" } command = "cargo" args = ["somecrate"] [tasks.alt-command-example2] install_crate = { crate_name = "somecrate", install_command = "custom-install" } ``` -------------------------------- ### Install Cargo Crates and Components with cargo-make Source: https://context7.com/sagiegurari/cargo-make/llms.txt Automatically install Cargo crates, plugins, and rustup components before task execution using the `install_crate` configuration. This ensures all necessary dependencies are met before a task runs. Supports specifying minimum versions, binary names, and custom installation commands. ```toml [config] skip_core_tasks = true [tasks.simple-example] install_crate = { min_version = "0.0.1" } command = "cargo" args = ["make", "--version"] [tasks.complex-example] install_crate = { crate_name = "cargo-make", binary = "cargo", test_arg = ["make", "--version"], min_version = "0.0.1" } command = "cargo" args = ["make", "--version"] [tasks.alt-command-example] install_crate = { crate_name = "somecrate", install_command = "custom-install" } [tasks.alt-command-example-full.install_crate] crate_name = "cargo-make" binary = "cargo" test_arg = ["make", "--help"] version = "9999.0.0" install_command = "custom-install" force = false [tasks.fmt] install_crate = { crate_name = "rustfmt", binary = "rustfmt", version = "1.4.37", test_arg = "--help" } command = "cargo" args = ["fmt"] ``` -------------------------------- ### Task Global Variables and Metadata Setup Source: https://github.com/sagiegurari/cargo-make/blob/master/docs/api/src/cli/plugin/runner.rs.html Configures global script variables for task execution including JSON representation, presence flags for various task features (condition, env, install instructions, command, script, dependencies), and metadata about task capabilities. ```rust fn setup_script_globals_for_task(context: &mut Context, step: &Step, script: &mut String) { // all task data as json let task = step.config.clone(); let json_string = json!(task); context .variables .insert("task.as_json".to_string(), json_string.to_string()); // meta info context.variables.insert( "task.has_condition".to_string(), (task.condition.is_some() || task.condition_script.is_some()).to_string(), ); context.variables.insert( "task.has_env".to_string(), (task.env_files.is_some() || task.env.is_some()).to_string(), ); context.variables.insert( "task.has_install_instructions".to_string(), (task.install_crate.is_some() || task.install_crate_args.is_some() || task.install_script.is_some()) .to_string(), ); context.variables.insert( "task.has_command".to_string(), task.command.is_some().to_string(), ); context.variables.insert( "task.has_script".to_string(), task.script.is_some().to_string(), ); context.variables.insert( "task.has_run_task".to_string(), task.run_task.is_some().to_string(), ); context.variables.insert( "task.has_dependencies".to_string(), task.dependencies.is_some().to_string(), ); } ``` -------------------------------- ### Load Scripts (Git Clone Example) (Shell) Source: https://github.com/sagiegurari/cargo-make/blob/master/docs/_includes/content.md Demonstrates loading a TOML file from a Git repository using the 'git clone' command. This provides a mechanism for fetching common task definitions from version control systems. ```toml [config] load_script = "git clone git@mygitserver:user/project.git /home/myuser/common" ``` -------------------------------- ### Global Configuration for cargo-make Source: https://github.com/sagiegurari/cargo-make/blob/master/docs/_includes/content.md Example configuration for cargo-make global settings including log level, color settings, default task name, and update check intervals. ```toml log_level = "info" disable_color = false default_task_name = "default" update_check_minimum_interval = "weekly" search_project_root = false ``` -------------------------------- ### Generate crate installation arguments Source: https://github.com/sagiegurari/cargo-make/blob/master/docs/api/src/cli/installer/cargo_plugin_installer.rs.html Function that constructs the argument vector for cargo install commands. Handles force installation, custom arguments, version specifications, and conditional locking based on environment variables. Supports skipping crate name for git installations. ```rust pub(crate) fn get_install_crate_args( crate_name: &str, force: bool, args: &Option>, version_option: &Option, install_command: &Option, ) -> Vec { let install_command_str = match install_command { Some(value) => value.clone(), None => "install".to_string(), }; let mut install_args = vec![install_command_str.to_string()]; if force { install_args.push("--force".to_string()); } match *args { Some(ref args_vec) => { for arg in args_vec.iter() { install_args.push(arg.to_string()); } } None => debug!("No crate installation args defined."), }; let skip_crate_name = should_skip_crate_name(&args); if !skip_crate_name { // add locked flags if let Some(version) = version_option { if envmnt::is("CARGO_MAKE_CRATE_INSTALLATION_LOCKED") { install_args.push("--locked".to_string()); install_args.push("--version".to_string()); install_args.push(version.to_string()); } } install_args.push(crate_name.to_string()); } install_args } ``` -------------------------------- ### Rust: Install Dependencies for Cargo-Make Task Source: https://github.com/sagiegurari/cargo-make/blob/master/docs/api/src/cli/installer/mod.rs.html Initiates the installation process for dependencies defined in a task configuration. It first checks if dependency installation is disabled in the flow configuration. If not disabled, it proceeds with the installation logic. ```rust pub(crate) fn install( task_config: &Task, flow_info: &FlowInfo, flow_state: Rc>, ) -> Result<(), CargoMakeError> { if let Some(disable_install) = flow_info.config.config.disable_install { if disable_install { ``` -------------------------------- ### Install Rust Crate via Cargo Source: https://github.com/sagiegurari/cargo-make/blob/master/docs/api/src/cli/installer/crate_installer.rs.html Installs a Rust crate using the `cargo install` command. It handles versioning, force installation, and locking to prevent duplicate installations. The function also supports wrapping the command with a specified toolchain. ```rust fn invoke_cargo_install( toolchain: &Option, info: &InstallCrateInfo, args: &Option>, validate: bool, ) -> Result<(), CargoMakeError> { let (automatic_lock_version, version_option) = if info.min_version.is_some() { (false, &info.min_version) } else { (info.version.is_some(), &info.version) }; let remove_lock = if automatic_lock_version && !envmnt::is("CARGO_MAKE_CRATE_INSTALLATION_LOCKED") { envmnt::set_bool("CARGO_MAKE_CRATE_INSTALLATION_LOCKED", true); true } else { false }; let install_args = cargo_plugin_installer::get_install_crate_args( &info.crate_name, info.force.unwrap_or(true), &args, version_option, &info.install_command, ); let command_spec = match toolchain { Some(ref toolchain_string) => wrap_command(toolchain_string, "cargo", &Some(install_args)), None => CommandSpec { command: "cargo".to_string(), args: Some(install_args), }, }; command::run_command(&command_spec.command, &command_spec.args, validate)?; if remove_lock { envmnt::remove("CARGO_MAKE_CRATE_INSTALLATION_LOCKED"); } Ok(()) } ``` -------------------------------- ### Plugin Script Global Context Setup Source: https://github.com/sagiegurari/cargo-make/blob/master/docs/api/src/cli/plugin/runner.rs.html Sets up global variables and script content for plugin execution, including flow task name, CLI arguments array population, plugin implementation name, and delegation to task-specific global setup. ```rust fn setup_script_globals( context: &mut Context, flow_info: &FlowInfo, step: &Step, impl_plugin_name: &str, script: &mut String, ) { context .variables .insert("flow.task.name".to_string(), flow_info.task.to_string()); script.push_str("flow.cli.args = array\n"); if let Some(ref cli_arguments) = flow_info.cli_arguments { for arg in cli_arguments { script.push_str("array_push ${flow.cli.args} \""); script.push_str(&arg.replace("$", "\\$")); script.push_str("\"\n"); } } context .variables .insert("plugin.impl.name".to_string(), impl_plugin_name.to_string()); setup_script_globals_for_task(context, step, script); } ``` -------------------------------- ### Execute cargo-make task with automatic dependency installation Source: https://context7.com/sagiegurari/cargo-make/llms.txt This bash command executes the 'fmt' task defined in a cargo-make file. Dependencies specified via `install_crate` in the TOML configuration will be automatically installed before the task runs. ```bash cargo make fmt ``` -------------------------------- ### drone.io Integration Source: https://github.com/sagiegurari/cargo-make/blob/master/docs/_includes/content.md Provides a minimal drone.yml example for running the ci-flow task using the docker runner. It outlines the necessary image and commands for executing cargo-make within a drone.io pipeline. Configuration in a .drone.yml file required. ```yaml pipeline: ci-flow: image: rust:1.38-slim commands: - cargo install --debug cargo-make - cargo make ci-flow ``` -------------------------------- ### Install Rustup Component via rustup Source: https://github.com/sagiegurari/cargo-make/blob/master/docs/api/src/cli/installer/crate_installer.rs.html Installs a specified rustup component. This function checks if the component name is provided in the `InstallCrateInfo` and then calls the `rustup_component_installer::invoke_rustup_install` function. It returns a boolean indicating whether the installation was attempted. ```rust fn invoke_rustup_install(toolchain: &Option, info: &InstallCrateInfo) -> bool { match info.rustup_component_name { Some(ref component) => { let rustup_component_info = InstallRustupComponentInfo { rustup_component_name: component.to_string(), binary: Some(info.binary.clone()), test_arg: Some(info.test_arg.clone()), }; rustup_component_installer::invoke_rustup_install(&toolchain, &rustup_component_info) } None => false, } } ``` -------------------------------- ### Install Crate Logic in Rust Source: https://github.com/sagiegurari/cargo-make/blob/master/docs/api/src/cli/installer/mod.rs.html This Rust code handles the installation of crates based on various configuration options within cargo-make. It supports direct crate names, cargo plugin information, and rustup components. The function determines the appropriate installer based on the `install_crate` configuration and executes the installation process, validating inputs and handling potential errors. ```Rust let mut install_crate = task_config.install_crate.clone(); if let Some(ref install_crate_value) = install_crate { if let InstallCrate::Enabled(enabled) = install_crate_value { if *enabled { // enabled true is the same as no install_crate defined install_crate = None; } } } match install_crate { Some(ref install_crate_info) => match install_crate_info { InstallCrate::Enabled(_) => (), InstallCrate::Value(ref crate_name) => { let first_arg = get_first_command_arg(task_config); match first_arg { Some(ref cargo_command) => cargo_plugin_installer::install_crate( &toolchain, Some(cargo_command), crate_name, &task_config.install_crate_args, validate, &None, &None, &None, ), None => cargo_plugin_installer::install_crate( &toolchain, None, crate_name, &task_config.install_crate_args, validate, &None, &None, &Some(false), // we can't validate, so we do not allow force ), }?; } InstallCrate::CargoPluginInfo(ref install_info) => { let (cargo_command, crate_name) = match get_cargo_plugin_info_from_command(&task_config) { Some(cargo_plugin_info) => cargo_plugin_info, None => match get_first_command_arg(task_config) { Some(arg) => match install_info.crate_name { Some(ref crate_name) => (arg, crate_name.to_string()), None => { error!("Missing crate name to invoke."); return Err(CargoMakeError::NotFound(String::from( "Missing crate name to invoke." ))); } }, None => match install_info.crate_name { Some(ref crate_name) => { (crate_name.to_string(), crate_name.to_string()) } None => { error!("Missing cargo command to invoke."); return Err(CargoMakeError::NotFound(String::from( "Missing cargo command to invoke." ))); } }, }, }; cargo_plugin_installer::install_crate( &toolchain, Some(&cargo_command), &crate_name, &task_config.install_crate_args, validate, &install_info.min_version, &install_info.install_command, &install_info.force, )?; } InstallCrate::CrateInfo(ref install_info) => crate_installer::install( &toolchain, install_info, &task_config.install_crate_args, validate, )?, InstallCrate::RustupComponentInfo(ref install_info) => { rustup_component_installer::install(&toolchain, install_info, validate); } }, None => match task_config.install_script { Some(ref script) => { scriptengine::invoke_script_in_flow_context( &script, task_config.script_runner.clone(), task_config.script_runner_args.clone(), task_config.script_extension.clone(), validate, Some(flow_info), Some(flow_state), )?; () } }, } ``` -------------------------------- ### Rust Clone Implementation for InstallCrateInfo Source: https://github.com/sagiegurari/cargo-make/blob/master/docs/api/cli/types/struct.InstallCrateInfo.html Provides a Clone implementation for the InstallCrateInfo struct, allowing for easy copying of struct instances. This is useful for creating copies of installation instructions. ```rust impl Clone for InstallCrateInfo { fn clone(&self) -> InstallCrateInfo { InstallCrateInfo { crate_name: self.crate_name.clone(), rustup_component_name: self.rustup_component_name.clone(), binary: self.binary.clone(), test_arg: self.test_arg.clone(), min_version: self.min_version.clone(), version: self.version.clone(), install_command: self.install_command.clone(), force: self.force.clone(), } } } ``` -------------------------------- ### Defining Task for Cargo Xbuild Execution Source: https://github.com/sagiegurari/cargo-make/blob/master/docs/_includes/content.md This TOML configuration defines a task to run cargo xbuild with specified arguments, automatically installing xbuild if absent. It includes dependencies on tasks for installing RLS and Rust source. A flow task is also defined depending on multiple xbuild variants. Inputs are task names; outputs are executed commands with potential installations. ```toml # run cargo xbuild, if xbuild is not installed, it will be automatically installed for you command = "cargo" args = [ "xbuild", "another arg" ] dependencies = [ "install-rls", "install-rust-src" ] [tasks.myflow] dependencies = [ "xbuild1", "xbuild2" ] ``` -------------------------------- ### Disable Force Flag in Alternate Install Command in TOML Source: https://github.com/sagiegurari/cargo-make/blob/master/docs/_includes/content.md This TOML configuration disables the default --force flag for custom install commands. It builds on alternate install setups to prevent overwriting existing installations. Requires specifying force = false alongside other attributes. ```toml [tasks.alt-command-example2] install_crate = { crate_name = "somecrate", install_command = "custom-install", force = false } ``` -------------------------------- ### Listing Cargo Make Steps Source: https://github.com/sagiegurari/cargo-make/blob/master/docs/_includes/content.md Shows how to list currently supported providers by using the grep command. ```sh cargo make --list-all-steps | grep "coverage-" ``` -------------------------------- ### Disable Automatic Crate Installation in cargo-make Source: https://github.com/sagiegurari/cargo-make/blob/master/docs/_includes/content.md Example of disabling automatic installation of cargo plugins by setting install_crate to false, useful when the plugin is already available. ```toml [tasks.test] command = "cargo" args = ["test"] install_crate = false ``` -------------------------------- ### Trim Start Whitespace from Environment Variable (TOML) Source: https://github.com/sagiegurari/cargo-make/blob/master/docs/_includes/content.md This example demonstrates using the trim function to remove only leading whitespace from an environment variable. The trim function accepts the environment variable name and 'start' as the trim type. ```toml [env] TRIM_VALUE=" 123 " [tasks.trim-start] command = "echo" args = ["@@trim(TRIM_VALUE,start)"] ``` -------------------------------- ### PowerShell Script Execution with 'powershell' Runner Source: https://github.com/sagiegurari/cargo-make/blob/master/docs/_includes/content.md Example of running PowerShell scripts using cargo-make. The 'powershell' script runner and '.ps1' script extension are specified. The PowerShell commands are provided as a string within the task configuration. ```toml [tasks.powershell] script_runner = "powershell" script_extension = "ps1" script = ''' Write-Host "Hello, World!" ''' ``` -------------------------------- ### Rust: Get Cargo Plugin Info from Task Config Source: https://github.com/sagiegurari/cargo-make/blob/master/docs/api/src/cli/installer/mod.rs.html Extracts the command and crate name for a cargo plugin installation from a task configuration. It checks if the command is 'cargo' and if arguments are provided, specifically looking for the first argument that is not a flag. Returns the command and the derived crate name if found, otherwise None. ```rust fn get_cargo_plugin_info_from_command(task_config: &Task) -> Option<(String, String)> { match task_config.command { Some(ref command) => { if command == "cargo" { match task_config.args { Some(ref args) => { if args.len() > 0 && !args[0].starts_with("-") { // create crate name let mut crate_name = "cargo-".to_string(); crate_name = crate_name + &args[0]; Some((args[0].clone(), crate_name)) } else { None } } None => None, } } else { None } } None => None, } } ``` -------------------------------- ### List Tasks - Rust (cargo-make) Source: https://github.com/sagiegurari/cargo-make/blob/master/docs/api/src/cli/cli_commands/list_steps.rs.html Entry point run() parses CLI options and prints or writes output. Helper create_list() aggregates tasks, applies category/visibility filters, and formats results for different output formats. ```rust //! # list_steps //! //! Lists all known tasks in multiple formats. //! Or can list tasks based on a category //! #[cfg(test)] #[path = "list_steps_test.rs"] mod list_steps_test; use crate::error::CargoMakeError; use crate::execution_plan; use crate::io; use crate::types::{Config, DeprecationInfo}; use std::collections::{BTreeMap, BTreeSet}; pub fn run( config: &Config, output_format: &str, output_file: &Option, category: &Option, hide_uninteresting: bool, ) -> Result<(), CargoMakeError> { let output = create_list(&config, output_format, category, hide_uninteresting)?; match output_file { Some(file) => { io::write_text_file(&file, &output); () } None => print!("{}", output), }; Ok(()) } pub(crate) fn create_list( config: &Config, output_format: &str, category_filter: &Option, hide_uninteresting: bool, ) -> Result { // category -> actual_task -> description let mut categories: BTreeMap> = BTreeMap::new(); // actual_task -> aliases let mut aliases: BTreeMap> = BTreeMap::new(); // iterate over all tasks to build categories and aliases for key in config.tasks.keys() { let actual_task_name = execution_plan::get_actual_task_name(&config, &key)?; let task = execution_plan::get_normalized_task(&config, &actual_task_name, true)?; let is_private = match task.private { Some(private) => private, None => false, }; let skip_task = if is_private { true } else if hide_uninteresting { key.contains("pre-") || key.contains("post-") || key == "init" || key == "end" || key == "empty" } else { false }; if !skip_task { let category = match task.category { Some(value) => value, None => "No Category".to_string(), }; ``` -------------------------------- ### Init and End Tasks Configuration Source: https://github.com/sagiegurari/cargo-make/blob/master/docs/_includes/content.md Configures global init and end tasks that are automatically invoked at the start and end of all cargo-make flows. These special tasks can be used for setup and cleanup operations that should run regardless of which specific flow is executed. ```toml [config] init_task = "init" end_task = "end" [tasks.init] [tasks.end] ``` -------------------------------- ### Get Project Root Directory by Cargo.toml Source: https://github.com/sagiegurari/cargo-make/blob/master/docs/api/src/cli/environment/mod.rs.html Recursively searches for a Cargo.toml file starting from the provided directory. Returns the path to the directory containing Cargo.toml if found, otherwise None. Handles the current directory if '.' is provided. ```rust pub(crate) fn get_project_root_for_path(directory: &PathBuf) -> Option { let from_dir = if directory.to_str().unwrap_or(".") == "." { current_dir_or(directory) } else { directory.to_path_buf() }; debug!("Looking for project root from directory: {:?}", &from_dir); let file_path = Path::new(&from_dir).join("Cargo.toml"); if file_path.exists() { match from_dir.to_str() { Some(directory_string) => Some(directory_string.to_string()), _ => None, } } else { match from_dir.parent() { Some(parent_directory) => { let parent_directory_path = parent_directory.to_path_buf(); get_project_root_for_path(&parent_directory_path) } None => None, } } } ``` -------------------------------- ### Define Minimum Crate Version in TOML Source: https://github.com/sagiegurari/cargo-make/blob/master/docs/_includes/content.md This TOML configuration defines tasks with minimum version requirements for installed crates, ensuring compatibility. It supports simple and complex examples with test arguments. Limitations include ignoring versions when toolchain or rustup components are specified. ```toml [tasks.simple-example] install_crate = { min_version = "0.0.1" } command = "cargo" args = ["make", "--version"] [tasks.complex-example] install_crate = { crate_name = "cargo-make", binary = "cargo", test_arg = ["make", "--version"], min_version = "0.0.1" } command = "cargo" args = ["make", "--version"] ``` -------------------------------- ### Get Latest Cargo-Make Version via Cargo Search Source: https://github.com/sagiegurari/cargo-make/blob/master/docs/api/src/cli/version.rs.html Fetches the latest version of the 'cargo-make' crate from the crates.io registry using the 'cargo search' command. It parses the output to extract the version string. This function is crucial for comparing the installed version with the latest available. ```rust fn get_latest_version() -> Option { let result = Command::new("cargo") .arg("search") .arg("cargo-make") .arg("--limit=1") .output(); match result { Ok(output) => { let exit_code = command::get_exit_code(Ok(output.status), false); if exit_code == 0 { let stdout = String::from_utf8_lossy(&output.stdout); let lines: Vec<&str> = stdout.split('\n').collect(); let mut output = None; for mut line in lines { line = line.trim(); debug!("Checking: {}", &line); if line.starts_with("cargo-make = ") { // ... rest of the parsing logic ... } } output } else { error!("cargo search failed with exit code: {}", exit_code); None } } Err(e) => { error!("Failed to execute cargo search: {}", e); None } } } ``` -------------------------------- ### Rust: Get First Command Argument from Task Config Source: https://github.com/sagiegurari/cargo-make/blob/master/docs/api/src/cli/installer/mod.rs.html Retrieves the first argument provided in a task's command arguments. If the task has arguments and the list is not empty, it returns the first argument as a String. Returns None if there are no arguments or if the argument list is empty. ```rust fn get_first_command_arg(task_config: &Task) -> Option { match task_config.args { Some(ref args) => { if args.is_empty() { None } else { Some(args[0].to_string()) } } None => None, } } ``` -------------------------------- ### Implement Script Reusability with Pre/Main/Post Forms Source: https://github.com/sagiegurari/cargo-make/blob/master/docs/_includes/content.md Shows how to create reusable script components using script pre, main, and post properties. Demonstrates script extension functionality where tasks can inherit from base scripts and override specific parts while preserving common setup and cleanup logic. ```toml [tasks.base-script] script.pre = "echo start" script.main = "echo old" script.post = "echo end" [tasks.extended-script] extend = "base-script" script.main = "echo new" ``` -------------------------------- ### Cargo-Make Task Execution Flow Example Source: https://github.com/sagiegurari/cargo-make/blob/master/docs/_includes/content.md Illustrates the command to execute a cargo-make task ('test') using a specified makefile. cargo-make analyzes task dependencies to create an execution plan, ensuring tasks are run in the correct order (e.g., format -> build -> test) and that each task runs only once. ```sh cargo make --makefile ./my_build.toml test ``` -------------------------------- ### Define Skip Tasks Pattern Argument in Rust for cargo-make Source: https://github.com/sagiegurari/cargo-make/blob/master/docs/api/src/cli/cli_parser.rs.html This Rust code defines the '--skip-tasks' argument for cargo-make, which accepts a regex pattern. It allows users to skip multiple tasks based on a provided pattern, with an example showing how to skip tasks starting with 'pre' or 'post'. ```Rust name: "skip-tasks-pattern".to_string(), key: vec!["--skip-tasks".to_string()], argument_occurrence: ArgumentOccurrence::Single, value_type: ArgumentValueType::Single, default_value: None, help: Some(ArgumentHelp::TextAndParam( "Skip all tasks that match the provided regex (example: pre.*|post.*)".to_string(), "SKIP_TASK_PATTERNS".to_string(), )), ``` -------------------------------- ### Invoke Basic Sub Task in cargo-make (TOML) Source: https://github.com/sagiegurari/cargo-make/blob/master/docs/_includes/content.md This example shows how to use run_task to invoke a simple sub task. The flow task executes the echo task defined by its script. No dependencies are required beyond basic cargo-make setup; input is the task name, output is the sub task's result. Note that this does not support conditions or forking. ```toml [tasks.echo] script = "echo hello world" [tasks.flow] run_task = "echo" ``` -------------------------------- ### Example output of cargo-make task execution Source: https://github.com/sagiegurari/cargo-make/blob/master/docs/_includes/content.md This console output shows the step-by-step execution of the 'my-flow' task defined in a Makefile.toml. It logs the initiation of each sub-task (format, clean, build, test), the commands being executed, and the progress of compilation and test runs. The output concludes with the total build time, providing insight into the automation process. ```console [cargo-make] INFO - cargo make {{ site.version }} [cargo-make] INFO - Build File: Makefile.toml [cargo-make] INFO - Task: my-flow [cargo-make] INFO - Setting Up Env. [cargo-make] INFO - Running Task: format [cargo-make] INFO - Execute Command: "cargo" "fmt" "--" "--emit=files" [cargo-make] INFO - Running Task: clean [cargo-make] INFO - Execute Command: "cargo" "clean" [cargo-make] INFO - Running Task: build [cargo-make] INFO - Execute Command: "cargo" "build" Compiling bitflags v0.9.1 Compiling unicode-width v0.1.4 Compiling quote v0.3.15 Compiling unicode-segmentation v1.1.0 Compiling strsim v0.6.0 Compiling libc v0.2.24 Compiling serde v1.0.8 Compiling vec_map v0.8.0 Compiling ansi_term v0.9.0 Compiling unicode-xid v0.0.4 Compiling synom v0.11.3 Compiling rand v0.3.15 Compiling term_size v0.3.0 Compiling atty v0.2.2 Compiling syn v0.11.11 Compiling textwrap v0.6.0 Compiling clap v2.25.0 Compiling serde_derive_internals v0.15.1 Compiling toml v0.4.2 Compiling serde_derive v1.0.8 Compiling cargo-make v0.1.2 (file:///home/ubuntu/workspace) Finished dev [unoptimized + debuginfo] target(s) in 79.75 secs [cargo-make] INFO - Running Task: test [cargo-make] INFO - Execute Command: "cargo" "test" Compiling cargo-make v0.1.2 (file:///home/ubuntu/workspace) Finished dev [unoptimized + debuginfo] target(s) in 5.1 secs Running target/debug/deps/cargo_make-d5f8d30d73043ede running 10 tests test log::tests::create_info ... ok test log::tests::get_level_error ... ok test log::tests::create_verbose ... ok test log::tests::get_level_info ... ok test log::tests::get_level_other ... ok test log::tests::get_level_verbose ... ok test installer::tests::is_crate_installed_false ... ok test installer::tests::is_crate_installed_true ... ok test command::tests::validate_exit_code_error ... ok test log::tests::create_error ... ok test result: ok. 10 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out [cargo-make] INFO - Running Task: my-flow [cargo-make] INFO - Build done in 72 seconds. ``` -------------------------------- ### Load Scripts (HTTP Example) (Shell) Source: https://github.com/sagiegurari/cargo-make/blob/master/docs/_includes/content.md Illustrates how to use load scripts to download a common TOML file from a remote server using HTTP via the 'wget' command. This allows for pulling common task definitions from remote locations before extending. ```toml [config] load_script = "wget -O /home/myuser/common.toml companyserver.com/common.toml" ``` -------------------------------- ### Check if Install Info is Crate Only Source: https://github.com/sagiegurari/cargo-make/blob/master/docs/api/src/cli/installer/crate_installer.rs.html Determines if the provided `InstallCrateInfo` solely pertains to a crate installation, without any associated rustup component. This is useful for differentiating installation strategies. ```rust fn is_crate_only_info(info: &InstallCrateInfo) -> bool { match info.rustup_component_name { Some(_) => false, None => true, } } ``` -------------------------------- ### Cargo Make Coverage Command Source: https://github.com/sagiegurari/cargo-make/blob/master/docs/_includes/content.md Demonstrates running the coverage command for coverage report generation. ```sh cargo make coverage ``` -------------------------------- ### Implementing Composite Flow for Workspace and Members Source: https://github.com/sagiegurari/cargo-make/blob/master/docs/_includes/content.md Define a composite task in TOML that depends on member and workspace flows, using fork=true to trigger member execution while running root tasks directly. Invoke with --no-workspace to start the composite at root, ensuring both levels are processed. Dependencies include defined sub-tasks; outputs sequential execution across root and members; limitation: requires proper fork setup for detection. ```toml [tasks.composite] dependencies = ["member_flow", "workspace_flow"] [tasks.member_flow] # by forking, cargo make starts and by default detects it is a workspace and runs the member_task for each member run_task = { name = "member_task", fork = true } [tasks.workspace_flow] #run some workspace level command or flow ``` ```sh cargo make --no-workspace composite ``` -------------------------------- ### Cirrus CI Integration Source: https://github.com/sagiegurari/cargo-make/blob/master/docs/_includes/content.md Demonstrates integrating cargo-make into Cirrus CI, outlining the container image and task configuration required to execute the ci-flow. Requires a .cirrus.yml file. ```yaml container: image: rust:latest task: name: ci-flow install_script: cargo install --debug cargo-make flow_script: cargo make ci-flow ```