reinfer-cli 0.38.5

Command line interface for Re:infer, the conversational data intelligence platform
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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
use super::thousands::Thousands;
use colored::Colorize;
use prettytable::{format, row, Row, Table};
use reinfer_client::{
    resources::{
        audit::PrintableAuditEvent,
        bucket::KeyedSyncState,
        bucket_statistics::{Count, Statistics as BucketStatistics},
        dataset::DatasetAndStats,
        integration::Integration,
        quota::Quota,
    },
    Bucket, CommentStatistics, Dataset, Project, Source, Stream, User,
};
use serde::{Serialize, Serializer};

use anyhow::{anyhow, Context, Error, Result};
use std::{
    io::{self, Write},
    str::FromStr,
};

pub fn print_resources_as_json<Resource>(
    resources: impl IntoIterator<Item = Resource>,
    mut writer: impl Write,
) -> Result<()>
where
    Resource: Serialize,
{
    for resource in resources {
        serde_json::to_writer(&mut writer, &resource)
            .context("Could not serialise resource.")
            .and_then(|_| writeln!(writer).context("Failed to write JSON resource to writer."))?;
    }
    Ok(())
}

#[derive(Copy, Clone, Default, Debug)]
pub enum OutputFormat {
    Json,
    #[default]
    Table,
}

impl FromStr for OutputFormat {
    type Err = Error;

    fn from_str(string: &str) -> Result<Self> {
        if string == "table" {
            Ok(OutputFormat::Table)
        } else if string == "json" {
            Ok(OutputFormat::Json)
        } else {
            Err(anyhow!("{}", string))
        }
    }
}

/// Represents a resource that is able to be displayed as a table.
///
/// The implementation must implement `to_table_headers` to return headers for the resource type,
/// and `to_table_row`, which should return a data row for the given resource instance.
pub trait DisplayTable {
    fn to_table_headers() -> Row;

    fn to_table_row(&self) -> Row;
}

impl DisplayTable for Integration {
    fn to_table_headers() -> Row {
        row![bFg => "Project", "Name", "ID", "Created (UTC)", "Mailbox Count"]
    }

    fn to_table_row(&self) -> Row {
        row![
            self.owner.0,
            self.name.0,
            self.id.0,
            self.created_at.format("%Y-%m-%d %H:%M:%S"),
            self.configuration.mailboxes.len()
        ]
    }
}
impl DisplayTable for Bucket {
    fn to_table_headers() -> Row {
        row![bFg => "Name", "ID", "Created (UTC)"]
    }

    fn to_table_row(&self) -> Row {
        let full_name = format!("{}{}{}", self.owner.0.dimmed(), "/".dimmed(), self.name.0);
        row![
            full_name,
            self.id.0,
            self.created_at.format("%Y-%m-%d %H:%M:%S"),
        ]
    }
}

impl DisplayTable for Quota {
    fn to_table_headers() -> Row {
        row![bFg => "Kind", "Hard Limit", "Usage (Total)", "Usage %"]
    }

    fn to_table_row(&self) -> Row {
        row![
            self.quota_kind,
            Thousands(self.hard_limit),
            Thousands(self.current_max_usage),
            if self.hard_limit > 0 {
                format!(
                    "{:.0}%",
                    (self.current_max_usage as f64 / self.hard_limit as f64) * 100.0
                )
            } else {
                "N/A".dimmed().to_string()
            }
        ]
    }
}

impl DisplayTable for Dataset {
    fn to_table_headers() -> Row {
        row![bFg => "Name", "ID", "Updated (UTC)", "Title"]
    }

    fn to_table_row(&self) -> Row {
        let full_name = format!("{}{}{}", self.owner.0.dimmed(), "/".dimmed(), self.name.0);
        row![
            full_name,
            self.id.0,
            self.updated_at.format("%Y-%m-%d %H:%M:%S"),
            self.title,
        ]
    }
}

impl DisplayTable for DatasetAndStats {
    fn to_table_headers() -> Row {
        row![bFg => "Name", "ID", "Updated (UTC)", "Title","Total Verbatims", "Num Reviewed","Latest Model", "Score", "Quality"]
    }

