Skip to content

Commit 4e17170

Browse files
committed
rustdoc: auto create output directory when "--output-format json"
This PR allows rustdoc to automatically create output directory in case it does not exist (when run with `--output-format json`). This fixes rustdoc crash: ```` $ rustdoc --output-format json -Z unstable-options src/main.rs error: couldn't generate documentation: No such file or directory (os error 2) | = note: failed to create or modify "doc/main.json" error: aborting due to previous error ```` With this fix behavior of `rustdoc --output-format json` becomes consistent with `rustdoc --output-format html` (which already auto-creates output directory if it's missing)
1 parent e5e2b0b commit 4e17170

File tree

1 file changed

+8
-4
lines changed

1 file changed

+8
-4
lines changed

src/librustdoc/json/mod.rs

+8-4
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
mod conversions;
88

99
use std::cell::RefCell;
10-
use std::fs::File;
10+
use std::fs::{create_dir_all, File};
1111
use std::path::PathBuf;
1212
use std::rc::Rc;
1313

@@ -18,13 +18,14 @@ use rustc_session::Session;
1818

1919
use rustdoc_json_types as types;
2020

21-
use crate::clean;
2221
use crate::clean::types::{ExternalCrate, ExternalLocation};
2322
use crate::config::RenderOptions;
23+
use crate::docfs::PathError;
2424
use crate::error::Error;
2525
use crate::formats::cache::Cache;
2626
use crate::formats::FormatRenderer;
2727
use crate::json::conversions::{from_item_id, IntoWithTcx};
28+
use crate::{clean, try_err};
2829

2930
#[derive(Clone)]
3031
crate struct JsonRenderer<'tcx> {
@@ -256,10 +257,13 @@ impl<'tcx> FormatRenderer<'tcx> for JsonRenderer<'tcx> {
256257
.collect(),
257258
format_version: types::FORMAT_VERSION,
258259
};
259-
let mut p = self.out_path.clone();
260+
let out_dir = self.out_path.clone();
261+
try_err!(create_dir_all(&out_dir), out_dir);
262+
263+
let mut p = out_dir;
260264
p.push(output.index.get(&output.root).unwrap().name.clone().unwrap());
261265
p.set_extension("json");
262-
let file = File::create(&p).map_err(|error| Error { error: error.to_string(), file: p })?;
266+
let file = try_err!(File::create(&p), p);
263267
serde_json::ser::to_writer(&file, &output).unwrap();
264268
Ok(())
265269
}

0 commit comments

Comments
 (0)