1use std::collections::HashMap;
2use std::fs;
3use std::path::Path;
4
5use failure::Fail;
6use opener;
7
8use crate::core::Workspace;
9use crate::ops;
10use crate::util::CargoResult;
11
12#[derive(Debug)]
14pub struct DocOptions<'a> {
15 pub open_result: bool,
17 pub compile_opts: ops::CompileOptions<'a>,
19}
20
21pub fn doc(ws: &Workspace<'_>, options: &DocOptions<'_>) -> CargoResult<()> {
23 let specs = options.compile_opts.spec.to_package_id_specs(ws)?;
24 let resolve = ops::resolve_ws_precisely(
25 ws,
26 None,
27 &options.compile_opts.features,
28 options.compile_opts.all_features,
29 options.compile_opts.no_default_features,
30 &specs,
31 )?;
32 let (packages, resolve_with_overrides) = resolve;
33
34 let ids = specs
35 .iter()
36 .map(|s| s.query(resolve_with_overrides.iter()))
37 .collect::<CargoResult<Vec<_>>>()?;
38 let pkgs = packages.get_many(ids)?;
39
40 let mut lib_names = HashMap::new();
41 let mut bin_names = HashMap::new();
42 for package in &pkgs {
43 for target in package.targets().iter().filter(|t| t.documented()) {
44 if target.is_lib() {
45 if let Some(prev) = lib_names.insert(target.crate_name(), package) {
46 failure::bail!(
47 "The library `{}` is specified by packages `{}` and \
48 `{}` but can only be documented once. Consider renaming \
49 or marking one of the targets as `doc = false`.",
50 target.crate_name(),
51 prev,
52 package
53 );
54 }
55 } else if let Some(prev) = bin_names.insert(target.crate_name(), package) {
56 failure::bail!(
57 "The binary `{}` is specified by packages `{}` and \
58 `{}` but can be documented only once. Consider renaming \
59 or marking one of the targets as `doc = false`.",
60 target.crate_name(),
61 prev,
62 package
63 );
64 }
65 }
66 }
67
68 ops::compile(ws, &options.compile_opts)?;
69
70 if options.open_result {
71 let name = if pkgs.len() > 1 {
72 failure::bail!(
73 "Passing multiple packages and `open` is not supported.\n\
74 Please re-run this command with `-p <spec>` where `<spec>` \
75 is one of the following:\n {}",
76 pkgs.iter()
77 .map(|p| p.name().as_str())
78 .collect::<Vec<_>>()
79 .join("\n ")
80 );
81 } else {
82 match lib_names.keys().chain(bin_names.keys()).nth(0) {
83 Some(s) => s.to_string(),
84 None => return Ok(()),
85 }
86 };
87
88 let mut target_dir = ws.target_dir();
92 if let Some(ref triple) = options.compile_opts.build_config.requested_target {
93 target_dir.push(Path::new(triple).file_stem().unwrap());
94 }
95 let path = target_dir.join("doc").join(&name).join("index.html");
96 let path = path.into_path_unlocked();
97 if fs::metadata(&path).is_ok() {
98 let mut shell = options.compile_opts.config.shell();
99 shell.status("Opening", path.display())?;
100 if let Err(e) = opener::open(&path) {
101 shell.warn(format!("Couldn't open docs: {}", e))?;
102 for cause in (&e as &dyn Fail).iter_chain() {
103 shell.warn(format!("Caused by:\n {}", cause))?;
104 }
105 }
106 }
107 }
108
109 Ok(())
110}