Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add possibility to generate rustdoc JSON output to stdout #128963

Merged
merged 4 commits into from
Aug 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/doc/rustdoc/src/unstable-features.md
Original file line number Diff line number Diff line change
Expand Up @@ -515,6 +515,9 @@ pub fn no_documentation() {}

Note that the third item is the crate root, which in this case is undocumented.

If you want the JSON output to be displayed on `stdout` instead of having a file generated, you can
use `-o -`.

### `-w`/`--output-format`: output format

`--output-format json` emits documentation in the experimental
Expand Down
15 changes: 10 additions & 5 deletions src/librustdoc/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,9 @@ pub(crate) struct RenderOptions {
pub(crate) no_emit_shared: bool,
/// If `true`, HTML source code pages won't be generated.
pub(crate) html_no_source: bool,
/// This field is only used for the JSON output. If it's set to true, no file will be created
/// and content will be displayed in stdout directly.
pub(crate) output_to_stdout: bool,
}

#[derive(Copy, Clone, Debug, PartialEq, Eq)]
Expand Down Expand Up @@ -548,16 +551,17 @@ impl Options {
dcx.fatal("the `--test` flag must be passed to enable `--no-run`");
}

let mut output_to_stdout = false;
let test_builder_wrappers =
matches.opt_strs("test-builder-wrapper").iter().map(PathBuf::from).collect();
let out_dir = matches.opt_str("out-dir").map(|s| PathBuf::from(&s));
let output = matches.opt_str("output").map(|s| PathBuf::from(&s));
let output = match (out_dir, output) {
let output = match (matches.opt_str("out-dir"), matches.opt_str("output")) {
(Some(_), Some(_)) => {
dcx.fatal("cannot use both 'out-dir' and 'output' at once");
}
(Some(out_dir), None) => out_dir,
(None, Some(output)) => output,
(Some(out_dir), None) | (None, Some(out_dir)) => {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since we discovered they're the same option, it simplifies a lot the handling of this new option.

output_to_stdout = out_dir == "-";
PathBuf::from(out_dir)
}
(None, None) => PathBuf::from("doc"),
};

Expand Down Expand Up @@ -816,6 +820,7 @@ impl Options {
call_locations,
no_emit_shared: false,
html_no_source,
output_to_stdout,
};
Some((options, render_options))
}
Expand Down
47 changes: 31 additions & 16 deletions src/librustdoc/json/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ mod import_finder;

use std::cell::RefCell;
use std::fs::{create_dir_all, File};
use std::io::{BufWriter, Write};
use std::io::{stdout, BufWriter, Write};
use std::path::PathBuf;
use std::rc::Rc;

Expand Down Expand Up @@ -37,7 +37,7 @@ pub(crate) struct JsonRenderer<'tcx> {
/// level field of the JSON blob.
index: Rc<RefCell<FxHashMap<types::Id, types::Item>>>,
/// The directory where the blob will be written to.
out_path: PathBuf,
out_path: Option<PathBuf>,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should probably be renamed to out_dir, as it's not the path to the JSON file, but the path to the directory that contains the JSON file. (But also, maybe we should do this logic earlier, see my later comments)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sadly, as we discovered, output and out-dir are actually the same option and output is deprecated. I think it'll require a bigger discussion.

Copy link
Member

@jieyouxu jieyouxu Aug 12, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remark (peanut gallery): that is very surprising, rustc's --output and --out-dir means (I understand this is rustdoc not rustc):

The output filename can be set with the -o flag. A suffix may be added to the filename with the -C extra-filename flag.
Output files are written to the current directory unless the --out-dir flag is used.

cf. https://doc.rust-lang.org/rustc/command-line-arguments.html#--out-dir-directory-to-write-the-output-in

(rustc's cli docs is kinda inaccurate here because it's actually output path for -o not just filename)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cache: Rc<Cache>,
imported_items: DefIdSet,
}
Expand Down Expand Up @@ -97,6 +97,20 @@ impl<'tcx> JsonRenderer<'tcx> {
})
.unwrap_or_default()
}

fn write<T: Write>(
&self,
output: types::Crate,
mut writer: BufWriter<T>,
path: &str,
) -> Result<(), Error> {
self.tcx
.sess
.time("rustdoc_json_serialization", || serde_json::ser::to_writer(&mut writer, &output))
.unwrap();
try_err!(writer.flush(), path);
Ok(())
}
}

