labt 0.3.4

Lab-t Lightweight Android build tool
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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
use std::collections::{HashMap, HashSet};
use std::fmt::Display;
use std::fs::{self, File};
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::str::FromStr;

use anyhow::{bail, Context};
use toml_edit::{value, ArrayOfTables, Document, Table};

use crate::config::repository::{ChannelType, Revision};
use crate::submodules::sdk::{get_sdk_path, toml_strings};

use super::ToId;

const INSTALLED_LIST: &str = "installed.toml";
const INSTALLED_LIST_OPEN_ERR: &str = "Failed to open sdk installed.toml";
const PACKAGE: &str = "package";
const ACCEPTED_LICENSES: &str = "accepted_licenses";
pub const SDK_PATH_ERR_STRING: &str = "Failed to get android sdk path";

#[derive(Debug, Default, PartialEq, Eq, Hash, Clone)]
pub struct InstalledPackage {
    pub path: String,
    pub version: Revision,
    pub channel: ChannelType,
    pub url: String,
    pub directory: Option<PathBuf>,
}
impl InstalledPackage {
    pub fn new(path: String, version: Revision, channel: ChannelType) -> Self {
        Self {
            path,
            version,
            channel,
            url: String::default(),
            directory: None,
        }
    }
}
impl ToId for InstalledPackage {
    fn create_id(&self) -> (&String, &Revision, &ChannelType) {
        (&self.path, &self.version, &self.channel)
    }
}

impl Display for InstalledPackage {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        writeln!(f, "{},{}", self.path, self.version)
    }
}

#[derive(Debug)]
pub struct InstalledListErr {
    kind: InstalledListErrKind,
    file: Option<String>,
}

impl InstalledListErr {
    pub fn new(kind: InstalledListErrKind, file: Option<String>) -> Self {
        Self { kind, file }
    }
}

