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
use crate::remote::GetRemoteCliArgs;
use crate::Result;
use std::{collections::HashMap, io::Write};

#[derive(Clone, Debug, Default)]
pub enum Format {
    CSV,
    JSON,
    #[default]
    PIPE,
}

impl From<Format> for u8 {
    fn from(f: Format) -> Self {
        match f {
            Format::CSV => b',',
            Format::PIPE => b'|',
            Format::JSON => 0,
        }
    }
}

pub struct DisplayBody {
    pub columns: Vec<Column>,
}

impl DisplayBody {
    pub fn new(columns: Vec<Column>) -> Self {
        Self { columns }
    }
}

#[derive(Builder)]
pub struct Column {
    pub name: String,
    pub value: String,
    #[builder(default)]
    pub optional: bool,
}

impl Column {
    pub fn builder() -> ColumnBuilder {
        ColumnBuilder::default()
    }
    pub fn new(name: impl Into<String>, value: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            value: value.into(),
            optional: false,
        }
    }
}

pub fn print<W: Write, D: Into<DisplayBody> + Clone>(
    w: &mut W,
    data: Vec<D>,
    args: GetRemoteCliArgs,
) -> Result<()> {
    if data.is_empty() {
        return Ok(());
    }
    match args.format {
        Format::JSON => {
            for d in data {
                let d = d.into();
                let kvs: HashMap<String, String> = d
                    .columns
                    .into_iter()
                    .filter(|c| !c.optional || args.display_optional)
                    .map(|item| (item.name, item.value))
                    .collect();
                writeln!(w, "{}", serde_json::to_string(&kvs)?)?;
            }
        }
        _ => {
            let mut wtr = csv::WriterBuilder::new()
                .delimiter(args.format.into())
                .from_writer(w);
            if !args.no_headers {
                // Get the headers from the first row of columns
                let headers = data[0]
                    .clone()
                    .into()
                    .columns
                    .iter()
                    .filter(|c| !c.optional || args.display_optional)
                    .map(|c| c.name.clone())
                    .collect::<Vec<_>>();
                wtr.write_record(&headers)?;
            }
            for d in data {
                let d = d.into();
                let row = d
                    .columns
                    .into_iter()
                    .filter(|c| !c.optional || args.display_optional)
                    .map(|c| c.value)
                    .collect::<Vec<_>>();
                wtr.write_record(&row)?;
            }
            wtr.flush()?;
        }
    }
    Ok(())
}

#[cfg(test)]
mod test {
    use super::*;

    #[derive(Clone)]
    struct Book {
        pub title: String,
        pub author: String,
    }

    impl Book {
        pub fn new(title: impl Into<String>, author: impl Into<String>) -> Self {
            Self {
                title: title.into(),
                author: author.into(),
            }
        }
    }

    impl From<Book> for DisplayBody {
        fn from(b: Book) -> Self {
            DisplayBody::new(vec![
                Column::new("title", b.title),
                Column::new("author", b.author),
            ])
        }
    }

    #[test]
    fn test_json() {
        let mut w = Vec::new();
        let books = vec![
            Book::new("The Catcher in the Rye", "J.D. Salinger"),
            Book::new("The Adventures of Huckleberry Finn", "Mark Twain"),
        ];
        let args = GetRemoteCliArgs::builder()
            .no_headers(true)
            .format(Format::JSON)
            .build()
            .unwrap();
        print(&mut w, books, args).unwrap();
        let s = String::from_utf8(w).unwrap();
        assert_eq!(2, s.lines().count());
        for line in s.lines() {
            let v: serde_json::Value = serde_json::from_str(line).unwrap();
            assert!(v.is_object());
            let obj = v.as_object().unwrap();
            assert_eq!(obj.len(), 2);
            assert!(obj.contains_key("title"));
            assert!(obj.contains_key("author"));
        }
    }

    #[test]
    fn test_csv_multiple_commas_one_field() {
        let mut w = Vec::new();
        let books = vec![
            Book::new("Faust, Part One", "Goethe"),
            Book::new("The Adventures of Huckleberry Finn", "Mark Twain"),
        ];
        let args = GetRemoteCliArgs::builder()
            .no_headers(true)
            .format(Format::CSV)
            .build()
            .unwrap();
        print(&mut w, books, args).unwrap();
        let mut reader = csv::ReaderBuilder::new()
            .has_headers(false)
            .from_reader(w.as_slice());
        assert_eq!(
            "Faust, Part One",
            &reader.records().next().unwrap().unwrap()[0]
        );
    }

    #[derive(Clone)]
    struct BookOptionalColumns {
        pub title: String,
        pub author: String,
        pub isbn: String,
    }

    impl BookOptionalColumns {
        pub fn new(
            title: impl Into<String>,
            author: impl Into<String>,
            isbn: impl Into<String>,
        ) -> Self {
            Self {
                title: title.into(),
                author: author.into(),
                isbn: isbn.into(),
            }
        }
    }

    impl From<BookOptionalColumns> for DisplayBody {
        fn from(b: BookOptionalColumns) -> Self {
            DisplayBody::new(vec![
                Column::new("title", b.title),
                Column::new("author", b.author),
                Column::builder()
                    .name("isbn".to_string())
                    .value(b.isbn)
                    .optional(true)
                    .build()
                    .unwrap(),
            ])
        }
    }

    #[test]
    fn test_csv_optional_columns() {
        let mut w = Vec::new();
        let books = vec![
            BookOptionalColumns::new("The Catcher in the Rye", "J.D. Salinger", "0316769487"),
            BookOptionalColumns::new(
                "The Adventures of Huckleberry Finn",
                "Mark Twain",
                "9780199536559",
            ),
        ];
        let args = GetRemoteCliArgs::builder()
            .format(Format::CSV)
            .build()
            .unwrap();
        print(&mut w, books, args).unwrap();
        assert_eq!(
            "title,author\nThe Catcher in the Rye,J.D. Salinger\nThe Adventures of Huckleberry Finn,Mark Twain\n",
            String::from_utf8(w).unwrap()
        );
    }

    #[test]
    fn test_csv_display_optional_columns_on_args() {
        let mut w = Vec::new();
        let books = vec![
            BookOptionalColumns::new("The Catcher in the Rye", "J.D. Salinger", "0316769487"),
            BookOptionalColumns::new(
                "The Adventures of Huckleberry Finn",
                "Mark Twain",
                "9780199536559",
            ),
        ];
        let args = GetRemoteCliArgs::builder()
            .format(Format::CSV)
            .display_optional(true)
            .build()
            .unwrap();
        print(&mut w, books, args).unwrap();
        assert_eq!(
            "title,author,isbn\nThe Catcher in the Rye,J.D. Salinger,0316769487\nThe Adventures of Huckleberry Finn,Mark Twain,9780199536559\n",
            String::from_utf8(w).unwrap()
        );
    }
}