set metadata to json when opening json files

This commit is contained in:
Jack Wright 2024-06-28 13:16:26 -07:00
parent 60e44ffbb0
commit c74b52ffbe
2 changed files with 27 additions and 5 deletions

View File

@ -4,7 +4,7 @@ use std::{
};
use nu_engine::command_prelude::*;
use nu_protocol::ListStream;
use nu_protocol::{ListStream, PipelineMetadata};
#[derive(Clone)]
pub struct FromJson;
@ -81,7 +81,7 @@ impl Command for FromJson {
PipelineData::Value(Value::String { val, .. }, metadata) => {
Ok(PipelineData::ListStream(
read_json_lines(Cursor::new(val), span, strict, engine_state.ctrlc.clone()),
metadata,
update_metadata(metadata),
))
}
PipelineData::ByteStream(stream, metadata)
@ -90,7 +90,7 @@ impl Command for FromJson {
if let Some(reader) = stream.reader() {
Ok(PipelineData::ListStream(
read_json_lines(reader, span, strict, None),
metadata,
update_metadata(metadata),
))
} else {
Ok(PipelineData::Empty)
@ -113,10 +113,10 @@ impl Command for FromJson {
if strict {
Ok(convert_string_to_value_strict(&string_input, span)?
.into_pipeline_data_with_metadata(metadata))
.into_pipeline_data_with_metadata(update_metadata(metadata)))
} else {
Ok(convert_string_to_value(&string_input, span)?
.into_pipeline_data_with_metadata(metadata))
.into_pipeline_data_with_metadata(update_metadata(metadata)))
}
}
}
@ -263,6 +263,12 @@ fn convert_string_to_value_strict(string_input: &str, span: Span) -> Result<Valu
}
}
fn update_metadata(metadata: Option<PipelineMetadata>) -> Option<PipelineMetadata> {
metadata
.map(|md| md.with_content_type(Some("application/json".into())))
.or_else(|| Some(PipelineMetadata::default().with_content_type(Some("application/json".into()))))
}
#[cfg(test)]
mod test {
use super::*;

View File

@ -7,6 +7,22 @@ pub struct PipelineMetadata {
pub content_type: Option<String>,
}
impl PipelineMetadata {
pub fn with_data_source(self, data_source: DataSource) -> Self {
Self {
data_source,
..self
}
}
pub fn with_content_type(self, content_type: Option<String>) -> Self {
Self {
content_type,
..self
}
}
}
/// Describes where the particular [`PipelineMetadata`] originates.
///
/// This can either be a particular family of commands (useful so downstream commands can adjust