From ec0bd20f296f8973425ec66a3e590ce0e6ba41cd Mon Sep 17 00:00:00 2001 From: Sam Hedin Date: Fri, 27 Mar 2020 22:14:28 +0100 Subject: [PATCH] Add ability to extract headers from first row --- crates/nu-cli/src/commands/headers.rs | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/crates/nu-cli/src/commands/headers.rs b/crates/nu-cli/src/commands/headers.rs index c7c9ab0db..3ae4b52f4 100644 --- a/crates/nu-cli/src/commands/headers.rs +++ b/crates/nu-cli/src/commands/headers.rs @@ -1,9 +1,12 @@ use crate::commands::WholeStreamCommand; +use indexmap::IndexMap; use crate::context::CommandRegistry; use crate::prelude::*; use futures::stream::StreamExt; use nu_errors::ShellError; use nu_protocol::{ReturnSuccess, Signature, UntaggedValue, Value}; +use std::fs::File; +use std::io::Write; pub struct Headers; #[derive(Deserialize)] @@ -27,13 +30,37 @@ impl WholeStreamCommand for Headers { args.process(registry, count)?.run() } } + +//Rows is an array of dictionaries. Each dictionary maps header to content for that row. +//Take the first row and extract all content and save them as headers. +//Take the rest of the rows and replace the old column names with the new headers. + pub fn count( HeadersArgs {}: HeadersArgs, RunnableContext { input, name, .. }: RunnableContext, ) -> Result { + + let stream = async_stream! { let rows: Vec = input.values.collect().await; + let mut entries = IndexMap::new(); + let headers: Value = rows[0].clone(); + match &headers.value { + UntaggedValue::Row(d) => { + entries = d.entries.clone(); + () + } + _ => () + } + let mut heads = vec![]; + for (k, v) in entries.iter() { + heads.push(v.as_string().unwrap()); + } + + let mut file = File::create("headout").unwrap(); + write!(file, "args: {:#?}", heads); + yield ReturnSuccess::value(UntaggedValue::int(rows.len()).into_value(name)) };