    fn to_table_row(&self) -> Row {
        let full_name = format!(
            "{}{}{}",
            self.dataset.owner.0.dimmed(),
            "/".dimmed(),
            self.dataset.name.0
        );

        if let Some(validation_response) = &self.stats.validation {
            row![
                full_name,
                self.dataset.id.0,
                self.dataset.updated_at.format("%Y-%m-%d %H:%M:%S"),
                self.dataset.title,
                self.stats.total_verbatims,
                validation_response.validation.reviewed_size,
                validation_response.validation.version,
                validation_response.validation.model_rating.score,
                validation_response.validation.model_rating.quality
            ]
        } else {
            row![
                full_name,
                self.dataset.id.0,
                self.dataset.updated_at.format("%Y-%m-%d %H:%M:%S"),
                self.dataset.title,
                self.stats.total_verbatims,
                "N/A".dimmed(),
                "N/A".dimmed(),
                "N/A".dimmed(),
                "N/A".dimmed(),
            ]
        }
    }
}

impl DisplayTable for Project {
    fn to_table_headers() -> Row {
        row![bFg => "Name", "ID", "Title"]
    }

    fn to_table_row(&self) -> Row {
        row![
            self.name.0,
            match &self.id {
                Some(id) => id.0.as_str().into(),
                None => "unknown".dimmed(),
            },
            self.title
        ]
    }
}

impl DisplayTable for Source {
    fn to_table_headers() -> Row {
        row![bFg => "Name", "ID", "Updated (UTC)", "Transform Tag", "Title", "Bucket"]
    }

    fn to_table_row(&self) -> Row {
        let full_name = format!("{}{}{}", self.owner.0.dimmed(), "/".dimmed(), self.name.0);
        row![
            full_name,
            self.id.0,
            self.updated_at.format("%Y-%m-%d %H:%M:%S"),
            match &self.transform_tag {
                Some(transform_tag) => transform_tag.0.as_str().into(),
                None => "missing".dimmed(),
            },
            self.title,
            match &self.bucket_id {
                Some(bucket) => bucket.0.as_str().into(),
                None => "missing".dimmed(),
            }
        ]
    }
}

#[derive(Debug)]
pub struct PrintableBucket {
    pub bucket: Bucket,
    pub stats: Option<BucketStatistics>,
}
impl DisplayTable for PrintableBucket {
    fn to_table_headers() -> Row {
        row![bFg => "Name", "ID", "Created (UTC)", "Num Emails"]
    }

    fn to_table_row(&self) -> Row {
        let full_name = format!(
            "{}{}{}",
            self.bucket.owner.0.dimmed(),
            "/".dimmed(),
            self.bucket.name.0
        );
        let count_str = if let Some(stats) = &self.stats {
            match &stats.count {
                Count::LowerBoundBucketCount { value } => format!(">={value}"),
                Count::ExactBucketCount { value } => format!("={value}"),
            }
        } else {
            "none".dimmed().to_string()
        };
        row![
            full_name,
            self.bucket.id.0,
            self.bucket.created_at.format("%Y-%m-%d %H:%M:%S"),
            count_str
        ]
    }
}
impl Serialize for PrintableBucket {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        Serialize::serialize(&self.bucket, serializer)
    }
}

/// Source with additional fields for printing
/// Serializes to a Source
#[derive(Debug)]
pub struct PrintableSource {
    pub source: Source,
    pub bucket: Option<Bucket>,
    pub stats: Option<CommentStatistics>,
}

impl Serialize for PrintableSource {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        Serialize::serialize(&self.source, serializer)
    }
}

impl DisplayTable for PrintableSource {
    fn to_table_headers() -> Row {
        row![bFg => "Name", "ID", "Updated (UTC)", "Transform Tag", "Bucket", "Title", "Num Comments"]
    }

    fn to_table_row(&self) -> Row {
        let full_name = format!(
            "{}{}{}",
            self.source.owner.0.dimmed(),
            "/".dimmed(),
            self.source.name.0
        );
        row![
            full_name,
            self.source.id.0,
            self.source.updated_at.format("%Y-%m-%d %H:%M:%S"),
            match &self.source.transform_tag {
                Some(transform_tag) => transform_tag.0.as_str().into(),
                None => "missing".dimmed(),
            },
            match &self.bucket {
                Some(bucket) => bucket.name.0.as_str().into(),
                None => match &self.source.bucket_id {
                    Some(bucket_id) => bucket_id.0.as_str().dimmed(),
                    None => "none".dimmed(),
                },
            },
            self.source.title,
            if let Some(stats) = &self.stats {
                stats.num_comments.to_string().as_str().into()
            } else {
                "none".dimmed()
            }
        ]
    }
}

