1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
use crate::prelude::*; use indexmap::set::IndexSet; use log::trace; use nu_engine::WholeStreamCommand; use nu_errors::ShellError; use nu_protocol::{ did_you_mean, ColumnPath, Dictionary, PathMember, Primitive, ReturnSuccess, Signature, SyntaxShape, UnspannedPathMember, UntaggedValue, Value, }; use nu_source::HasFallibleSpan; use nu_value_ext::get_data_by_column_path; pub struct Command; impl WholeStreamCommand for Command { fn name(&self) -> &str { "get" } fn signature(&self) -> Signature { Signature::build("get").rest( SyntaxShape::ColumnPath, "optionally return additional data by path", ) } fn usage(&self) -> &str { "Open given cells as text." } fn run_with_actions(&self, args: CommandArgs) -> Result<ActionStream, ShellError> { get(args) } fn examples(&self) -> Vec<Example> { vec![ Example { description: "Extract the name of files as a list", example: "ls | get name", result: None, }, Example { description: "Extract the cpu list from the sys information", example: "sys | get cpu", result: None, }, ] } } pub fn get(args: CommandArgs) -> Result<ActionStream, ShellError> { let column_paths: Vec<ColumnPath> = args.rest(0)?; let mut input = args.input; if column_paths.is_empty() { let vec = input.drain_vec(); let descs = nu_protocol::merge_descriptors(&vec); Ok(descs .into_iter() .map(ReturnSuccess::value) .into_action_stream()) } else { trace!("get {:?}", column_paths); let output_stream = input .map(move |item| { column_paths .iter() .map(move |path| get_output(&item, path)) .flatten() .collect::<Vec<_>>() }) .flatten() .into_action_stream(); Ok(output_stream) } } fn get_output(item: &Value, path: &ColumnPath) -> Vec<Result<ReturnSuccess, ShellError>> { match get_column_path(path, item) { Ok(Value { value: UntaggedValue::Primitive(Primitive::Nothing), .. }) => vec![], Ok(Value { value: UntaggedValue::Table(rows), .. }) => rows.into_iter().map(ReturnSuccess::value).collect(), Ok(other) => vec![ReturnSuccess::value(other)], Err(reason) => vec![ReturnSuccess::value( UntaggedValue::Error(reason).into_untagged_value(), )], } } pub fn get_column_path(path: &ColumnPath, obj: &Value) -> Result<Value, ShellError> { get_data_by_column_path(obj, path, move |obj_source, column_path_tried, error| { let path_members_span = path.maybe_span().unwrap_or_else(Span::unknown); match &obj_source.value { UntaggedValue::Table(rows) => { return get_column_path_from_table_error( rows, column_path_tried, &path_members_span, ); } UntaggedValue::Row(columns) => { if let Some(error) = get_column_from_row_error( columns, column_path_tried, &path_members_span, obj_source, ) { return error; } } _ => {} } if let Some(suggestions) = did_you_mean(obj_source, column_path_tried.as_string()) { ShellError::labeled_error( "Unknown column", format!("did you mean '{}'?", suggestions[0]), column_path_tried.span.since(path_members_span), ) } else { error } }) } pub fn get_column_path_from_table_error( rows: &[Value], column_path_tried: &PathMember, path_members_span: &Span, ) -> ShellError { match column_path_tried { PathMember { unspanned: UnspannedPathMember::String(column), .. } => { let primary_label = format!("There isn't a column named '{}'", &column); let suggestions: IndexSet<_> = rows .iter() .filter_map(|r| did_you_mean(r, column_path_tried.as_string())) .map(|s| s[0].to_owned()) .collect(); let mut existing_columns: IndexSet<_> = IndexSet::default(); let mut names: Vec<String> = vec![]; for row in rows { for field in row.data_descriptors() { if !existing_columns.contains(&field[..]) { existing_columns.insert(field.clone()); names.push(field); } } } if names.is_empty() { ShellError::labeled_error_with_secondary( "Unknown column", primary_label, column_path_tried.span, "Appears to contain rows. Try indexing instead.", column_path_tried.span.since(path_members_span), ) } else { ShellError::labeled_error_with_secondary( "Unknown column", primary_label, column_path_tried.span, format!( "Perhaps you meant '{}'? Columns available: {}", suggestions .iter() .map(|x| x.to_owned()) .collect::<Vec<String>>() .join(","), names.join(", ") ), column_path_tried.span.since(path_members_span), ) } } PathMember { unspanned: UnspannedPathMember::Int(idx), .. } => { let total = rows.len(); let secondary_label = if total == 1 { "The table only has 1 row".to_owned() } else { format!("The table only has {} rows (0 to {})", total, total - 1) }; ShellError::labeled_error_with_secondary( "Row not found", format!("There isn't a row indexed at {}", idx), column_path_tried.span, secondary_label, column_path_tried.span.since(path_members_span), ) } } } pub fn get_column_from_row_error( columns: &Dictionary, column_path_tried: &PathMember, path_members_span: &Span, obj_source: &Value, ) -> Option<ShellError> { match column_path_tried { PathMember { unspanned: UnspannedPathMember::String(column), .. } => { let primary_label = format!("There isn't a column named '{}'", &column); did_you_mean(obj_source, column_path_tried.as_string()).map(|suggestions| { ShellError::labeled_error_with_secondary( "Unknown column", primary_label, column_path_tried.span, format!( "Perhaps you meant '{}'? Columns available: {}", suggestions[0], &obj_source.data_descriptors().join(", ") ), column_path_tried.span.since(path_members_span), ) }) } PathMember { unspanned: UnspannedPathMember::Int(idx), .. } => Some(ShellError::labeled_error_with_secondary( "No rows available", format!("A row at '{}' can't be indexed.", &idx), column_path_tried.span, format!( "Appears to contain columns. Columns available: {}", columns.keys().join(", ") ), column_path_tried.span.since(path_members_span), )), } }