kdeets 0.1.30

Query crates.io for information about a crate.
Documentation
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
use crate::Error;

use clap::Parser;
use clap_verbosity::Verbosity;
use colorful::Colorful;
use smol_str::SmolStr;
use tame_index::{IndexKrate, KrateName, index::FileLock};

#[derive(Parser, Debug, Default)]
#[clap(author, version, about, long_about = None)]
pub struct CrateVersions {
    #[clap(flatten)]
    logging: Verbosity,
    /// The name of the crate
    crate_: String,
    /// Display bare version number without text for recent, highest normal, higest or earliest version.
    #[clap(short = 'b', long = "bare")]
    bare: bool,
    /// First version ever published. May be yanked.
    #[clap(short = 'e', long = "earliest")]
    earliest: bool,
    /// Returns crate version with the highest version number according to semver, but excludes pre-release and yanked versions.
    #[clap(short = 'n', long = "normal")]
    normal: bool,
    /// The highest version as per semantic versioning specification
    #[clap(short = 't', long = "top")]
    highest: bool,
    /// The last release by date, even if it’s yanked or less than highest version.
    #[clap(short = 'r', long = "recent")]
    recent: bool,
    /// List all versions of the crate
    #[clap(short = 'l', long = "list")]
    list: bool,
    /// List key values (equivalent to `-entr`)
    #[clap(short = 'k', long = "key")]
    key: bool,
    /// List all versions and key values (equivalent to `-entrl`)
    #[clap(short = 'a', long = "all")]
    all: bool,

    #[clap(skip)]
    output: String,
}

impl CrateVersions {
    pub fn run(&mut self, no_colour: bool) -> Result<String, Error> {
        log::info!("Getting details for crate: {}", self.crate_);
        let lock = FileLock::unlocked();
        let index = crate::get_remote_combo_index()?;
        let index_crate = index.krate(KrateName::crates_io(&self.crate_)?, true, &lock)?;

        let Some(index_crate) = index_crate else {
            return Err(Error::CrateNotFoundOnIndex);
        };

        if self.bare {
            self.output = if self.recent {
                index_crate.most_recent_version().version.to_string()
            } else if self.highest {
                index_crate.highest_version().version.to_string()
            } else if self.normal {
                index_crate
                    .highest_normal_version()
                    .unwrap_or_else(|| index_crate.highest_version())
                    .version
                    .to_string()
            } else {
                index_crate.earliest_version().version.to_string()
            }
        } else {
            self.append_header(no_colour, index_crate.name());

            if self.earliest | self.all | self.key {
                let description = "Earliest version";
                let version = &index_crate.earliest_version().version;
                let colour = TextColour::None;
                self.append_specific_version(description, version, colour);
            };

            if self.normal | self.all | self.key {
                let description = "Highest normal version";
                let version = &index_crate
                    .highest_normal_version()
                    .unwrap_or_else(|| index_crate.highest_version())
                    .version;
                let colour = if no_colour {
                    TextColour::None
                } else {
                    TextColour::Blue
                };
                self.append_specific_version(description, version, colour);
            };

            if self.highest | self.all | self.key {
                let description = "Highest version";
                let version = &index_crate.highest_version().version;
                let colour = if no_colour {
                    TextColour::None
                } else {
                    TextColour::Green
                };
                self.append_specific_version(description, version, colour);
            };

            if self.recent | self.all | self.key {
                let description = "Most recent version";
                let version = &index_crate.most_recent_version().version;
                let colour = if no_colour {
                    TextColour::None
                } else {
                    TextColour::Yellow
                };
                self.append_specific_version(description, version, colour);
            };

            if self.list | self.all {
                self.append_list(index_crate, no_colour);
            }
        };

        Ok(self.output.to_string())
    }