impl<'tcx> FormatRenderer<'tcx> for JsonRenderer<'tcx> {
Expand All @@ -120,7 +134,7 @@ impl<'tcx> FormatRenderer<'tcx> for JsonRenderer<'tcx> {
JsonRenderer {
tcx,
index: Rc::new(RefCell::new(FxHashMap::default())),
out_path: options.output,
out_path: if options.output_to_stdout { None } else { Some(options.output) },
cache: Rc::new(cache),
imported_items,
},
Expand Down Expand Up @@ -264,20 +278,21 @@ impl<'tcx> FormatRenderer<'tcx> for JsonRenderer<'tcx> {
.collect(),
format_version: types::FORMAT_VERSION,
};
let out_dir = self.out_path.clone();
try_err!(create_dir_all(&out_dir), out_dir);
if let Some(ref out_path) = self.out_path {
let out_dir = out_path.clone();
try_err!(create_dir_all(&out_dir), out_dir);

let mut p = out_dir;
p.push(output.index.get(&output.root).unwrap().name.clone().unwrap());
p.set_extension("json");
let mut file = BufWriter::new(try_err!(File::create(&p), p));
self.tcx
.sess
.time("rustdoc_json_serialization", || serde_json::ser::to_writer(&mut file, &output))
.unwrap();
try_err!(file.flush(), p);

Ok(())
let mut p = out_dir;
p.push(output.index.get(&output.root).unwrap().name.clone().unwrap());
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should also respect the --output flag here, even if it's not for a file. Currently --output is ignored for JSON, but if --output - works, then --output some_file.json should also work to rename the JSON (instead of using the crate name).

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good idea!

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So, from what I can see, --out-dir and --output are kinda considered the same by rustdoc and --output is deprecated. So currently we don't really have a way to say I want JSON output to be generated into "this file".

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remark (peanut gallery): I would've thought --output=PATH would cause the json output to be dumped to this specific file at PATH, and that if --output is specified, --out-dir would be ignored.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes it's the whole problem here. The --output option was created when the HTML format was the only format, making it useless and why we created --out-dir. Currently, both options are actually the same, which is pretty bad.

p.set_extension("json");
self.write(
output,
BufWriter::new(try_err!(File::create(&p), p)),
&p.display().to_string(),
)
} else {
self.write(output, BufWriter::new(stdout()), "<stdout>")
}
}

fn cache(&self) -> &Cache {
Expand Down
15 changes: 15 additions & 0 deletions src/tools/run-make-support/src/path_helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,3 +84,18 @@ pub fn has_suffix<P: AsRef<Path>>(path: P, suffix: &str) -> bool {
pub fn filename_contains<P: AsRef<Path>>(path: P, needle: &str) -> bool {
path.as_ref().file_name().is_some_and(|name| name.to_str().unwrap().contains(needle))
}

/// Helper for reading entries in a given directory and its children.
pub fn read_dir_entries_recursive<P: AsRef<Path>, F: FnMut(&Path)>(dir: P, mut callback: F) {
fn read_dir_entries_recursive_inner<P: AsRef<Path>, F: FnMut(&Path)>(dir: P, callback: &mut F) {
for entry in rfs::read_dir(dir) {
let path = entry.unwrap().path();
callback(&path);
if path.is_dir() {
read_dir_entries_recursive_inner(path, callback);
}
}
}

read_dir_entries_recursive_inner(dir, &mut callback);
}
1 change: 1 addition & 0 deletions tests/run-make/rustdoc-output-stdout/foo.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pub struct Foo;
25 changes: 25 additions & 0 deletions tests/run-make/rustdoc-output-stdout/rmake.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// This test verifies that rustdoc `-o -` prints JSON on stdout and doesn't generate
// a JSON file.

use std::path::PathBuf;

use run_make_support::path_helpers::{cwd, has_extension, read_dir_entries_recursive};
use run_make_support::rustdoc;

fn main() {
// First we check that we generate the JSON in the stdout.
rustdoc()
.input("foo.rs")
.output("-")
.arg("-Zunstable-options")
.output_format("json")
.run()
.assert_stdout_contains("{\"");
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remark: I suppose this is a reasonable heuristic.


// Then we check it didn't generate any JSON file.
read_dir_entries_recursive(cwd(), |path| {
if path.is_file() && has_extension(path, "json") {
panic!("Found a JSON file {path:?}");
}
});
}
Loading