impl DisplayTable for KeyedSyncState {
    fn to_table_headers() -> Row {
        row![bFg => "Mailbox Name", "Folder Path", "Status", "Synced Until", "Last Synced At"]
    }

    fn to_table_row(&self) -> Row {
        row![
            self.mailbox_name,
            self.folder_path.join("/"),
            self.status,
            if let Some(synced_until) = self.synced_until {
                synced_until.to_rfc2822().normal()
            } else {
                "N/A".dimmed()
            },
            self.last_synced_at
        ]
    }
}

impl DisplayTable for Stream {
    fn to_table_headers() -> Row {
        row![bFg => "Name", "ID", "Updated (UTC)", "Title"]
    }

    fn to_table_row(&self) -> Row {
        row![
            self.name.0,
            self.id.0,
            self.updated_at.format("%Y-%m-%d %H:%M:%S"),
            self.title
        ]
    }
}

impl DisplayTable for User {
    fn to_table_headers() -> Row {
        row![bFg => "Name", "Email", "ID", "Created (UTC)", "Global Permissions"]
    }

    fn to_table_row(&self) -> Row {
        row![
            self.username.0,
            self.email.0,
            self.id.0,
            self.created_at.format("%Y-%m-%d %H:%M:%S"),
            self.global_permissions
                .iter()
                .chain(self.sso_global_permissions.iter())
                .map(|permission| permission.to_string())
                .collect::<Vec<String>>()
                .join(", ")
        ]
    }
}

impl DisplayTable for PrintableAuditEvent {
    fn to_table_headers() -> Row {
        row![bFg => "Timestamp", "Event Id", "Event Type", "Actor Email", "Actor Tenant", "Dataset Names",  "Project Names", "Tenant Names"]
    }

    fn to_table_row(&self) -> Row {
        row![
            self.timestamp,
            self.event_id.0,
            self.event_type.0,
            self.actor_email.0,
            self.actor_tenant_name.0,
            if self.dataset_names.is_empty() {
                "none".dimmed()
            } else {
                self.dataset_names
                    .iter()
                    .map(|dataset| dataset.0.clone())
                    .collect::<Vec<String>>()
                    .join(" & ")
                    .normal()
            },
            if self.project_names.is_empty() {
                "none".dimmed()
            } else {
                self.project_names
                    .iter()
                    .map(|project| project.0.clone())
                    .collect::<Vec<String>>()
                    .join(" & ")
                    .normal()
            },
            if self.tenant_names.is_empty() {
                "none".dimmed()
            } else {
                self.tenant_names
                    .iter()
                    .map(|name| name.0.clone())
                    .collect::<Vec<String>>()
                    .join(" & ")
                    .normal()
            }
        ]
    }
}

/// Helper trait to allow collection of resources to be converted into a table.
pub trait IntoTable {
    fn into_table(self) -> Table;
}

/// All iterators of resources can be converted into a table.
impl<'a, Iterable, Item: 'a> IntoTable for Iterable
where
    Iterable: IntoIterator<Item = &'a Item>,
    Item: DisplayTable,
{
    fn into_table(self) -> Table {
        let mut table = new_table();
        table.set_titles(Item::to_table_headers());
        for source in self.into_iter() {
            table.add_row(source.to_table_row());
        }
        table
    }
}

fn new_table() -> Table {
    let mut table = Table::new();
    let format = format::FormatBuilder::new()
        .column_separator(' ')
        .borders(' ')
        .separators(&[], format::LineSeparator::new('-', '+', '+', '+'))
        .padding(0, 1)
        .build();
    table.set_format(format);
    table
}

fn print_table<T: IntoTable>(resources: T) {
    let table = resources.into_table();
    table.printstd();
}

/// Print resources using the selected output format.
///
/// Resources passed to the printer must be able to be formatted using all supported
/// `OutputFormat`s.
#[derive(Default, Debug)]
pub struct Printer {
    output: OutputFormat,
}

impl Printer {
    pub fn new(output: OutputFormat) -> Self {
        Self { output }
    }

    pub fn print_resources<T, Resource>(&self, resources: T) -> Result<()>
    where
        T: IntoIterator<Item = Resource> + IntoTable,
        Resource: Serialize,
    {
        match self.output {
            OutputFormat::Table => print_table(resources),
            OutputFormat::Json => print_resources_as_json(resources, io::stdout().lock())?,
        };
        Ok(())
    }
}