nvim_gtk/
nvim_config.rs

1use std::path::PathBuf;
2use std::fs::{remove_file, OpenOptions};
3use std::io::Write;
4
5use crate::dirs;
6use crate::plug_manager;
7
8#[derive(Clone)]
9pub struct NvimConfig {
10    plug_config: Option<plug_manager::PlugManagerConfigSource>,
11}
12
13impl NvimConfig {
14    const CONFIG_PATH: &'static str = "settings.vim";
15
16    pub fn new(plug_config: Option<plug_manager::PlugManagerConfigSource>) -> Self {
17        NvimConfig { plug_config }
18    }
19
20    pub fn generate_config(&self) -> Option<PathBuf> {
21        if self.plug_config.is_some() {
22            match self.write_file() {
23                Err(err) => {
24                    error!("{}", err);
25                    None
26                }
27                Ok(file) => Some(file),
28            }
29        } else {
30            NvimConfig::config_path().map(remove_file);
31            None
32        }
33    }
34
35    pub fn config_path() -> Option<PathBuf> {
36        if let Ok(mut path) = dirs::get_app_config_dir() {
37            path.push(NvimConfig::CONFIG_PATH);
38            if path.is_file() {
39                return Some(path);
40            }
41        }
42
43        None
44    }
45
46    fn write_file(&self) -> Result<PathBuf, String> {
47        let mut config_dir = dirs::get_app_config_dir_create()?;
48        config_dir.push(NvimConfig::CONFIG_PATH);
49
50        let mut file = OpenOptions::new()
51            .create(true)
52            .write(true)
53            .truncate(true)
54            .open(&config_dir)
55            .map_err(|e| format!("{}", e))?;
56
57        let content = &self.plug_config.as_ref().unwrap().source;
58        if !content.is_empty() {
59            debug!("{}", content);
60            file.write_all(content.as_bytes()).map_err(
61                |e| format!("{}", e),
62            )?;
63        }
64
65        file.sync_all().map_err(|e| format!("{}", e))?;
66        Ok(config_dir)
67    }
68}