/src/cargo/ops/cargo_doc.rs

https://gitlab.com/frewsxcv/cargo · Rust · 74 lines · 62 code · 8 blank · 4 comment · 5 complexity · 74a998534ffcba2a616cfa0bfcb764ec MD5 · raw file

  1. use crate::core::{Shell, Workspace};
  2. use crate::ops;
  3. use crate::util::config::PathAndArgs;
  4. use crate::util::CargoResult;
  5. use std::path::Path;
  6. use std::path::PathBuf;
  7. use std::process::Command;
  8. /// Strongly typed options for the `cargo doc` command.
  9. #[derive(Debug)]
  10. pub struct DocOptions {
  11. /// Whether to attempt to open the browser after compiling the docs
  12. pub open_result: bool,
  13. /// Options to pass through to the compiler
  14. pub compile_opts: ops::CompileOptions,
  15. }
  16. /// Main method for `cargo doc`.
  17. pub fn doc(ws: &Workspace<'_>, options: &DocOptions) -> CargoResult<()> {
  18. let compilation = ops::compile(ws, &options.compile_opts)?;
  19. if options.open_result {
  20. let name = &compilation
  21. .root_crate_names
  22. .get(0)
  23. .ok_or_else(|| anyhow::anyhow!("no crates with documentation"))?;
  24. let kind = options.compile_opts.build_config.single_requested_kind()?;
  25. let path = compilation.root_output[&kind]
  26. .with_file_name("doc")
  27. .join(&name)
  28. .join("index.html");
  29. if path.exists() {
  30. let config_browser = {
  31. let cfg: Option<PathAndArgs> = ws.config().get("doc.browser")?;
  32. cfg.map(|path_args| (path_args.path.resolve_program(ws.config()), path_args.args))
  33. };
  34. let mut shell = ws.config().shell();
  35. shell.status("Opening", path.display())?;
  36. open_docs(&path, &mut shell, config_browser)?;
  37. }
  38. }
  39. Ok(())
  40. }
  41. fn open_docs(
  42. path: &Path,
  43. shell: &mut Shell,
  44. config_browser: Option<(PathBuf, Vec<String>)>,
  45. ) -> CargoResult<()> {
  46. let browser =
  47. config_browser.or_else(|| Some((PathBuf::from(std::env::var_os("BROWSER")?), Vec::new())));
  48. match browser {
  49. Some((browser, initial_args)) => {
  50. if let Err(e) = Command::new(&browser).args(initial_args).arg(path).status() {
  51. shell.warn(format!(
  52. "Couldn't open docs with {}: {}",
  53. browser.to_string_lossy(),
  54. e
  55. ))?;
  56. }
  57. }
  58. None => {
  59. if let Err(e) = opener::open(&path) {
  60. let e = e.into();
  61. crate::display_warning_with_error("couldn't open docs", &e, shell);
  62. }
  63. }
  64. };
  65. Ok(())
  66. }