-
Notifications
You must be signed in to change notification settings - Fork 901
/
source_kind.rs
92 lines (83 loc) · 2.8 KB
/
source_kind.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
use std::io;
use std::io::Write;
use std::path::Path;
use anyhow::Result;
use thiserror::Error;
use ruff_diagnostics::SourceMap;
use ruff_notebook::{Notebook, NotebookError};
use ruff_python_ast::PySourceType;
#[derive(Clone, Debug, PartialEq, is_macro::Is)]
pub enum SourceKind {
/// The source contains Python source code.
Python(String),
/// The source contains a Jupyter notebook.
IpyNotebook(Notebook),
}
impl SourceKind {
#[must_use]
pub(crate) fn updated(&self, new_source: String, source_map: &SourceMap) -> Self {
match self {
SourceKind::IpyNotebook(notebook) => {
let mut cloned = notebook.clone();
cloned.update(source_map, new_source);
SourceKind::IpyNotebook(cloned)
}
SourceKind::Python(_) => SourceKind::Python(new_source),
}
}
/// Returns the source code for this source kind.
pub fn source_code(&self) -> &str {
match self {
SourceKind::Python(source) => source,
SourceKind::IpyNotebook(notebook) => notebook.source_code(),
}
}
/// Read the [`SourceKind`] from the given path. Returns `None` if the source is not a Python
/// source file.
pub fn from_path(path: &Path, source_type: PySourceType) -> Result<Option<Self>, SourceError> {
if source_type.is_ipynb() {
let notebook = Notebook::from_path(path)?;
Ok(notebook
.is_python_notebook()
.then_some(Self::IpyNotebook(notebook)))
} else {
let contents = std::fs::read_to_string(path)?;
Ok(Some(Self::Python(contents)))
}
}
/// Read the [`SourceKind`] from the given source code. Returns `None` if the source is not
/// Python source code.
pub fn from_source_code(
source_code: String,
source_type: PySourceType,
) -> Result<Option<Self>, SourceError> {
if source_type.is_ipynb() {
let notebook = Notebook::from_source_code(&source_code)?;
Ok(notebook
.is_python_notebook()
.then_some(Self::IpyNotebook(notebook)))
} else {
Ok(Some(Self::Python(source_code)))
}
}
/// Write the [`SourceKind`] to the given writer.
pub fn write(&self, writer: &mut dyn Write) -> Result<(), SourceError> {
match self {
SourceKind::Python(source) => {
writer.write_all(source.as_bytes())?;
Ok(())
}
SourceKind::IpyNotebook(notebook) => {
notebook.write(writer)?;
Ok(())
}
}
}
}
#[derive(Error, Debug)]
pub enum SourceError {
#[error(transparent)]
Io(#[from] io::Error),
#[error(transparent)]
Notebook(#[from] NotebookError),
}