use std::ptr::NonNull;
use crate::error::{EditTarget, Error, edit_status};
use crate::value::{Value, value_text, value_text_with};
use crate::{Format, SerializeOptions, ffi};
#[derive(Clone, Copy, Debug)]
pub enum Segment<'a> {
Key(&'a str),
Index(usize),
}
impl<'a> From<&'a str> for Segment<'a> {
fn from(key: &'a str) -> Self {
Segment::Key(key)
}
}
impl From<usize> for Segment<'_> {
fn from(index: usize) -> Self {
Segment::Index(index)
}
}
pub(crate) fn to_ffi_path(path: &[Segment]) -> Vec<ffi::FigPathSegment> {
path.iter()
.map(|seg| match seg {
Segment::Key(k) => ffi::FigPathSegment {
kind: 0,
key_ptr: k.as_ptr(),
key_len: k.len(),
index: 0,
},
Segment::Index(i) => ffi::FigPathSegment {
kind: 1,
key_ptr: std::ptr::null(),
key_len: 0,
index: *i,
},
})
.collect()
}
pub(crate) fn to_ffi_keys<S: AsRef<str>>(keys: &[S]) -> Vec<ffi::FigStr> {
keys.iter()
.map(|k| {
let s = k.as_ref();
ffi::FigStr {
ptr: s.as_ptr(),
len: s.len(),
}
})
.collect()
}
#[derive(Debug)]
pub struct Editor {
raw: NonNull<ffi::FigEditor>,
format: Format,
}
unsafe impl Send for Editor {}
impl Editor {
pub fn open(input: &[u8], format: Format) -> Result<Self, Error> {
let mut raw = std::ptr::null_mut();
let status =
unsafe { ffi::fig_editor_create(input.as_ptr(), input.len(), format.to_c(), &mut raw) };
if status == ffi::FigStatus::PARSE_ERROR {
return Err(match crate::Document::parse(input, format) {
Err(e @ Error::Parse(_)) => e,
_ => Error::Parse(crate::error::ParseError::generic()),
});
}
Error::from_status(status)?;
let raw = NonNull::new(raw).ok_or(Error::Internal)?;
Ok(Self { raw, format })
}
fn ptr(&self) -> *mut ffi::FigEditor {
self.raw.as_ptr()
}
pub fn replace_value(
&mut self,
path: &[Segment],
value: impl Into<Value>,
) -> Result<(), Error> {
let value = value.into();
let repl = value_text(&value, self.format)?;
self.replace_rendered(path, &repl, &value)
}
pub fn rename_key(&mut self, path: &[Segment], key: &str) -> Result<(), Error> {
let p = to_ffi_path(path);
let status = unsafe {
ffi::fig_editor_replace_named_key(
self.ptr(),
p.as_ptr(),
p.len(),
key.as_ptr(),
key.len(),
)
};
edit_status(status, self.format, EditTarget::Key)
}
pub fn insert_value(
&mut self,
path: &[Segment],
key: &str,
value: impl Into<Value>,
) -> Result<(), Error> {
let val = value_text(&value.into(), self.format)?;
let p = to_ffi_path(path);
let status = unsafe {
ffi::fig_editor_insert_named_key(
self.ptr(),
p.as_ptr(),
p.len(),
key.as_ptr(),
key.len(),
val.as_ptr(),
val.len(),
)
};
edit_status(status, self.format, EditTarget::Value)
}
pub fn set_value(&mut self, path: &[Segment], value: impl Into<Value>) -> Result<(), Error> {
let value = value.into();
let val = value_text(&value, self.format)?;
self.set_rendered(path, &val, &value)
}
pub fn replace_value_with(
&mut self,
path: &[Segment],
value: impl Into<Value>,
options: SerializeOptions,
) -> Result<(), Error> {
let value = value.into();
let repl = value_text_with(&value, self.format, options)?;
self.replace_rendered(path, &repl, &value)
}
pub fn insert_value_with(
&mut self,
path: &[Segment],
key: &str,
value: impl Into<Value>,
options: SerializeOptions,
) -> Result<(), Error> {
let val = value_text_with(&value.into(), self.format, options)?;
let p = to_ffi_path(path);
let status = unsafe {
ffi::fig_editor_insert_named_key(
self.ptr(),
p.as_ptr(),
p.len(),
key.as_ptr(),
key.len(),
val.as_ptr(),
val.len(),
)
};
edit_status(status, self.format, EditTarget::Value)
}
pub fn set_value_with(
&mut self,
path: &[Segment],
value: impl Into<Value>,
options: SerializeOptions,
) -> Result<(), Error> {
let value = value.into();
let val = value_text_with(&value, self.format, options)?;
self.set_rendered(path, &val, &value)
}
fn replace_rendered(
&mut self,
path: &[Segment],
repl: &str,
value: &Value,
) -> Result<(), Error> {
let p = to_ffi_path(path);
let status = match value {
Value::Str(s) => unsafe {
ffi::fig_editor_replace_string(
self.ptr(),
p.as_ptr(),
p.len(),
repl.as_ptr(),
repl.len(),
s.as_ptr(),
s.len(),
)
},
_ => unsafe {
ffi::fig_editor_replace_val(
self.ptr(),
p.as_ptr(),
p.len(),
repl.as_ptr(),
repl.len(),
)
},
};
edit_status(status, self.format, EditTarget::Value)
}
fn set_rendered(&mut self, path: &[Segment], val: &str, value: &Value) -> Result<(), Error> {
let p = to_ffi_path(path);
let status = match value {
Value::Str(s) => unsafe {
ffi::fig_editor_set_string(
self.ptr(),
p.as_ptr(),
p.len(),
val.as_ptr(),
val.len(),
s.as_ptr(),
s.len(),
)
},
_ => unsafe {
ffi::fig_editor_set(self.ptr(), p.as_ptr(), p.len(), val.as_ptr(), val.len())
},
};
edit_status(status, self.format, EditTarget::Value)
}
pub fn append_value(&mut self, path: &[Segment], value: impl Into<Value>) -> Result<(), Error> {
let val = value_text(&value.into(), self.format)?;
self.append_text(path, &val)
}
pub fn append_value_with(
&mut self,
path: &[Segment],
value: impl Into<Value>,
options: SerializeOptions,
) -> Result<(), Error> {
let val = value_text_with(&value.into(), self.format, options)?;
self.append_text(path, &val)
}
fn append_text(&mut self, path: &[Segment], val: &str) -> Result<(), Error> {
let p = to_ffi_path(path);
let status = unsafe {
ffi::fig_editor_append_seq(self.ptr(), p.as_ptr(), p.len(), val.as_ptr(), val.len())
};
edit_status(status, self.format, EditTarget::Value)
}
pub fn prepend_value(
&mut self,
path: &[Segment],
value: impl Into<Value>,
) -> Result<(), Error> {
let val = value_text(&value.into(), self.format)?;
self.prepend_text(path, &val)
}
pub fn prepend_value_with(
&mut self,
path: &[Segment],
value: impl Into<Value>,
options: SerializeOptions,
) -> Result<(), Error> {
let val = value_text_with(&value.into(), self.format, options)?;
self.prepend_text(path, &val)
}
fn prepend_text(&mut self, path: &[Segment], val: &str) -> Result<(), Error> {
let p = to_ffi_path(path);
let status = unsafe {
ffi::fig_editor_prepend_seq(self.ptr(), p.as_ptr(), p.len(), val.as_ptr(), val.len())
};
edit_status(status, self.format, EditTarget::Value)
}
pub fn insert_item(
&mut self,
path: &[Segment],
index: usize,
value: impl Into<Value>,
) -> Result<(), Error> {
let val = value_text(&value.into(), self.format)?;
self.insert_item_text(path, index, &val)
}
pub fn insert_item_with(
&mut self,
path: &[Segment],
index: usize,
value: impl Into<Value>,
options: SerializeOptions,
) -> Result<(), Error> {
let val = value_text_with(&value.into(), self.format, options)?;
self.insert_item_text(path, index, &val)
}
fn insert_item_text(&mut self, path: &[Segment], index: usize, val: &str) -> Result<(), Error> {
let p = to_ffi_path(path);
let status = unsafe {
ffi::fig_editor_insert_seq_item(
self.ptr(),
p.as_ptr(),
p.len(),
index,
val.as_ptr(),
val.len(),
)
};
edit_status(status, self.format, EditTarget::Value)
}
pub fn add_leading_comment(&mut self, path: &[Segment], text: &str) -> Result<(), Error> {
let p = to_ffi_path(path);
let status = unsafe {
ffi::fig_editor_add_leading_comment(
self.ptr(),
p.as_ptr(),
p.len(),
text.as_ptr(),
text.len(),
)
};
edit_status(status, self.format, EditTarget::Comment)
}
pub fn set_trailing_comment(&mut self, path: &[Segment], text: &str) -> Result<(), Error> {
let p = to_ffi_path(path);
let status = unsafe {
ffi::fig_editor_set_trailing_comment(
self.ptr(),
p.as_ptr(),
p.len(),
text.as_ptr(),
text.len(),
)
};
edit_status(status, self.format, EditTarget::Comment)
}
pub fn delete_leading_comment(&mut self, path: &[Segment]) -> Result<(), Error> {
let p = to_ffi_path(path);
let status =
unsafe { ffi::fig_editor_delete_leading_comments(self.ptr(), p.as_ptr(), p.len()) };
edit_status(status, self.format, EditTarget::Document)
}
pub fn delete_trailing_comment(&mut self, path: &[Segment]) -> Result<(), Error> {
let p = to_ffi_path(path);
let status =
unsafe { ffi::fig_editor_delete_trailing_comment(self.ptr(), p.as_ptr(), p.len()) };
edit_status(status, self.format, EditTarget::Document)
}
pub fn leading_comment(&self, path: &[Segment]) -> Result<Option<String>, Error> {
self.read_comment(path, false)
}
pub fn trailing_comment(&self, path: &[Segment]) -> Result<Option<String>, Error> {
self.read_comment(path, true)
}
fn read_comment(&self, path: &[Segment], trailing: bool) -> Result<Option<String>, Error> {
let p = to_ffi_path(path);
let mut ptr: *const u8 = std::ptr::null();
let mut len: usize = 0;
let status = unsafe {
if trailing {
ffi::fig_editor_get_trailing_comment(
self.ptr(),
p.as_ptr(),
p.len(),
&mut ptr,
&mut len,
)
} else {
ffi::fig_editor_get_leading_comment(
self.ptr(),
p.as_ptr(),
p.len(),
&mut ptr,
&mut len,
)
}
};
if status == ffi::FigStatus::NOT_FOUND {
return Ok(None);
}
Error::from_status(status)?;
Ok(Some(borrow_str(ptr, len)?.to_string()))
}
pub fn add_dangling_comment(&mut self, path: &[Segment], text: &str) -> Result<(), Error> {
let p = to_ffi_path(path);
let status = unsafe {
ffi::fig_editor_add_dangling_comment(
self.ptr(),
p.as_ptr(),
p.len(),
text.as_ptr(),
text.len(),
)
};
edit_status(status, self.format, EditTarget::Comment)
}
pub fn delete_dangling_comment(&mut self, path: &[Segment]) -> Result<(), Error> {
let p = to_ffi_path(path);
let status =
unsafe { ffi::fig_editor_delete_dangling_comments(self.ptr(), p.as_ptr(), p.len()) };
edit_status(status, self.format, EditTarget::Document)
}
pub fn dangling_comment(&self, path: &[Segment]) -> Result<Option<String>, Error> {
let p = to_ffi_path(path);
let mut ptr: *const u8 = std::ptr::null();
let mut len: usize = 0;
let status = unsafe {
ffi::fig_editor_get_dangling_comment(
self.ptr(),
p.as_ptr(),
p.len(),
&mut ptr,
&mut len,
)
};
if status == ffi::FigStatus::NOT_FOUND {
return Ok(None);
}
Error::from_status(status)?;
Ok(Some(borrow_str(ptr, len)?.to_string()))
}
pub fn comment_out(&mut self, path: &[Segment]) -> Result<(), Error> {
let p = to_ffi_path(path);
let status = unsafe { ffi::fig_editor_comment_out(self.ptr(), p.as_ptr(), p.len()) };
edit_status(status, self.format, EditTarget::Document)
}
pub fn uncomment_leading(
&mut self,
path: &[Segment],
first_line: usize,
line_count: usize,
) -> Result<(), Error> {
let p = to_ffi_path(path);
let status = unsafe {
ffi::fig_editor_uncomment_leading(
self.ptr(),
p.as_ptr(),
p.len(),
first_line,
line_count,
)
};
edit_status(status, self.format, EditTarget::Document)
}
pub fn uncomment_dangling(
&mut self,
path: &[Segment],
first_line: usize,
line_count: usize,
) -> Result<(), Error> {
let p = to_ffi_path(path);
let status = unsafe {
ffi::fig_editor_uncomment_dangling(
self.ptr(),
p.as_ptr(),
p.len(),
first_line,
line_count,
)
};
edit_status(status, self.format, EditTarget::Document)
}
pub fn delete_key(&mut self, path: &[Segment]) -> Result<(), Error> {
let p = to_ffi_path(path);
let status = unsafe { ffi::fig_editor_delete_key(self.ptr(), p.as_ptr(), p.len()) };
edit_status(status, self.format, EditTarget::Document)
}
pub fn delete_item(&mut self, path: &[Segment], index: usize) -> Result<(), Error> {
let p = to_ffi_path(path);
let status =
unsafe { ffi::fig_editor_remove_seq_item(self.ptr(), p.as_ptr(), p.len(), index) };
edit_status(status, self.format, EditTarget::Document)
}
pub fn move_key(&mut self, src_path: &[Segment], dest_path: &[Segment]) -> Result<(), Error> {
let s = to_ffi_path(src_path);
let d = to_ffi_path(dest_path);
let status = unsafe {
ffi::fig_editor_move_key(self.ptr(), s.as_ptr(), s.len(), d.as_ptr(), d.len())
};
edit_status(status, self.format, EditTarget::Document)
}
pub fn reorder_keys<S: AsRef<str>>(
&mut self,
path: &[Segment],
keys: &[S],
) -> Result<(), Error> {
let p = to_ffi_path(path);
let k = to_ffi_keys(keys);
let status = unsafe {
ffi::fig_editor_reorder_keys(self.ptr(), p.as_ptr(), p.len(), k.as_ptr(), k.len())
};
edit_status(status, self.format, EditTarget::Document)
}
pub fn move_item(&mut self, path: &[Segment], from: usize, to: usize) -> Result<(), Error> {
let p = to_ffi_path(path);
let status =
unsafe { ffi::fig_editor_move_item(self.ptr(), p.as_ptr(), p.len(), from, to) };
edit_status(status, self.format, EditTarget::Document)
}
pub fn reorder_items(&mut self, path: &[Segment], indices: &[usize]) -> Result<(), Error> {
let p = to_ffi_path(path);
let status = unsafe {
ffi::fig_editor_reorder_items(
self.ptr(),
p.as_ptr(),
p.len(),
indices.as_ptr(),
indices.len(),
)
};
edit_status(status, self.format, EditTarget::Document)
}
pub fn set_sequence<I>(&mut self, path: &[Segment], items: I) -> Result<(), Error>
where
I: IntoIterator,
I::Item: Into<Value>,
{
let texts: Vec<String> = items
.into_iter()
.map(|v| value_text(&v.into(), self.format))
.collect::<Result<_, _>>()?;
let strs = to_ffi_keys(&texts);
let p = to_ffi_path(path);
let status = unsafe {
ffi::fig_editor_set_sequence(self.ptr(), p.as_ptr(), p.len(), strs.as_ptr(), strs.len())
};
edit_status(status, self.format, EditTarget::Value)
}
pub fn delete_container(&mut self, path: &[Segment]) -> Result<(), Error> {
let p = to_ffi_path(path);
let status = unsafe { ffi::fig_editor_delete_container(self.ptr(), p.as_ptr(), p.len()) };
edit_status(status, self.format, EditTarget::Document)
}
pub fn insert_container(&mut self, path: &[Segment], body: &str) -> Result<(), Error> {
let p = to_ffi_path(path);
let status = unsafe {
ffi::fig_editor_insert_container(
self.ptr(),
p.as_ptr(),
p.len(),
body.as_ptr(),
body.len(),
)
};
edit_status(status, self.format, EditTarget::Value)
}
pub fn rename_container(&mut self, path: &[Segment], new_leaf: &str) -> Result<(), Error> {
let p = to_ffi_path(path);
let status = unsafe {
ffi::fig_editor_rename_container(
self.ptr(),
p.as_ptr(),
p.len(),
new_leaf.as_ptr(),
new_leaf.len(),
)
};
edit_status(status, self.format, EditTarget::Key)
}
pub fn move_container(
&mut self,
src_path: &[Segment],
dest_path: Option<&[Segment]>,
) -> Result<(), Error> {
let s = to_ffi_path(src_path);
let d = dest_path.map(to_ffi_path);
let (d_ptr, d_len) = match &d {
Some(v) => (v.as_ptr(), v.len()),
None => (std::ptr::null(), 0),
};
let status = unsafe {
ffi::fig_editor_move_container(self.ptr(), s.as_ptr(), s.len(), d_ptr, d_len)
};
edit_status(status, self.format, EditTarget::Document)
}
pub fn reorder_containers<S: AsRef<str>>(&mut self, order: &[S]) -> Result<(), Error> {
let o = to_ffi_keys(order);
let status = unsafe { ffi::fig_editor_reorder_containers(self.ptr(), o.as_ptr(), o.len()) };
edit_status(status, self.format, EditTarget::Document)
}
pub fn append_container_to_seq(&mut self, path: &[Segment], body: &str) -> Result<(), Error> {
let p = to_ffi_path(path);
let status = unsafe {
ffi::fig_editor_append_container_to_seq(
self.ptr(),
p.as_ptr(),
p.len(),
body.as_ptr(),
body.len(),
)
};
edit_status(status, self.format, EditTarget::Value)
}
pub fn source(&self) -> Result<&str, Error> {
let mut ptr: *const u8 = std::ptr::null();
let mut len: usize = 0;
let status = unsafe { ffi::fig_editor_source(self.raw.as_ptr(), &mut ptr, &mut len) };
Error::from_status(status)?;
borrow_str(ptr, len)
}
}
impl Drop for Editor {
fn drop(&mut self) {
unsafe { ffi::fig_editor_destroy(self.raw.as_ptr()) };
}
}
pub(crate) fn borrow_str<'a>(ptr: *const u8, len: usize) -> Result<&'a str, Error> {
if len == 0 {
return Ok("");
}
let bytes = unsafe { std::slice::from_raw_parts(ptr, len) };
std::str::from_utf8(bytes).map_err(|_| Error::Utf8)
}