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
use std::{collections::HashMap, fs, path::PathBuf};

use crate::{
    cli::{CommitOperationArguments, SetClipboardCommands, SetFormat, UseTemplate},
    file_utils::config_file::get_path_to_config,
};
use anyhow::{Error, Result};
use regex::Regex;
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
pub struct GitConfig {
    pub data: Data,
    config_path: PathBuf,
}

type Variants = HashMap<String, String>;

#[derive(Debug, Serialize, Deserialize)]
pub struct ClipboardCommands {
    pub copy: String,
    pub paste: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Data {
    pub clipboard_commands: ClipboardCommands,
    pub commit_template_variants: Variants,
    pub branch_template_variants: Variants,
    pub branch_prefix_variants: Variants,
    pub autocomplete_values: Option<Vec<String>>,
}

pub struct Templates {
    pub commit_template_variants: Variants,
    pub branch_template_variants: Variants,
}

pub enum BranchOrCommitAction {
    Commit(CommitOperationArguments),
    BranchFromTemplate(UseTemplate),
}

impl Data {
    fn default() -> Self {
        Data {
            clipboard_commands: ClipboardCommands {
                copy: "pbcopy".to_string(),
                paste: "pbpaste".to_string(),
            },
            commit_template_variants: HashMap::new(),
            branch_template_variants: HashMap::new(),
            branch_prefix_variants: HashMap::new(),
            autocomplete_values: None,
        }
    }
}

impl GitConfig {
    fn default_config() -> Self {
        return GitConfig {
            data: Data::default(),
            config_path: get_path_to_config(None).to_path_buf(),
        };
    }

    pub fn new_config(
        clipboard_commands: ClipboardCommands,
        branch_prefix_variants: Variants,
        branch_format_variants: Variants,
        commit_format_variants: Variants,
        config_path: Option<PathBuf>,
    ) -> Self {
        return GitConfig {
            data: Data {
                clipboard_commands,
                branch_template_variants: branch_format_variants,
                commit_template_variants: commit_format_variants,
                branch_prefix_variants,
                autocomplete_values: None,
            },
            config_path: if let Some(config_path) = config_path {
                config_path
            } else {
                get_path_to_config(None).to_path_buf()
            },
        };
    }

    pub fn from_file(path_to_file: PathBuf) -> Self {
        if fs::metadata(&path_to_file).is_ok() {
            let contents = fs::read_to_string(&path_to_file);
            let contents = contents.unwrap_or(
                "{\
                    \"clipboard_commands\": {}, \
                    \"branch_template_variants\": {}, \
                    \"commit_template_variants\": {}, \
                    \"branch_prefix_variants\": {}
                }"
                .to_string(),
            );

            let data = serde_json::from_str(&contents);
            let data: Data = data.unwrap_or(Data::default());

            GitConfig {
                data: data,
                config_path: path_to_file,
            }
        } else {
            Self::default_config()
        }
    }

    pub fn validate_against_interpolation_regex<'a>(
        string_to_interpolate: &'a String,
        name_of_field_to_check: &'static str,
    ) -> Result<&'a String> {
        let interpolation_regex = Regex::new(r"\{.*?\}").unwrap();
        if interpolation_regex.is_match(string_to_interpolate) {
            return Ok(string_to_interpolate);
        };
        return Err(Error::msg(format!(
            "There was no interpolation signature: {{}} introduced in {name_of_field_to_check}"
        )));
    }

    pub fn set_branch_template_variant(&mut self, arg: SetFormat) -> Result<()> {
        let result = Self::validate_against_interpolation_regex(&arg.value, "branch_template");
        match result {
            Err(e) => panic!("{}", e),
            Ok(_) => self
                .data
                .branch_template_variants
                .insert(arg.key, arg.value),
        };
        self.save_to_file()
    }

    pub fn set_commit_template_variant(&mut self, arg: SetFormat) -> Result<()> {
        let result = Self::validate_against_interpolation_regex(&arg.value, "commit_template");
        match result {
            Err(e) => panic!("{}", e),
            Ok(_) => {
                self.data
                    .commit_template_variants
                    .insert(arg.key, arg.value);
            }
        };
        self.save_to_file()
    }

    pub fn set_branch_prefix_variant(&mut self, key: String, value: String) -> Result<()> {
        self.data.branch_prefix_variants.insert(key, value);
        self.save_to_file()
    }

    pub fn set_clipboard_command(&mut self, args: SetClipboardCommands) -> Result<()> {
        let new_clipboard_commands = ClipboardCommands {
            copy: args.copy,
            paste: args.paste,
        };

        self.data.clipboard_commands = new_clipboard_commands;
        self.save_to_file()
    }

    pub fn delete_branch_prefix_variant(&mut self, key: String) -> Result<()> {
        let old_val = self.data.branch_prefix_variants.remove(&key);
        println!(
            "Removed {} : {} from config ",
            key,
            old_val.unwrap_or(String::from("None"))
        );
        self.save_to_file()
    }

    fn save_to_file(&self) -> Result<()> {
        if let Some(dir) = self.config_path.parent() {
            if !std::fs::metadata(&dir).is_ok() {
                std::fs::create_dir_all(dir)?;
            }
        };

        let contents = serde_json::to_string(&self.data)?;
        std::fs::write(&self.config_path, contents)?;
        return Ok(());
    }

    pub fn display_config(&self) -> Result<String> {
        let clipboard_command = &self.data.clipboard_commands;
        let copy = &clipboard_command.copy;
        let paste = &clipboard_command.paste;
        let branch = self.data.branch_template_variants.to_owned();
        let commit = self.data.commit_template_variants.to_owned();
        let prefixes = self.data.branch_prefix_variants.to_owned();

        Ok(format!(
            "
        clipboard commands: {{
            \"copy\": {:?}
            \"paste\": {:?}
        }}
        branch formats: {:?} 
        commit formats: {:?} 
        branch prefixes: {:?} 
        ",
            *copy, *paste, branch, commit, prefixes
        ))
    }
}