xtask/main.rs
1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4//! OpenVMM repo-specific automation.
5//!
6//! This host-side CLI implements standalone development utilities such as
7//! repository formatting, fuzz-target management, guest-test image creation,
8//! cleanup, binary-size verification, and git-hook installation. Invoke it
9//! through the repository's `cargo xtask <command>` alias.
10//!
11//! `xtask` owns tools that perform project-specific work. Multi-step build and
12//! test orchestration instead belongs in `cargo xflowey`.
13//!
14//! Follows the xtask workflow/convention, as described at
15//! <https://github.com/matklad/cargo-xtask>
16
17#![forbid(unsafe_code)]
18
19use anyhow::Context;
20use clap::Parser;
21use clap::Subcommand;
22use std::path::Path;
23use std::path::PathBuf;
24
25mod completions;
26pub mod fs_helpers;
27pub mod shell;
28pub mod tasks;
29
30/// Default location to maintain a `xtask-path` file
31///
32/// This file contains a fully-resolved path to the actual `xtask` binary,
33/// allowing other tooling (e.g: git hook) to invoke the xtask without having to
34/// go through `cargo`.
35pub const XTASK_PATH_FILE: &str = "./target/xtask-path";
36
37/// Common context passed into every Xtask
38#[derive(Clone)]
39pub struct XtaskCtx {
40 /// Project root directory
41 pub root: PathBuf,
42 /// xtask is running within a hook
43 pub in_git_hook: bool,
44 /// xtask was invoked as part of a "run on save" operation
45 pub in_run_on_save: bool,
46}
47
48/// Common trait implemented by all Xtask subcommands.
49pub trait Xtask: Parser {
50 /// Run the Xtask.
51 ///
52 /// For consistency and simplicity, `Xtask` implementations are allowed to
53 /// assume that they are being run from the root of the repo's filesystem.
54 /// Callers of `Xtask::run` should take care to ensure
55 /// [`std::env::set_current_dir`] was called prior to invoking `Xtask::run`.
56 fn run(self, ctx: XtaskCtx) -> anyhow::Result<()>;
57}
58
59#[derive(Parser)]
60#[clap(name = "xtask", about = "OpenVMM repo automation")]
61struct Cli {
62 #[clap(subcommand)]
63 command: Commands,
64
65 /// Specify a custom project root directory.
66 ///
67 /// Can be used to ensure consistent formatting between the OpenVMM base
68 /// repo, and any custom out-of-tree overlay repos.
69 #[clap(long)]
70 custom_root: Option<PathBuf>,
71
72 /// Signal that this `xtask` is being invoked as part of a "run on save"
73 /// operation.
74 ///
75 /// When set, certain tasks may choose to skip certain expensive checks in
76 /// order to execute as quickly as possible.
77 ///
78 /// e.g: instead of calling `cargo run` in order to execute a project-local
79 /// tool, `xtask` may instead attempt to find and use an existing pre-built
80 /// binary, if one is available. This will be faster, but may run the risk
81 /// of executing a slightly stale binary.
82 #[clap(long)]
83 run_on_save: bool,
84}
85
86#[derive(Subcommand)]
87enum Commands {
88 #[clap(hide = true)]
89 Hook(tasks::RunGitHook),
90 #[clap(hide = true)]
91 Complete(clap_dyn_complete::Complete),
92 Completions(completions::Completions),
93 #[clap(hide = true)]
94 CoverageSources(tasks::CoverageSources),
95
96 Clean(tasks::Clean),
97 Fmt(tasks::Fmt),
98 Fuzz(tasks::Fuzz),
99 GuestTest(tasks::GuestTest),
100 InstallGitHooks(tasks::InstallGitHooks),
101 VerifySize(tasks::VerifySize),
102}
103
104fn main() {
105 ci_logger::init("XTASK_LOG").unwrap();
106
107 if let Err(e) = try_main() {
108 log::error!("Error: {:#}", e);
109 std::process::exit(-1);
110 }
111}
112
113fn try_main() -> anyhow::Result<()> {
114 let cli = Cli::parse();
115
116 let orig_root = Path::new(&env!("CARGO_MANIFEST_DIR"))
117 .ancestors()
118 .nth(1)
119 .unwrap()
120 .to_path_buf();
121
122 let root = cli
123 .custom_root
124 .map(std::path::absolute)
125 .transpose()?
126 .unwrap_or(orig_root.clone());
127
128 // for consistency, always run xtasks as though they were run from the root
129 std::env::set_current_dir(&root)?;
130
131 // drop the path to the xtask binary in an easy-to-find place. this gets
132 // used by the pre-commit hook, as well as the fmt-on-save dev-flow to avoid
133 // rebuilding the xtask.
134 if let Ok(path) = std::env::current_exe() {
135 if let Err(e) = fs_err::write(orig_root.join(XTASK_PATH_FILE), path.display().to_string()) {
136 log::debug!("Unable to create XTASK_PATH_FILE: {:#}", e)
137 }
138 }
139
140 if !matches!(
141 cli.command,
142 Commands::Complete(..) | Commands::CoverageSources(..)
143 ) {
144 tasks::update_hooks(&root).context("failed to update git hooks")?;
145 }
146
147 let ctx = XtaskCtx {
148 root,
149 in_git_hook: matches!(cli.command, Commands::Hook(..)),
150 in_run_on_save: cli.run_on_save,
151 };
152
153 match cli.command {
154 Commands::Hook(task) => task.run(ctx),
155 Commands::Completions(task) => task.run(),
156 Commands::Complete(task) => {
157 futures::executor::block_on(task.println_to_stub_script::<Cli>(
158 Some("cargo"),
159 completions::XtaskCompleteFactory { ctx },
160 ));
161 Ok(())
162 }
163
164 Commands::Clean(task) => task.run(ctx),
165 Commands::CoverageSources(task) => task.run(ctx),
166 Commands::Fmt(task) => task.run(ctx),
167 Commands::Fuzz(task) => task.run(ctx),
168 Commands::GuestTest(task) => task.run(ctx),
169 Commands::InstallGitHooks(task) => task.run(ctx),
170 Commands::VerifySize(task) => task.run(ctx),
171 }
172}