Write full Jupyter notebook to stdout (#7748)

## Summary

When writing back notebooks via `stdout`, we need to write back the
entire JSON content, not _just_ the fixed source code. Otherwise,
writing the output _back_ to the file will yield an invalid notebook.

Closes https://github.com/astral-sh/ruff/issues/7747

## Test Plan

`cargo test`
This commit is contained in:
Charlie Marsh 2023-10-02 10:20:13 -04:00 committed by GitHub
parent c71ff7eae1
commit ebdfcee87f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 190 additions and 6 deletions

View file

@ -1,3 +1,7 @@
use std::io::Write;
use anyhow::Result;
use ruff_diagnostics::SourceMap;
use ruff_notebook::Notebook;
@ -22,10 +26,21 @@ impl SourceKind {
}
}
/// Returns the Python source code for this source kind.
pub fn source_code(&self) -> &str {
match self {
SourceKind::Python(source) => source,
SourceKind::IpyNotebook(notebook) => notebook.source_code(),
}
}
/// Write the transformed source file to the given writer.
///
/// For Jupyter notebooks, this will write out the notebook as JSON.
pub fn write(&self, writer: &mut dyn Write) -> Result<()> {
match self {
SourceKind::Python(source) => writer.write_all(source.as_bytes()).map_err(Into::into),
SourceKind::IpyNotebook(notebook) => notebook.write(writer).map_err(Into::into),
}
}
}