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
use anyhow::{Context, Result};

use log::debug;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap};
use std::fs;
use std::io::ErrorKind;
use std::path::PathBuf;

use crate::error::ProjectError;

#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct ProjectData {
    pub manifest: HashMap<String, String>,
}

#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct AndaConfig {
    pub project: BTreeMap<String, Project>,
}

impl AndaConfig {
    pub fn find_key_for_value(&self, value: &Project) -> Option<&String> {
        self.project.iter().find_map(|(key, val)| {
            if val == value {
                Some(key)
            } else {
                None
            }
        })
    }
}

#[derive(Deserialize, PartialEq, Eq, Serialize, Debug, Clone)]
pub struct Project {
    pub rpm: Option<RpmBuild>,
    pub podman: Option<Docker>,
    pub docker: Option<Docker>,
    pub flatpak: Option<Flatpak>,
    pub pre_script: Option<PreScript>,
    pub post_script: Option<PostScript>,
    pub env: Option<BTreeMap<String, String>>,
}
#[derive(Deserialize, Eq, PartialEq, Hash, PartialOrd, Ord, Serialize, Debug, Clone)]
pub struct PreScript {
    pub commands: Vec<String>,
}

#[derive(Deserialize, Eq, PartialEq, Hash, Serialize, Debug, Clone)]
pub struct PostScript {
    pub commands: Vec<String>,
}

#[derive(Deserialize, PartialEq, Eq, Serialize, Debug, Clone)]
pub struct RpmBuild {
    pub spec: PathBuf,
    pub sources: Option<PathBuf>,
    pub package: Option<String>,
    pub pre_script: Option<PreScript>,
    pub post_script: Option<PostScript>,
    pub enable_scm: Option<bool>,
    pub scm_opts: Option<BTreeMap<String, String>>,
    pub config: Option<BTreeMap<String, String>>,
    pub mock_config: Option<String>,
    pub plugin_opts: Option<BTreeMap<String, String>>,
}

#[derive(Deserialize, PartialEq, Eq, Serialize, Debug, Clone)]
pub struct Docker {
    pub image: BTreeMap<String, DockerImage>, // tag, file
}

#[derive(Deserialize, PartialEq, Eq, Serialize, Debug, Clone)]
pub struct DockerImage {
    pub dockerfile: Option<String>,
    pub import: Option<PathBuf>,
    pub tag_latest: Option<bool>,
    pub context: String,
    pub version: Option<String>,
}

#[derive(Deserialize, PartialEq, Eq, Serialize, Debug, Clone)]
pub struct Flatpak {
    pub manifest: PathBuf,
    pub pre_script: Option<PreScript>,
    pub post_script: Option<PostScript>,
}

pub fn load_from_file(path: &PathBuf) -> Result<AndaConfig, ProjectError> {
    let file = fs::read_to_string(path).map_err(|e| match e.kind() {
        ErrorKind::NotFound => ProjectError::NoManifest,
        _ => ProjectError::InvalidManifest(e.to_string()),
    })?;

    let mut config = load_from_string(&file)?;
    debug!("Loading config from {}", path.display());

    // recursively merge configs

    // get parent path of config file
    let parent = if path.parent().unwrap().to_str().unwrap() == "" {
        PathBuf::from(".")
    } else {
        path.parent().unwrap().to_path_buf()
    };

    let walk = ignore::Walk::new(parent);

    for entry in walk {
        // debug!("Loading config from {:?}", entry);
        let entry = entry.unwrap();

        // check if path is same path as config file
        if entry.path().strip_prefix("./").unwrap() == path {
            continue;
        }

        if entry.file_type().unwrap().is_file() && entry.path().file_name().unwrap() == "anda.hcl" {
            let readfile = fs::read_to_string(entry.path())
                .map_err(|e| ProjectError::InvalidManifest(e.to_string()))?;

            let nested_config = prefix_config(
                load_from_string(&readfile)?,
                &entry
                    .path()
                    .parent()
                    .unwrap()
                    .strip_prefix("./")
                    .unwrap()
                    .display()
                    .to_string(),
            );
            // merge the btreemap
            config.project.extend(nested_config.project);
        }
    }

    debug!("Loaded config: {:#?}", config);
    //let config = config.map_err(ProjectError::HclError);

    check_config(config)
}

pub fn prefix_config(config: AndaConfig, prefix: &str) -> AndaConfig {
    let mut new_config = config.clone();

    for (project_name, project) in config.project.iter() {
        // set project name to prefix
        let new_project_name = format!("{}/{}", prefix, project_name);
        // modify project data
        let mut new_project = project.clone();

        if let Some(rpm) = &mut new_project.rpm {
            rpm.spec = PathBuf::from(format!("{}/{}", prefix, rpm.spec.display()));
            if let Some(sources) = &mut rpm.sources {
                *sources = PathBuf::from(format!("{}/{}", prefix, sources.display()));
            }
        }

        new_config.project.remove(project_name);
        new_config.project.insert(new_project_name, new_project);
    }

    new_config
}

pub fn load_from_string(config: &str) -> Result<AndaConfig, ProjectError> {
    let config = hcl::from_str(config).context("Failed to parse config file")?;
    check_config(config)
}

// Lints and checks the config for errors.
pub fn check_config(config: AndaConfig) -> Result<AndaConfig, ProjectError> {
    // do nothing for now
    Ok(config)
}

#[cfg(test)]
mod test_parser {
    use super::*;

    #[test]
    fn test_parse() {
        // set env var
        std::env::set_var("RUST_LOG", "trace");
        env_logger::init();
        let config = r#"
        project "anda" {
            pre_script {
                commands = ["echo 'hello'"]
            }
            env = {
                TEST = "test"
            }
        }
        "#;

        let body = hcl::parse(config).unwrap();

        print!("{:#?}", body);

        let config: AndaConfig = hcl::from_str(config).unwrap();

        println!("{:#?}", config);
    }
}