1use std::collections::BTreeMap;
7
8use regex::Regex;
9
10use crate::ast::{Arg, Command};
11use crate::query::{FieldSel, QueryOp};
12
13#[derive(Debug, Clone, PartialEq, Eq)]
14pub enum WidgetKind {
15 Text,
16 Tail,
17 List,
18 Gauge,
19 Bars,
20 Histo,
21 Spark,
22 Chart,
23 Table,
24 Tabs,
25 Block,
26 Frame,
27}
28
29impl WidgetKind {
30 fn from(verb: &str) -> Option<WidgetKind> {
31 Some(match verb {
32 "text" => WidgetKind::Text,
33 "tail" => WidgetKind::Tail,
34 "list" => WidgetKind::List,
35 "gauge" => WidgetKind::Gauge,
36 "bars" => WidgetKind::Bars,
37 "histo" => WidgetKind::Histo,
38 "spark" => WidgetKind::Spark,
39 "chart" => WidgetKind::Chart,
40 "table" => WidgetKind::Table,
41 "tabs" => WidgetKind::Tabs,
42 "block" => WidgetKind::Block,
43 "frame" => WidgetKind::Frame,
44 _ => return None,
45 })
46 }
47
48 pub fn label(&self) -> &'static str {
49 match self {
50 WidgetKind::Text => "text",
51 WidgetKind::Tail => "tail",
52 WidgetKind::List => "list",
53 WidgetKind::Gauge => "gauge",
54 WidgetKind::Bars => "bars",
55 WidgetKind::Histo => "histo",
56 WidgetKind::Spark => "spark",
57 WidgetKind::Chart => "chart",
58 WidgetKind::Table => "table",
59 WidgetKind::Tabs => "tabs",
60 WidgetKind::Block => "block",
61 WidgetKind::Frame => "frame",
62 }
63 }
64}
65
66#[derive(Debug, Clone)]
68pub struct Source {
69 pub pipeline: Vec<QueryOp>,
70}
71
72#[derive(Debug, Clone)]
73pub struct Widget {
74 pub path: String,
75 pub kind: WidgetKind,
76 pub opts: BTreeMap<String, String>,
77 pub source: Option<Source>,
78 pub grid: Option<(usize, usize)>,
80}
81
82#[derive(Debug, Default)]
83pub struct Spec {
84 pub widgets: Vec<Widget>,
85 pub out: Option<Vec<QueryOp>>,
88}
89
90pub fn build(cmds: &[Command]) -> Result<Spec, String> {
92 let mut spec = Spec::default();
93 build_into(&mut spec, cmds, 0)?;
94 Ok(spec)
95}
96
97fn build_into(spec: &mut Spec, cmds: &[Command], depth: usize) -> Result<(), String> {
100 if depth > 16 {
101 return Err("import: module nesting too deep (cycle?)".into());
102 }
103 for c in cmds {
104 if c.name == "import" {
105 let name = c
106 .args
107 .first()
108 .and_then(Arg::as_str)
109 .ok_or("import: missing module name")?;
110 let src = resolve_module(name)?;
111 let sub = crate::parser::parse(&src)?;
112 build_into(spec, &sub, depth + 1)?;
113 } else if let Some(kind) = WidgetKind::from(&c.name) {
114 let path = c
115 .args
116 .first()
117 .and_then(Arg::as_str)
118 .ok_or_else(|| format!("{}: missing widget path", c.name))?;
119 if !path.starts_with('.') {
120 return Err(format!(
121 "{}: widget path must start with '.', got `{path}`",
122 c.name
123 ));
124 }
125 spec.widgets.push(Widget {
126 path: path.to_string(),
127 kind,
128 opts: parse_opts(&c.args[1..]),
129 source: None,
130 grid: None,
131 });
132 } else if c.name == "source" {
133 let path = c
134 .args
135 .first()
136 .and_then(Arg::as_str)
137 .ok_or("source: missing path")?;
138 let body = match c.args.get(1) {
139 Some(Arg::Block(b)) => b,
140 _ => return Err("source: expected `{ body }`".into()),
141 };
142 let pipeline = pipeline_from_body(body)?;
143 set_source(spec, path, Source { pipeline })?;
144 } else if c.name == "out" {
145 let body = match c.args.first() {
146 Some(Arg::Block(b)) => b,
147 _ => return Err("out: expected `{ body }`".into()),
148 };
149 spec.out = Some(pipeline_from_body(body)?);
150 } else if c.name == "grid" {
151 let path = c
152 .args
153 .first()
154 .and_then(Arg::as_str)
155 .ok_or("grid: missing path")?;
156 let o = parse_opts(&c.args[1..]);
157 let cell = |k| {
158 o.get(k)
159 .and_then(|s: &String| s.parse::<usize>().ok())
160 .unwrap_or(0)
161 };
162 set_grid(spec, path, (cell("row"), cell("col")))?;
163 } else if c.name.starts_with('.') {
164 if c.args.first().and_then(Arg::as_str) == Some("<-")
166 && c.args.get(1).and_then(Arg::as_str) == Some("in")
167 {
168 let path = c.name.clone();
169 set_source(spec, &path, Source { pipeline: vec![] })?;
170 }
171 }
172 }
174 Ok(())
175}
176
177fn resolve_module(name: &str) -> Result<String, String> {
180 let local = format!("{name}.arb");
181 if let Ok(s) = std::fs::read_to_string(&local) {
182 return Ok(s);
183 }
184 if let Some(home) = std::env::var_os("HOME") {
185 let p = std::path::Path::new(&home)
186 .join(".arb/lib")
187 .join(format!("{name}.arb"));
188 if let Ok(s) = std::fs::read_to_string(p) {
189 return Ok(s);
190 }
191 }
192 bundled_module(name)
193 .map(str::to_string)
194 .ok_or_else(|| format!("import: module `{name}` not found"))
195}
196
197pub const STDLIB_NAMES: &[&str] = &[
199 "nums", "logs", "http", "json", "table", "top", "docker", "k8s", "nginx", "git", "systemd",
200 "redis", "postgres", "mysql", "mongodb", "kafka", "prometheus", "elasticsearch", "rabbitmq",
201 "apache", "haproxy", "journalctl", "dmesg", "ps", "htop", "iostat", "vmstat", "ss", "dig",
202 "curl", "gh", "terraform", "aws", "gcloud", "azure", "ansible", "consul", "vault", "etcd",
203 "nomad", "envoy", "memcached", "varnish", "pgbouncer", "celery", "sidekiq", "gunicorn",
204 "supervisor", "fail2ban", "iptables", "conntrack", "sar",
205];
206
207fn bundled_module(name: &str) -> Option<&'static str> {
208 Some(match name {
209 "nums" => include_str!("../stdlib/nums.arb"),
210 "logs" => include_str!("../stdlib/logs.arb"),
211 "http" => include_str!("../stdlib/http.arb"),
212 "json" => include_str!("../stdlib/json.arb"),
213 "table" => include_str!("../stdlib/table.arb"),
214 "top" => include_str!("../stdlib/top.arb"),
215 "docker" => include_str!("../stdlib/docker.arb"),
216 "k8s" => include_str!("../stdlib/k8s.arb"),
217 "nginx" => include_str!("../stdlib/nginx.arb"),
218 "git" => include_str!("../stdlib/git.arb"),
219 "systemd" => include_str!("../stdlib/systemd.arb"),
220 "redis" => include_str!("../stdlib/redis.arb"),
221 "postgres" => include_str!("../stdlib/postgres.arb"),
222 "mysql" => include_str!("../stdlib/mysql.arb"),
223 "mongodb" => include_str!("../stdlib/mongodb.arb"),
224 "kafka" => include_str!("../stdlib/kafka.arb"),
225 "prometheus" => include_str!("../stdlib/prometheus.arb"),
226 "elasticsearch" => include_str!("../stdlib/elasticsearch.arb"),
227 "rabbitmq" => include_str!("../stdlib/rabbitmq.arb"),
228 "apache" => include_str!("../stdlib/apache.arb"),
229 "haproxy" => include_str!("../stdlib/haproxy.arb"),
230 "journalctl" => include_str!("../stdlib/journalctl.arb"),
231 "dmesg" => include_str!("../stdlib/dmesg.arb"),
232 "ps" => include_str!("../stdlib/ps.arb"),
233 "htop" => include_str!("../stdlib/htop.arb"),
234 "iostat" => include_str!("../stdlib/iostat.arb"),
235 "vmstat" => include_str!("../stdlib/vmstat.arb"),
236 "ss" => include_str!("../stdlib/ss.arb"),
237 "dig" => include_str!("../stdlib/dig.arb"),
238 "curl" => include_str!("../stdlib/curl.arb"),
239 "gh" => include_str!("../stdlib/gh.arb"),
240 "terraform" => include_str!("../stdlib/terraform.arb"),
241 "aws" => include_str!("../stdlib/aws.arb"),
242 "gcloud" => include_str!("../stdlib/gcloud.arb"),
243 "azure" => include_str!("../stdlib/azure.arb"),
244 "ansible" => include_str!("../stdlib/ansible.arb"),
245 "consul" => include_str!("../stdlib/consul.arb"),
246 "vault" => include_str!("../stdlib/vault.arb"),
247 "etcd" => include_str!("../stdlib/etcd.arb"),
248 "nomad" => include_str!("../stdlib/nomad.arb"),
249 "envoy" => include_str!("../stdlib/envoy.arb"),
250 "memcached" => include_str!("../stdlib/memcached.arb"),
251 "varnish" => include_str!("../stdlib/varnish.arb"),
252 "pgbouncer" => include_str!("../stdlib/pgbouncer.arb"),
253 "celery" => include_str!("../stdlib/celery.arb"),
254 "sidekiq" => include_str!("../stdlib/sidekiq.arb"),
255 "gunicorn" => include_str!("../stdlib/gunicorn.arb"),
256 "supervisor" => include_str!("../stdlib/supervisor.arb"),
257 "fail2ban" => include_str!("../stdlib/fail2ban.arb"),
258 "iptables" => include_str!("../stdlib/iptables.arb"),
259 "conntrack" => include_str!("../stdlib/conntrack.arb"),
260 "sar" => include_str!("../stdlib/sar.arb"),
261 _ => return None,
262 })
263}
264
265pub fn list_presets() -> Vec<(String, String)> {
268 let mut out: Vec<(String, String)> = STDLIB_NAMES
269 .iter()
270 .map(|n| {
271 (
272 n.to_string(),
273 first_comment(bundled_module(n).unwrap_or("")),
274 )
275 })
276 .collect();
277 if let Some(home) = std::env::var_os("HOME") {
278 let dir = std::path::Path::new(&home).join(".arb/lib");
279 if let Ok(entries) = std::fs::read_dir(dir) {
280 for e in entries.flatten() {
281 let path = e.path();
282 if path.extension().and_then(|s| s.to_str()) == Some("arb") {
283 if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) {
284 let src = std::fs::read_to_string(&path).unwrap_or_default();
285 out.push((stem.to_string(), first_comment(&src)));
286 }
287 }
288 }
289 }
290 }
291 out
292}
293
294fn first_comment(src: &str) -> String {
295 src.lines()
296 .find_map(|l| l.trim().strip_prefix('#'))
297 .map(|s| s.trim().to_string())
298 .unwrap_or_default()
299}
300
301fn parse_opts(args: &[Arg]) -> BTreeMap<String, String> {
303 let mut m = BTreeMap::new();
304 let mut i = 0;
305 while i < args.len() {
306 if let Some(flag) = args[i].as_str().and_then(|w| w.strip_prefix('-')) {
307 let val = args
308 .get(i + 1)
309 .and_then(Arg::as_str)
310 .unwrap_or("")
311 .to_string();
312 m.insert(flag.to_string(), val);
313 i += 2;
314 } else {
315 i += 1;
316 }
317 }
318 m
319}
320
321fn pipeline_from_body(cmds: &[Command]) -> Result<Vec<QueryOp>, String> {
323 let mut ops = Vec::new();
324 let mut saw_in = false;
325 for c in cmds {
326 match c.name.as_str() {
327 "in" | "in.json" | "in.html" | "in.xml" | "in.logfmt" => saw_in = true,
328 "in.csv" => {
329 saw_in = true;
330 ops.push(QueryOp::Csv);
331 }
332 "in.tsv" => {
333 saw_in = true;
334 ops.push(QueryOp::Tsv);
335 }
336 "in.yaml" | "in.yml" => {
337 saw_in = true;
338 ops.push(QueryOp::Yaml);
339 }
340 "in.toml" => {
341 saw_in = true;
342 ops.push(QueryOp::Toml);
343 }
344 "sel" => {
345 let words: Vec<&str> = c.args.iter().filter_map(Arg::as_str).collect();
346 let mut css_parts = Vec::new();
347 let mut attr = None;
348 let mut i = 0;
349 while i < words.len() {
350 if words[i] == "-attr" {
351 attr = words.get(i + 1).map(|s| s.to_string());
352 i += 2;
353 } else {
354 css_parts.push(words[i]);
355 i += 1;
356 }
357 }
358 let css = css_parts.join(" ");
359 if css.trim().is_empty() {
360 return Err("sel: expected a CSS selector".into());
361 }
362 ops.push(QueryOp::Sel { css, attr });
363 }
364 "find" => {
365 let css = c
366 .args
367 .iter()
368 .filter_map(Arg::as_str)
369 .collect::<Vec<_>>()
370 .join(" ");
371 if css.trim().is_empty() {
372 return Err("find: expected a tag/selector".into());
373 }
374 ops.push(QueryOp::Find(css));
375 }
376 "attr" => {
377 let name = str_arg(c);
378 if name.is_empty() {
379 return Err("attr: expected an attribute name".into());
380 }
381 ops.push(QueryOp::Attr(name));
382 }
383 "text" => ops.push(QueryOp::Text),
384 "match" | "grep" => ops.push(QueryOp::Match(regex_arg(c)?)),
385 "reject" | "grepv" => ops.push(QueryOp::Reject(regex_arg(c)?)),
386 "field" => ops.push(QueryOp::Field(field_sel(&c.args)?)),
387 "each" => ops.push(QueryOp::Each),
388 "count" => ops.push(QueryOp::Count),
389 "rate" => ops.push(QueryOp::Rate),
390 "tally" => ops.push(QueryOp::Tally),
391 "sum" => ops.push(QueryOp::Sum),
392 "min" => ops.push(QueryOp::Min),
393 "max" => ops.push(QueryOp::Max),
394 "avg" => ops.push(QueryOp::Avg),
395 "keys" => ops.push(QueryOp::Keys),
396 "vals" => ops.push(QueryOp::Vals),
397 "pick" => {
398 let keys: Vec<String> = c
399 .args
400 .iter()
401 .filter_map(Arg::as_str)
402 .map(str::to_string)
403 .collect();
404 if keys.is_empty() {
405 return Err("pick: expected one or more key names".into());
406 }
407 ops.push(QueryOp::Pick(keys));
408 }
409 "sort" => {
410 let flags: Vec<&str> = c.args.iter().filter_map(Arg::as_str).collect();
411 ops.push(QueryOp::Sort {
412 numeric: flags.contains(&"-n"),
413 reverse: flags.contains(&"-r"),
414 });
415 }
416 "uniq" => ops.push(QueryOp::Uniq),
417 "rev" => ops.push(QueryOp::Rev),
418 "first" => ops.push(QueryOp::First),
419 "last" => ops.push(QueryOp::Last),
420 "upper" => ops.push(QueryOp::Upper),
421 "lower" => ops.push(QueryOp::Lower),
422 "trim" => ops.push(QueryOp::Trim),
423 "replace" => {
424 let re = regex_arg(c)?;
425 let to = c
426 .args
427 .get(1)
428 .and_then(Arg::as_str)
429 .unwrap_or("")
430 .to_string();
431 ops.push(QueryOp::Replace(re, to));
432 }
433 "join" => {
434 let sep = c
435 .args
436 .first()
437 .and_then(Arg::as_str)
438 .unwrap_or(" ")
439 .to_string();
440 ops.push(QueryOp::Join(sep));
441 }
442 "nth" => ops.push(QueryOp::Nth(count_arg(c, "nth")?)),
443 "take" => ops.push(QueryOp::Take(count_arg(c, "take")?)),
444 "drop" => ops.push(QueryOp::Drop(count_arg(c, "drop")?)),
445 "calc" => {
446 let src = c
447 .args
448 .iter()
449 .filter_map(Arg::as_str)
450 .collect::<Vec<_>>()
451 .join(" ");
452 ops.push(QueryOp::Calc(crate::expr::parse(&src)?));
453 }
454 "where" => {
455 let src = c
456 .args
457 .iter()
458 .filter_map(Arg::as_str)
459 .collect::<Vec<_>>()
460 .join(" ");
461 ops.push(QueryOp::Where(crate::expr::parse(&src)?));
462 }
463 "map" => {
464 let src = c
465 .args
466 .iter()
467 .filter_map(Arg::as_str)
468 .collect::<Vec<_>>()
469 .join(" ");
470 ops.push(QueryOp::Map(crate::expr::parse(&src)?));
471 }
472 "sort_by" => {
473 let field = str_arg(c);
474 if field.is_empty() {
475 return Err("sort_by: expected a field name".into());
476 }
477 ops.push(QueryOp::SortBy(field));
478 }
479 "unique_by" => {
480 let field = str_arg(c);
481 if field.is_empty() {
482 return Err("unique_by: expected a field name".into());
483 }
484 ops.push(QueryOp::UniqueBy(field));
485 }
486 "count_by" => {
487 let field = str_arg(c);
488 if field.is_empty() {
489 return Err("count_by: expected a field name".into());
490 }
491 ops.push(QueryOp::CountBy(field));
492 }
493 "min_by" => {
494 let field = str_arg(c);
495 if field.is_empty() {
496 return Err("min_by: expected a field name".into());
497 }
498 ops.push(QueryOp::MinBy(field));
499 }
500 "max_by" => {
501 let field = str_arg(c);
502 if field.is_empty() {
503 return Err("max_by: expected a field name".into());
504 }
505 ops.push(QueryOp::MaxBy(field));
506 }
507 "has" => {
508 let key = str_arg(c);
509 if key.is_empty() {
510 return Err("has: expected a key name".into());
511 }
512 ops.push(QueryOp::Has(key));
513 }
514 "entries" => {
515 if !c.args.is_empty() { return Err("entries: takes no arguments".into()); }
516 ops.push(QueryOp::Entries);
517 }
518 "flatten" => ops.push(QueryOp::Flatten),
519 "add" => ops.push(QueryOp::Add),
520 "over" => {
521 let n = c
522 .args
523 .first()
524 .and_then(Arg::as_str)
525 .and_then(|s| s.parse::<f64>().ok())
526 .ok_or_else(|| "over: expected a numeric threshold".to_string())?;
527 ops.push(QueryOp::Over(n));
528 }
529 "under" => {
530 let n: f64 = str_arg(c)
531 .parse()
532 .map_err(|_| "under: expected a number".to_string())?;
533 ops.push(QueryOp::Under(n));
534 }
535 "between" => {
536 let lo = c
537 .args
538 .first()
539 .and_then(Arg::as_str)
540 .and_then(|s| s.parse::<f64>().ok())
541 .ok_or_else(|| "between: expected two numbers A B".to_string())?;
542 let hi = c
543 .args
544 .get(1)
545 .and_then(Arg::as_str)
546 .and_then(|s| s.parse::<f64>().ok())
547 .ok_or_else(|| "between: expected two numbers A B".to_string())?;
548 ops.push(QueryOp::Between(lo, hi));
549 }
550 "enumerate" => {
551 ops.push(QueryOp::Enumerate);
552 }
553 "words" => {
554 if !c.args.is_empty() { return Err("words: takes no arguments".into()); }
555 ops.push(QueryOp::Words);
556 }
557 "dedup" => ops.push(QueryOp::Dedup),
558 "tailn" => ops.push(QueryOp::Tailn(count_arg(c, "tailn")?)),
559 "pad" => {
560 let n = count_arg(c, "pad")?;
561 ops.push(QueryOp::Pad(n));
562 }
563 "lpad" => ops.push(QueryOp::Lpad(count_arg(c, "lpad")?)),
564 "grepf" => {
565 let field = c
566 .args
567 .first()
568 .and_then(Arg::as_str)
569 .ok_or_else(|| "grepf: expected FIELD and /re/".to_string())?
570 .to_string();
571 let raw = c
572 .args
573 .get(1)
574 .and_then(Arg::as_str)
575 .ok_or_else(|| "grepf: expected a pattern".to_string())?;
576 let pat = raw
577 .strip_prefix('/')
578 .and_then(|s| s.strip_suffix('/'))
579 .unwrap_or(raw);
580 let re = regex::Regex::new(pat).map_err(|e| format!("grepf: bad regex: {e}"))?;
581 ops.push(QueryOp::Grepf(field, re));
582 }
583 "flip" => {
584 ops.push(QueryOp::Flip);
585 }
586 "b64" => {
587 ops.push(QueryOp::B64);
588 }
589 "b64d" => {
590 ops.push(QueryOp::B64d);
591 }
592 "hex" => ops.push(QueryOp::Hex),
593 "unhex" => {
594 ops.push(QueryOp::Unhex);
595 }
596 "urlenc" => {
597 ops.push(QueryOp::Urlenc);
598 }
599 "urldec" => {
600 ops.push(QueryOp::Urldec);
601 }
602 "extract" => {
603 ops.push(QueryOp::Extract(regex_arg(c)?));
604 }
605 "split" => {
606 let delim = str_arg(c);
607 if delim.is_empty() { return Err("split: expected a non-empty delimiter".into()); }
608 ops.push(QueryOp::Split(delim));
609 }
610 "substr" => {
611 let args: Vec<usize> = c
612 .args
613 .iter()
614 .filter_map(Arg::as_str)
615 .filter_map(|s| s.parse::<usize>().ok())
616 .collect();
617 if args.len() != 2 {
618 return Err("substr: expected two non-negative integer args A B".into());
619 }
620 ops.push(QueryOp::Substr(args[0], args[1]));
621 }
622 "chars" => ops.push(QueryOp::Chars),
623 "title" => {
624 ops.push(QueryOp::Title);
625 }
626 "repeat" => {
627 let n = count_arg(c, "repeat")?;
628 ops.push(QueryOp::Repeat(n));
629 }
630 "set" => {
631 let key = str_arg(c);
632 if key.is_empty() { return Err("set: expected key and value".into()); }
633 let val = c.args.iter().filter_map(Arg::as_str).nth(1).unwrap_or("").to_string();
634 ops.push(QueryOp::Set(key, val));
635 }
636 "del" => {
637 let key = str_arg(c);
638 if key.is_empty() { return Err("del: expected a key name".into()); }
639 ops.push(QueryOp::Del(key));
640 }
641 "rename" => {
642 let args: Vec<String> = c.args.iter().filter_map(Arg::as_str).map(str::to_string).collect();
643 if args.len() != 2 || args[0].is_empty() || args[1].is_empty() {
644 return Err("rename: expected OLD NEW key names".into());
645 }
646 ops.push(QueryOp::Rename(args[0].clone(), args[1].clone()));
647 }
648 "default" => {
649 let args: Vec<String> = c.args.iter().filter_map(Arg::as_str).map(str::to_string).collect();
650 if args.len() != 2 {
651 return Err("default: expected exactly two args: key value".into());
652 }
653 ops.push(QueryOp::Default(args[0].clone(), args[1].clone()));
654 }
655 "merge" => {
656 ops.push(QueryOp::Merge);
657 }
658 "floor" => {
659 ops.push(QueryOp::Floor);
660 }
661 "ceil" => {
662 ops.push(QueryOp::Ceil);
663 }
664 "clamp" => {
665 let mut it = c.args.iter().filter_map(Arg::as_str);
666 let lo = it.next().and_then(|s| s.parse::<f64>().ok());
667 let hi = it.next().and_then(|s| s.parse::<f64>().ok());
668 match (lo, hi) {
669 (Some(lo), Some(hi)) => ops.push(QueryOp::Clamp(lo, hi)),
670 _ => return Err("clamp: expected LO HI numeric args".into()),
671 }
672 }
673 "contains" => ops.push(QueryOp::Contains(str_arg(c))),
674 "starts" => ops.push(QueryOp::Starts(str_arg(c))),
675 "ends" => ops.push(QueryOp::Ends(str_arg(c))),
676 "nonempty" => ops.push(QueryOp::Nonempty),
677 "numeric" => ops.push(QueryOp::Numeric),
678 "len" => ops.push(QueryOp::Len),
679 "wc" => ops.push(QueryOp::Wc),
680 "abs" => ops.push(QueryOp::Abs),
681 "round" => ops.push(QueryOp::Round),
682 "prepend" => ops.push(QueryOp::Prepend(str_arg(c))),
683 "append" => ops.push(QueryOp::Append(str_arg(c))),
684 "cut" => {
685 let delim = str_arg(c);
686 let n = c
687 .args
688 .get(1)
689 .and_then(Arg::as_str)
690 .and_then(|s| s.parse::<usize>().ok())
691 .unwrap_or(0);
692 ops.push(QueryOp::Cut(delim, n));
693 }
694 "median" => ops.push(QueryOp::Median),
695 "stddev" => ops.push(QueryOp::Stddev),
696 "p95" => ops.push(QueryOp::P95),
697 "range" => ops.push(QueryOp::Range),
698 "product" => ops.push(QueryOp::Product),
699 "distinct" => ops.push(QueryOp::Distinct),
700 "sample" => ops.push(QueryOp::Sample(count_arg(c, "sample")?)),
701 "bins" => ops.push(QueryOp::Bins(count_arg(c, "bins")?)),
702 "slice" => {
703 let a = c
704 .args
705 .first()
706 .and_then(Arg::as_str)
707 .and_then(|s| s.parse::<usize>().ok())
708 .unwrap_or(1);
709 let b = c
710 .args
711 .get(1)
712 .and_then(Arg::as_str)
713 .and_then(|s| s.parse::<usize>().ok())
714 .unwrap_or(usize::MAX);
715 ops.push(QueryOp::Slice(a, b));
716 }
717 other => return Err(format!("source: unknown verb `{other}`")),
718 }
719 }
720 if !saw_in {
721 return Err("source: pipeline must start with `in`".into());
722 }
723 Ok(ops)
724}
725
726fn regex_arg(c: &Command) -> Result<Regex, String> {
728 let raw = c
729 .args
730 .first()
731 .and_then(Arg::as_str)
732 .ok_or_else(|| format!("{}: expected a pattern", c.name))?;
733 let pat = raw
734 .strip_prefix('/')
735 .and_then(|s| s.strip_suffix('/'))
736 .unwrap_or(raw);
737 Regex::new(pat).map_err(|e| format!("{}: bad regex: {e}", c.name))
738}
739
740fn str_arg(c: &Command) -> String {
743 c.args
744 .first()
745 .and_then(Arg::as_str)
746 .unwrap_or("")
747 .to_string()
748}
749
750fn count_arg(c: &Command, verb: &str) -> Result<usize, String> {
751 c.args
752 .first()
753 .and_then(Arg::as_str)
754 .and_then(|s| s.parse::<usize>().ok())
755 .ok_or_else(|| format!("{verb}: expected a count"))
756}
757
758fn field_sel(args: &[Arg]) -> Result<FieldSel, String> {
761 let words: Vec<&str> = args.iter().filter_map(Arg::as_str).collect();
762 if words.is_empty() {
763 return Err("field: expected a column number or key path".into());
764 }
765 if words.len() == 1 {
766 if let Ok(n) = words[0].parse::<usize>() {
767 return Ok(FieldSel::Col(n));
768 }
769 }
770 Ok(FieldSel::Key(words.iter().map(|s| s.to_string()).collect()))
771}
772
773fn set_source(spec: &mut Spec, path: &str, src: Source) -> Result<(), String> {
774 for w in &mut spec.widgets {
775 if w.path == path {
776 w.source = Some(src);
777 return Ok(());
778 }
779 }
780 Err(format!("source: no widget named `{path}`"))
781}
782
783fn set_grid(spec: &mut Spec, path: &str, cell: (usize, usize)) -> Result<(), String> {
784 for w in &mut spec.widgets {
785 if w.path == path {
786 w.grid = Some(cell);
787 return Ok(());
788 }
789 }
790 Err(format!("grid: no widget named `{path}`"))
791}