1use model::SingleProcessModelFieldId;
16
17use super::*;
18
19pub struct Process {
20 opts: GeneralOpt,
21 select: Option<SingleProcessModelFieldId>,
22 fields: Vec<ProcessField>,
23}
24
25impl Process {
26 pub fn new(
27 opts: &GeneralOpt,
28 select: Option<SingleProcessModelFieldId>,
29 fields: Vec<ProcessField>,
30 ) -> Self {
31 Self {
32 opts: opts.to_owned(),
33 select,
34 fields,
35 }
36 }
37}
38
39impl Dumper for Process {
40 fn dump_model(
41 &self,
42 ctx: &CommonFieldContext,
43 model: &model::Model,
44 output: &mut dyn Write,
45 round: &mut usize,
46 comma_flag: bool,
47 ) -> Result<IterExecResult> {
48 let mut processes: Vec<_> = model
49 .process
50 .processes
51 .iter()
52 .filter_map(
53 |(_, spm)| match (self.select.as_ref(), self.opts.filter.as_ref()) {
54 (Some(field_id), Some(filter))
55 if !filter.is_match(
56 &spm.query(field_id)
57 .map_or("?".to_owned(), |v| v.to_string()),
58 ) =>
59 {
60 None
61 }
62 _ => Some(spm),
63 },
64 )
65 .collect();
66
67 if processes.is_empty() {
69 return Ok(IterExecResult::Skip);
70 }
71
72 if let Some(field_id) = self.select.as_ref() {
73 if self.opts.sort {
74 model::sort_queriables(&mut processes, field_id, false);
75 }
76
77 if self.opts.rsort {
78 model::sort_queriables(&mut processes, field_id, true);
79 }
80
81 if (self.opts.sort || self.opts.rsort) && self.opts.top != 0 {
82 processes.truncate(self.opts.top as usize);
83 }
84 }
85 let mut json_output = json!([]);
86
87 processes
88 .into_iter()
89 .map(|spm| {
90 match self.opts.output_format {
91 Some(OutputFormat::Raw) | None => write!(
92 output,
93 "{}",
94 print::dump_raw(
95 &self.fields,
96 ctx,
97 spm,
98 *round,
99 self.opts.repeat_title,
100 self.opts.disable_title,
101 self.opts.raw
102 )
103 )?,
104 Some(OutputFormat::Csv) => write!(
105 output,
106 "{}",
107 print::dump_csv(
108 &self.fields,
109 ctx,
110 spm,
111 *round,
112 self.opts.disable_title,
113 self.opts.raw
114 )
115 )?,
116 Some(OutputFormat::Tsv) => write!(
117 output,
118 "{}",
119 print::dump_tsv(
120 &self.fields,
121 ctx,
122 spm,
123 *round,
124 self.opts.disable_title,
125 self.opts.raw
126 )
127 )?,
128 Some(OutputFormat::KeyVal) => write!(
129 output,
130 "{}",
131 print::dump_kv(&self.fields, ctx, spm, self.opts.raw)
132 )?,
133 Some(OutputFormat::Json) => {
134 let par = print::dump_json(&self.fields, ctx, spm, self.opts.raw);
135 json_output.as_array_mut().unwrap().push(par);
136 }
137 Some(OutputFormat::OpenMetrics) => write!(
138 output,
139 "{}",
140 print::dump_openmetrics(&self.fields, ctx, spm)
141 )?,
142 }
143 *round += 1;
144 Ok(())
145 })
146 .collect::<Result<Vec<_>>>()?;
147
148 match (self.opts.output_format, comma_flag) {
149 (Some(OutputFormat::Json), true) => write!(output, ",{}", json_output)?,
150 (Some(OutputFormat::Json), false) => write!(output, "{}", json_output)?,
151 (Some(OutputFormat::OpenMetrics), _) => (),
152 _ => writeln!(output)?,
153 };
154
155 Ok(IterExecResult::Success)
156 }
157}