Skip to main content

flowey_lib_common/
run_cargo_doc.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4//! Encapsulates the logic of invoking `cargo doc`, taking into account
5//! bits of "global" configuration and dependency management, such as setting
6//! global cargo flags (e.g: --verbose, --locked), ensuring base Rust
7//! dependencies are installed, etc...
8
9use crate::_util::cargo_output;
10use flowey::node::prelude::*;
11use flowey::shell::FloweyCmd;
12use std::collections::BTreeMap;
13#[derive(Serialize, Deserialize)]
14pub struct CargoDocCommands {
15    cmds: Vec<Vec<String>>,
16    cargo_work_dir: PathBuf,
17    no_incremental: bool,
18}
19
20impl CargoDocCommands {
21    /// Execute the doc command(s), returning a path to the built docs
22    /// directory.
23    pub fn run(self, rt: &RustRuntimeServices<'_>) -> anyhow::Result<PathBuf> {
24        self.run_with(rt, |x| x)
25    }
26
27    /// Execute the doc command(s), returning path(s) to the built artifact.
28    ///
29    /// Unlike `run`, this method allows tweaking the build command prior to
30    /// running it (e.g: to add env vars, change the working directory where the
31    /// artifacts will be placed, etc...).
32    pub fn run_with(
33        self,
34        rt: &RustRuntimeServices<'_>,
35        f: impl Fn(FloweyCmd<'_>) -> FloweyCmd<'_>,
36    ) -> anyhow::Result<PathBuf> {
37        let Self {
38            cmds,
39            cargo_work_dir,
40            no_incremental,
41        } = self;
42
43        let out_dir = rt.sh.current_dir();
44        rt.sh.change_dir(cargo_work_dir);
45
46        let mut json = String::new();
47        for mut cmd in cmds {
48            let argv0 = cmd.remove(0);
49            let cmd = flowey::shell_cmd!(rt, "{argv0} {cmd...}");
50            let cmd = if no_incremental {
51                cmd.env("CARGO_INCREMENTAL", "0")
52            } else {
53                cmd
54            };
55            let cmd = f(cmd);
56            json.push_str(&cmd.read()?);
57        }
58        let messages: Vec<cargo_output::Message> = serde_json::Deserializer::from_str(&json)
59            .into_iter()
60            .collect::<Result<_, _>>()?;
61
62        // Find the output directory. Look for a file name like `foo/bar/doc/mycrate/index.html`.
63        let cargo_out_dir = messages
64            .iter()
65            .find_map(|msg| match msg {
66                cargo_output::Message::CompilerArtifact { filenames, .. } => {
67                    filenames.iter().find_map(|filename| {
68                        filename
69                            .file_name()
70                            .is_some_and(|f| f == "index.html")
71                            .then(|| filename.parent().unwrap().parent().unwrap())
72                    })
73                }
74                _ => None,
75            })
76            .context("could not find cargo doc output directory")?;
77
78        assert_eq!(cargo_out_dir.file_name().unwrap(), "doc");
79
80        let final_dir = out_dir.join("cargo-doc-out");
81        fs_err::rename(cargo_out_dir, &final_dir)?;
82        Ok(final_dir)
83    }
84}
85
86/// Packages that can be documented
87#[derive(Serialize, Deserialize)]
88pub enum DocPackageKind {
89    /// Document an entire workspace workspace (with exclusions)
90    Workspace { exclude: Vec<String> },
91    /// Document a specific crate.
92    Crate(String),
93    /// Document a specific no_std crate.
94    ///
95    /// This is its own variant, as a single `cargo doc` command has issues
96    /// documenting mixed `std` and `no_std` crates.
97    NoStdCrate(String),
98}
99
100/// The "what and how" of packages to documents
101#[derive(Serialize, Deserialize)]
102pub struct DocPackage {
103    /// The thing being documented.
104    pub kind: DocPackageKind,
105    /// Whether to document non-workspace dependencies (i.e: pass `--no-deps`)
106    pub no_deps: bool,
107    /// Whether to document private items (i.e: pass `--document-private-items`)
108    pub document_private_items: bool,
109}
110
111flowey_request! {
112    pub struct Request {
113        pub in_folder: ReadVar<PathBuf>,
114        /// Targets to include in the generated docs.
115        pub packages: Vec<DocPackage>,
116        /// What target-triple things should get documented with.
117        pub target_triple: target_lexicon::Triple,
118        pub cargo_cmd: WriteVar<CargoDocCommands>,
119    }
120}
121
122#[derive(Default)]
123struct ResolvedDocPackages {
124    // where each (bool, bool) represents (no_deps, document_private_items)
125    workspace: Option<(bool, bool)>,
126    exclude: Vec<String>,
127    crates: BTreeMap<(bool, bool), Vec<String>>,
128    crates_no_std: BTreeMap<(bool, bool), Vec<String>>,
129}
130
131new_flow_node!(struct Node);
132
133impl FlowNode for Node {
134    type Request = Request;
135
136    fn imports(ctx: &mut ImportCtx<'_>) {
137        ctx.import::<crate::cfg_cargo_common_flags::Node>();
138        ctx.import::<crate::install_rust::Node>();
139    }
140
141    fn emit(requests: Vec<Self::Request>, ctx: &mut NodeCtx<'_>) -> anyhow::Result<()> {
142        let rust_toolchain = ctx.reqv(crate::install_rust::Request::GetRustupToolchain);
143        let flags = ctx.reqv(crate::cfg_cargo_common_flags::Request::GetFlags);
144
145        for Request {
146            in_folder,
147            packages,
148            target_triple,
149            cargo_cmd,
150        } in requests
151        {
152            ctx.req(crate::install_rust::Request::InstallTargetTriple(
153                target_triple.clone(),
154            ));
155
156            // figure out what cargo commands we'll need to invoke
157            let mut targets = ResolvedDocPackages::default();
158            for DocPackage {
159                kind,
160                no_deps,
161                document_private_items,
162            } in packages
163            {
164                match kind {
165                    DocPackageKind::Workspace { exclude } => {
166                        if targets.workspace.is_some() {
167                            anyhow::bail!("cannot pass Workspace variant multiple times")
168                        }
169                        targets.exclude.extend(exclude);
170                        targets.workspace = Some((no_deps, document_private_items))
171                    }
172                    DocPackageKind::Crate(name) => targets
173                        .crates
174                        .entry((no_deps, document_private_items))
175                        .or_default()
176                        .push(name),
177                    DocPackageKind::NoStdCrate(name) => targets
178                        .crates_no_std
179                        .entry((no_deps, document_private_items))
180                        .or_default()
181                        .push(name),
182                }
183            }
184
185            let doc_targets = targets;
186
187            ctx.emit_minor_rust_step("construct cargo doc command", |ctx| {
188                let rust_toolchain = rust_toolchain.clone().claim(ctx);
189                let flags = flags.clone().claim(ctx);
190                let in_folder = in_folder.claim(ctx);
191                let write_doc_cmd = cargo_cmd.claim(ctx);
192
193                move |rt| {
194                    let rust_toolchain = rt.read(rust_toolchain);
195                    let flags = rt.read(flags);
196                    let in_folder = rt.read(in_folder);
197
198                    let crate::cfg_cargo_common_flags::Flags {
199                        locked,
200                        verbose,
201                        no_incremental,
202                    } = flags;
203
204                    let mut cmds = Vec::new();
205                    let ResolvedDocPackages {
206                        workspace,
207                        exclude,
208                        mut crates,
209                        crates_no_std,
210                    } = doc_targets;
211
212                    let base_cmd = |no_deps: bool, document_private_items: bool| -> Vec<String> {
213                        let mut v = Vec::new();
214                        v.push("cargo".into());
215                        if let Some(rust_toolchain) = &rust_toolchain {
216                            v.push(format!("+{rust_toolchain}"))
217                        }
218                        v.push("doc".into());
219                        v.push("--message-format=json-render-diagnostics".into());
220                        v.push("--target".into());
221                        v.push(target_triple.to_string());
222                        if locked {
223                            v.push("--locked".into());
224                        }
225                        if verbose {
226                            v.push("--verbose".into());
227                        }
228                        if no_deps {
229                            v.push("--no-deps".into());
230                        }
231                        if document_private_items {
232                            v.push("--document-private-items".into())
233                        }
234                        v
235                    };
236
237                    // first command to run should be the workspace-level
238                    // command (if one was provided)
239                    if let Some((no_deps, document_private_items)) = workspace {
240                        // subsume crates with the same options
241                        crates.remove(&(no_deps, document_private_items));
242
243                        let mut v = base_cmd(no_deps, document_private_items);
244
245                        v.push("--workspace".into());
246
247                        for crates_no_std in crates_no_std.values() {
248                            for c in crates_no_std.iter().chain(exclude.iter()) {
249                                v.push("--exclude".into());
250                                v.push(c.into())
251                            }
252                        }
253
254                        cmds.push(v);
255                    }
256
257                    // subsequently: document any specific std crates
258                    for ((no_deps, document_private_items), crates) in crates {
259                        let mut v = base_cmd(no_deps, document_private_items);
260
261                        for c in crates {
262                            v.push("-p".into());
263                            v.push(c);
264                        }
265
266                        cmds.push(v)
267                    }
268
269                    // lastly: document any no_std crates
270                    for ((no_deps, document_private_items), crates) in crates_no_std {
271                        let mut v = base_cmd(no_deps, document_private_items);
272
273                        for c in crates {
274                            v.push("-p".into());
275                            v.push(c);
276                        }
277
278                        cmds.push(v)
279                    }
280
281                    let cmd = CargoDocCommands {
282                        cmds,
283                        cargo_work_dir: in_folder.clone(),
284                        no_incremental,
285                    };
286
287                    rt.write(write_doc_cmd, &cmd);
288                }
289            });
290        }
291
292        Ok(())
293    }
294}