1use nu_engine::command_prelude::*;
2use nu_protocol::ast::PathMember;
3
4#[derive(Clone)]
5pub struct ToYaml;
6
7impl Command for ToYaml {
8 fn name(&self) -> &str {
9 "to yaml"
10 }
11
12 fn signature(&self) -> Signature {
13 Signature::build("to yaml")
14 .input_output_types(vec![(Type::Any, Type::String)])
15 .switch(
16 "serialize",
17 "serialize nushell types that cannot be deserialized",
18 Some('s'),
19 )
20 .category(Category::Formats)
21 }
22
23 fn description(&self) -> &str {
24 "Convert table into .yaml/.yml text."
25 }
26
27 fn examples(&self) -> Vec<Example<'_>> {
28 vec![Example {
29 description: "Outputs a YAML string representing the contents of this table",
30 example: r#"[[foo bar]; ["1" "2"]] | to yaml"#,
31 result: Some(Value::test_string("- foo: '1'\n bar: '2'\n")),
32 }]
33 }
34
35 fn run(
36 &self,
37 engine_state: &EngineState,
38 stack: &mut Stack,
39 call: &Call,
40 input: PipelineData,
41 ) -> Result<PipelineData, ShellError> {
42 let head = call.head;
43 let serialize_types = call.has_flag(engine_state, stack, "serialize")?;
44 let input = input.try_expand_range()?;
45
46 to_yaml(engine_state, input, head, serialize_types)
47 }
48}
49
50#[derive(Clone)]
51pub struct ToYml;
52
53impl Command for ToYml {
54 fn name(&self) -> &str {
55 "to yml"
56 }
57
58 fn signature(&self) -> Signature {
59 Signature::build("to yml")
60 .input_output_types(vec![(Type::Any, Type::String)])
61 .switch(
62 "serialize",
63 "serialize nushell types that cannot be deserialized",
64 Some('s'),
65 )
66 .category(Category::Formats)
67 }
68
69 fn description(&self) -> &str {
70 "Convert table into .yaml/.yml text."
71 }
72
73 fn examples(&self) -> Vec<Example<'_>> {
74 vec![Example {
75 description: "Outputs a YAML string representing the contents of this table",
76 example: r#"[[foo bar]; ["1" "2"]] | to yml"#,
77 result: Some(Value::test_string("- foo: '1'\n bar: '2'\n")),
78 }]
79 }
80
81 fn run(
82 &self,
83 engine_state: &EngineState,
84 stack: &mut Stack,
85 call: &Call,
86 input: PipelineData,
87 ) -> Result<PipelineData, ShellError> {
88 let head = call.head;
89 let serialize_types = call.has_flag(engine_state, stack, "serialize")?;
90 let input = input.try_expand_range()?;
91
92 to_yaml(engine_state, input, head, serialize_types)
93 }
94}
95
96pub fn value_to_yaml_value(
97 engine_state: &EngineState,
98 v: &Value,
99 serialize_types: bool,
100) -> Result<serde_yaml::Value, ShellError> {
101 Ok(match &v {
102 Value::Bool { val, .. } => serde_yaml::Value::Bool(*val),
103 Value::Int { val, .. } => serde_yaml::Value::Number(serde_yaml::Number::from(*val)),
104 Value::Filesize { val, .. } => {
105 serde_yaml::Value::Number(serde_yaml::Number::from(val.get()))
106 }
107 Value::Duration { val, .. } => serde_yaml::Value::String(val.to_string()),
108 Value::Date { val, .. } => serde_yaml::Value::String(val.to_string()),
109 Value::Range { .. } => serde_yaml::Value::Null,
110 Value::Float { val, .. } => serde_yaml::Value::Number(serde_yaml::Number::from(*val)),
111 Value::String { val, .. } | Value::Glob { val, .. } => {
112 serde_yaml::Value::String(val.clone())
113 }
114 Value::Record { val, .. } => {
115 let mut m = serde_yaml::Mapping::new();
116 for (k, v) in &**val {
117 m.insert(
118 serde_yaml::Value::String(k.clone()),
119 value_to_yaml_value(engine_state, v, serialize_types)?,
120 );
121 }
122 serde_yaml::Value::Mapping(m)
123 }
124 Value::List { vals, .. } => {
125 let mut out = vec![];
126
127 for value in vals {
128 out.push(value_to_yaml_value(engine_state, value, serialize_types)?);
129 }
130
131 serde_yaml::Value::Sequence(out)
132 }
133 Value::Closure { val, .. } => {
134 if serialize_types {
135 let block = engine_state.get_block(val.block_id);
136 if let Some(span) = block.span {
137 let contents_bytes = engine_state.get_span_contents(span);
138 let contents_string = String::from_utf8_lossy(contents_bytes);
139 serde_yaml::Value::String(contents_string.to_string())
140 } else {
141 serde_yaml::Value::String(format!(
142 "unable to retrieve block contents for yaml block_id {}",
143 val.block_id.get()
144 ))
145 }
146 } else {
147 serde_yaml::Value::Null
148 }
149 }
150 Value::Nothing { .. } => serde_yaml::Value::Null,
151 Value::Error { error, .. } => return Err(*error.clone()),
152 Value::Binary { val, .. } => serde_yaml::Value::Sequence(
153 val.iter()
154 .map(|x| serde_yaml::Value::Number(serde_yaml::Number::from(*x)))
155 .collect(),
156 ),
157 Value::CellPath { val, .. } => serde_yaml::Value::Sequence(
158 val.members
159 .iter()
160 .map(|x| match &x {
161 PathMember::String { val, .. } => Ok(serde_yaml::Value::String(val.clone())),
162 PathMember::Int { val, .. } => {
163 Ok(serde_yaml::Value::Number(serde_yaml::Number::from(*val)))
164 }
165 })
166 .collect::<Result<Vec<serde_yaml::Value>, ShellError>>()?,
167 ),
168 Value::Custom { .. } => serde_yaml::Value::Null,
169 })
170}
171
172fn to_yaml(
173 engine_state: &EngineState,
174 input: PipelineData,
175 head: Span,
176 serialize_types: bool,
177) -> Result<PipelineData, ShellError> {
178 let metadata = input
179 .metadata()
180 .unwrap_or_default()
181 .with_content_type(Some("application/yaml".into()));
183 let value = input.into_value(head)?;
184
185 let yaml_value = value_to_yaml_value(engine_state, &value, serialize_types)?;
186 match serde_yaml::to_string(&yaml_value) {
187 Ok(serde_yaml_string) => {
188 Ok(Value::string(serde_yaml_string, head)
189 .into_pipeline_data_with_metadata(Some(metadata)))
190 }
191 _ => Ok(Value::error(
192 ShellError::CantConvert {
193 to_type: "YAML".into(),
194 from_type: value.get_type().to_string(),
195 span: head,
196 help: None,
197 },
198 head,
199 )
200 .into_pipeline_data_with_metadata(Some(metadata))),
201 }
202}
203
204#[cfg(test)]
205mod test {
206 use super::*;
207 use crate::{Get, Metadata};
208 use nu_cmd_lang::eval_pipeline_without_terminal_expression;
209
210 #[test]
211 fn test_examples() {
212 use crate::test_examples;
213
214 test_examples(ToYaml {})
215 }
216
217 #[test]
218 fn test_content_type_metadata() {
219 let mut engine_state = Box::new(EngineState::new());
220 let delta = {
221 let mut working_set = StateWorkingSet::new(&engine_state);
224
225 working_set.add_decl(Box::new(ToYaml {}));
226 working_set.add_decl(Box::new(Metadata {}));
227 working_set.add_decl(Box::new(Get {}));
228
229 working_set.render()
230 };
231
232 engine_state
233 .merge_delta(delta)
234 .expect("Error merging delta");
235
236 let cmd = "{a: 1 b: 2} | to yaml | metadata | get content_type | $in";
237 let result = eval_pipeline_without_terminal_expression(
238 cmd,
239 std::env::temp_dir().as_ref(),
240 &mut engine_state,
241 );
242 assert_eq!(
243 Value::test_string("application/yaml"),
244 result.expect("There should be a result")
245 );
246 }
247}