#[derive(Debug)]
pub enum InstalledListErrKind {
    /// A required key in toml is missing
    MissingKey(&'static str, usize),
    /// Failed converting a toml value to string
    ToStringErr(&'static str, usize),
    /// Failed to read license id entry as string
    LicenseIdStrError(&'static str, usize),
}

impl Display for InstalledListErr {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        const UNKNOWN: &str = "[unknown]";
        match self.kind {
            InstalledListErrKind::MissingKey(key, position) => write!(
                f,
                "{}: Missing {} in table at position {}",
                self.file.as_ref().map_or(UNKNOWN, |p| p.as_str()),
                key,
                position
            ),
            InstalledListErrKind::ToStringErr(key, position) => write!(
                f,
                "{}: Failed to parse {} value as string on table at position {}",
                self.file.as_ref().map_or(UNKNOWN, |p| p.as_str()),
                key,
                position
            ),
            InstalledListErrKind::LicenseIdStrError(key, index) => write!(
                f,
                "{}: Failed to parse {} value as string at index {}",
                self.file.as_ref().map_or(UNKNOWN, |p| p.as_str()),
                key,
                index
            ),
        }
    }
}

impl std::error::Error for InstalledListErr {}

#[derive(Default, Debug)]
pub struct InstalledList {
    /// A list of licenses that the user pressed accept
    pub accepted_licenses: HashSet<String>,
    pub packages: Vec<InstalledPackage>,
}

impl InstalledList {
    pub fn new() -> Self {
        Self {
            packages: Vec::new(),
            accepted_licenses: HashSet::new(),
        }
    }
    /// Reads file from disk and parses it into an installed list struct
    pub fn from_file(path: &Path) -> anyhow::Result<Self> {
        if !path.exists() {
            return Ok(InstalledList::default());
        }

        let mut file = File::open(path)?;
        let mut data = String::new();
        file.read_to_string(&mut data)
            .context(format!("Failed to read ({:?})", path.to_string_lossy()))?;

        data.parse()
    }
    /// Reads the installed.toml from the standard sdk path and returns the resulting parsed list
    pub fn parse_from_sdk() -> anyhow::Result<Self> {
        let mut sdk = get_sdk_path().context(SDK_PATH_ERR_STRING)?;
        sdk.push(INSTALLED_LIST);

        Self::from_file(&sdk)
    }
    pub fn get_hash_map(&self) -> HashMap<String, &InstalledPackage> {
        self.packages.iter().map(|p| (p.to_id(), p)).collect()
    }
    pub fn contains(&self, package: &InstalledPackage) -> bool {
        self.packages.contains(package)
    }
    /// Searches for a package with a given path id. Returns first match.
    pub fn contains_path(&self, path: &String) -> Option<&InstalledPackage> {
        self.packages.iter().find(|p| p.path.eq(path))
    }
    /// Searches for a packages with a given path id. Returns all matches.
    pub fn contains_paths(&self, path: &String) -> Vec<&InstalledPackage> {
        self.packages.iter().filter(|p| p.path.eq(path)).collect()
    }
    /// Searches for a first occurence of a package using `InstalledPackage::to_id`
    pub fn contains_id(&self, package: &InstalledPackage) -> Option<&InstalledPackage> {
        self.packages.iter().find(|p| p.to_id() == package.to_id())
    }
    /// Searches for a first occurence of a package using `InstalledPackage::to_id`. Returns a mutable reference.
    pub fn contains_id_mut(&mut self, package: &InstalledPackage) -> Option<&mut InstalledPackage> {
        self.packages
            .iter_mut()
            .find(|p| p.to_id() == package.to_id())
    }
    /// This will push a package to the end of the list without checking for its existence
    pub fn add_installed_package(&mut self, package: InstalledPackage) {
        self.packages.push(package);
    }
    /// This will try to find a package with same id and replace it with the new package or
    /// add it at the end of package list if missing.
    /// This function uses the package id (`to_id`) to search for matches.
    pub fn insert_installed_package(&mut self, package: InstalledPackage) {
        if let Some(p) = self.contains_id_mut(&package) {
            *p = package;
        } else {
            self.add_installed_package(package);
        }
    }
    /// Removes a package from the list of packages with matching id
    /// This function uses the package id (`to_id`) to search for matches.
    pub fn remove_installed_package(&mut self, package: &InstalledPackage) {
        if let Some((i, _)) = self
            .packages
            .iter()
            .enumerate()
            .find(|(_, p)| p.to_id() == package.to_id())
        {
            self.packages.remove(i);
        }
    }
    /// Checks if user has already accepted a license.
    /// This allows displaying of license for only one time
    pub fn has_accepted(&self, license_id: &String) -> bool {
        self.accepted_licenses.contains(license_id)
    }
    /// Marks a license as accepted so we don't have to nag the user again to accept
    pub fn accept_license(&mut self, license_id: String) {
        self.accepted_licenses.insert(license_id);
    }
    pub fn save_to_file(&mut self) -> anyhow::Result<()> {
        let mut sdk = get_sdk_path().context(SDK_PATH_ERR_STRING)?;
        sdk.push(INSTALLED_LIST);

        let mut file = File::create(&sdk).context(format!(
            "Failed to open/create ({:?}) to write installed package list.",
            sdk
        ))?;

        file.write_all(self.to_string().as_bytes())?;

        Ok(())
    }
}

impl FromStr for InstalledList {
    type Err = anyhow::Error;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        use toml_strings::*;
        let doc: Document = s
            .parse()
            .context(format!("Failed to parse {INSTALLED_LIST}"))?;

        let mut accepted_licenses: HashSet<String> = HashSet::new();
        if doc.contains_key(ACCEPTED_LICENSES) {
            if let Some(list) = doc[ACCEPTED_LICENSES].as_array() {
                for (i, value) in list.iter().enumerate() {
                    let id = value
                        .as_str()
                        .ok_or_else(|| {
                            InstalledListErr::new(
                                InstalledListErrKind::LicenseIdStrError(ACCEPTED_LICENSES, i),
                                Some(INSTALLED_LIST.to_string()),
                            )
                        })?
                        .to_string();
                    accepted_licenses.insert(id);
                }
            }
        }

        let mut package_list: Vec<InstalledPackage> = Vec::new();
        if doc.contains_array_of_tables(PACKAGE) {
            if let Some(packages) = doc[PACKAGE].as_array_of_tables() {
                for package in packages {
                    let mut p = InstalledPackage::default();
                    let position = package.position().unwrap_or(0);

                    // parse path
                    if let Some(path) = package.get(PATH) {
                        p.path = path
                            .as_str()
                            .ok_or_else(|| {
                                InstalledListErr::new(
                                    InstalledListErrKind::ToStringErr(PATH, position),
                                    Some(INSTALLED_LIST.to_string()),
                                )
                            })?
                            .to_string();
                    } else {
                        bail!(InstalledListErr::new(
                            InstalledListErrKind::MissingKey(PATH, position),
                            Some(INSTALLED_LIST.to_string()),
                        ));
                    }

                    // parse url
                    if let Some(url) = package.get(URL) {
                        p.url = url
                            .as_str()
                            .ok_or_else(|| {
                                InstalledListErr::new(
                                    InstalledListErrKind::ToStringErr(URL, position),
                                    Some(INSTALLED_LIST.to_string()),
                                )
                            })?
                            .to_string();
                    } else {
                        bail!(InstalledListErr::new(
                            InstalledListErrKind::MissingKey(URL, position),
                            Some(INSTALLED_LIST.to_string()),
                        ));
                    }

                    // parse version
                    if let Some(version) = package.get(VERSION) {
                        p.version = version
                            .as_str()
                            .ok_or_else(|| {
                                InstalledListErr::new(
                                    InstalledListErrKind::ToStringErr(VERSION, position),
                                    Some(INSTALLED_LIST.to_string()),
                                )
                            })?
                            .parse()
                            .context("Failed to parse version string to revision")?;
                    } else {
                        bail!(InstalledListErr::new(
                            InstalledListErrKind::MissingKey(VERSION, position),
                            Some(INSTALLED_LIST.to_string()),
                        ));
                    }

                    // parse channel
                    if let Some(channel) = package.get(CHANNEL) {
                        p.channel = channel
                            .as_str()
                            .ok_or_else(|| {
                                InstalledListErr::new(
                                    InstalledListErrKind::ToStringErr(CHANNEL, position),
                                    Some(INSTALLED_LIST.to_string()),
                                )
                            })?
                            .into();
                    } else {
                        bail!(InstalledListErr::new(
                            InstalledListErrKind::MissingKey(CHANNEL, position),
                            Some(INSTALLED_LIST.to_string()),
                        ));
                    }

                    // parse directory
                    if let Some(directory) = package.get(DIRECTORY) {
                        p.directory = Some(
                            directory
                                .as_str()
                                .ok_or_else(|| {
                                    InstalledListErr::new(
                                        InstalledListErrKind::ToStringErr(DIRECTORY, position),
                                        Some(INSTALLED_LIST.to_string()),
                                    )
                                })?
                                .into(),
                        );
                    }

                    package_list.push(p);
                }
            }
        }
        let installed = Self {
            packages: package_list,
            accepted_licenses,
        };
        Ok(installed)
    }
}

impl Display for InstalledList {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut doc = toml_edit::Document::new();