    fn append_header(&mut self, no_colour: bool, crate_name: &str) {
        let output = format!(
            "\n {}",
            if no_colour {
                format!("Crate versions for {crate_name}.")
            } else {
                format!("Crate versions for {}.", crate_name.cyan())
                    .bold()
                    .to_string()
            }
        );

        let mut i = 0;
        let mut line = String::from(" ");

        while i < 20 + crate_name.len() {
            line.push('đŸ­¶');
            i += 1;
        }

        self.output = format!("{output}\n{line}\n");
    }

    fn append_specific_version(
        &mut self,
        description: &str,
        version: &SmolStr,
        colour: TextColour,
    ) {
        let addition = format!("{description}: {version}");
        let addition = colour.paint(addition);
        self.output = format!("{}   {}\n", self.output, addition)
    }

    fn append_list(&mut self, index_crate: IndexKrate, no_colour: bool) {
        const BASE_HEADER: &str = " Yanked  Version ";

        let mut header = BASE_HEADER.to_string();

        let rows = index_crate
            .versions
            .iter()
            .map(|x| {
                format!(
                    "   {}     {}",
                    match (x.yanked, no_colour) {
                        (true, true) => "Yes".to_string(),
                        (false, true) => " No".to_string(),
                        (true, false) => "Yes".red().to_string(),
                        (false, false) => " No".green().to_string(),
                    },
                    x.version
                )
            })
            .collect::<Vec<String>>();

        log::debug!("Rows: {rows:#?}!");

        let max_row = &rows
            .iter()
            .map(|x| {
                log::debug!("Line: `{}`, len: `{}`!", x, x.chars().count(),);
                x.len() - 12
            })
            .max()
            .unwrap_or(BASE_HEADER.len());
        log::debug!("Max row length: {max_row}!");

        while header.len() < *max_row {
            header = format!("{header} ");
        }
        log::debug!("Output: {}!", self.output);
        log::debug!("Header: {header}!");

        let rows = format!("   {}\n", rows.join("\n   "));

        self.output = format!(
            "{}   {}\n{}",
            self.output,
            if no_colour {
                header.to_string()
            } else {
                header.underlined().to_string()
            },
            rows
        );
    }
}

enum TextColour {
    None,
    Blue,
    Green,
    Yellow,
}

impl TextColour {
    fn paint(&self, text: String) -> String {
        match self {
            TextColour::None => text,
            TextColour::Blue => text.blue().to_string(),
            TextColour::Green => text.green().to_string(),
            TextColour::Yellow => text.yellow().to_string(),
        }
    }
}

#[cfg(test)]
mod tests {

    use colorful::Colorful;
    use rstest::fixture;

    use crate::crate_versions::CrateVersions;

    #[fixture]
    fn header(#[default("some_crate")] name: &str) -> String {
        let output = format!(
            "\n {}",
            format!("Crate versions for {}.", name.cyan()).bold()
        );

        let mut i = 0;
        let mut line = String::from(" ");

        while i < 20 + name.len() {
            line.push('đŸ­¶');
            i += 1;
        }

        format!("{output}\n{line}\n")
    }

    #[fixture]
    fn earliest() -> String {
        "   Earliest version: 0.1.0\n".to_string()
    }

    #[fixture]
    fn highest_normal() -> String {
        format!("   {}\n", "Highest normal version: 0.2.1".blue())
    }

    #[fixture]
    fn highest() -> String {
        format!("   {}\n", "Highest version: 0.2.1".green())
    }

    #[fixture]
    fn recent() -> String {
        format!("   {}\n", "Most recent version: 0.2.1".yellow())
    }

    #[fixture]
    fn list() -> String {
        "   \u{1b}[4m Yanked  Version \u{1b}[0m\n      \u{1b}[38;5;2m No\u{1b}[0m     0.1.0\n      \u{1b}[38;5;2m No\u{1b}[0m     0.1.1\n      \u{1b}[38;5;2m No\u{1b}[0m     0.1.3\n      \u{1b}[38;5;2m No\u{1b}[0m     0.2.1\n"
        .to_string()
    }

