1extern crate cmsis_pack;
2
3use std::fs::{create_dir_all, OpenOptions};
4use std::io::{BufRead, BufReader, Write};
5use std::path::PathBuf;
6
7use anyhow::Error;
8
9use cmsis_pack::update::DownloadConfig;
10
11use directories::ProjectDirs;
12
13pub struct Config {
14 pub pack_store: PathBuf,
15 pub vidx_list: PathBuf,
16}
17
18impl DownloadConfig for Config {
19 fn pack_store(&self) -> PathBuf {
20 self.pack_store.clone()
21 }
22}
23
24impl Config {
25 pub fn new() -> Result<Config, Error> {
26 let proj_dir = match ProjectDirs::from("", "", "cmsis-pack-manager") {
27 Some(p) => p,
28 None => return Err(anyhow::anyhow!("Could not determine home directory")),
29 };
30
31 let pack_store = proj_dir.config_dir().to_path_buf();
32 let mut vidx_list = proj_dir.config_dir().to_path_buf();
33 vidx_list.push("vendors.list");
34
35 Ok(Config {
36 pack_store,
37 vidx_list,
38 })
39 }
40
41 pub fn read_vidx_list(&self) -> Vec<String> {
42 let fd = OpenOptions::new().read(true).open(&self.vidx_list);
43 match fd.map_err(Error::from) {
44 Ok(r) => BufReader::new(r)
45 .lines()
46 .enumerate()
47 .flat_map(|(linenum, line)| {
48 line.map_err(|e| log::error!("Could not parse line #{}: {}", linenum, e))
49 .into_iter()
50 })
51 .collect(),
52 Err(_) => {
53 log::warn!("Failed to open vendor index list read only. Recreating.");
54 let new_content = vec![String::from("http://www.keil.com/pack/index.pidx")];
55 match self.vidx_list.parent() {
56 Some(par) => {
57 create_dir_all(par).unwrap_or_else(|e| {
58 log::error!(
59 "Could not create parent directory for vendor index list.\
60 Error: {}",
61 e
62 );
63 });
64 }
65 None => {
66 log::error!("Could not get parent directory for vendors.list");
67 }
68 }
69 match OpenOptions::new()
70 .create(true)
71 .truncate(true)
72 .write(true)
73 .open(&self.vidx_list)
74 {
75 Ok(mut fd) => {
76 let lines = new_content.join("\n");
77 fd.write_all(lines.as_bytes()).unwrap_or_else(|e| {
78 log::error!("Could not create vendor list file: {}", e);
79 });
80 }
81 Err(e) => {
82 log::error!("Could not open vendors index list file for writing {}", e)
83 }
84 }
85 new_content
86 }
87 }
88 }
89}