        let mut packages = toml_edit::ArrayOfTables::new();
        let mut licenses: Vec<&String> = self.accepted_licenses.iter().collect();
        licenses.sort_unstable();

        let mut accepted = toml_edit::Array::new();
        for id in licenses {
            accepted.push(id);
        }
        doc.insert(ACCEPTED_LICENSES, toml_edit::value(accepted));

        for package in &self.packages {
            let mut table = toml_edit::Table::new();
            table.insert(toml_strings::PATH, value(&package.path));
            table.insert(toml_strings::VERSION, value(package.version.to_string()));
            table.insert(toml_strings::CHANNEL, value(package.channel.to_string()));
            if let Some(dir) = &package.directory {
                table.insert(
                    toml_strings::DIRECTORY,
                    value(dir.to_string_lossy().to_string()),
                );
            }
            table.insert(toml_strings::URL, value(&package.url));

            packages.push(table);
        }

        doc.insert(PACKAGE, toml_edit::Item::ArrayOfTables(packages));
        write!(f, "{}", doc)
    }
}

/// Writes the provided hashset to a installed.list file in sdk folder
/// Order is not guaranteed as it is a hashmap
pub fn write_installed_list(
    list: Vec<InstalledPackage>,
    writer: &mut dyn Write,
) -> anyhow::Result<()> {
    // let mut sdk = get_sdk_path().context(SDK_PATH_ERR_STRING)?;
    // sdk.push(INSTALLED_LIST);

    let mut doc = toml_edit::Document::new();

    // let mut file = File::create(&sdk).context(INSTALLED_LIST_OPEN_ERR)?;

    let mut packages = toml_edit::ArrayOfTables::new();

    for package in list {
        let mut table = toml_edit::Table::new();
        table.insert(toml_strings::PATH, value(&package.path));
        table.insert(toml_strings::VERSION, value(package.version.to_string()));
        table.insert(toml_strings::CHANNEL, value(package.channel.to_string()));
        if let Some(dir) = package.directory {
            table.insert(
                toml_strings::DIRECTORY,
                value(dir.to_string_lossy().to_string()),
            );
        }
        table.insert(toml_strings::URL, value(package.url));

        packages.push(table);
    }

    doc.insert(PACKAGE, toml_edit::Item::ArrayOfTables(packages));
    writer.write_all(doc.to_string().as_bytes())?;
    // .context(format!(
    //     "Failed to write installed sdk package list to {}",
    //     sdk.to_string_lossy()
    // ))?;

    Ok(())
}

