-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdocument.rs
More file actions
191 lines (172 loc) · 6.79 KB
/
Copy pathdocument.rs
File metadata and controls
191 lines (172 loc) · 6.79 KB
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
use pyo3::prelude::*;
use crate::ops::PyPatch;
use crate::types::{PyFeature, PyFeatureKind, PyLocation, PyRoute};
/// A parsed YAML document.
#[pyclass(name = "Document", module = "yamltrip._core")]
pub struct PyDocument {
inner: yamlpath::Document,
source_hash: u64,
}
fn hash_source(source: &str) -> u64 {
use std::hash::{Hash, Hasher};
let mut hasher = std::collections::hash_map::DefaultHasher::new();
source.hash(&mut hasher);
hasher.finish()
}
#[pymethods]
impl PyDocument {
#[new]
fn new(source: &str) -> PyResult<Self> {
let doc = yamlpath::Document::new(source).map_err(|e| {
PyErr::new::<pyo3::exceptions::PyValueError, _>(format!("Failed to parse YAML: {e}"))
})?;
Ok(Self {
source_hash: hash_source(doc.source()),
inner: doc,
})
}
fn source(&self) -> &str {
self.inner.source()
}
fn query_exists(&self, route: &PyRoute) -> bool {
let r = route.to_yamlpath_route();
self.inner.query_exists(&r)
}
fn query_exact(&self, route: &PyRoute) -> PyResult<Option<PyFeature>> {
let r = route.to_yamlpath_route();
match self.inner.query_exact(&r) {
Ok(Some(feature)) => Ok(Some(convert_feature(&feature, self.source_hash))),
Ok(None) => Ok(None),
Err(e) => Err(PyErr::new::<pyo3::exceptions::PyKeyError, _>(format!(
"Query failed: {e}"
))),
}
}
fn query_pretty(&self, route: &PyRoute) -> PyResult<PyFeature> {
let r = route.to_yamlpath_route();
match self.inner.query_pretty(&r) {
Ok(feature) => Ok(convert_feature(&feature, self.source_hash)),
Err(e) => Err(PyErr::new::<pyo3::exceptions::PyKeyError, _>(format!(
"Query failed: {e}"
))),
}
}
fn extract(&self, feature: &PyFeature) -> PyResult<String> {
if feature.source_hash != self.source_hash {
return Err(PyErr::new::<pyo3::exceptions::PyValueError, _>(
"Feature does not belong to this document",
));
}
let source = self.inner.source();
let start = feature.location.start;
let end = feature.location.end;
if end > source.len() || start > end {
return Err(PyErr::new::<pyo3::exceptions::PyValueError, _>(
"Feature location is out of bounds",
));
}
source
.get(start..end)
.map(|s| s.to_string())
.ok_or_else(|| {
PyErr::new::<pyo3::exceptions::PyValueError, _>(
"Feature location is not aligned to UTF-8 character boundaries",
)
})
}
fn has_anchors(&self) -> bool {
self.inner.has_anchors()
}
/// Parse the YAML value at a route and return it as a Python object.
fn parse_value(&self, py: Python<'_>, route: &PyRoute) -> PyResult<Py<PyAny>> {
let source = self.inner.source();
let r = route.to_yamlpath_route();
if !self.inner.query_exists(&r) {
return Err(PyErr::new::<pyo3::exceptions::PyKeyError, _>(
"Path not found",
));
}
// For root-level, parse entire document.
// Note: tree-sitter gives us the AST structure, but not parsed scalar
// values, so we extract the raw YAML substring and re-parse it with
// serde_yaml. The dedenting is needed because serde_yaml expects
// root-level indentation.
let yaml_str = if route.components.is_empty() {
source.to_string()
} else {
match self.inner.query_exact(&r) {
Ok(Some(feature)) => {
let span = feature.location.byte_span;
let raw = &source[span.0..span.1];
// Calculate the column offset (in bytes) of the value
// start relative to the beginning of its line, so we can
// dedent continuation lines.
let line_start = source[..span.0].rfind('\n').map(|nl| nl + 1).unwrap_or(0);
let col = span.0 - line_start;
if col == 0 {
raw.to_string()
} else {
raw.split('\n')
.enumerate()
.map(|(i, line)| {
if i == 0 {
line.to_string()
} else if line.len() >= col
&& line.as_bytes()[..col].iter().all(|&b| b == b' ')
{
line[col..].to_string()
} else {
line.to_string()
}
})
.collect::<Vec<_>>()
.join("\n")
}
}
Ok(None) => return Ok(py.None()),
Err(e) => {
return Err(PyErr::new::<pyo3::exceptions::PyKeyError, _>(format!(
"Query error: {e}"
)));
}
}
};
let value: serde_yaml::Value = serde_yaml::from_str(&yaml_str).map_err(|e| {
PyErr::new::<pyo3::exceptions::PyValueError, _>(format!("YAML parse error: {e}"))
})?;
crate::convert::yaml_value_to_py(py, &value)
}
/// Apply patches to this document and return a new document.
/// NOTE: Similar patch-application logic exists in ops::apply_patches (returns String).
fn apply_patches(&self, patches: Vec<PyPatch>) -> PyResult<Self> {
let yaml_patches: Vec<yamlpatch::Patch<'_>> = patches
.iter()
.map(|p| yamlpatch::Patch {
route: p.route.to_yamlpath_route(),
operation: p.operation.inner.clone(),
})
.collect();
let result = yamlpatch::apply_yaml_patches(&self.inner, &yaml_patches).map_err(|e| {
PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(format!("Patch failed: {e}"))
})?;
Ok(Self {
source_hash: hash_source(result.source()),
inner: result,
})
}
}
fn convert_feature(feature: &yamlpath::Feature<'_>, source_hash: u64) -> PyFeature {
PyFeature {
location: PyLocation {
start: feature.location.byte_span.0,
end: feature.location.byte_span.1,
},
context: feature.context.as_ref().map(|c| PyLocation {
start: c.byte_span.0,
end: c.byte_span.1,
}),
kind: PyFeatureKind::from(feature.kind()),
is_multiline: feature.is_multiline(),
source_hash,
}
}