    #[test]
    fn test_run_earliest() {
        let name = "some_crate";
        let expected = format!("{}{}", header(name), &earliest());

        let mut crate_versions = CrateVersions {
            crate_: "some_crate".to_string(),
            earliest: true,
            ..Default::default()
        };

        assert_eq!(crate_versions.crate_, "some_crate".to_string());
        assert!(crate_versions.earliest);
        assert!(!crate_versions.normal);
        assert!(!crate_versions.highest);
        assert!(!crate_versions.recent);
        assert!(!crate_versions.list);
        assert!(!crate_versions.all);
        assert!(!crate_versions.key);

        let result = crate_versions.run(false);
        assert!(result.is_ok());
        let output = result.unwrap();
        assert_eq!(output, expected);
    }

    #[test]
    fn test_run_normal() {
        let name = "some_crate";
        let expected = format!("{}{}", header(name), &highest_normal());

        let mut crate_versions = CrateVersions {
            crate_: "some_crate".to_string(),
            normal: true,
            ..Default::default()
        };

        let result = crate_versions.run(false);
        assert!(result.is_ok());
        let output = result.unwrap();
        assert_eq!(output, expected);
    }

    #[test]
    fn test_run_top() {
        let name = "some_crate";
        let expected = format!("{}{}", header(name), &highest());

        let mut crate_versions = CrateVersions {
            crate_: "some_crate".to_string(),
            highest: true,
            ..Default::default()
        };

        let result = crate_versions.run(false);
        assert!(result.is_ok());
        let output = result.unwrap();
        assert_eq!(output, expected);
    }

    #[test]
    fn test_run_recent() {
        let name = "some_crate";
        let expected = format!("{}{}", header(name), &recent());

        let mut crate_versions = CrateVersions {
            crate_: "some_crate".to_string(),
            recent: true,
            ..Default::default()
        };

        let result = crate_versions.run(false);
        assert!(result.is_ok());
        let output = result.unwrap();
        assert_eq!(output, expected);
    }

    #[test]
    fn test_run_list() {
        let name = "some_crate";
        let expected = format!("{}{}", header(name), &list());

        let mut crate_versions = CrateVersions {
            crate_: "some_crate".to_string(),
            list: true,
            ..Default::default()
        };

        let result = crate_versions.run(false);
        assert!(result.is_ok());
        let output = result.unwrap();
        assert_eq!(output, expected);
    }

    #[test]
    fn test_run_all() {
        let name = "some_crate";
        let expected = format!(
            "{}{}{}{}{}{}",
            header(name),
            &earliest(),
            &highest_normal(),
            &highest(),
            &recent(),
            &list()
        );

        let mut crate_versions = CrateVersions {
            crate_: "some_crate".to_string(),
            all: true,
            ..Default::default()
        };

        let result = crate_versions.run(false);
        assert!(result.is_ok());
        let output = result.unwrap();
        println!("Expected:\n`{expected}`\n\nGot:\n`{output}`");
        assert_eq!(output, expected);
    }

    #[test]
    fn test_run_key() {
        let name = "some_crate";
        let expected = format!(
            "{}{}{}{}{}",
            header(name),
            &earliest(),
            &highest_normal(),
            &highest(),
            &recent(),
        );

        let mut crate_versions = CrateVersions {
            crate_: "some_crate".to_string(),
            key: true,
            ..Default::default()
        };

        let result = crate_versions.run(false);
        assert!(result.is_ok());
        let output = result.unwrap();
        assert_eq!(output, expected);
    }

    #[test]
    fn test_run_invalid_crate() {
        let mut crate_versions = CrateVersions {
            crate_: "some_non-existing_crate".to_string(),
            ..Default::default()
        };

        let result = crate_versions.run(false);
        assert!(result.is_err());
    }

    #[test]
    fn test_run_invalid_crate_earliest() {
        let mut crate_versions = CrateVersions {
            crate_: "sdc_apis".to_string(),
            earliest: true,
            ..Default::default()
        };

        let result = crate_versions.run(false);
        assert!(result.is_ok());
    }
}