{"id":33609448,"url":"https://github.com/tracel-ai/xtask","last_synced_at":"2026-04-01T19:05:28.476Z","repository":{"id":249300947,"uuid":"830569290","full_name":"tracel-ai/xtask","owner":"tracel-ai","description":"Reusable and Extensible xtask commands to manage repositories.","archived":false,"fork":false,"pushed_at":"2026-01-22T17:37:26.000Z","size":1512,"stargazers_count":15,"open_issues_count":3,"forks_count":7,"subscribers_count":2,"default_branch":"main","last_synced_at":"2026-01-23T10:41:20.191Z","etag":null,"topics":["cargo","cli","extensible","rust","xtask"],"latest_commit_sha":null,"homepage":"","language":"Rust","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/tracel-ai.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE-APACHE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2024-07-18T14:18:27.000Z","updated_at":"2026-01-22T17:24:39.000Z","dependencies_parsed_at":"2024-08-05T19:02:56.750Z","dependency_job_id":"82f20069-73bb-43d4-9da5-42f121177a73","html_url":"https://github.com/tracel-ai/xtask","commit_stats":null,"previous_names":["tracel-ai/xtask"],"tags_count":65,"template":false,"template_full_name":null,"purl":"pkg:github/tracel-ai/xtask","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tracel-ai%2Fxtask","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tracel-ai%2Fxtask/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tracel-ai%2Fxtask/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tracel-ai%2Fxtask/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/tracel-ai","download_url":"https://codeload.github.com/tracel-ai/xtask/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tracel-ai%2Fxtask/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28846830,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-28T15:15:36.453Z","status":"ssl_error","status_checked_at":"2026-01-28T15:15:13.020Z","response_time":57,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cargo","cli","extensible","rust","xtask"],"created_at":"2025-11-30T19:03:02.522Z","updated_at":"2026-04-01T19:05:28.457Z","avatar_url":"https://github.com/tracel-ai.png","language":"Rust","funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003cdiv align=\"center\"\u003e\n\u003cimg src=\"https://raw.githubusercontent.com/tracel-ai/xtask/main/assets/xtask.png\" width=\"256px\"/\u003e\n\n\u003ch1\u003eTracel Xtask\u003c/h1\u003e\n\n[![Discord](https://img.shields.io/discord/1038839012602941528.svg?color=7289da\u0026\u0026logo=discord)](https://discord.gg/uPEBbYYDB6)\n[![Current Crates.io Version](https://img.shields.io/crates/v/tracel-xtask)](https://crates.io/crates/tracel-xtask)\n[![Minimum Supported Rust Version](https://img.shields.io/crates/msrv/tracel-xtask)](https://crates.io/crates/tracel-xtask)\n[![Test Status](https://github.com/tracel-ai/xtask/actions/workflows/ci.yml/badge.svg)](https://github.com/tracel-ai/xtask/actions/workflows/ci.yml)\n![license](https://shields.io/badge/license-MIT%2FApache--2.0-blue)\n\n---\n\n\u003cbr/\u003e\n\u003c/div\u003e\n\nA collection of easy-to-use and extensible commands to be used in your [xtask CLI][1] based on [clap][2].\n\nWe rely on these commands in each of our Tracel repositories. By centralizing our redundant commands we save a big amount\nof code duplication, boilerplate and considerably lower their maintenance cost. This also provides a unified interface across\nall of our repositories.\n\nThese commands are not specific to Tracel repositories and they should be pretty much usable in any Rust repositories with\na cargo workspace as well as other repositories where Rust is not necessarily the only language. The commands can be easily\nextended using handy proc macros and by following some patterns described in this README.\n\n## Getting Started\n\n### Install xtask CLI\n\n```bash\ncargo install tracel-xtask-cli\n```\n\n### Setting Up a Cargo Workspace with an xtask binary crate\n\n#### Using the CLI\n\n**Not available yet**\n\n#### Manually\n\n1. **Create a new Cargo workspace:**\n\n```bash\ncargo new my_workspace\ncd my_workspace\n```\n\n2. **Create the `xtask` binary crate:**\n\n```bash\ncargo new xtask --bin\n```\n\n3. **Configure the workspace:**\n\nEdit the `Cargo.toml` file in the root of the workspace to include the following:\n\n```toml\n[workspace]\nmembers = [\"xtask\"]\n```\n\n4. **Add the `tracel-xtask` dependency:**\n\nIn the `xtask/Cargo.toml` file, add the following under `[dependencies]`:\n\n```toml\n[dependencies]\ntracel-xtask = \"3.0\"\n```\n\n5. **Build the workspace:**\n\n ```bash\n cargo build\n ```\n\nYour workspace is now set up with a `xtask` binary crate that depends on `tracel-xtask` version 2.0.x.\n\n### Bootstrap main.rs\n\n1. In the `main.rs` file of the newly created `xtask` crate, import the `tracel_xtask` prelude module and then declare\n   a `Command` enum. Select the base commands you want to use by adding the `macros::base_commands` attribute:\n\n```rust\nuse tracel_xtask::prelude::*;\n\n#[macros::base_commands(\n    Build,\n    Check,\n    Fix\n    Test,\n)]\npub enum Command {}\n```\n\n2. Update the `main` function to initialize xtask and dispatch the base commands:\n\n```rust\nfn main() -\u003e anyhow::Result\u003c()\u003e {\n    let args = init_xtask::\u003cCommand\u003e(parse_args::\u003cCommand\u003e()?)?;\n    match args.command {\n        // dispatch_base_commands function is generated by the commands macro\n        _ =\u003e dispatch_base_commands(args),\n    }\n}\n```\n\n3. Build the workspace with `cargo build` at the root of the repository to verify that everything is.\n\n\n4. You should now be able to display the main help screen which lists the commands you selected previously:\n\n```sh\nxtask --help\n```\n\n## Conventions\n\n### Repository structure\n\nAll our repositories follow the same directory hierarchy:\n- a `crates` directory which contains all the crates of the workspace\n- an `examples` directory which holds all the examples crates\n- a `xtask` directory is a release of xtask CLI with all the base commands\n\n### About tests\n\nAs per Cargo convention, [Integration tests][3] are tests contained in a `tests` directory of a crate besides its `src` directory.\n\nInline tests in `src` directory are called [Unit tests][4].\n\n`tracel-xtask` allows to easily execute them separately using the `test` command.\n\n## Interface generalities\n\n### Target\n\nThere are 4 default targets provided by `tracel-xtask`:\n- `workspace` which targets the cargo workspace, this is the default target\n- `crates` are all the binary crates and library crates\n- `examples` are all the example crates\n- `all-packages` are both `crates` and `examples` targets\n\n`workspace` and `all-packages` are different because `workspace` uses the `--workspace` flag of cargo whereas `all-packages`\nrelies on `crates` and `examples` targets which use the `--package` flag. So `all-packages` executes a command for each crate\nor example individually.\n\nHere are some examples:\n\n```sh\n# run all the crates tests\nxtask test --target crates all\n# check format for examples, binaries and libs\nxtask check --target all-packages unit\n# build the workspace\nxtask build --target workspace\n# workspace is the default target so this has the same effect\nxtask build\n```\n\n### Global options\n\nThe following options are global and precede the actual command on the command line.\n\n#### Environment\n\n`-e`, `--environment`\n\n```sh\nxtask -e production build\n```\n\nThis `--environment` parameter is passed to all the `handle_command` function as `env`.\n\nIts main role is to inform your custom commands or dispatch functions about the targeted environment. An environment\nhas 3 different display names: a short one, a medium one and a long one.\n\nThe available environments are listed below:\n\n| Environment | Short | Medium | Long        |\n|:------------|:------|:-------|:------------|\n| Development | d     | dev    | development |\n| Test        | t     | test   | test        |\n| Staging     | s     | stag   | staging     |\n| Production  | p     | prod   | production  |\n\nIt also automatically loads the following environment variables files if they exists in the working directory:\n- `.env` for any set environment,\n- `.env.secrets` containing secrets for any set environment,\n- `.env.{environment}` (example: `.env.dev`) for the non-sensitive configuration,\n- `.env.{environment}.secrets` (example `.env.dev.secrets`) for the sensitive configuration like password. These\n  files must be added to the ignore file of your VCS tool (for git add `.env.*.secrets` to the `.gitignore` file\n  at the root of your repository).\n\nThe `.secrets` component in `.env.secrets` is called a `dotenv family`. There exists two additional `dotenv families`:\n- `.infra` for infrastructure related variable, this allows to nicely split application config from pure infra config,\n- `.infra.secrets` for infrastructure secrets.\n\nFor each family both `.env.{family}` and `.env.{environment}.{family}` are sourced if they exists.\n\n**Note:** If an environment variable is already defined in the process environment, it takes precedence over the\nvalue defined in `.env` files.\n\nAt last, the display form used in dotenv filenames for the environment is the `medium` one (see table above).\n\n#### Environment Index\n\nBy default the index is transparent because it is set to 1 and the first index does not appear in the environment name.\nSo for instance the `stag` environment is actually the `stag1` environment but it is always printed `stag`.\n\nAny provided index greater than 1 is always explicit and always appear in the environment name.\n\nTo turn an environment into an explicit environment you can call the function `into_explicit` on the environment\nwhich returns a new environment. This new environment always prints the index so instead of printing `s`, `stag`\nor `staging`, it will print `s1`, `stag1` and `staging1` explicitly.\n\n#### Context\n\n`-c`, `--context`\n\n```sh\nxtask --context no-std build\n```\n\nThis argument has no effect in the base commands. Its purpose is to provide additional context to your custom commands\nor dispatch functions — for example, to indicate whether the current build context is `std` or `no-std`.\n\nThis parameter is passed to all the `handle_command` function as `context`.\n\n#### Coverage\n\n`--enable-coverage`\n\nIt setups the Rust toolchain to generate coverage information.\n\n## Standard repository vs. Monorepo\n\n`xtask` CLI is capable of handling traditional repositories with a single Rust workspase at the root of the repository and\nmonorepos which are a collection of Cargo workspaces in their own directories called `subrepos`.\n\nA `subrepo` is basically the same as a standard repository with its own `Cargo.toml` and `xtask` crate. For instance this\nsimple monorepo contains the following files and directories at the root:\n\n```\n.git\n.gitignore\nDependencies.toml\n[backend]\n  |__Cargo.toml\n  |__[crates]\n  |__[xtask]\n[frontend]\n  |__Cargo.toml\n  |__[xtask]\n\n```\n\n`backend` and `frontend` are subrepos with separate Cargo workspaces with their own members. They all have an `xtask` member\nto manage them.\n\nThe root `Dependencies.toml` does not represent a real Cargo workspace, its only purpose is to centralize all the dependency\nversions and features. `xtask` CLI will push the dependency versions in `Dependencies.toml` to the subrepos `Cargo.toml`\nfiles whenever a dependency is used in the subrepo.\n\nFor instance, say we have this `Dependencies.toml` file:\n\n```toml\n[workspace.dependencies]\nlog = \"0.4.29\"\nrand = \"0.9.2\"\ntokio = { version = \"1.48.0\", features = [\"full\"] }\n```\n\nand `backend` subrepo `Cargo.toml` is:\n\n```toml\n[workspace]\nresolver = \"2\"\nmembers = [\"crates/*\", \"xtask\"]\n\n[workspace.dependencies]\nrand = \"0.8.0\"\ntokio = \"1.46.0\"\n```\n\nWhenever the `xtask` CLI executes a command it will enforce the dependency versions to by in sync with the `Dependencies.toml`,\nwhich means that the `backend` subrepo `Cargo.toml` will be modified to be:\n\n```toml\n[workspace]\nresolver = \"2\"\nmembers = [\"crates/*\", \"xtask\"]\n\n[workspace.dependencies]\nrand = \"0.9.2\"\ntokio = { version = \"1.48.0\", features = [\"full\"] }\n```\n\nNote that it is possible to drop `features = [\"full\"]` from the `Dependencies.toml` file and make the decision about which\nfeature to use at the subrepo or even crate level.\n\n## Anatomy of a base command\n\nWe use the derive API of clap which is based on structs, enums and attribute proc macros. Each base command is a\nsubmodule of the `base_commands` module. If the command accepts arguments there is a corresponding struct named `\u003ccommand\u003eCmdArgs`\nwhich declare the options, arguments and subcommands. In the case of subcommands a corresponding enum named `\u003ccommand\u003eSubCommand`\nis defined.\n\nHere is an example with a `foo` command:\n\n```rust\n#[macros::declare_command_args(Target, FooSubCommand)]\nstruct FooCmdArgs {}\n\npub enum FooSubCommand {\n    /// A sub command for foo (usage on the command line: xtask foo print-something)\n    PrintSomething,\n}\n```\n\nNote that it is possible to have an arbitrary level of nested subcommands but deeper nested subcommands cannot be extended,\nin other words, only the first level of subcommands can be extended. If possible, try to design commands with only one\nlevel of subcommands to keep the interface simple.\n\nIn the following sections we will see how to create completely new commands as well how to extend existing base commands.\n\n## Customization\n\nThe crate `xtask-tests` contains examples of the following sections.\n\n### Create a new command\n\n1. First, we organize commands by creating a `commands` module. Create a file `xtask/src/commands/mycommand.rs` as well\n   as the corresponding `mod.rs` file to declare the module contents.\n\n2. Then, in `mycommand.rs` define the arguments struct with the `declare_command_args` macro and define the `handle_command`\n   function. The `declare_command_args` macro takes two parameters, the first is the type of the target enum and the second\n   is the type of the subcommand enum if any. If the command has no target or no subcommand then put `None` for each argument\n   respectively. `Target` is the default target type provided by `tracel-xtask`. This type can be extended to support more\n   targets as we will see in a later section.\n\n```rust\nuse tracel_xtask::prelude::*;\n\n#[macros::declare_command_args(Target, None)]\nstruct MyCommandCmdArgs {}\n\npub fn handle_command(_args: MyCommandCmdArgs) -\u003e anyhow::Result\u003c()\u003e {\n    println!(\"Hello from my-command\");\n    Ok(())\n}\n```\n\n3. Make sure to update the `mod.rs` file to declare the command module:\n\n```\npub(crate) mod my_command;\n```\n\n4. We can now add a new variant to the `Command` enum in `main.rs`:\n\n```rust\nmod commands;\n\nuse tracel_xtask::prelude::*;\n\n#[macros::base_commands(\n    Bump,\n    Check,\n    Fix,\n    Test,\n)]\npub enum Command {\n    MyCommand(commands::mycommand::MyCommandCmdArgs),\n}\n```\n\n5. And dispatch its handling to our new command module:\n\n```rust\nfn main() -\u003e anyhow::Result\u003c()\u003e {\n    let args = init_xtask::\u003cCommand\u003e()?;\n    match args.command {\n        Command::NewCommand(args) =\u003e commands::new_command::handle_command(args),\n        _ =\u003e dispatch_base_commands(args),\n    }\n}\n```\n\n6. You can now test your new command with:\n\n```sh\nxtask my-command --help\n\nxtask my-command\n```\n\n### Extend the default Target enum\n\nLet's implement a new command called `extended-target` to illustrate how to extend the default `Target` enum.\n\n1. Create a `commands/extended_target.rs` file and update the `mod.rs` file as we saw in the previous section.\n\n2. We also need to add a new `strum` dependency to our `Cargo.toml` file:\n\n```toml\n[dependencies]\nstrum = {version = \"0.26.3\", features = [\"derive\"]}\n```\n\n3. Then we can extend the `Target` enum with the `macros::extend_targets` attribute in our `extended_target.rs` file.\n   Here we choose to add a new target called `frontend` which targets the frontend component we could find for instance\n   in a monorepo:\n\n```rust\nuse tracel_xtask::prelude::*;\n\n#[macros::extend_targets]\npub enum MyTarget {\n    /// Target the frontend component of the monorepo.\n    Frontend,\n}\n```\n\n4. Then we define our command arguments by referencing our newly created `MyTarget` enum in the `declare_command_args` attribute:\n\n```rust\n#[macros::declare_command_args(MyTarget, None)]\nstruct ExtendedTargetCmdArgs {}\n```\n\n5. Our new target is then available for use in the `handle_command` function:\n\n```rust\npub fn handle_command(args: ExtendedTargetCmdArgs) -\u003e anyhow::Result\u003c()\u003e {\n    match args.target {\n        // Default targets\n        MyTarget::AllPackages =\u003e println!(\"You chose the target: all-packages\"),\n        MyTarget::Crates =\u003e println!(\"You chose the target: crates\"),\n        MyTarget::Examples =\u003e println!(\"You chose the target: examples\"),\n        MyTarget::Workspace =\u003e println!(\"You chose the target: workspace\"),\n\n        // Additional target\n        MyTarget::Frontend =\u003e println!(\"You chose the target: frontend\"),\n    };\n    Ok(())\n}\n```\n\n6. Register our new command the usual way by adding it to our `Command` enum and dispatch it\n   in the `main` function:\n\n```rust\nmod commands;\n\nuse tracel_xtask::prelude::*;\n\n#[macros::base_commands(\n    Bump,\n    Check,\n    Fix,\n    Test,\n)]\npub enum Command {\n    ExtendedTarget(commands::extended_target::ExtendedTargetCmdArgs),\n}\n\nfn main() -\u003e anyhow::Result\u003c()\u003e {\n    let args = init_xtask::\u003cCommand\u003e()?;\n    match args.command {\n        Command::ExtendedTarget(args) =\u003e commands::extended_target::handle_command(args),\n        _ =\u003e dispatch_base_commands(args),\n    }\n}\n```\n\n7. Test the command with:\n\n```rust\nxtask extended-target --help\n\nxtask extended-target --target frontend\n```\n\n### Target aliases\n\nWhen extending a command we can mark a new variant as an _alias_ of base target (the default ones).\n\nThis example defines `Backend` target as the same as `Worspace` target for all the base commands:\n\n```rust\nuse tracel_xtask::prelude::*;\n\n#[macros::extend_targets]\npub enum MyTarget {\n    /// Target the backend component of the monorepo, same thing as Workspace\n    #[alias(Workspace)]\n    Backend,\n    /// Target the frontend component of the monorepo.\n    Frontend,\n}\n```\n\n### Extend a base command\n\nTo extend an existing command we use the `macros::extend_command_args` attribute which takes three parameters:\n- first argument is the type of the base command arguments struct to extend,\n- second argument is the target type (or `None` if there is no target),\n- third argument is the subcommand type (or `None` if there is no subcommand).\n\nLet's use two examples to illustrate this, the first is a command to extend the `build` base command with\na new `--debug` argument; and the second is a new command to extend the subcommands of the `check` base command\nto add a new `my-check` subcommand.\n\nNote that you can find more examples in the `xtask` crate of this repository.\n\n#### Extend the arguments of a base command\n\nWe create a new command called `extended-build-args` which will have an additional argument called `--debug`.\n\n1. Create the `commands/extended_build_args.rs` file and update the `mod.rs` file as we saw in the previous section.\n\n2. Extend the `BuildCommandArgs` struct using the attribute `macros::extend_command_args` and define the `handle_command` function.\n   Note that the macro automatically implements the `TryInto` trait which makes it easy to dispatch back to the base command\n   own `handle_command` function. Also note that if the base command requires a target then you need to provide a target as well\n   in your extension, i.e. the target parameter of the macro cannot be `None` if the base command has a `Target`.\n\n```rust\nuse tracel_xtask::prelude::*;\n\n#[macros::extend_command_args(BuildCmdArgs, Target, None)]\npub struct ExtendedBuildArgsCmdArgs {\n    /// Print additional debug info when set\n    #[arg(short, long)]\n    pub debug: bool,\n}\n\npub fn handle_command(args: ExtendedBuildArgsCmdArgs) -\u003e anyhow::Result\u003c()\u003e {\n    if args.debug {\n        println!(\"Debug is enabled\");\n    }\n    base_commands::build::handle_command(args.try_into().unwrap())\n}\n```\n\n3. Register the new command the usual way by adding it to the `Command` enum and dispatch it\n   in the `main` function:\n\n```rust\nmod commands;\n\nuse tracel_xtask::prelude::*;\n\n#[macros::base_commands(\n    Bump,\n    Check,\n    Fix,\n    Test,\n)]\npub enum Command {\n    ExtendedBuildArgs(commands::extended_build_args::ExtendedBuildArgsCmdArgs),\n}\n\nfn main() -\u003e anyhow::Result\u003c()\u003e {\n    let args = init_xtask::\u003cCommand\u003e()?;\n    match args.command {\n        Command::ExtendedBuildArgs(args) =\u003e commands::extended_build_args::handle_command(args),\n        _ =\u003e dispatch_base_commands(args),\n    }\n}\n```\n\n4. Test the command with:\n\n```rust\nxtask extended-build-args --help\n\nxtask extended-build-args --debug\n```\n\n#### Extend the subcommands of a base command\n\nFor this one we create a new command called `extended-check-subcommands` which will have an additional subcommand.\n\n1. Create a `commands/extended_check_subcommands.rs` file and update the `mod.rs` file as we saw in the previous section.\n\n2. Extend the `CheckCommandArgs` struct using the attribute `macros::extend_command_args`:\n\n```rust\nuse tracel_xtask::prelude::*;\n\n#[macros::extend_command_args(CheckCmdArgs, Target, ExtendedCheckSubcommand)]\npub struct ExtendedCheckedArgsCmdArgs {}\n```\n\n3. Implement the `ExtendedCheckSubcommand` enum by extending the `CheckSubcommand` base enum with the macro `extend_subcommands`.\n   It takes the name of the type of the subcommand enum to extend:\n\n```rust\n#[macros::extend_subcommands(CheckSubCommand)]\npub enum ExtendedCheckSubcommand {\n    /// An additional subcommand for our extended check command.\n    MySubcommand,\n}\n```\n\n4. Implement the `handle_command` function to handle the new subcommand. Note that we must handle the `All` subcommand as well:\n\n```rust\nuse strum::IntoEnumIterator;\n\npub fn handle_command(args: ExtendedCheckedArgsCmdArgs) -\u003e anyhow::Result\u003c()\u003e {\n    match args.get_command() {\n        ExtendedCheckSubcommand::MySubcommand =\u003e run_my_subcommand(args.clone()),\n        ExtendedCheckSubcommand::All =\u003e {\n            ExtendedCheckSubcommand::iter()\n                .filter(|c| *c != ExtendedCheckSubcommand::All)\n                .try_for_each(|c| {\n                    handle_command(\n                        ExtendedCheckedArgsCmdArgs {\n                            command: Some(c),\n                            target: args.target.clone(),\n                            exclude: args.exclude.clone(),\n                            only: args.only.clone(),\n                        },\n                    )\n                })\n        }\n        _ =\u003e base_commands::check::handle_command(args.try_into().unwrap()),\n    }\n}\n\nfn run_my_subcommand(_args: ExtendedCheckedArgsCmdArgs) -\u003e Result\u003c(), anyhow::Error\u003e {\n    println!(\"Executing new subcommand\");\n    Ok(())\n}\n```\n\n5. Register the new command the usual way by adding it to the `Command` enum and dispatch it\n   in the `main` function:\n\n```rust\nmod commands;\n\nuse tracel_xtask::prelude::*;\n\n#[macros::base_commands(\n    Bump,\n    Check,\n    Fix,\n    Test,\n)]\npub enum Command {\n    ExtendedCheckSubcommand(commands::extended_check_subcommands::ExtendedCheckedArgsCmdArgs),\n}\n\nfn main() -\u003e anyhow::Result\u003c()\u003e {\n    let args = init_xtask::\u003cCommand\u003e()?;\n    match args.command {\n        Command::ExtendedCheckSubcommand(args) =\u003e commands::extended_check_subcommands::handle_command(args),\n        _ =\u003e dispatch_base_commands(args),\n    }\n}\n```\n\n6. Test the command with:\n\n```rust\nxtask extended-check-subcommands --help\n\nxtask extended-check-subcommands my-check\n```\n\n## Custom builds and tests\n\n`tracel-xtask` provides helper functions to easily execute custom builds or tests with specific features or build targets (do not confuse\nRust build targets which is an argument of the `cargo build` command with the xtask target we introduced previously).\n\nFor instance we can extend the `build` command to build additional crates with custom features or build targets using the helper function:\n\n```rust\npub fn handle_command(mut args: tracel_xtask::commands::build::BuildCmdArgs)  -\u003e anyhow::Result\u003c()\u003e {\n    // regular execution of the build command\n    tracel_xtask::commands::build::handle_command(args)?;\n\n    // additional crate builds\n    // build 'my-crate' with all the features\n    tracel_xtask::utils::helpers::custom_crates_build(vec![\"my-crate\"], vec![\"--all-features\"], None, None, \"all features\")?;\n    // build 'my-crate' with specific features\n    tracel_xtask::utils::helpers::custom_crates_build(vec![\"my-crate\"], vec![\"--features\", \"myfeature1,myfeature2\"], None, None, \"myfeature1,myfeature2\")?;\n    // build 'my-crate' with a different target than the default one\n    tracel_xtask::utils::helpers::custom_crates_build(vec![\"my-crate\"], vec![\"--target\", \"thumbv7m-none-eabi\"], None, None, \"thumbv7m-none-eabi target\")?;\n    Ok(())\n}\n```\n\n## Enable and generate coverage information\n\nHere is a example GitHub job which shows how to setup coverage, enable it and upload coverage information to codecov:\n\n```yaml\nenv:\n  GRCOV_LINK: \"https://github.com/mozilla/grcov/releases/download\"\n  GRCOV_VERSION: \"0.8.19\"\n\njobs:\n  my-job:\n    runs-on: ubuntu-22.04\n    steps:\n      - name: Checkout\n        uses: actions/checkout@v4\n      - name: install rust\n        uses: dtolnay/rust-toolchain@master\n        with:\n          components: rustfmt, clippy\n          toolchain: stable\n      - name: Install grcov\n        shell: bash\n        run: |\n          curl -L \"$GRCOV_LINK/v$GRCOV_VERSION/grcov-x86_64-unknown-linux-musl.tar.bz2\" |\n          tar xj -C $HOME/.cargo/bin\n          xtask coverage install\n      - name: Build\n        shell: bash\n        run: xtask build\n      - name: Tests\n        shell: bash\n        run: xtask --enable-coverage test all\n      - name: Generate lcov.info\n        shell: bash\n        # /* is to exclude std library code coverage from analysis\n        run: xtask coverage generate --ignore \"/*,xtask/*,examples/*\"\n      - name: Codecov upload lcov.info\n        uses: codecov/codecov-action@v4\n        with:\n          files: lcov.info\n          token: ${{ secrets.CODECOV_TOKEN }}\n```\n\n## Special command 'validate'\n\nBy convention this command is responsible to run all the checks, builds, and/or tests that validate the code\nbefore opening a pull request or merge request.\n\nThe command `Validate` can been added via the macro `tracel_xtask_macros::commands` like the other commands.\n\nBy default all the checks from the `check` command are run as well as both unit and integration tests from\nthe `test` command.\n\nYou can make your own `handle_command` function if you need to perform more validations. Ideally this function\nshould only call the other commands `handle_command` functions.\n\nFor quick reference here is a simple example to perform all checks and tests against the workspace:\n\n```rust\npub fn handle_command(args: ValidateCmdArgs) -\u003e anyhow::Result\u003c()\u003e {\n    let target = Target::Workspace;\n    let exclude = vec![];\n    let only = vec![];\n\n    // checks\n    [\n        CheckSubCommand::Audit,\n        CheckSubCommand::Format,\n        CheckSubCommand::Lint,\n        CheckSubCommand::Typos,\n    ]\n    .iter()\n    .try_for_each(|c| {\n        super::check::handle_command(CheckCmdArgs {\n            target: target.clone(),\n            exclude: exclude.clone(),\n            only: only.clone(),\n            command: Some(c.clone()),\n            ignore_audit: args.ignore_audit,\n        })\n    })?;\n\n    // tests\n    super::test::handle_command(TestCmdArgs {\n        target: target.clone(),\n        exclude: exclude.clone(),\n        only: only.clone(),\n        threads: None,\n        jobs: None,\n        command: Some(TestSubCommand::All),\n    })?;\n\n    Ok(())\n}\n```\n\n## Base commands list\n\n### Check and Fix\n\nThe `check` and `fix` commands are designed to help you maintain code quality during development.\nThey run various checks and fix issues, ensuring that your code is clean and follows best practices.\n\n`check` and `fix` contains the same subcommands to audit, format, lint or proofread a code base.\n\nWhile the `check` command only reports issues, the `fix` command attempts to fix them as they are encountered.\n\nEach check can be executed separately or all of them can be executed sequentially using `all`.\n\nUsage to lint the code base:\n\n```sh\nxtask check lint\n\nxtask fix lint\n\nxtask fix all\n```\n\n### Running Tests\n\nTesting is a crucial part of development, and the `test` command is designed to make this process easy.\n\nThis command makes the distinction between unit tests and integrations tests. [Unit tests][4] are inline tests under the\n`src` directory of a crate. [Integration tests][3] are tests defined in files under the `tests` directory of a crate besides\nthe `src` directory.\n\nUsage:\n```sh\n# execute workspace unit tests\nxtask test unit\n# execute workspace integration tests\nxtask test integration\n# execute workspace both unit tests and integration tests\nxtask test all\n```\n\nNote that documentation tests are supported by the `doc` command.\n\n### Documentation\n\nCommand to build and test the documentation in a workspace.\n\n### Bumping Versions\n\nThis is a command reserved for repository maintainers.\n\nThe `bump` command is used to update the version numbers of all first-party crates in the repository.\nThis is particularly useful when you're preparing for a new release and need to ensure that all crates have the correct version.\n\nYou can bump the version by major, minor, or patch levels, depending on the changes made.\nFor example, if you’ve made breaking changes, you should bump the major version.\nFor new features that are backwards compatible, bump the minor version.\nFor bug fixes, bump the patch version.\n\nUsage:\n```sh\nxtask bump \u003cSUBCOMMAND\u003e\n```\n\n### Publishing Crates\n\nThis is a command reserved for repository maintainers and is typically used in `publish` GitHub workflows.\n\nThis command automates the process of publishing crates to `crates.io`, the Rust package registry.\nBy specifying the name of the crate, `xtask` handles the publication process, ensuring that the crate is available for others to use.\n\nUsage:\n```sh\nxtask publish \u003cNAME\u003e\n```\n\nAs mentioned, this command is often used in a GitHub workflow.\nWe provide a Tracel's reusable [publish-crate][8] workflow that makes use of this command.\nHere is a simple example with a workflow that publishes two crates A and B with A depending on B.\n\n```yaml\nname: publish all crates\n\non:\n  push:\n    tags:\n      - \"v*\"\n\njobs:\n  publish-B:\n    uses: tracel-ai/github-actions/.github/workflows/publish-crate.yml@v6\n    with:\n      crate: B\n    secrets:\n      CRATES_IO_API_TOKEN: ${{ secrets.CRATES_IO_API_TOKEN }}\n\n  # --------------------------------------------------------------------------------\n  publish-A:\n    uses: tracel-ai/github-actions/.github/workflows/publish-crate.yml@v6\n    with:\n      crate: A\n    needs:\n      - publish-B\n    secrets:\n      CRATES_IO_API_TOKEN: ${{ secrets.CRATES_IO_API_TOKEN }}\n```\n\n### Coverage\n\nThis command provide a subcommand to install the necessary dependencies for performing code coverage and a subcommand to generate the\ncoverage info file that can then be uploaded to a service provider like codecov. See dedicated section `Enable and generate coverage information`.\n\n### Container\n\nThe `container` command standardizes how we build, publish, promote, and roll out containers.\nIt currently supports **Docker** for container builds, **AWS ECR** as the container registry and **AWS EC2 Auto Scaling Groups (ASG)** for deployment rollouts.\nThe design, however, could later be refactored to support other cloud providers or services (such as podman, AWS ECS, GCP Artifact Registry, Azure Container Registry, or self-hosted registries) with ideally minimal changes to the workflow.\n\n#### Conceptual Model\n\n##### Deploy\n\n**Build of container** -\u003e **Push to container registry** -\u003e **Promote to `\u003cenv_medium\u003e`** -\u003e **Rollout**\n\n##### Rollback\n\n**Rollback by promoting `rollback_\u003cenv_medium\u003e` to `\u003cenv_medium\u003e`** -\u003e **Rollout**\n\n#### Prerequisites\n\n- **AWS CLI** setup with permissions for ECR and Auto Scaling.\n- **Docker** installed locally or on your CI runners.\n\n#### Examples\n\nFirst build the container locally:\n\n```\nxtask -e stag container build --allow-dirty --context-dir . --build-file Dockerfile --image my_image\n```\n\nRetrieve the commit `SHA` tag from the output of the build command and push the container to the registry:\n\n```\nxtask -e stag container push --image my_image --local-tag SHA --repository my_image --auto-remote_tag --region AWS_REGION\n```\n\nThe container image will be pushed with the commit SHA tag and a monotonic number tag.\n\nPromote the pushed image to mark it as latest (move the latest tag to it):\n\n```\nxtask -e stag container promote --repository my_image --tag SHA --region AWS_REGION\n```\n\nThen to actually deploy to the targeted environment, initiate a rollout:\n\n```\nxtask -e stag container rollout --region AWS_REGION --asg ASG_NAME --wait\n```\n\nTo see the current `latest` and `rollback` images use the `list` subcommand:\n\n```\nxtask -e stag container list --region AWS_REGION --repository my_image\n```\n\n### Secrets\n\nThis command handles secrets to view, edit and even write an env file with them. For now it only supports AWS Secrets Manager.\n\n#### Examples\n\nView secrets:\n\n```\nxtask -e stag secrets view --region AWS_REGION my_secret\n```\n\n### Docker Compose\n\nThe `docker-compose` command provides `up` and `down` commands to start and stop stacks. The command is integrated with the environment\nconfiguration mechanism of `tracel-xtask`.\n\nThe name of the compose file must follow the template `docker-compose.{env}.yml` with `env` being the shorthand environment name.\nFor instance for the development environment the file is named `docker-compose.dev.yml`.\n\nThe command also requires a mandatory project name for the stack in order to have idempotent `up` commands.\n\n### Dependencies\n\nVarious additional subcommands about dependencies.\n\n`deny` make sure that all dependencies meet requirements using [cargo-deny][5].\n\n`unused` detects dependencies in the workspace that are not in ussed.\n\n### Vulnerabilities\n\nThis command makes it easier to execute sanitizers as described in [the Rust unstable book][6].\n\nThese sanitizers require a nightly toolchain.\n\n```\nRun the specified vulnerability check locally. These commands must be called with 'cargo +nightly'\n\nUsage: xtask vulnerabilities \u003cCOMMAND\u003e\n\nCommands:\n  all                            Run all most useful vulnerability checks\n  address-sanitizer              Run Address sanitizer (memory error detector)\n  control-flow-integrity         Run LLVM Control Flow Integrity (CFI) (provides forward-edge control flow protection)\n  hw-address-sanitizer           Run newer variant of Address sanitizer (memory error detector similar to AddressSanitizer, but based on partial hardware assistance)\n  kernel-control-flow-integrity  Run Kernel LLVM Control Flow Integrity (KCFI) (provides forward-edge control flow protection for operating systems kerneljs)\n  leak-sanitizer                 Run Leak sanitizer (run-time memory leak detector)\n  memory-sanitizer               Run memory sanitizer (detector of uninitialized reads)\n  mem-tag-sanitizer              Run another address sanitizer (like AddressSanitizer and HardwareAddressSanitizer but with lower overhead suitable for use as hardening for production binaries)\n  nightly-checks                 Run nightly-only checks through cargo-careful `\u003chttps://crates.io/crates/cargo-careful\u003e`\n  safe-stack                     Run SafeStack check (provides backward-edge control flow protection by separating stack into safe and unsafe regions)\n  shadow-call-stack              Run ShadowCall check (provides backward-edge control flow protection - aarch64 only)\n  thread-sanitizer               Run Thread sanitizer (data race detector)\n  help                           Print this message or the help of the given subcommand(s)\n```\n\n## Utilities\n\n### Easy CTRL+c management\n\n`tracel-xtask` gives access to two useful macros `register_cleanup` and `handle_cleanup` to easily define some cleanup functions to be executed at\na given time during the program as well as whenever the user presses \u003ckbd\u003eCTRL+c\u003c/kbd\u003e.\nIt is very useful to guard processes while executing some tests and make sure that the state is still cleaned up even if the program is interrupted by\nthe user.\n\nSince the cleanup handler is stored in a static variable, it's `drop` function is not automatically called when the program exits normally and the `handle_cleanup` macro needs to be called manually. However, when the program is interrupted by the user with \u003ckbd\u003eCTRL+c\u003c/kbd\u003e, the cleanup is automatically called.\n\nExample:\n\nRegister cleanup functions in your commands, say you have a customized `test` command that spins up some container.\n\n```rs\npub(crate) async fn handle_command(\n    args: TestCmdArgs,\n    env: Environment,\n    ctx: Context,\n) -\u003e anyhow::Result\u003c()\u003e {\n    match args.get_command() {\n        TestSubCommand::Integration =\u003e {\n            // spin up containers\n            // ...\n            // register cleanup command for them\n            register_cleanup!(\"Integration tests: Docker compose stack\", move || {\n                base_commands::docker::handle_command(\n                    DockerCmdArgs {\n                        build: false,\n                        project: super::DOCKER_COMPOSE_PROJECT_NAME.to_string(),\n                        command: Some(DockerSubCommand::Down),\n                        services: vec![],\n                    },\n                    Environment::Test,\n                    ctx.clone(),\n                )\n                .expect(\"Should be able to stop docker compose stack\");\n            });\n            // Execute xtask test base command\n            base_commands::test::run_integration(\u0026cmd_args.target, \u0026cmd_args)\n        }\n        TestSubCommand::All =\u003e { ... }\n    }\n}\n```\n\nThen call the `handle_cleanup` macro at the end of your main function to force a cleanup:\n\n```rs\nuse tracel_xtask::prelude::*;\n\n#[macros::base_commands(\n    Build,\n    Check,\n    Fix,\n    Test\n)]\npub enum Command {}\n\nfn main() -\u003e anyhow::Result\u003c()\u003e {\n    let args = init_xtask::\u003cCommand\u003e(parse_args::\u003cCommand\u003e()?)?;\n    match args.command {\n        Command::Test(cmd_args) =\u003e {\n            commands::test::handle_command(cmd_args, args.environment, args.context).await\n        }\n        _ =\u003e dispatch_base_commands(args),\n    }\n    handle_cleanup!();\n}\n```\n\n[1]: https://github.com/matklad/cargo-xtask\n[2]: https://github.com/clap-rs/clap\n[3]: https://doc.rust-lang.org/book/ch14-03-cargo-workspaces.html\n[4]: https://doc.rust-lang.org/book/ch11-03-test-organization.html#integration-tests\n[5]: https://doc.rust-lang.org/book/ch11-03-test-organization.html#unit-tests\n[6]: https://embarkstudios.github.io/cargo-deny/\n[7]: https://doc.rust-lang.org/beta/unstable-book/compiler-flags/sanitizer.html\n[8]: https://github.com/tracel-ai/github-actions/blob/main/.github/workflows/publish-crate.yml\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftracel-ai%2Fxtask","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftracel-ai%2Fxtask","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftracel-ai%2Fxtask/lists"}