use std::fmt;
use jsonc_parser::ParseOptions;
use jsonc_parser::cst::{CstInputValue, CstNode, CstRootNode};
use serde_json::Value;
use sha2::{Digest, Sha256};
use crate::plan::TargetPath;
#[derive(Debug)]
pub enum PlannedEdit {
Region(PlannedRegionEdit),
JsonValue(PlannedJsonEdit),
}
impl PlannedEdit {
pub fn path(&self) -> &TargetPath {
match self {
Self::Region(edit) => &edit.path,
Self::JsonValue(edit) => &edit.path,
}
}
}
#[derive(Debug)]
pub struct PlannedRegionEdit {
pub path: TargetPath,
pub region: RegionKey,
pub body: String,
pub marker: MarkerStyle,
pub anchor: Option<Anchor>,
pub create: bool,
pub source: Option<std::path::PathBuf>,
}
#[derive(Debug)]
pub struct PlannedJsonEdit {
pub path: TargetPath,
pub json_path: JsonPath,
pub desired: Value,
pub format: JsonFormat,
pub create: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RegionKey(String);
impl RegionKey {
pub fn parse(value: &str) -> Result<Self, String> {
if value.is_empty()
|| !value
.bytes()
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_' || b == b'-')
{
return Err(format!(
"invalid region key: {value} (use lowercase letters, digits, `_`, and `-`)"
));
}
Ok(Self(value.to_owned()))
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Display for RegionKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MarkerStyle {
pub prefix: String,
pub suffix: String,
}
impl MarkerStyle {
pub fn line(prefix: &str) -> Self {
Self {
prefix: prefix.to_owned(),
suffix: String::new(),
}
}
pub fn block(open: &str, close: &str) -> Self {
Self {
prefix: open.to_owned(),
suffix: format!(" {close}"),
}
}
pub fn infer(path: &TargetPath) -> Option<Self> {
let name = path.as_path().file_name()?.to_str()?;
let lower = name.to_ascii_lowercase();
match lower.as_str() {
"makefile" | "dockerfile" | "gitignore" | ".gitignore" | "dockerignore"
| ".dockerignore" | ".editorconfig" | ".env" | "cargo.lock" => {
return Some(Self::line("#"));
}
_ => {}
}
let ext = lower.rsplit_once('.').map(|(_, ext)| ext)?;
let style = match ext {
"sh" | "bash" | "zsh" | "fish" | "ksh" | "py" | "pyw" | "rb" | "pl" | "pm" | "r"
| "jl" | "ex" | "exs" | "nim" | "cr" | "toml" | "yaml" | "yml" | "ini" | "cfg"
| "conf" | "properties" | "tf" | "hcl" | "mk" | "env" | "gitignore" | "gitconfig"
| "dockerfile" | "ps1" | "psm1" | "awk" | "tcl" | "rake" | "gemspec" => Self::line("#"),
"rs" | "js" | "mjs" | "cjs" | "ts" | "tsx" | "jsx" | "mts" | "cts" | "c" | "h"
| "cpp" | "cxx" | "cc" | "hpp" | "hxx" | "hh" | "java" | "kt" | "kts" | "scala"
| "go" | "swift" | "cs" | "php" | "dart" | "proto" | "glsl" | "zig" | "v" | "rs2"
| "groovy" | "gradle" | "less" | "scss" | "sass" | "styl" => Self::line("//"),
"sql" | "lua" | "hs" | "elm" | "ada" | "adb" | "ads" | "vhd" | "vhdl" | "hql" => {
Self::line("--")
}
"clj" | "cljs" | "cljc" | "edn" | "lisp" | "lsp" | "el" | "scm" | "asm" | "s" => {
Self::line(";")
}
"tex" | "sty" | "cls" | "bib" | "erl" | "hrl" | "mat" | "m" => Self::line("%"),
"html" | "htm" | "xhtml" | "xml" | "svg" | "vue" | "xaml" | "md" | "markdown"
| "mdx" | "rss" | "atom" | "resx" | "plist" => Self::block("<!--", "-->"),
"css" => Self::block("/*", "*/"),
_ => return None,
};
Some(style)
}
fn begin(&self, key: &RegionKey) -> String {
format!("{} >>> toha:region {key} >>>{}", self.prefix, self.suffix)
}
fn end(&self, key: &RegionKey, sha: &str) -> String {
format!(
"{} <<< toha:end {key} sha256:{sha} <<<{}",
self.prefix, self.suffix
)
}
fn end_fixes(&self, key: &RegionKey) -> (String, String) {
(
format!("{} <<< toha:end {key} sha256:", self.prefix),
format!(" <<<{}", self.suffix),
)
}
}
#[derive(Debug, Clone)]
pub struct Anchor {
pub after: String,
pub occurrence: Occurrence,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Occurrence {
Only,
First,
Last,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum JsonFormat {
Json,
Jsonc,
Json5,
}
impl JsonFormat {
pub fn parse_options(self) -> ParseOptions {
match self {
Self::Json => ParseOptions {
allow_comments: false,
allow_loose_object_property_names: false,
allow_trailing_commas: false,
allow_missing_commas: false,
allow_single_quoted_strings: false,
allow_hexadecimal_numbers: false,
allow_unary_plus_numbers: false,
allow_bare_decimal_point_numbers: false,
allow_non_finite_numbers: false,
allow_extended_string_escapes: false,
},
Self::Jsonc => ParseOptions {
allow_comments: true,
allow_loose_object_property_names: false,
allow_trailing_commas: true,
allow_missing_commas: false,
allow_single_quoted_strings: false,
allow_hexadecimal_numbers: false,
allow_unary_plus_numbers: false,
allow_bare_decimal_point_numbers: false,
allow_non_finite_numbers: false,
allow_extended_string_escapes: false,
},
Self::Json5 => ParseOptions {
allow_comments: true,
allow_loose_object_property_names: true,
allow_trailing_commas: true,
allow_missing_commas: true,
allow_single_quoted_strings: true,
allow_hexadecimal_numbers: true,
allow_unary_plus_numbers: true,
allow_bare_decimal_point_numbers: true,
allow_non_finite_numbers: true,
allow_extended_string_escapes: true,
},
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct JsonPath(Vec<JsonPathSegment>);
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum JsonPathSegment {
Key(String),
Index(usize),
}
impl JsonPath {
pub fn parse(value: &str) -> Result<Self, String> {
let mut segments = Vec::new();
let mut chars = value.chars().peekable();
if value.is_empty() {
return Err("empty path".into());
}
if chars.peek() == Some(&'[') {
return Err("path must begin with a key".into());
}
loop {
match chars.peek() {
None => break,
Some('[') => {
chars.next();
let mut digits = String::new();
while let Some(&c) = chars.peek() {
if c == ']' {
break;
}
digits.push(c);
chars.next();
}
if chars.next() != Some(']') {
return Err(format!("unclosed array index in path: {value}"));
}
let index: usize = digits
.parse()
.map_err(|_| format!("invalid array index `{digits}` in path: {value}"))?;
segments.push(JsonPathSegment::Index(index));
if chars.peek() == Some(&'.') {
chars.next();
segments.push(read_key(&mut chars, value)?);
}
}
Some('.') => {
chars.next();
segments.push(read_key(&mut chars, value)?);
}
Some(_) => {
segments.push(read_key(&mut chars, value)?);
}
}
}
if segments.is_empty() {
return Err(format!("empty path: {value}"));
}
Ok(Self(segments))
}
pub fn segments(&self) -> &[JsonPathSegment] {
&self.0
}
pub fn overlaps(&self, other: &Self) -> bool {
let shorter = self.0.len().min(other.0.len());
self.0[..shorter] == other.0[..shorter]
}
}
impl fmt::Display for JsonPath {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for (i, segment) in self.0.iter().enumerate() {
match segment {
JsonPathSegment::Key(key) => {
if i > 0 {
write!(f, ".")?;
}
for ch in key.chars() {
if matches!(ch, '.' | '[' | ']' | '\\') {
write!(f, "\\")?;
}
write!(f, "{ch}")?;
}
}
JsonPathSegment::Index(index) => write!(f, "[{index}]")?,
}
}
Ok(())
}
}
fn read_key(
chars: &mut std::iter::Peekable<std::str::Chars>,
value: &str,
) -> Result<JsonPathSegment, String> {
let mut key = String::new();
while let Some(&c) = chars.peek() {
match c {
'.' | '[' => break,
']' => return Err(format!("unexpected `]` in path: {value}")),
'\\' => {
chars.next();
match chars.next() {
Some(escaped @ ('.' | '[' | ']' | '\\')) => key.push(escaped),
_ => return Err(format!("invalid escape in path: {value}")),
}
}
_ => {
key.push(c);
chars.next();
}
}
}
if key.is_empty() {
return Err(format!("empty key in path: {value}"));
}
Ok(JsonPathSegment::Key(key))
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EditResolution {
Unchanged,
Write(Vec<u8>),
Drift {
forced: Vec<u8>,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EditReport {
Inject,
Update,
Unchanged,
Drift,
}
#[derive(Debug, thiserror::Error)]
pub enum RegionError {
#[error("target missing for region `{0}`; declare create: true to create it")]
TargetMissing(RegionKey),
#[error("target is not UTF-8 text for region `{0}`")]
NotUtf8(RegionKey),
#[error("malformed or duplicate markers for region `{0}`")]
MalformedMarkers(RegionKey),
#[error("no line matches the anchor for region `{0}`")]
AnchorMissing(RegionKey),
#[error("the anchor for region `{0}` matches more than one line")]
AnchorAmbiguous(RegionKey),
}
#[derive(Debug, thiserror::Error)]
pub enum JsonEditError {
#[error("target missing for `{path}`; declare create: true to create it")]
TargetMissing { path: JsonPath },
#[error("target is not UTF-8 text for `{path}`")]
NotUtf8 { path: JsonPath },
#[error("malformed {format:?} source for `{path}`: {message}")]
Parse {
path: JsonPath,
format: JsonFormat,
message: String,
},
#[error("invalid traversal for `{path}`: {message}")]
Traversal { path: JsonPath, message: String },
#[error("array index {index} out of range for `{path}`")]
IndexOutOfRange { path: JsonPath, index: usize },
}
pub fn json_value_to_cst_input(value: &Value) -> CstInputValue {
match value {
Value::Null => CstInputValue::Null,
Value::Bool(b) => CstInputValue::Bool(*b),
Value::Number(n) => CstInputValue::Number(n.to_string()),
Value::String(s) => CstInputValue::String(s.clone()),
Value::Array(items) => {
CstInputValue::Array(items.iter().map(json_value_to_cst_input).collect())
}
Value::Object(map) => CstInputValue::Object(
map.iter()
.map(|(k, v)| (k.clone(), json_value_to_cst_input(v)))
.collect(),
),
}
}
pub fn resolve_region_edit(
current: Option<&[u8]>,
edit: &PlannedRegionEdit,
) -> Result<EditResolution, RegionError> {
Ok(match plan_region(current, edit)? {
RegionOutcome::Unchanged => EditResolution::Unchanged,
RegionOutcome::Write(bytes) => EditResolution::Write(bytes),
RegionOutcome::Drift(forced) => EditResolution::Drift { forced },
})
}
pub fn report_region_edit(
current: Option<&[u8]>,
edit: &PlannedRegionEdit,
) -> Result<EditReport, RegionError> {
Ok(match plan_region(current, edit)? {
RegionOutcome::Unchanged => EditReport::Unchanged,
RegionOutcome::Write(_) => report_region_kind(current, edit)?,
RegionOutcome::Drift(_) => EditReport::Drift,
})
}
fn report_region_kind(
current: Option<&[u8]>,
edit: &PlannedRegionEdit,
) -> Result<EditReport, RegionError> {
let present = match current {
None => false,
Some(bytes) => {
let text = std::str::from_utf8(bytes)
.map_err(|_| RegionError::NotUtf8(edit.region.clone()))?;
find_region(text, &edit.marker, &edit.region)?.is_some()
}
};
Ok(if present {
EditReport::Update
} else {
EditReport::Inject
})
}
enum RegionOutcome {
Unchanged,
Write(Vec<u8>),
Drift(Vec<u8>),
}
struct Located {
begin_start: usize,
body_start: usize,
end_start: usize,
end_line_end: usize,
recorded: String,
}
fn plan_region(
current: Option<&[u8]>,
edit: &PlannedRegionEdit,
) -> Result<RegionOutcome, RegionError> {
let bytes = match current {
Some(bytes) => bytes,
None => {
if !edit.create {
return Err(RegionError::TargetMissing(edit.region.clone()));
}
&[]
}
};
let text = std::str::from_utf8(bytes).map_err(|_| RegionError::NotUtf8(edit.region.clone()))?;
let body = normalize_body(&edit.body);
let sha = checksum(&body);
let begin = edit.marker.begin(&edit.region);
let end = edit.marker.end(&edit.region, &sha);
match find_region(text, &edit.marker, &edit.region)? {
Some(located) => {
let current_body = &text[located.body_start..located.end_start];
if current_body == body {
return Ok(RegionOutcome::Unchanged);
}
let replacement = format!("{begin}\n{body}{end}\n");
let mut out = String::with_capacity(text.len() + replacement.len());
out.push_str(&text[..located.begin_start]);
out.push_str(&replacement);
out.push_str(&text[located.end_line_end..]);
let bytes = out.into_bytes();
if checksum(current_body) == located.recorded {
Ok(RegionOutcome::Write(bytes))
} else {
Ok(RegionOutcome::Drift(bytes))
}
}
None => {
let block = format!("{begin}\n{body}{end}\n");
let out = place_region(text, edit, &block)?;
Ok(RegionOutcome::Write(out.into_bytes()))
}
}
}
fn normalize_body(body: &str) -> String {
if body.is_empty() {
String::new()
} else if body.ends_with('\n') {
body.to_owned()
} else {
format!("{body}\n")
}
}
fn checksum(body: &str) -> String {
let mut hasher = Sha256::new();
hasher.update(body.as_bytes());
format!("{:x}", hasher.finalize())
}
fn place_region(text: &str, edit: &PlannedRegionEdit, block: &str) -> Result<String, RegionError> {
match &edit.anchor {
Some(anchor) => {
let insert_at = anchor_offset(text, anchor, &edit.region)?;
let mut out = String::with_capacity(text.len() + block.len());
out.push_str(&text[..insert_at]);
out.push_str(block);
out.push_str(&text[insert_at..]);
Ok(out)
}
None => {
let mut out = String::with_capacity(text.len() + block.len() + 1);
out.push_str(text);
if !text.is_empty() && !text.ends_with('\n') {
out.push('\n');
}
out.push_str(block);
Ok(out)
}
}
}
fn anchor_offset(text: &str, anchor: &Anchor, key: &RegionKey) -> Result<usize, RegionError> {
let matched: Vec<Line> = scan_lines(text)
.into_iter()
.filter(|line| line_content(text, line) == anchor.after)
.collect();
let chosen = match anchor.occurrence {
Occurrence::Only => match matched.as_slice() {
[] => return Err(RegionError::AnchorMissing(key.clone())),
[one] => one,
_ => return Err(RegionError::AnchorAmbiguous(key.clone())),
},
Occurrence::First => matched
.first()
.ok_or_else(|| RegionError::AnchorMissing(key.clone()))?,
Occurrence::Last => matched
.last()
.ok_or_else(|| RegionError::AnchorMissing(key.clone()))?,
};
Ok(chosen.end)
}
fn find_region(
text: &str,
style: &MarkerStyle,
key: &RegionKey,
) -> Result<Option<Located>, RegionError> {
let begin = style.begin(key);
let (end_prefix, end_suffix) = style.end_fixes(key);
let lines = scan_lines(text);
let mut begins = Vec::new();
let mut ends = Vec::new();
for (i, line) in lines.iter().enumerate() {
let content = line_content(text, line);
if content == begin {
begins.push(i);
} else if let Some(recorded) = read_end(content, &end_prefix, &end_suffix) {
ends.push((i, recorded.to_owned()));
}
}
match (begins.as_slice(), ends.as_slice()) {
([], []) => Ok(None),
([bi], [(ei, recorded)]) if bi < ei => {
let begin_line = &lines[*bi];
let end_line = &lines[*ei];
Ok(Some(Located {
begin_start: begin_line.start,
body_start: begin_line.end,
end_start: end_line.start,
end_line_end: end_line.end,
recorded: recorded.clone(),
}))
}
_ => Err(RegionError::MalformedMarkers(key.clone())),
}
}
fn read_end<'a>(content: &'a str, prefix: &str, suffix: &str) -> Option<&'a str> {
let content = content.trim_end();
let inner = content.strip_prefix(prefix)?.strip_suffix(suffix)?;
(!inner.is_empty() && inner.bytes().all(|b| b.is_ascii_hexdigit())).then_some(inner)
}
#[derive(Clone)]
struct Line {
start: usize,
content_end: usize,
end: usize,
}
fn scan_lines(text: &str) -> Vec<Line> {
let mut lines = Vec::new();
let bytes = text.as_bytes();
let mut start = 0;
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'\n' {
let mut content_end = i;
if content_end > start && bytes[content_end - 1] == b'\r' {
content_end -= 1;
}
lines.push(Line {
start,
content_end,
end: i + 1,
});
start = i + 1;
}
i += 1;
}
if start < bytes.len() {
lines.push(Line {
start,
content_end: bytes.len(),
end: bytes.len(),
});
}
lines
}
fn line_content<'a>(text: &'a str, line: &Line) -> &'a str {
&text[line.start..line.content_end]
}
pub fn resolve_json_edit(
current: Option<&[u8]>,
edit: &PlannedJsonEdit,
) -> Result<EditResolution, JsonEditError> {
Ok(match plan_json(current, edit)? {
JsonOutcome::Unchanged => EditResolution::Unchanged,
JsonOutcome::Write { bytes, .. } => EditResolution::Write(bytes),
})
}
pub fn report_json_edit(
current: Option<&[u8]>,
edit: &PlannedJsonEdit,
) -> Result<EditReport, JsonEditError> {
Ok(match plan_json(current, edit)? {
JsonOutcome::Unchanged => EditReport::Unchanged,
JsonOutcome::Write { existed, .. } => {
if existed {
EditReport::Update
} else {
EditReport::Inject
}
}
})
}
enum JsonOutcome {
Unchanged,
Write { bytes: Vec<u8>, existed: bool },
}
enum Container {
Object(jsonc_parser::cst::CstObject),
Array(jsonc_parser::cst::CstArray),
}
fn plan_json(current: Option<&[u8]>, edit: &PlannedJsonEdit) -> Result<JsonOutcome, JsonEditError> {
let owned;
let bytes: &[u8] = match current {
Some(bytes) => bytes,
None => {
if !edit.create {
return Err(JsonEditError::TargetMissing {
path: edit.json_path.clone(),
});
}
owned = b"{}".to_vec();
&owned
}
};
let text = std::str::from_utf8(bytes).map_err(|_| JsonEditError::NotUtf8 {
path: edit.json_path.clone(),
})?;
if edit.format == JsonFormat::Json {
serde_json::from_str::<Value>(text).map_err(|e| JsonEditError::Parse {
path: edit.json_path.clone(),
format: edit.format,
message: e.to_string(),
})?;
}
let root = CstRootNode::parse(text, &edit.format.parse_options()).map_err(|e| {
JsonEditError::Parse {
path: edit.json_path.clone(),
format: edit.format,
message: e.to_string(),
}
})?;
let root_obj = match root.value() {
Some(node) => node.as_object().ok_or_else(|| JsonEditError::Traversal {
path: edit.json_path.clone(),
message: "root is not a JSON object".into(),
})?,
None => root.object_value_or_set(),
};
let segments = edit.json_path.segments();
let (last, parents) = segments
.split_last()
.expect("a parsed path has at least one segment");
let mut container = Container::Object(root_obj);
for (i, seg) in parents.iter().enumerate() {
let need_array = matches!(segments[i + 1], JsonPathSegment::Index(_));
container = descend(container, seg, need_array, edit)?;
}
let existed = match (container, last) {
(Container::Object(obj), JsonPathSegment::Key(k)) => match obj.get(k) {
Some(prop) => {
let current_value = prop.value().and_then(|n| n.to_serde_value());
if current_value.as_ref() == Some(&edit.desired) {
return Ok(JsonOutcome::Unchanged);
}
prop.set_value(json_value_to_cst_input(&edit.desired));
true
}
None => {
obj.append(k, json_value_to_cst_input(&edit.desired));
false
}
},
(Container::Array(arr), JsonPathSegment::Index(idx)) => {
let elements = arr.elements();
let element = elements
.get(*idx)
.ok_or_else(|| JsonEditError::IndexOutOfRange {
path: edit.json_path.clone(),
index: *idx,
})?
.clone();
if element.to_serde_value().as_ref() == Some(&edit.desired) {
return Ok(JsonOutcome::Unchanged);
}
replace_node(element, json_value_to_cst_input(&edit.desired));
true
}
(Container::Object(_), JsonPathSegment::Index(_)) => {
return Err(JsonEditError::Traversal {
path: edit.json_path.clone(),
message: "expected an array but found an object".into(),
});
}
(Container::Array(_), JsonPathSegment::Key(_)) => {
return Err(JsonEditError::Traversal {
path: edit.json_path.clone(),
message: "expected an object but found an array".into(),
});
}
};
Ok(JsonOutcome::Write {
bytes: root.to_string().into_bytes(),
existed,
})
}
fn descend(
container: Container,
seg: &JsonPathSegment,
need_array: bool,
edit: &PlannedJsonEdit,
) -> Result<Container, JsonEditError> {
let traversal = |message: &str| JsonEditError::Traversal {
path: edit.json_path.clone(),
message: message.into(),
};
match (container, seg) {
(Container::Object(obj), JsonPathSegment::Key(k)) => match obj.get(k) {
Some(prop) => match prop.value() {
Some(node) => {
if need_array {
node.as_array()
.map(Container::Array)
.ok_or_else(|| traversal("expected an array in the path"))
} else {
node.as_object()
.map(Container::Object)
.ok_or_else(|| traversal("expected an object in the path"))
}
}
None => Err(traversal("malformed property in the path")),
},
None => {
if need_array {
Err(traversal("an array in the path does not exist"))
} else {
Ok(Container::Object(obj.object_value_or_set(k)))
}
}
},
(Container::Array(arr), JsonPathSegment::Index(idx)) => {
let elements = arr.elements();
let element = elements
.get(*idx)
.ok_or(JsonEditError::IndexOutOfRange {
path: edit.json_path.clone(),
index: *idx,
})?
.clone();
if need_array {
element
.as_array()
.map(Container::Array)
.ok_or_else(|| traversal("expected an array in the path"))
} else {
element
.as_object()
.map(Container::Object)
.ok_or_else(|| traversal("expected an object in the path"))
}
}
(Container::Object(_), JsonPathSegment::Index(_)) => {
Err(traversal("expected an array but found an object"))
}
(Container::Array(_), JsonPathSegment::Key(_)) => {
Err(traversal("expected an object but found an array"))
}
}
}
fn replace_node(node: CstNode, input: CstInputValue) {
if let Some(object) = node.as_object() {
object.replace_with(input);
} else if let Some(array) = node.as_array() {
array.replace_with(input);
} else if let Some(string) = node.as_string_lit() {
string.replace_with(input);
} else if let Some(number) = node.as_number_lit() {
number.replace_with(input);
} else if let Some(boolean) = node.as_boolean_lit() {
boolean.replace_with(input);
} else if let Some(null) = node.as_null_keyword() {
null.replace_with(input);
} else if let Some(word) = node.as_word_lit() {
word.replace_with(input);
}
}
pub(crate) fn retract_region(
current: &[u8],
region: &RegionKey,
marker: &MarkerStyle,
) -> Result<Vec<u8>, RegionError> {
let text = std::str::from_utf8(current).map_err(|_| RegionError::NotUtf8(region.clone()))?;
match find_region(text, marker, region)? {
Some(located) => {
let mut out = String::with_capacity(text.len());
out.push_str(&text[..located.begin_start]);
out.push_str(&text[located.end_line_end..]);
Ok(out.into_bytes())
}
None => Ok(current.to_vec()),
}
}
pub(crate) fn retract_json_value(
current: &[u8],
json_path: &JsonPath,
format: JsonFormat,
) -> Result<Vec<u8>, JsonEditError> {
let text = std::str::from_utf8(current).map_err(|_| JsonEditError::NotUtf8 {
path: json_path.clone(),
})?;
if format == JsonFormat::Json {
serde_json::from_str::<Value>(text).map_err(|e| JsonEditError::Parse {
path: json_path.clone(),
format,
message: e.to_string(),
})?;
}
let root =
CstRootNode::parse(text, &format.parse_options()).map_err(|e| JsonEditError::Parse {
path: json_path.clone(),
format,
message: e.to_string(),
})?;
let Some(root_obj) = root.value().and_then(|node| node.as_object()) else {
return Ok(current.to_vec());
};
let segments = json_path.segments();
let (last, parents) = segments
.split_last()
.expect("a parsed path has at least one segment");
let mut container = Container::Object(root_obj);
for (i, seg) in parents.iter().enumerate() {
let need_array = matches!(segments[i + 1], JsonPathSegment::Index(_));
container = match navigate(container, seg, need_array) {
Some(next) => next,
None => return Ok(current.to_vec()),
};
}
match (container, last) {
(Container::Object(obj), JsonPathSegment::Key(k)) => {
if let Some(prop) = obj.get(k) {
prop.remove();
}
}
(Container::Array(arr), JsonPathSegment::Index(idx)) => {
if let Some(element) = arr.elements().get(*idx) {
element.clone().remove();
}
}
_ => return Ok(current.to_vec()),
}
Ok(root.to_string().into_bytes())
}
fn navigate(container: Container, seg: &JsonPathSegment, need_array: bool) -> Option<Container> {
let node = match (container, seg) {
(Container::Object(obj), JsonPathSegment::Key(k)) => obj.get(k)?.value()?,
(Container::Array(arr), JsonPathSegment::Index(idx)) => arr.elements().get(*idx)?.clone(),
_ => return None,
};
if need_array {
node.as_array().map(Container::Array)
} else {
node.as_object().map(Container::Object)
}
}
#[cfg(test)]
mod tests;