/// Inserts or updates an installed package entry on installed list
pub fn update_installed_list(
    package: InstalledPackage,
) -> anyhow::Result<HashMap<String, InstalledPackage>> {
    let mut sdk = get_sdk_path().context(SDK_PATH_ERR_STRING)?;
    sdk.push(INSTALLED_LIST);

    let mut installed: HashMap<String, InstalledPackage> = HashMap::new();

    if !sdk.exists() {
        let mut file = File::create(&sdk).context(INSTALLED_LIST_OPEN_ERR)?;
        write_installed_list(vec![package.clone()], &mut file)?;
        installed.insert(package.to_id(), package);
        return Ok(installed);
    }

    let data = fs::read_to_string(&sdk).context(format!("Failed to read ({:?})", sdk))?;
    let mut doc: Document = data
        .parse()
        .context(format!("Failed to parse ({:?})", sdk))?;

    let mut array = doc[PACKAGE]
        .as_array_of_tables()
        .map_or(ArrayOfTables::default(), |t| t.to_owned());

    let mut table = Table::new();
    table.insert(toml_strings::PATH, value(&package.path));
    table.insert(toml_strings::VERSION, value(package.version.to_string()));
    table.insert(toml_strings::CHANNEL, value(package.channel.to_string()));
    table.insert(toml_strings::URL, value(&package.url));
    if let Some(dir) = &package.directory {
        table.insert(
            toml_strings::DIRECTORY,
            value(dir.to_string_lossy().to_string()),
        );
    }

    array.push(table);

    let mut table = Table::new();
    table.insert(toml_strings::PATH, value(&package.path));
    table.insert(toml_strings::VERSION, value(package.version.to_string()));
    table.insert(toml_strings::CHANNEL, value(package.channel.to_string()));
    table.insert(toml_strings::URL, value(&package.url));
    if let Some(dir) = package.directory {
        table.insert(
            toml_strings::DIRECTORY,
            value(dir.to_string_lossy().to_string()),
        );
    }

    array.push(table);
    doc.insert(PACKAGE, toml_edit::Item::ArrayOfTables(array));

    println!("{}", doc);

    Ok(installed)
}

#[cfg(test)]
mod installed_list_test {
    use crate::{
        config::repository::{ChannelType, Revision},
        submodules::sdkmanager::ToId,
    };

    use super::{InstalledList, InstalledPackage};

    #[test]
    fn add_package() {
        let package_1: InstalledPackage = InstalledPackage {
            path: "sdk:package1".to_string(),
            version: Revision::new(1),
            channel: ChannelType::Stable,
            url: "gitlab.com".to_string(),
            directory: None,
        };

        let mut list = InstalledList::new();
        list.add_installed_package(package_1.clone());

        assert!(list.packages.contains(&package_1));
    }

    #[test]
    fn insert_package() {
        let package_1: InstalledPackage = InstalledPackage {
            path: "sdk:package1".to_string(),
            version: Revision::new(1),
            channel: ChannelType::Stable,
            url: "gitlab.com".to_string(),
            directory: None,
        };
        let package_2: InstalledPackage = InstalledPackage {
            path: "sdk:package2".to_string(),
            version: Revision::new(1),
            channel: ChannelType::Stable,
            url: "gitlab.com".to_string(),
            directory: None,
        };

        let mut list = InstalledList::new();
        list.add_installed_package(package_1.clone());
        list.add_installed_package(package_2.clone());

        // insert a package not available in list
        let package_3: InstalledPackage = InstalledPackage {
            path: "sdk:package3".to_string(),
            version: Revision::new(1),
            channel: ChannelType::Stable,
            url: "gitlab.com".to_string(),
            directory: None,
        };

        list.insert_installed_package(package_3);
        assert!(list.packages.len().eq(&3), "List length is not equal to 3");

        // try to re update package 1
        let package_1 = InstalledPackage {
            url: "example.com".to_string(),
            ..package_1
        };

        list.insert_installed_package(package_1.clone());
        assert!(list.packages.len().eq(&3), "List length is not equal to 3");

        assert_eq!(list.packages[0].url, package_1.url);
    }
    #[test]
    fn installed_package_list_from_str() {
        let toml = r#"
[[package]]
path = "extras;google;auto"
version = "2.0.0.0"
channel = "stable"
url = "http://example.com"
"#;

        let result: InstalledList = toml.parse().unwrap();
        let mut iter = result.packages.iter();
        let value: &InstalledPackage = iter.next().unwrap();

        let package = InstalledPackage {
            path: "extras;google;auto".to_string(),
            version: "2.0.0.0".parse().unwrap(),
            channel: ChannelType::Stable,
            url: "http://example.com".to_string(),
            directory: None,
        };

        assert_eq!(value.to_id(), package.to_id());
        assert_eq!(value, &package);
    }
    #[test]
    fn installed_package_list_to_toml() {
        let mut list = InstalledList::new();

        let package = InstalledPackage {
            path: "extras;google;auto".to_string(),
            version: "2.0.0.0".parse().unwrap(),
            channel: ChannelType::Stable,
            url: "http://example.com".to_string(),
            directory: None,
        };

        list.add_installed_package(package.clone());

        let toml = r#"
accepted_licenses = []

[[package]]
path = "extras;google;auto"
version = "2.0.0.0"
channel = "stable"
url = "http://example.com"
"#;
        assert_eq!(list.to_string(), toml.trim_start());
    }
}